From 18f63e5dcc081519a3d943fef4e0a07ca5ef4a06 Mon Sep 17 00:00:00 2001 From: oh_ci Date: Mon, 7 Jul 2025 11:09:50 +0000 Subject: [PATCH] =?UTF-8?q?=E5=9B=9E=E9=80=80=20'Pull=20Request=20!5042=20?= =?UTF-8?q?:=20cherry-pick=200603=20to=20master'?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- arkui-plugins/.gitignore | 2 - arkui-plugins/BUILD.gn | 9 - arkui-plugins/build_ui_plugins.py | 3 - arkui-plugins/common/arkts-utils.ts | 10 - arkui-plugins/common/plugin-context.ts | 1 - arkui-plugins/common/predefines.ts | 84 +- arkui-plugins/common/program-visitor.ts | 172 +--- .../interop-plugins/arkuiImportList.ts | 176 ---- .../interop-plugins/decl_transformer.ts | 71 +- arkui-plugins/interop-plugins/index.ts | 86 +- arkui-plugins/jest-test.config.js | 56 -- .../memo-plugins/function-transformer.ts | 615 ++++-------- arkui-plugins/memo-plugins/index.ts | 150 ++- .../memo-plugins/internal-transformer.ts | 49 - arkui-plugins/memo-plugins/memo-factory.ts | 180 +--- .../memo-plugins/parameter-transformer.ts | 276 +----- .../memo-plugins/return-transformer.ts | 24 +- .../memo-plugins/signature-transformer.ts | 68 +- arkui-plugins/memo-plugins/utils.ts | 342 +------ arkui-plugins/package.json | 4 +- .../demo/interop/1.2State-1.1Link-example.ets | 104 -- .../demo/localtest/build_config_template.json | 1 - .../test/demo/localtest/entry/new.ets | 7 +- .../demo/mock/animation/animation-basic.ets | 17 - .../custom-component-call.ets | 43 - .../mock/builder-lambda/simple-component.ets | 23 - .../builder-lambda/style-with-receiver.ets | 47 - .../builder-param/builder-param-passing.ets | 41 - .../builder-param/init-with-local-builder.ets | 29 - .../decorators/builder/global-builder.ets | 41 - .../mock/decorators/builder/local-builder.ets | 36 - .../mock/decorators/link/link-basic-type.ets | 29 - .../decorators/link/link-complex-type.ets | 49 - .../link/link-to-link-prop-state.ets | 41 - .../mock/decorators/link/state-to-link.ets | 70 -- .../objectlink/objectlink-basic.ets | 13 - .../objectlink/objectlink-observed.ets | 54 -- .../observed-track/observed-only.ets | 13 - .../observed-track-class-property.ets | 19 - .../observed-track-complex-type.ets | 76 -- .../observed-track/observed-track-extends.ets | 23 - .../observed-track-implements.ets | 20 - .../observed-track/observed-track.ets | 13 - .../decorators/observed-track/track-only.ets | 12 - .../mock/decorators/prop/prop-basic-type.ets | 29 - .../decorators/prop/prop-complex-type.ets | 49 - .../mock/decorators/prop/state-to-prop.ets | 54 -- .../provide-annotation-usage.ets | 32 - .../provide-basic-type.ets | 29 - .../provide-complex-type.ets | 49 - .../decorators/resource/resource-in-build.ets | 50 - .../resource/resource-in-property.ets | 31 - .../decorators/reusable/reusable-basic.ets | 19 - .../decorators/reusable/reusable-complex.ets | 53 -- .../decorators/state/state-basic-type.ets | 29 - .../decorators/state/state-complex-type.ets | 49 - .../mock/decorators/state/state-to-state.ets | 42 - .../storagelink/storagelink-appstorage.ets | 35 - .../storagelink/storagelink-complex-type.ets | 28 - .../storagelink-primitive-type.ets | 12 - .../storageprop/storageprop-appstorage.ets | 34 - .../storageprop/storageprop-complex-type.ets | 28 - .../storageprop-primitive-type.ets | 12 - .../mock/decorators/watch/watch-basic.ets | 41 - .../mock/memo/functions/argument-call.ets | 52 - .../mock/memo/functions/declare-and-call.ets | 35 - .../mock/memo/functions/inner-functions.ets | 37 - .../memo/functions/non-void-return-type.ets | 64 -- .../mock/memo/functions/type-reference.ets | 40 - .../mock/memo/functions/void-return-type.ets | 21 - .../demo/mock/memo/lambdas/argument-call.ets | 40 - .../memo/lambdas/function-with-receiver.ets | 32 - .../mock/memo/lambdas/trailing-lambdas.ets | 44 - .../demo/mock/memo/lambdas/void-lambda.ets | 26 - .../demo/mock/memo/lambdas/with-receiver.ets | 51 - .../demo/mock/memo/methods/argument-call.ets | 49 - .../test/demo/mock/memo/methods/callable.ets | 47 - .../mock/memo/methods/declare-and-call.ets | 41 - .../demo/mock/memo/methods/internal-calls.ets | 81 -- .../mock/memo/methods/non-void-method.ets | 67 -- .../demo/mock/memo/methods/void-method.ets | 57 -- .../memo/properties/class-constructor.ets | 39 - .../mock/memo/properties/class-properties.ets | 39 - .../demo/mock/memo/properties/implements.ets | 24 - .../demo/mock/memo/properties/interfaces.ets | 34 - .../demo/mock/xcomponent/xcomponent-basic.ets | 19 - arkui-plugins/test/package.json | 6 +- .../test/ut/common/annotation.test.ts | 16 +- .../argument-call.test.ts | 109 --- .../declare-and-call.test.ts | 90 -- .../inner-functions.test.ts | 112 --- .../non-void-return-type.test.ts | 112 --- .../type-reference.test.ts | 92 -- .../void-return-type.test.ts | 61 -- .../lambda-literals/argument-call.test.ts | 173 ---- .../function-with-receiver.test.ts | 97 -- .../lambda-literals/trailing-lambdas.test.ts | 169 ---- .../lambda-literals/void-lambda.test.ts | 73 -- .../lambda-literals/with-receiver.test.ts | 125 --- .../method-declarations/argument-call.test.ts | 145 --- .../method-declarations/callable.test.ts | 112 --- .../declare-and-call.test.ts | 83 -- .../internal-calls.test.ts | 186 ---- .../non-void-method.test.ts | 119 --- .../method-declarations/void-method.test.ts | 151 --- .../class-constructor.test.ts | 101 -- .../class-properties.test.ts | 106 --- .../property-declarations/interfaces.test.ts | 107 --- .../animation/animation-basic.test.ts | 121 --- .../custom-component-call.test.ts | 166 ---- .../builder-lambda/simple-component.test.ts | 91 -- .../style-with-receiver.test.ts | 102 -- .../builder-param-passing.test.ts | 133 --- .../init-with-local-builder.test.ts | 100 -- .../decorators/builder/global-builder.test.ts | 97 -- .../decorators/builder/local-builder.test.ts | 92 -- .../decorators/link/link-basic-type.test.ts | 151 --- .../decorators/link/link-complex-type.test.ts | 314 ------ .../link/link-to-link-prop-state.test.ts | 186 ---- .../decorators/link/state-to-link.test.ts | 175 ---- .../observed-track/observed-only.test.ts | 157 --- .../observed-track-class-property.test.ts | 206 ---- .../observed-track-complex-type.test.ts | 898 ------------------ .../observed-track-extends.test.ts | 204 ---- .../observed-track-implements.test.ts | 171 ---- .../observed-track/observed-track.test.ts | 142 --- .../observed-track/track-only.test.ts | 142 --- .../decorators/prop/prop-basic-type.test.ts | 161 ---- .../decorators/prop/prop-complex-type.test.ts | 337 ------- .../decorators/prop/state-to-prop.test.ts | 169 ---- .../provide-annotation-usage.test.ts | 179 ---- .../provide-basic-type.test.ts | 140 --- .../provide-complex-type.test.ts | 288 ------ .../resource/resource-in-build.test.ts | 142 --- .../resource/resource-in-property.test.ts | 108 --- .../reusable/reusable-basic.test.ts | 159 ---- .../reusable/reusable-complex.test.ts | 209 ---- .../decorators/state/state-basic-type.test.ts | 140 --- .../state/state-complex-type.test.ts | 288 ------ .../decorators/state/state-to-state.test.ts | 132 --- .../storagelink-appstorage.test.ts | 164 ---- .../storagelink-complex-type.test.ts | 313 ------ .../storagelink-primitive-type.test.ts | 153 --- .../storageprop-appstorage.test.ts | 165 ---- .../storageprop-complex-type.test.ts | 312 ------ .../storageprop-primitive-type.test.ts | 152 --- .../decorators/watch/watch-basic.test.ts | 306 ------ .../xcomponent/xcomponent-basic.test.ts | 132 --- arkui-plugins/test/utils/artkts-config.ts | 41 +- arkui-plugins/test/utils/cache.ts | 59 -- arkui-plugins/test/utils/compile.ts | 9 +- arkui-plugins/test/utils/global.ts | 34 +- arkui-plugins/test/utils/parse-string.ts | 15 +- arkui-plugins/test/utils/path-config.ts | 10 +- arkui-plugins/test/utils/plugin-driver.ts | 2 +- arkui-plugins/test/utils/plugin-tester.ts | 74 +- .../plugins/builder-lambda-no-recheck.ts | 48 - arkui-plugins/test/utils/plugins/index.ts | 24 - .../test/utils/plugins/memo-no-recheck.ts | 60 -- arkui-plugins/test/utils/plugins/recheck.ts | 35 - .../test/utils/plugins/struct-no-recheck.ts | 48 - .../test/utils/plugins/struct-to-component.ts | 47 - .../test/utils/plugins/ui-no-recheck.ts | 48 - arkui-plugins/tsconfig.build.json | 1 - arkui-plugins/tsconfig.json | 4 +- .../builder-lambda-transformer.ts | 257 ++++- .../builder-lambda-translators/factory.ts | 518 +--------- .../builder-lambda-translators/utils.ts | 192 +--- .../ui-plugins/checked-transformer.ts | 529 +++++------ .../ui-plugins/component-transformer.ts | 84 +- .../ui-plugins/entry-translators/factory.ts | 4 +- .../ui-plugins/entry-translators/utils.ts | 2 +- arkui-plugins/ui-plugins/index.ts | 69 +- arkui-plugins/ui-plugins/initstatevar.ts | 290 ------ arkui-plugins/ui-plugins/interop.ts | 595 ------------ .../ui-plugins/legacy-transformer.ts | 254 ----- .../ui-plugins/preprocessor-transform.ts | 54 +- .../property-translators/builderParam.ts | 41 +- .../property-translators/consume.ts | 61 +- .../property-translators/factory.ts | 66 +- .../ui-plugins/property-translators/index.ts | 9 - .../property-translators/objectlink.ts | 129 +-- .../property-translators/observedTrack.ts | 348 ------- .../property-translators/provide.ts | 91 +- .../property-translators/regularProperty.ts | 66 +- .../ui-plugins/property-translators/utils.ts | 113 +-- .../ui-plugins/struct-translators/factory.ts | 128 +-- .../struct-translators/struct-transformer.ts | 33 +- .../ui-plugins/struct-translators/utils.ts | 41 +- arkui-plugins/ui-plugins/ui-factory.ts | 66 +- arkui-plugins/ui-plugins/utils.ts | 90 +- arkui-plugins/ui-syntax-plugins/index.ts | 44 - .../ui-syntax-plugins/processor/index.ts | 64 -- .../rules/build-root-node.ts | 100 -- .../check-construct-private-parameter.ts | 93 -- .../rules/check-decorated-property-type.ts | 77 -- .../component-componentV2-mix-use-check.ts | 177 ---- .../rules/componentV2-mix-check.ts | 57 -- .../componentV2-state-usage-validation.ts | 168 ---- .../rules/construct-parameter-literal.ts | 112 --- .../consumer-provider-decorator-check.ts | 271 ------ .../rules/custom-dialog-missing-controller.ts | 68 -- .../rules/decorators-in-ui-component-only.ts | 102 -- .../rules/entry-localstorage-check.ts | 61 -- .../rules/entry-struct-no-export.ts | 53 -- .../ui-syntax-plugins/rules/index.ts | 99 -- .../rules/local-builder-check.ts | 63 -- .../rules/monitor-decorator-check.ts | 174 ---- .../rules/nested-relationship.ts | 191 ---- .../rules/no-child-in-button.ts | 89 -- .../rules/no-duplicate-decorators.ts | 104 -- .../rules/no-duplicate-entry.ts | 72 -- .../rules/no-duplicate-preview.ts | 73 -- .../rules/no-duplicate-state-manager.ts | 74 -- .../rules/no-prop-link-objectlink-in-entry.ts | 75 -- .../rules/no-same-as-built-in-attribute.ts | 47 - .../observed-heritage-compatible-check.ts | 106 --- .../rules/observed-observedV2-check.ts | 47 - .../observedV2-trace-usage-validation.ts | 146 --- .../rules/old-new-decorator-mix-use-check.ts | 111 --- .../rules/once-decorator-check.ts | 187 ---- .../rules/one-decorator-on-function-method.ts | 68 -- .../rules/reuse-attribute-check.ts | 107 --- .../rules/struct-missing-decorator.ts | 74 -- .../rules/struct-property-decorator.ts | 52 - .../rules/struct-variable-initialization.ts | 72 -- .../rules/track-decorator-check.ts | 146 --- .../rules/type-decorator-check.ts | 167 ---- .../ui-syntax-plugins/rules/ui-syntax-rule.ts | 43 - .../rules/validate-build-in-struct.ts | 135 --- ...iable-initialization-via-component-cons.ts | 210 ---- .../rules/watch-decorator-function.ts | 128 --- .../rules/watch-decorator-regular.ts | 60 -- .../rules/wrap-builder-check.ts | 109 --- .../parsed-ui-syntax-linter-transformer.ts | 25 - .../transformers/ui-syntax-linter-visitor.ts | 23 - .../ui-syntax-plugins/utils/index.ts | 200 ---- koala-wrapper/BUILD.gn | 9 - koala-wrapper/native/src/bridges.cc | 165 +--- koala-wrapper/native/src/common.cc | 38 +- koala-wrapper/native/src/generated/bridges.cc | 124 ++- koala-wrapper/src/Es2pandaEnums.ts | 8 +- koala-wrapper/src/Es2pandaNativeModule.ts | 71 +- .../src/arkts-api/factory/nodeFactory.ts | 82 +- .../src/arkts-api/factory/nodeTests.ts | 12 +- koala-wrapper/src/arkts-api/index.ts | 6 - .../node-utilities/AnnotationUsage.ts | 10 - .../node-utilities/ArrayExpression.ts | 38 - .../node-utilities/ForInStatement.ts | 37 - .../node-utilities/ForOfStatement.ts | 38 - .../node-utilities/ForUpdateStatement.ts | 39 - .../node-utilities/MethodDefinition.ts | 3 +- .../node-utilities/ObjectExpression.ts | 37 - .../src/arkts-api/node-utilities/Property.ts | 27 - .../node-utilities/TemplateLiteral.ts | 35 - .../arkts-api/node-utilities/TryStatement.ts | 41 - .../node-utilities/VariableDeclaration.ts | 6 +- koala-wrapper/src/arkts-api/peers/AstNode.ts | 7 +- koala-wrapper/src/arkts-api/peers/Context.ts | 54 +- .../src/arkts-api/peers/SourceRange.ts | 38 - koala-wrapper/src/arkts-api/types.ts | 32 +- .../src/arkts-api/utilities/public.ts | 214 +---- koala-wrapper/src/arkts-api/visitor.ts | 481 +++------- koala-wrapper/src/generated/Es2pandaEnums.ts | 380 ++++---- .../src/generated/Es2pandaNativeModule.ts | 39 +- koala-wrapper/src/generated/index.ts | 3 +- koala-wrapper/src/generated/node-map.ts | 305 +++--- .../src/generated/peers/AnnotationUsage.ts | 8 +- .../src/generated/peers/ArrayExpression.ts | 76 +- .../peers/ArrowFunctionExpression.ts | 8 +- .../src/generated/peers/AssertStatement.ts | 8 +- .../src/generated/peers/AwaitExpression.ts | 8 +- .../src/generated/peers/BigIntLiteral.ts | 8 +- .../src/generated/peers/BinaryExpression.ts | 8 +- .../src/generated/peers/BlockExpression.ts | 8 +- .../src/generated/peers/BlockStatement.ts | 8 +- .../src/generated/peers/BooleanLiteral.ts | 8 +- .../src/generated/peers/BreakStatement.ts | 8 +- .../src/generated/peers/CallExpression.ts | 8 +- .../src/generated/peers/CatchClause.ts | 8 +- .../src/generated/peers/ChainExpression.ts | 8 +- .../src/generated/peers/CharLiteral.ts | 8 +- .../src/generated/peers/ClassDeclaration.ts | 8 +- .../src/generated/peers/ClassDefinition.ts | 8 +- .../src/generated/peers/ClassExpression.ts | 8 +- .../src/generated/peers/ClassProperty.ts | 8 +- .../src/generated/peers/ClassStaticBlock.ts | 8 +- .../generated/peers/ConditionalExpression.ts | 8 +- .../src/generated/peers/ContinueStatement.ts | 8 +- .../src/generated/peers/DebuggerStatement.ts | 8 +- .../src/generated/peers/Decorator.ts | 8 +- .../generated/peers/DirectEvalExpression.ts | 8 +- .../src/generated/peers/DoWhileStatement.ts | 8 +- .../src/generated/peers/ETSClassLiteral.ts | 8 +- .../src/generated/peers/ETSFunctionType.ts | 8 +- .../generated/peers/ETSImportDeclaration.ts | 13 +- .../src/generated/peers/ETSModule.ts | 8 +- .../peers/ETSNewArrayInstanceExpression.ts | 8 +- .../peers/ETSNewClassInstanceExpression.ts | 8 +- .../ETSNewMultiDimArrayInstanceExpression.ts | 8 +- .../src/generated/peers/ETSNullType.ts | 8 +- .../generated/peers/ETSPackageDeclaration.ts | 8 +- .../generated/peers/ETSParameterExpression.ts | 8 +- .../src/generated/peers/ETSPrimitiveType.ts | 8 +- .../generated/peers/ETSReExportDeclaration.ts | 8 +- .../generated/peers/ETSStructDeclaration.ts | 8 +- koala-wrapper/src/generated/peers/ETSTuple.ts | 8 +- .../src/generated/peers/ETSTypeReference.ts | 8 +- .../generated/peers/ETSTypeReferencePart.ts | 8 +- .../src/generated/peers/ETSUndefinedType.ts | 8 +- .../src/generated/peers/ETSUnionType.ts | 8 +- .../src/generated/peers/ETSWildcardType.ts | 8 +- .../src/generated/peers/EmptyStatement.ts | 8 +- .../generated/peers/ExportAllDeclaration.ts | 8 +- .../peers/ExportDefaultDeclaration.ts | 8 +- .../generated/peers/ExportNamedDeclaration.ts | 8 +- .../src/generated/peers/ExportSpecifier.ts | 8 +- .../generated/peers/ExpressionStatement.ts | 8 +- .../src/generated/peers/ForInStatement.ts | 63 +- .../src/generated/peers/ForOfStatement.ts | 75 +- .../src/generated/peers/ForUpdateStatement.ts | 80 +- .../generated/peers/FunctionDeclaration.ts | 8 +- .../src/generated/peers/FunctionExpression.ts | 8 +- .../src/generated/peers/Identifier.ts | 8 +- .../src/generated/peers/IfStatement.ts | 8 +- .../src/generated/peers/ImportDeclaration.ts | 6 +- .../generated/peers/ImportDefaultSpecifier.ts | 8 +- .../src/generated/peers/ImportExpression.ts | 8 +- .../peers/ImportNamespaceSpecifier.ts | 8 +- .../src/generated/peers/ImportSpecifier.ts | 8 +- .../src/generated/peers/LabelPair.ts | 35 - .../src/generated/peers/LabelledStatement.ts | 8 +- .../src/generated/peers/MemberExpression.ts | 8 +- .../src/generated/peers/MetaProperty.ts | 8 +- .../src/generated/peers/MethodDefinition.ts | 8 +- .../src/generated/peers/NamedType.ts | 8 +- .../src/generated/peers/NewExpression.ts | 8 +- .../src/generated/peers/NullLiteral.ts | 8 +- .../src/generated/peers/NumberLiteral.ts | 11 +- .../src/generated/peers/OmittedExpression.ts | 8 +- .../src/generated/peers/OpaqueTypeNode.ts | 8 +- .../peers/PrefixAssertionExpression.ts | 8 +- koala-wrapper/src/generated/peers/Property.ts | 8 +- .../src/generated/peers/RegExpLiteral.ts | 8 +- .../src/generated/peers/ReturnStatement.ts | 8 +- .../src/generated/peers/ScriptFunction.ts | 8 +- .../src/generated/peers/SequenceExpression.ts | 8 +- .../src/generated/peers/StringLiteral.ts | 8 +- .../src/generated/peers/SuperExpression.ts | 8 +- .../generated/peers/SwitchCaseStatement.ts | 8 +- .../src/generated/peers/SwitchStatement.ts | 8 +- .../src/generated/peers/TSAnyKeyword.ts | 8 +- .../src/generated/peers/TSArrayType.ts | 8 +- .../src/generated/peers/TSAsExpression.ts | 8 +- .../src/generated/peers/TSBigintKeyword.ts | 8 +- .../src/generated/peers/TSBooleanKeyword.ts | 8 +- .../src/generated/peers/TSClassImplements.ts | 8 +- .../src/generated/peers/TSConditionalType.ts | 8 +- .../src/generated/peers/TSConstructorType.ts | 8 +- .../src/generated/peers/TSEnumDeclaration.ts | 8 +- .../src/generated/peers/TSEnumMember.ts | 8 +- .../peers/TSExternalModuleReference.ts | 8 +- .../src/generated/peers/TSFunctionType.ts | 8 +- .../peers/TSImportEqualsDeclaration.ts | 8 +- .../src/generated/peers/TSImportType.ts | 8 +- .../src/generated/peers/TSIndexSignature.ts | 8 +- .../generated/peers/TSIndexedAccessType.ts | 8 +- .../src/generated/peers/TSInferType.ts | 8 +- .../src/generated/peers/TSInterfaceBody.ts | 8 +- .../generated/peers/TSInterfaceDeclaration.ts | 8 +- .../generated/peers/TSInterfaceHeritage.ts | 8 +- .../src/generated/peers/TSIntersectionType.ts | 8 +- .../src/generated/peers/TSLiteralType.ts | 8 +- .../src/generated/peers/TSMappedType.ts | 8 +- .../src/generated/peers/TSMethodSignature.ts | 8 +- .../src/generated/peers/TSModuleBlock.ts | 8 +- .../generated/peers/TSModuleDeclaration.ts | 8 +- .../src/generated/peers/TSNamedTupleMember.ts | 8 +- .../src/generated/peers/TSNeverKeyword.ts | 8 +- .../generated/peers/TSNonNullExpression.ts | 8 +- .../src/generated/peers/TSNullKeyword.ts | 8 +- .../src/generated/peers/TSNumberKeyword.ts | 8 +- .../src/generated/peers/TSObjectKeyword.ts | 8 +- .../generated/peers/TSParameterProperty.ts | 8 +- .../generated/peers/TSParenthesizedType.ts | 8 +- .../generated/peers/TSPropertySignature.ts | 8 +- .../src/generated/peers/TSQualifiedName.ts | 8 +- .../generated/peers/TSSignatureDeclaration.ts | 8 +- .../src/generated/peers/TSStringKeyword.ts | 8 +- .../src/generated/peers/TSThisType.ts | 8 +- .../src/generated/peers/TSTupleType.ts | 8 +- .../generated/peers/TSTypeAliasDeclaration.ts | 8 +- .../src/generated/peers/TSTypeAssertion.ts | 8 +- .../src/generated/peers/TSTypeLiteral.ts | 8 +- .../src/generated/peers/TSTypeOperator.ts | 6 +- .../src/generated/peers/TSTypeParameter.ts | 6 +- .../peers/TSTypeParameterDeclaration.ts | 6 +- .../peers/TSTypeParameterInstantiation.ts | 6 +- .../src/generated/peers/TSTypePredicate.ts | 6 +- .../src/generated/peers/TSTypeQuery.ts | 6 +- .../src/generated/peers/TSTypeReference.ts | 6 +- .../src/generated/peers/TSUndefinedKeyword.ts | 6 +- .../src/generated/peers/TSUnionType.ts | 6 +- .../src/generated/peers/TSUnknownKeyword.ts | 6 +- .../src/generated/peers/TSVoidKeyword.ts | 6 +- .../peers/TaggedTemplateExpression.ts | 8 +- .../src/generated/peers/TemplateElement.ts | 8 +- .../src/generated/peers/TemplateLiteral.ts | 11 +- .../src/generated/peers/ThisExpression.ts | 8 +- .../src/generated/peers/ThrowStatement.ts | 8 +- .../src/generated/peers/TryStatement.ts | 36 +- .../src/generated/peers/TypeofExpression.ts | 6 +- .../src/generated/peers/UnaryExpression.ts | 6 +- .../src/generated/peers/UndefinedLiteral.ts | 6 +- .../src/generated/peers/UpdateExpression.ts | 6 +- .../generated/peers/VariableDeclaration.ts | 6 +- .../src/generated/peers/VariableDeclarator.ts | 6 +- .../src/generated/peers/WhileStatement.ts | 6 +- .../src/generated/peers/YieldExpression.ts | 6 +- 419 files changed, 2724 insertions(+), 25557 deletions(-) delete mode 100644 arkui-plugins/interop-plugins/arkuiImportList.ts delete mode 100644 arkui-plugins/jest-test.config.js delete mode 100644 arkui-plugins/memo-plugins/internal-transformer.ts delete mode 100644 arkui-plugins/test/demo/interop/1.2State-1.1Link-example.ets delete mode 100644 arkui-plugins/test/demo/mock/animation/animation-basic.ets delete mode 100644 arkui-plugins/test/demo/mock/builder-lambda/custom-component/custom-component-call.ets delete mode 100644 arkui-plugins/test/demo/mock/builder-lambda/simple-component.ets delete mode 100644 arkui-plugins/test/demo/mock/builder-lambda/style-with-receiver.ets delete mode 100644 arkui-plugins/test/demo/mock/decorators/builder-param/builder-param-passing.ets delete mode 100644 arkui-plugins/test/demo/mock/decorators/builder-param/init-with-local-builder.ets delete mode 100644 arkui-plugins/test/demo/mock/decorators/builder/global-builder.ets delete mode 100644 arkui-plugins/test/demo/mock/decorators/builder/local-builder.ets delete mode 100644 arkui-plugins/test/demo/mock/decorators/link/link-basic-type.ets delete mode 100644 arkui-plugins/test/demo/mock/decorators/link/link-complex-type.ets delete mode 100644 arkui-plugins/test/demo/mock/decorators/link/link-to-link-prop-state.ets delete mode 100644 arkui-plugins/test/demo/mock/decorators/link/state-to-link.ets delete mode 100644 arkui-plugins/test/demo/mock/decorators/objectlink/objectlink-basic.ets delete mode 100644 arkui-plugins/test/demo/mock/decorators/objectlink/objectlink-observed.ets delete mode 100644 arkui-plugins/test/demo/mock/decorators/observed-track/observed-only.ets delete mode 100644 arkui-plugins/test/demo/mock/decorators/observed-track/observed-track-class-property.ets delete mode 100644 arkui-plugins/test/demo/mock/decorators/observed-track/observed-track-complex-type.ets delete mode 100644 arkui-plugins/test/demo/mock/decorators/observed-track/observed-track-extends.ets delete mode 100644 arkui-plugins/test/demo/mock/decorators/observed-track/observed-track-implements.ets delete mode 100644 arkui-plugins/test/demo/mock/decorators/observed-track/observed-track.ets delete mode 100644 arkui-plugins/test/demo/mock/decorators/observed-track/track-only.ets delete mode 100644 arkui-plugins/test/demo/mock/decorators/prop/prop-basic-type.ets delete mode 100644 arkui-plugins/test/demo/mock/decorators/prop/prop-complex-type.ets delete mode 100644 arkui-plugins/test/demo/mock/decorators/prop/state-to-prop.ets delete mode 100644 arkui-plugins/test/demo/mock/decorators/provide-and-consume/provide-annotation-usage.ets delete mode 100644 arkui-plugins/test/demo/mock/decorators/provide-and-consume/provide-basic-type.ets delete mode 100644 arkui-plugins/test/demo/mock/decorators/provide-and-consume/provide-complex-type.ets delete mode 100644 arkui-plugins/test/demo/mock/decorators/resource/resource-in-build.ets delete mode 100644 arkui-plugins/test/demo/mock/decorators/resource/resource-in-property.ets delete mode 100644 arkui-plugins/test/demo/mock/decorators/reusable/reusable-basic.ets delete mode 100644 arkui-plugins/test/demo/mock/decorators/reusable/reusable-complex.ets delete mode 100644 arkui-plugins/test/demo/mock/decorators/state/state-basic-type.ets delete mode 100644 arkui-plugins/test/demo/mock/decorators/state/state-complex-type.ets delete mode 100644 arkui-plugins/test/demo/mock/decorators/state/state-to-state.ets delete mode 100644 arkui-plugins/test/demo/mock/decorators/storagelink/storagelink-appstorage.ets delete mode 100644 arkui-plugins/test/demo/mock/decorators/storagelink/storagelink-complex-type.ets delete mode 100644 arkui-plugins/test/demo/mock/decorators/storagelink/storagelink-primitive-type.ets delete mode 100644 arkui-plugins/test/demo/mock/decorators/storageprop/storageprop-appstorage.ets delete mode 100644 arkui-plugins/test/demo/mock/decorators/storageprop/storageprop-complex-type.ets delete mode 100644 arkui-plugins/test/demo/mock/decorators/storageprop/storageprop-primitive-type.ets delete mode 100644 arkui-plugins/test/demo/mock/decorators/watch/watch-basic.ets delete mode 100644 arkui-plugins/test/demo/mock/memo/functions/argument-call.ets delete mode 100644 arkui-plugins/test/demo/mock/memo/functions/declare-and-call.ets delete mode 100644 arkui-plugins/test/demo/mock/memo/functions/inner-functions.ets delete mode 100644 arkui-plugins/test/demo/mock/memo/functions/non-void-return-type.ets delete mode 100644 arkui-plugins/test/demo/mock/memo/functions/type-reference.ets delete mode 100644 arkui-plugins/test/demo/mock/memo/functions/void-return-type.ets delete mode 100644 arkui-plugins/test/demo/mock/memo/lambdas/argument-call.ets delete mode 100644 arkui-plugins/test/demo/mock/memo/lambdas/function-with-receiver.ets delete mode 100644 arkui-plugins/test/demo/mock/memo/lambdas/trailing-lambdas.ets delete mode 100644 arkui-plugins/test/demo/mock/memo/lambdas/void-lambda.ets delete mode 100644 arkui-plugins/test/demo/mock/memo/lambdas/with-receiver.ets delete mode 100644 arkui-plugins/test/demo/mock/memo/methods/argument-call.ets delete mode 100644 arkui-plugins/test/demo/mock/memo/methods/callable.ets delete mode 100644 arkui-plugins/test/demo/mock/memo/methods/declare-and-call.ets delete mode 100644 arkui-plugins/test/demo/mock/memo/methods/internal-calls.ets delete mode 100644 arkui-plugins/test/demo/mock/memo/methods/non-void-method.ets delete mode 100644 arkui-plugins/test/demo/mock/memo/methods/void-method.ets delete mode 100644 arkui-plugins/test/demo/mock/memo/properties/class-constructor.ets delete mode 100644 arkui-plugins/test/demo/mock/memo/properties/class-properties.ets delete mode 100644 arkui-plugins/test/demo/mock/memo/properties/implements.ets delete mode 100644 arkui-plugins/test/demo/mock/memo/properties/interfaces.ets delete mode 100644 arkui-plugins/test/demo/mock/xcomponent/xcomponent-basic.ets delete mode 100644 arkui-plugins/test/ut/memo-plugins/function-declarations/argument-call.test.ts delete mode 100644 arkui-plugins/test/ut/memo-plugins/function-declarations/declare-and-call.test.ts delete mode 100644 arkui-plugins/test/ut/memo-plugins/function-declarations/inner-functions.test.ts delete mode 100644 arkui-plugins/test/ut/memo-plugins/function-declarations/non-void-return-type.test.ts delete mode 100644 arkui-plugins/test/ut/memo-plugins/function-declarations/type-reference.test.ts delete mode 100644 arkui-plugins/test/ut/memo-plugins/function-declarations/void-return-type.test.ts delete mode 100644 arkui-plugins/test/ut/memo-plugins/lambda-literals/argument-call.test.ts delete mode 100644 arkui-plugins/test/ut/memo-plugins/lambda-literals/function-with-receiver.test.ts delete mode 100644 arkui-plugins/test/ut/memo-plugins/lambda-literals/trailing-lambdas.test.ts delete mode 100644 arkui-plugins/test/ut/memo-plugins/lambda-literals/void-lambda.test.ts delete mode 100644 arkui-plugins/test/ut/memo-plugins/lambda-literals/with-receiver.test.ts delete mode 100644 arkui-plugins/test/ut/memo-plugins/method-declarations/argument-call.test.ts delete mode 100644 arkui-plugins/test/ut/memo-plugins/method-declarations/callable.test.ts delete mode 100644 arkui-plugins/test/ut/memo-plugins/method-declarations/declare-and-call.test.ts delete mode 100644 arkui-plugins/test/ut/memo-plugins/method-declarations/internal-calls.test.ts delete mode 100644 arkui-plugins/test/ut/memo-plugins/method-declarations/non-void-method.test.ts delete mode 100644 arkui-plugins/test/ut/memo-plugins/method-declarations/void-method.test.ts delete mode 100644 arkui-plugins/test/ut/memo-plugins/property-declarations/class-constructor.test.ts delete mode 100644 arkui-plugins/test/ut/memo-plugins/property-declarations/class-properties.test.ts delete mode 100644 arkui-plugins/test/ut/memo-plugins/property-declarations/interfaces.test.ts delete mode 100644 arkui-plugins/test/ut/ui-plugins/animation/animation-basic.test.ts delete mode 100644 arkui-plugins/test/ut/ui-plugins/builder-lambda/custom-component/custom-component-call.test.ts delete mode 100644 arkui-plugins/test/ut/ui-plugins/builder-lambda/simple-component.test.ts delete mode 100644 arkui-plugins/test/ut/ui-plugins/builder-lambda/style-with-receiver.test.ts delete mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/builder-param/builder-param-passing.test.ts delete mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/builder-param/init-with-local-builder.test.ts delete mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/builder/global-builder.test.ts delete mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/builder/local-builder.test.ts delete mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/link/link-basic-type.test.ts delete mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/link/link-complex-type.test.ts delete mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/link/link-to-link-prop-state.test.ts delete mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/link/state-to-link.test.ts delete mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-only.test.ts delete mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-class-property.test.ts delete mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-complex-type.test.ts delete mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-extends.test.ts delete mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-implements.test.ts delete mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track.test.ts delete mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/observed-track/track-only.test.ts delete mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/prop/prop-basic-type.test.ts delete mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/prop/prop-complex-type.test.ts delete mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/prop/state-to-prop.test.ts delete mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-annotation-usage.test.ts delete mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-basic-type.test.ts delete mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-complex-type.test.ts delete mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/resource/resource-in-build.test.ts delete mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/resource/resource-in-property.test.ts delete mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/reusable/reusable-basic.test.ts delete mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/reusable/reusable-complex.test.ts delete mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/state/state-basic-type.test.ts delete mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/state/state-complex-type.test.ts delete mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/state/state-to-state.test.ts delete mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-appstorage.test.ts delete mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-complex-type.test.ts delete mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-primitive-type.test.ts delete mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-appstorage.test.ts delete mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-complex-type.test.ts delete mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-primitive-type.test.ts delete mode 100644 arkui-plugins/test/ut/ui-plugins/decorators/watch/watch-basic.test.ts delete mode 100644 arkui-plugins/test/ut/ui-plugins/xcomponent/xcomponent-basic.test.ts delete mode 100644 arkui-plugins/test/utils/cache.ts delete mode 100644 arkui-plugins/test/utils/plugins/builder-lambda-no-recheck.ts delete mode 100644 arkui-plugins/test/utils/plugins/index.ts delete mode 100644 arkui-plugins/test/utils/plugins/memo-no-recheck.ts delete mode 100644 arkui-plugins/test/utils/plugins/recheck.ts delete mode 100644 arkui-plugins/test/utils/plugins/struct-no-recheck.ts delete mode 100644 arkui-plugins/test/utils/plugins/struct-to-component.ts delete mode 100644 arkui-plugins/test/utils/plugins/ui-no-recheck.ts delete mode 100644 arkui-plugins/ui-plugins/initstatevar.ts delete mode 100644 arkui-plugins/ui-plugins/interop.ts delete mode 100644 arkui-plugins/ui-plugins/legacy-transformer.ts delete mode 100644 arkui-plugins/ui-plugins/property-translators/observedTrack.ts delete mode 100644 arkui-plugins/ui-syntax-plugins/index.ts delete mode 100644 arkui-plugins/ui-syntax-plugins/processor/index.ts delete mode 100644 arkui-plugins/ui-syntax-plugins/rules/build-root-node.ts delete mode 100644 arkui-plugins/ui-syntax-plugins/rules/check-construct-private-parameter.ts delete mode 100644 arkui-plugins/ui-syntax-plugins/rules/check-decorated-property-type.ts delete mode 100644 arkui-plugins/ui-syntax-plugins/rules/component-componentV2-mix-use-check.ts delete mode 100644 arkui-plugins/ui-syntax-plugins/rules/componentV2-mix-check.ts delete mode 100644 arkui-plugins/ui-syntax-plugins/rules/componentV2-state-usage-validation.ts delete mode 100644 arkui-plugins/ui-syntax-plugins/rules/construct-parameter-literal.ts delete mode 100644 arkui-plugins/ui-syntax-plugins/rules/consumer-provider-decorator-check.ts delete mode 100644 arkui-plugins/ui-syntax-plugins/rules/custom-dialog-missing-controller.ts delete mode 100644 arkui-plugins/ui-syntax-plugins/rules/decorators-in-ui-component-only.ts delete mode 100644 arkui-plugins/ui-syntax-plugins/rules/entry-localstorage-check.ts delete mode 100644 arkui-plugins/ui-syntax-plugins/rules/entry-struct-no-export.ts delete mode 100644 arkui-plugins/ui-syntax-plugins/rules/index.ts delete mode 100644 arkui-plugins/ui-syntax-plugins/rules/local-builder-check.ts delete mode 100644 arkui-plugins/ui-syntax-plugins/rules/monitor-decorator-check.ts delete mode 100644 arkui-plugins/ui-syntax-plugins/rules/nested-relationship.ts delete mode 100644 arkui-plugins/ui-syntax-plugins/rules/no-child-in-button.ts delete mode 100644 arkui-plugins/ui-syntax-plugins/rules/no-duplicate-decorators.ts delete mode 100644 arkui-plugins/ui-syntax-plugins/rules/no-duplicate-entry.ts delete mode 100644 arkui-plugins/ui-syntax-plugins/rules/no-duplicate-preview.ts delete mode 100644 arkui-plugins/ui-syntax-plugins/rules/no-duplicate-state-manager.ts delete mode 100644 arkui-plugins/ui-syntax-plugins/rules/no-prop-link-objectlink-in-entry.ts delete mode 100644 arkui-plugins/ui-syntax-plugins/rules/no-same-as-built-in-attribute.ts delete mode 100644 arkui-plugins/ui-syntax-plugins/rules/observed-heritage-compatible-check.ts delete mode 100644 arkui-plugins/ui-syntax-plugins/rules/observed-observedV2-check.ts delete mode 100644 arkui-plugins/ui-syntax-plugins/rules/observedV2-trace-usage-validation.ts delete mode 100644 arkui-plugins/ui-syntax-plugins/rules/old-new-decorator-mix-use-check.ts delete mode 100644 arkui-plugins/ui-syntax-plugins/rules/once-decorator-check.ts delete mode 100644 arkui-plugins/ui-syntax-plugins/rules/one-decorator-on-function-method.ts delete mode 100644 arkui-plugins/ui-syntax-plugins/rules/reuse-attribute-check.ts delete mode 100644 arkui-plugins/ui-syntax-plugins/rules/struct-missing-decorator.ts delete mode 100644 arkui-plugins/ui-syntax-plugins/rules/struct-property-decorator.ts delete mode 100644 arkui-plugins/ui-syntax-plugins/rules/struct-variable-initialization.ts delete mode 100644 arkui-plugins/ui-syntax-plugins/rules/track-decorator-check.ts delete mode 100644 arkui-plugins/ui-syntax-plugins/rules/type-decorator-check.ts delete mode 100644 arkui-plugins/ui-syntax-plugins/rules/ui-syntax-rule.ts delete mode 100644 arkui-plugins/ui-syntax-plugins/rules/validate-build-in-struct.ts delete mode 100644 arkui-plugins/ui-syntax-plugins/rules/variable-initialization-via-component-cons.ts delete mode 100644 arkui-plugins/ui-syntax-plugins/rules/watch-decorator-function.ts delete mode 100644 arkui-plugins/ui-syntax-plugins/rules/watch-decorator-regular.ts delete mode 100644 arkui-plugins/ui-syntax-plugins/rules/wrap-builder-check.ts delete mode 100644 arkui-plugins/ui-syntax-plugins/transformers/parsed-ui-syntax-linter-transformer.ts delete mode 100644 arkui-plugins/ui-syntax-plugins/transformers/ui-syntax-linter-visitor.ts delete mode 100644 arkui-plugins/ui-syntax-plugins/utils/index.ts delete mode 100644 koala-wrapper/src/arkts-api/node-utilities/ArrayExpression.ts delete mode 100644 koala-wrapper/src/arkts-api/node-utilities/ForInStatement.ts delete mode 100644 koala-wrapper/src/arkts-api/node-utilities/ForOfStatement.ts delete mode 100644 koala-wrapper/src/arkts-api/node-utilities/ForUpdateStatement.ts delete mode 100644 koala-wrapper/src/arkts-api/node-utilities/ObjectExpression.ts delete mode 100644 koala-wrapper/src/arkts-api/node-utilities/Property.ts delete mode 100644 koala-wrapper/src/arkts-api/node-utilities/TemplateLiteral.ts delete mode 100644 koala-wrapper/src/arkts-api/node-utilities/TryStatement.ts delete mode 100644 koala-wrapper/src/arkts-api/peers/SourceRange.ts delete mode 100644 koala-wrapper/src/generated/peers/LabelPair.ts diff --git a/arkui-plugins/.gitignore b/arkui-plugins/.gitignore index 98f9b3e90..7f8e5351e 100644 --- a/arkui-plugins/.gitignore +++ b/arkui-plugins/.gitignore @@ -3,7 +3,6 @@ node_modules/ **/*/dist/ **/*/build/ -dist/ build/ lib/ @@ -14,6 +13,5 @@ package-lock.json coverage/ **/*/generated -**/*/report test/demo/localtest/build_config.json diff --git a/arkui-plugins/BUILD.gn b/arkui-plugins/BUILD.gn index ef1316286..a262ea4c0 100755 --- a/arkui-plugins/BUILD.gn +++ b/arkui-plugins/BUILD.gn @@ -12,7 +12,6 @@ # limitations under the License. import("//build/ohos.gni") -import("//build/config/components/ets_frontend/ets2abc_config.gni") npm_path = "//prebuilts/build-tools/common/nodejs/current/bin/npm" @@ -42,11 +41,3 @@ ohos_copy("ui_plugin") { subsystem_name = "developtools" part_name = "ace_ets2bundle" } - -ohos_copy("ohos_ets_ui_plugins") { - deps = [ ":gen_ui_plugins" ] - sources = [ rebase_path("$target_gen_dir") ] - outputs = [ ohos_ets_ui_plugins_path ] - subsystem_name = "developtools" - part_name = "ace_ets2bundle" -} \ No newline at end of file diff --git a/arkui-plugins/build_ui_plugins.py b/arkui-plugins/build_ui_plugins.py index 6ae5d669e..3fe73510c 100755 --- a/arkui-plugins/build_ui_plugins.py +++ b/arkui-plugins/build_ui_plugins.py @@ -53,9 +53,6 @@ def copy_output(options): copy_files(os.path.join(options.source_path, 'lib'), os.path.join(options.output_path, 'lib')) - copy_files(os.path.join(options.source_path, '../compiler/components'), - os.path.join(options.output_path, 'lib/components')) - copy_files(os.path.join(options.source_path, 'package.json'), os.path.join(options.output_path, 'package.json'), True) diff --git a/arkui-plugins/common/arkts-utils.ts b/arkui-plugins/common/arkts-utils.ts index e62d9c991..771442543 100644 --- a/arkui-plugins/common/arkts-utils.ts +++ b/arkui-plugins/common/arkts-utils.ts @@ -97,13 +97,3 @@ export function updateStructMetadata( structInfo.metadata = metadata; return structInfo; } - -export function moveToFront(arr: T[], idx: number): T[] { - if (idx < 0 || idx >= arr.length) { - throw new Error(`Index ${idx} is out of bounds for array of length ${arr.length}`); - } - - const copy = [...arr]; - const [item] = copy.splice(idx, 1); - return [item, ...copy]; -} \ No newline at end of file diff --git a/arkui-plugins/common/plugin-context.ts b/arkui-plugins/common/plugin-context.ts index 95cce9152..f0ad9ccb4 100644 --- a/arkui-plugins/common/plugin-context.ts +++ b/arkui-plugins/common/plugin-context.ts @@ -78,7 +78,6 @@ export interface ProjectConfig { bundleName: string; moduleName: string; cachePath: string; - frameworkMode?: string; } export type PluginHandlerFunction = () => void; diff --git a/arkui-plugins/common/predefines.ts b/arkui-plugins/common/predefines.ts index 64b90a29b..08ce2babe 100644 --- a/arkui-plugins/common/predefines.ts +++ b/arkui-plugins/common/predefines.ts @@ -24,18 +24,13 @@ export const EXTERNAL_SOURCE_PREFIX_NAMES: (string | RegExp)[] = [ /@arkts\..*/, /@ohos\.(?!arkui).*/, /@system\..*/, + /arkui\.(?![Uu]serView$)[A-Z]/, // temporary solution /ability\..*/, ]; -export const EXTERNAL_SOURCE_PREFIX_NAMES_FOR_FRAMEWORK: (string | RegExp)[] = [ - 'std', - 'escompat', - /@arkts\..*/ -]; - export const ARKUI_COMPONENT_IMPORT_NAME: string = '@ohos.arkui.component'; + export const ARKUI_STATEMANAGEMENT_IMPORT_NAME: string = '@ohos.arkui.stateManagement'; -export const KIT_ARKUI_NAME: string = '@kit.ArkUI'; export const EXTERNAL_SOURCE_ALLOWED_IMPORT_INSERT_NAMES: string[] = [ ARKUI_COMPONENT_IMPORT_NAME, @@ -43,7 +38,40 @@ export const EXTERNAL_SOURCE_ALLOWED_IMPORT_INSERT_NAMES: string[] = [ ]; export const IMPORT_SOURCE_MAP: Map> = new Map>([ - ['arkui.stateManagement.runtime', new Set(['memo', '__memo_context_type', '__memo_id_type'])] + ['@ohos.arkui.component', new Set(['$r', '$rawfile', '_r', '_rawfile'])], + [ + '@ohos.arkui.stateManagement', + new Set([ + 'State', + 'Prop', + 'Provide', + 'Consume', + 'StorageLink', + 'StorageProp', + 'LocalStorageLink', + 'LocalStorageProp', + 'Watch', + 'ObjectLink', + 'StateDecoratedVariable', + 'MutableState', + 'contextLocalStateOf', + 'contextLocal', + 'observableProxy', + 'SyncedProperty', + 'objectLinkState', + 'propState', + 'AppStorageLinkState', + 'StorageLinkState', + 'DecoratedV1VariableBase', + 'LinkDecoratedVariable', + 'PropDecoratedVariable', + 'StorageLinkDecoratedVariable', + 'StoragePropDecoratedVariable', + 'memo', + '__memo_context_type', + '__memo_id_type', + ]), + ], ]); export const OUTPUT_DEPENDENCY_MAP: Map = new Map([ @@ -52,43 +80,11 @@ export const OUTPUT_DEPENDENCY_MAP: Map = new Map { - const prefix = ARKUI_COMPONENT_IMPORT_NAME || KIT_ARKUI_NAME; + const prefix = ARKUI_COMPONENT_IMPORT_NAME; const hasPrefixA = a.getName().startsWith(prefix); const hasPrefixB = b.getName().startsWith(prefix); @@ -78,10 +76,6 @@ function sortExternalSources(externalSources: arkts.ExternalSource[]): arkts.Ext }); } -export interface StructMap { - [key: string]: string; -} - export class ProgramVisitor extends AbstractVisitor { private readonly pluginName: string; private readonly state: arkts.Es2pandaContextState; @@ -90,8 +84,6 @@ export class ProgramVisitor extends AbstractVisitor { private readonly hooks?: ProgramHooks; private filenames: Map; private pluginContext?: PluginContext; - private legacyModuleList: string[] = []; - private legacyStructMap: Map; constructor(options: ProgramVisitorOptions) { super(options); @@ -102,86 +94,55 @@ export class ProgramVisitor extends AbstractVisitor { this.hooks = options.hooks; this.filenames = new Map(); this.pluginContext = options.pluginContext; - this.legacyModuleList = []; - this.legacyStructMap = new Map(); } reset(): void { super.reset(); this.filenames = new Map(); - this.legacyStructMap = new Map(); - this.legacyModuleList = []; - } - - getLegacyModule(): void { - const moduleList = this.pluginContext?.getProjectConfig()?.dependentModuleList; - if (moduleList === undefined) { - return; - } - for (const module of moduleList) { - const language = module.language; - const moduleName = module.moduleName; - if (language !== InteroperAbilityNames.ARKTS_1_1) { - continue; - } - if (!this.legacyStructMap.has(moduleName)) { - this.legacyStructMap.set(moduleName, {}); - this.legacyModuleList.push(moduleName); - } - } - } - - dumpHeaders( - currProgram: arkts.Program, - name: string, - cachePath: string | undefined, - prefixName: string, - extensionName: string - ): void { - debugDump( - currProgram.astNode.dumpSrc(), - getDumpFileName(this.state, prefixName, undefined, name), - true, - cachePath, - extensionName - ); } programVisitor(program: arkts.Program): arkts.Program { const skipPrefixes: (string | RegExp)[] = this.skipPrefixNames; + const visited = new Set(); const queue: arkts.Program[] = [program]; - this.getLegacyModule(); + while (queue.length > 0) { const currProgram = queue.shift()!; if (visited.has(currProgram.peer)) { continue; } + if (currProgram.peer !== program.peer) { const name: string = this.filenames.get(currProgram.peer)!; const cachePath: string | undefined = this.pluginContext?.getProjectConfig()?.cachePath; - if (this.legacyModuleList && matchPrefix(this.legacyModuleList, name)) { - if (this.state === arkts.Es2pandaContextState.ES2PANDA_STATE_PARSED) { - const structList = this.visitorLegacy(currProgram.astNode, currProgram, name); - const moduleName = name.split('/')[0]; - const structMap = this.legacyStructMap.get(moduleName)!; - for (const struct of structList) { - structMap[struct] = name; - } - } - } else { - this.dumpHeaders(currProgram, name, cachePath, 'Ori', program.programFileNameWithExtension); - const script = this.visitor(currProgram.astNode, currProgram, name); - if (script) { - this.dumpHeaders(currProgram, name, cachePath, this.pluginName, program.programFileNameWithExtension); - } + debugDump( + currProgram.astNode.dumpSrc(), + getDumpFileName(this.state, 'ORI', undefined, name), + true, + cachePath, + program.programFileNameWithExtension + ); + const script = this.visitor(currProgram.astNode, currProgram, name); + if (script) { + debugDump( + script.dumpSrc(), + getDumpFileName(this.state, this.pluginName, undefined, name), + true, + cachePath, + program.programFileNameWithExtension + ); } } + visited.add(currProgram.peer); + for (const externalSource of sortExternalSources(currProgram.externalSources)) { + // TODO: this is very time-consuming... if (matchPrefix(skipPrefixes, externalSource.getName())) { continue; } + const nextProgramArr: arkts.Program[] = externalSource.programs ?? []; for (const nextProgram of nextProgramArr) { this.filenames.set(nextProgram.peer, externalSource.getName()); @@ -191,76 +152,38 @@ export class ProgramVisitor extends AbstractVisitor { } } } - const hasLegacy = this.legacyStructMap.size ? true : false; + let programScript = program.astNode; - programScript = this.visitor(programScript, program, this.externalSourceName, hasLegacy); + programScript = this.visitor(programScript, program, this.externalSourceName); + const visitorsToReset = flattenVisitorsInHooks(this.hooks, this.state); visitorsToReset.forEach((visitor) => visitor.reset()); + return program; } - preVisitor( - node: arkts.AstNode, - program?: arkts.Program, - externalSourceName?: string - ): void { - const isExternal: boolean = !!externalSourceName; - let hook: ProgramHookLifeCycle | undefined = isExternal ? this.hooks?.external : this.hooks?.source; + visitor(node: arkts.AstNode, program?: arkts.Program, externalSourceName?: string): arkts.EtsScript { + let hook: ProgramHookLifeCycle | undefined; + let script: arkts.EtsScript = node as arkts.EtsScript; + let count: number = 0; + const isExternal: boolean = !!externalSourceName; + // pre-run visitors + hook = isExternal ? this.hooks?.external : this.hooks?.source; const preVisitors = hook?.pre?.visitors ?? []; for (const transformer of preVisitors) { transformer.isExternal = isExternal; transformer.externalSourceName = externalSourceName; transformer.program = program; transformer.visitor(script); - if (!this.hooks?.external?.pre?.resetAfter) { - transformer.reset(); - } - } - } - - postVisitor( - node: arkts.AstNode, - program?: arkts.Program, - externalSourceName?: string - ): void { - const isExternal: boolean = !!externalSourceName; - let hook: ProgramHookLifeCycle | undefined = isExternal ? this.hooks?.external : this.hooks?.source; - let script: arkts.EtsScript = node as arkts.EtsScript; - - const postVisitors = hook?.post?.visitors ?? []; - for (const transformer of postVisitors) { - transformer.isExternal = isExternal; - transformer.externalSourceName = externalSourceName; - transformer.program = program; - transformer.visitor(script); - if (!this.hooks?.external?.pre?.resetAfter) { - transformer.reset(); - } + if (!this.hooks?.external?.pre?.resetAfter) transformer.reset(); } - } - - visitor( - node: arkts.AstNode, - program?: arkts.Program, - externalSourceName?: string, - hasLegacy: boolean = false - ): arkts.EtsScript { - let script: arkts.EtsScript = node as arkts.EtsScript; - let count: number = 0; - const isExternal: boolean = !!externalSourceName; - - // pre-run visitors - this.preVisitor(node, program, externalSourceName); for (const transformer of this.visitors) { transformer.isExternal = isExternal; transformer.externalSourceName = externalSourceName; transformer.program = program; - if (hasLegacy && transformer instanceof ComponentTransformer) { - transformer.registerMap(this.legacyStructMap); - } script = transformer.visitor(script) as arkts.EtsScript; transformer.reset(); arkts.setAllParents(script); @@ -277,19 +200,16 @@ export class ProgramVisitor extends AbstractVisitor { } // post-run visitors - this.postVisitor(node, program, externalSourceName); + hook = isExternal ? this.hooks?.external : this.hooks?.source; + const postVisitors = hook?.post?.visitors ?? []; + for (const transformer of postVisitors) { + transformer.isExternal = isExternal; + transformer.externalSourceName = externalSourceName; + transformer.program = program; + transformer.visitor(script); + if (!this.hooks?.external?.pre?.resetAfter) transformer.reset(); + } return script; } - - visitorLegacy( - node: arkts.AstNode, - program?: arkts.Program, - externalSourceName?: string, - ): string[] { - const visitor = new LegacyTransformer(); - const script = visitor.visitor(node) as arkts.EtsScript; - const structList = visitor.getList(); - return structList; - } } diff --git a/arkui-plugins/interop-plugins/arkuiImportList.ts b/arkui-plugins/interop-plugins/arkuiImportList.ts deleted file mode 100644 index ddc19b2bd..000000000 --- a/arkui-plugins/interop-plugins/arkuiImportList.ts +++ /dev/null @@ -1,176 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -export const ARKUI_DECLARE_LIST: Set = new Set([ - 'AbilityComponent', - 'AlphabetIndexer', - 'AnalogClock', - 'Animator', - 'Badge', - 'Blank', - 'Button', - 'Calendar', - 'CalendarPicker', - 'Camera', - 'Canvas', - 'Checkbox', - 'CheckboxGroup', - 'Circle', - 'ColorPicker', - 'ColorPickerDialog', - 'Column', - 'ColumnSplit', - 'ContentSlot', - 'Counter', - 'DataPanel', - 'DatePicker', - 'Divider', - 'EffectComponent', - 'Ellipse', - 'EmbeddedComponent', - 'Flex', - 'FolderStack', - 'FormComponent', - 'FormLink', - 'Gauge', - 'GeometryView', - 'Grid', - 'GridItem', - 'GridContainer', - 'Hyperlink', - 'Image', - 'ImageAnimator', - 'Line', - 'LinearIndicator', - 'List', - 'ListItem', - 'ListItemGroup', - 'LoadingProgress', - 'Marquee', - 'MediaCachedImage', - 'Menu', - 'MenuItem', - 'MenuItemGroup', - 'MovingPhotoView', - 'NavDestination', - 'NavRouter', - 'Navigation', - 'Navigator', - 'NodeContainer', - 'Option', - 'PageTransitionEnter', - 'PageTransitionExit', - 'Panel', - 'Particle', - 'Path', - 'PatternLock', - 'Piece', - 'PlatformView', - 'PluginComponent', - 'Polygon', - 'Polyline', - 'Progress', - 'QRCode', - 'Radio', - 'Rating', - 'Rect', - 'Refresh', - 'RelativeContainer', - 'RemoteWindow', - 'RootScene', - 'Row', - 'RowSplit', - 'RichText', - 'Screen', - 'Scroll', - 'ScrollBar', - 'Search', - 'Section', - 'Select', - 'Shape', - 'Sheet', - 'SideBarContainer', - 'Slider', - 'Span', - 'Stack', - 'Stepper', - 'StepperItem', - 'Swiper', - 'SymbolGlyph', - 'SymbolSpan', - 'TabContent', - 'Tabs', - 'Text', - 'TextPicker', - 'TextClock', - 'TextArea', - 'TextInput', - 'TextTimer', - 'TimePicker', - 'Toggle', - 'Video', - 'Web', - 'WindowScene', - 'WithTheme', - 'XComponent', - 'GridRow', - 'GridCol', - 'WaterFlow', - 'FlowItem', - 'ImageSpan', - 'LocationButton', - 'PasteButton', - 'SaveButton', - 'UIExtensionComponent', - 'IsolatedComponent', - 'RichEditor', - 'Component3D', - 'ContainerSpan', - 'Require', - 'BuilderParam', - 'Local', - 'Param', - 'Once', - 'Event', - 'State', - 'Track', - 'Trace', - 'Prop', - 'Link', - 'ObjectLink', - 'Provide', - 'Provider', - 'Consume', - 'Consumer', - 'StorageProp', - 'StorageLink', - 'Watch', - 'LocalStorageLink', - 'LocalStorageProp', - 'Component', - 'ComponentV2', - 'Entry', - 'Observed', - 'ObservedV2', - 'Preview', - 'CustomDialog', - 'Reusable', - 'Computed', - 'Builder', - 'LocalBuilder', - 'Styles', - 'Extend', - 'AnimatableExtend' -]); \ No newline at end of file diff --git a/arkui-plugins/interop-plugins/decl_transformer.ts b/arkui-plugins/interop-plugins/decl_transformer.ts index 58d5a6a6d..57cf9906d 100644 --- a/arkui-plugins/interop-plugins/decl_transformer.ts +++ b/arkui-plugins/interop-plugins/decl_transformer.ts @@ -16,7 +16,7 @@ import * as arkts from '@koalaui/libarkts'; import { AbstractVisitor } from '../common/abstract-visitor'; -import { ARKUI_DECLARE_LIST } from './arkuiImportList'; + import { debugLog } from '../common/debug'; export class DeclTransformer extends AbstractVisitor { @@ -55,6 +55,7 @@ export class DeclTransformer extends AbstractVisitor { if (arkts.isEtsScript(astNode)) { astNode = this.transformImportDecl(astNode); } + const node = this.visitEachChild(astNode); if (arkts.isStructDeclaration(node)) { debugLog(`DeclTransformer:before:flag:${arkts.classDefinitionIsFromStructConst(node.definition!)}`); @@ -62,73 +63,27 @@ export class DeclTransformer extends AbstractVisitor { let newnode = this.processComponent(node); debugLog(`DeclTransformer:after:flag:${arkts.classDefinitionIsFromStructConst(newnode.definition!)}`); return newnode; - } else if (arkts.isETSImportDeclaration(astNode)) { - return this.updateImportDeclaration(astNode); - } else if (arkts.isMethodDefinition(astNode)) { - if (astNode.name?.name === 'build' ) { - return this.transformMethodDefinition(astNode); - } - return astNode; } return node; } - transformImportDecl(astNode: arkts.AstNode):arkts.AstNode { - if (!arkts.isEtsScript(astNode)) { - return astNode; + transformImportDecl(estNode: arkts.AstNode): arkts.AstNode { + if (!arkts.isEtsScript(estNode)) { + return estNode; } - let statements = astNode.statements.filter(node => this.isImportDeclarationNeedFilter(node)); - return arkts.factory.updateEtsScript(astNode, statements); - } - transformMethodDefinition(node: arkts.MethodDefinition): arkts.AstNode { - const func: arkts.ScriptFunction = node.scriptFunction; - const isFunctionCall: boolean = false; - const typeNode: arkts.TypeNode | undefined = node.scriptFunction?.returnTypeAnnotation; - const updateFunc = arkts.factory.updateScriptFunction( - func, - !!func.body && arkts.isBlockStatement(func.body) - ? arkts.factory.updateBlock( - func.body, - func.body.statements.filter((st) => false) - ) - : undefined, - arkts.FunctionSignature.createFunctionSignature(func.typeParams, func.params, func.returnTypeAnnotation, false), - func?.flags, - func?.modifiers - ); + let statements = estNode.statements + .filter((node) => this.isImportDeclarationNeedFilter(node)) + .map((node) => this.updateImportDeclaration(node)); - return arkts.factory.updateMethodDefinition( - node, - node.kind, - arkts.factory.updateIdentifier( - node.name, - node.name?.name - ), - updateFunc, - node.modifiers, - false - ); + return arkts.factory.updateEtsScript(estNode, statements); } - - isImportDeclarationNeedFilter(astNode: arkts.AstNode):boolean { - if (!arkts.isETSImportDeclaration(astNode)) { - return true; - } - return astNode?.source?.str !== '@global.arkui'; + + isImportDeclarationNeedFilter(astNode: arkts.AstNode): boolean { + return !arkts.isETSImportDeclaration(astNode); } - updateImportDeclaration(astNode: arkts.AstNode):arkts.AstNode { - if (!arkts.isETSImportDeclaration(astNode) || astNode?.source?.str !== '@ohos.arkui.component') { - return astNode; - } - astNode.specifiers.forEach((element) => { - if (arkts.isImportSpecifier(element)) { - if (ARKUI_DECLARE_LIST.has(element.imported?.name as string)) { - arkts.ImportSpecifierSetRemovable(element); - } - } - }); + updateImportDeclaration(astNode: arkts.AstNode): arkts.AstNode { return astNode; } } diff --git a/arkui-plugins/interop-plugins/index.ts b/arkui-plugins/interop-plugins/index.ts index 404892c34..bac3e903b 100644 --- a/arkui-plugins/interop-plugins/index.ts +++ b/arkui-plugins/interop-plugins/index.ts @@ -13,88 +13,8 @@ * limitations under the License. */ -import * as arkts from '@koalaui/libarkts'; +import { interopPlugin } from './interop_plugin'; -import { DeclTransformer } from './decl_transformer'; -import { EmitTransformer } from './emit_transformer'; - -import { ProgramVisitor } from '../common/program-visitor'; -import { EXTERNAL_SOURCE_PREFIX_NAMES } from '../common/predefines'; -import { debugLog } from '../common/debug'; -import { PluginContext, Plugins } from 'common/plugin-context'; - -export function interopTransform():Plugins { - return { - name: 'interop-plugin', - parsed: parsedTransform, - checked: checkedTransform, - clean() { - arkts.arktsGlobal.clearContext(); - }, - }; -} - -function parsedTransform(this: PluginContext): arkts.EtsScript | undefined { - let script: arkts.EtsScript | undefined; - debugLog('interopTransform:parsed'); - const contextPtr = arkts.arktsGlobal.compilerContext?.peer ?? this.getContextPtr(); - if (!!contextPtr) { - let program = arkts.getOrUpdateGlobalContext(contextPtr).program; - script = program.astNode; - - if (script) { - const declTransformer = new DeclTransformer({ - arkui: '@koalaui.arkts-arkui.StructParse' as interop.TransfromerName - }); - - const programVisitor = new ProgramVisitor({ - pluginName: interopTransform().name, - state: arkts.Es2pandaContextState.ES2PANDA_STATE_PARSED, - visitors: [declTransformer], - skipPrefixNames: EXTERNAL_SOURCE_PREFIX_NAMES, - pluginContext: this as unknown as PluginContext - }); - - program = programVisitor.programVisitor(program); - script = program.astNode; - this.setArkTSAst(script); - debugLog('interopTransform:parsed exit'); - return script; - } - } - debugLog('interopTransform: parsed exit with no transform'); - return script; -} - -function checkedTransform(this: PluginContext): arkts.EtsScript | undefined { - let script: arkts.EtsScript | undefined; - debugLog('interopTransform:checked'); - const contextPtr = arkts.arktsGlobal.compilerContext?.peer ?? this.getContextPtr(); - if (!!contextPtr) { - let program = arkts.getOrUpdateGlobalContext(contextPtr).program; - script = program.astNode; - if (script) { - const emitTransformer = new EmitTransformer({ - arkui: '@koalaui.arkts-arkui.EmitBase' as interop.TransfromerName - }); - - const programVisitor = new ProgramVisitor({ - pluginName: interopTransform().name, - state: arkts.Es2pandaContextState.ES2PANDA_STATE_CHECKED, - visitors: [emitTransformer], - skipPrefixNames: EXTERNAL_SOURCE_PREFIX_NAMES, - pluginContext: this as unknown as PluginContext - }); - - program = programVisitor.programVisitor(program); - script = program.astNode; - arkts.GlobalInfo.getInfoInstance()?.reset(); - arkts.recheckSubtree(script); - this.setArkTSAst(script); - debugLog('interopTransform:checked exit'); - return script; - } - } - debugLog('interopTransform:checked exit with no transform'); - return script; +export function interopTransform() { + return interopPlugin; } diff --git a/arkui-plugins/jest-test.config.js b/arkui-plugins/jest-test.config.js deleted file mode 100644 index 541b1dc39..000000000 --- a/arkui-plugins/jest-test.config.js +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -const path = require('path'); - -const rootPath = path.resolve(__dirname, '../../../'); -const sdkPath = path.resolve(rootPath, './out/sdk/ohos-sdk/linux/ets/ets1.2'); -const pandaSdkPath = path.resolve(sdkPath, './build-tools/ets2panda'); -const apiPath = path.resolve(sdkPath, './api'); - -module.exports = { - testEnvironment: 'node', - transform: { - '^.+\\.ts$': ['ts-jest'], - }, - testRegex: './test/ut/.+\\.test\\.ts$', - moduleFileExtensions: ['ts', 'js', 'json', 'node'], - coverageDirectory: './test/report', - collectCoverageFrom: [ - 'common/**', - 'memo-plugins/**', - 'ui-plugins/**' - ], - coveragePathIgnorePatterns: [ - 'common/debug.ts', - 'common/etsglobal-remover.ts', - 'common/print-visitor.ts', - 'common/plugin-context.ts', - 'memo-plugins/index.ts', - 'memo-plugins/import-transformer.ts', - 'memo-plugins/memo-transformer.ts', - 'ui-plugins/index.ts', - 'ui-plugins/printer-transformer.ts', - 'ui-plugins/builder-lambda-translators/builder-lambda-transformer.ts', - 'ui-plugins/entry-translators/entry-transformer.ts', - 'ui-plugins/struct-translators/struct-transformer.ts' - ], - verbose: true, - globals: { - SDK_PATH: sdkPath, - PANDA_SDK_PATH: pandaSdkPath, - API_PATH: apiPath, - }, -}; diff --git a/arkui-plugins/memo-plugins/function-transformer.ts b/arkui-plugins/memo-plugins/function-transformer.ts index 68bc9083d..1d9b5a3cf 100644 --- a/arkui-plugins/memo-plugins/function-transformer.ts +++ b/arkui-plugins/memo-plugins/function-transformer.ts @@ -17,55 +17,117 @@ import * as arkts from '@koalaui/libarkts'; import { factory } from './memo-factory'; import { AbstractVisitor, VisitorOptions } from '../common/abstract-visitor'; import { - MemoInfo, PositionalIdTracker, - ReturnTypeInfo, - buildReturnTypeInfo, castArrowFunctionExpression, - castIdentifier, + castFunctionExpression, castOverloadsToMethods, castParameters, findMemoFromTypeAnnotation, - findThisAttribute, - getDeclResolveAlias, hasMemoAnnotation, - hasMemoEntryAnnotation, hasMemoIntrinsicAnnotation, hasMemoStableAnnotation, - isDeclaredMethodWithMemoParams, - isFunctionProperty, isMemoArrowFunction, isMemoClassProperty, - isMemoDeclaredClassProperty, - isMemoDeclaredIdentifier, - isMemoDeclaredMethod, - isMemoETSParameterExpression, isMemoMethodDefinition, - isMemoProperty, isMemoTSTypeAliasDeclaration, - isMemoThisAttribute, - isMemoVariableDeclarator, isStandaloneArrowFunction, - isThisAttributeAssignment, + isVoidType, removeMemoAnnotation, - parametrizedNodeHasReceiver } from './utils'; import { ParameterTransformer } from './parameter-transformer'; import { ReturnTransformer } from './return-transformer'; import { SignatureTransformer } from './signature-transformer'; -import { moveToFront } from '../common/arkts-utils'; -import { InternalsTransformer } from './internal-transformer'; -interface ScopeInfo extends MemoInfo { - regardAsSameScope?: boolean; +function mayAddLastReturn(node: arkts.BlockStatement): boolean { + return ( + node.statements.length > 0 && + !arkts.isReturnStatement(node.statements[node.statements.length - 1]) && + !arkts.isThrowStatement(node.statements[node.statements.length - 1]) + ); } +function updateFunctionBody( + node: arkts.BlockStatement, + parameters: arkts.ETSParameterExpression[], + returnTypeAnnotation: arkts.TypeNode | undefined, + stableThis: boolean, + hash: arkts.NumberLiteral | arkts.StringLiteral +): [ + arkts.BlockStatement, + arkts.VariableDeclaration | undefined, + arkts.ReturnStatement | arkts.BlockStatement | undefined +] { + let returnTypeAnno = + !returnTypeAnnotation || stableThis + ? arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID) + : returnTypeAnnotation; + const scopeDeclaration = factory.createScopeDeclaration(returnTypeAnno, hash, parameters.length); + const memoParameters = parameters.map((name, id) => { + return factory.createMemoParameterDeclarator(id, name.identifier.name); + }); + const memoParametersDeclaration = memoParameters.length + ? [ + arkts.factory.createVariableDeclaration( + 0, + arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_CONST, + memoParameters + ), + ] + : []; + const syntheticReturnStatement = factory.createSyntheticReturnStatement(stableThis); + const isVoidValue = isVoidType(returnTypeAnno); + const unchangedCheck = factory.createIfStatementWithSyntheticReturnStatement(syntheticReturnStatement, isVoidValue); + if (node) { + return [ + arkts.factory.updateBlock(node, [ + scopeDeclaration, + ...memoParametersDeclaration, + unchangedCheck, + ...node.statements, + ...(mayAddLastReturn(node) ? [arkts.factory.createReturnStatement()] : []), + ]), + memoParametersDeclaration.length ? memoParametersDeclaration[0] : undefined, + syntheticReturnStatement, + ]; + } else { + return [ + node, + memoParametersDeclaration.length ? memoParametersDeclaration[0] : undefined, + syntheticReturnStatement, + ]; + } +} + +function updateMemoTypeAnnotation(typeAnnotation: arkts.AstNode | undefined): arkts.TypeNode | undefined { + if (!typeAnnotation) return undefined; + if (!arkts.isTypeNode(typeAnnotation)) return undefined; + + if (typeAnnotation && arkts.isETSFunctionType(typeAnnotation)) { + return factory.updateFunctionTypeWithMemoParameters(typeAnnotation); + } else if (typeAnnotation && arkts.isETSUnionType(typeAnnotation)) { + return arkts.factory.updateUnionType( + typeAnnotation, + typeAnnotation.types.map((it) => { + if (arkts.isETSFunctionType(it)) { + return factory.updateFunctionTypeWithMemoParameters(it); + } + return it; + }) + ); + } + return typeAnnotation; +} + +type ScopeInfo = { + name?: string; + isMemo: boolean; +}; + export interface FunctionTransformerOptions extends VisitorOptions { positionalIdTracker: PositionalIdTracker; parameterTransformer: ParameterTransformer; returnTransformer: ReturnTransformer; signatureTransformer: SignatureTransformer; - internalsTransformer?: InternalsTransformer; } export class FunctionTransformer extends AbstractVisitor { @@ -73,10 +135,6 @@ export class FunctionTransformer extends AbstractVisitor { private readonly parameterTransformer: ParameterTransformer; private readonly returnTransformer: ReturnTransformer; private readonly signatureTransformer: SignatureTransformer; - private readonly internalsTransformer?: InternalsTransformer; - - /* Tracking whether should import `__memo_context_type` and `__memo_id_type` */ - private modified = false; constructor(options: FunctionTransformerOptions) { super(options); @@ -84,7 +142,6 @@ export class FunctionTransformer extends AbstractVisitor { this.parameterTransformer = options.parameterTransformer; this.returnTransformer = options.returnTransformer; this.signatureTransformer = options.signatureTransformer; - this.internalsTransformer = options.internalsTransformer; } private scopes: ScopeInfo[] = []; @@ -94,84 +151,31 @@ export class FunctionTransformer extends AbstractVisitor { super.reset(); this.scopes = []; this.stable = 0; - this.modified = false; this.parameterTransformer.reset(); this.returnTransformer.reset(); this.signatureTransformer.reset(); } - private enterMethod(node: arkts.MethodDefinition): void { - const name = node.name.name; - const isMemo = isMemoMethodDefinition(node); - this.scopes.push({ name, isMemo }); - } - - private enterClassPropety(node: arkts.ClassProperty): void { - const name = castIdentifier(node.key).name; - const isMemo = isMemoClassProperty(node); - this.scopes.push({ name, isMemo }); - } - - private enterStandaloneArrowFunction(node: arkts.ArrowFunctionExpression): void { - const name = undefined; - const isMemo = isMemoArrowFunction(node); - this.scopes.push({ name, isMemo }); - } - - private enterTSTypeAliasDeclaration(node: arkts.TSTypeAliasDeclaration): void { - const name = castIdentifier(node.id).name; - const isMemo = isMemoTSTypeAliasDeclaration(node); - this.scopes.push({ name, isMemo }); - } - - private enterVariableDeclarator(node: arkts.VariableDeclarator): void { - const name = node.name.name; - const isMemo = isMemoVariableDeclarator(node); - this.scopes.push({ name, isMemo, regardAsSameScope: !!node.initializer }); - } - - private enterTSAsExpression(node: arkts.TSAsExpression): void { - const isMemo = findMemoFromTypeAnnotation(node.typeAnnotation); - this.scopes.push({ isMemo }); - } - - private enterFunctionProperty(node: arkts.Property): void { - const name = castIdentifier(node.key).name; - const isMemo = isMemoProperty(node, castArrowFunctionExpression(node.value)); - this.scopes.push({ name, isMemo }); - } - - private enterThisAttributeAssignment(node: arkts.AssignmentExpression): void { - const thisAttribute = findThisAttribute(node.left!)!; - const name = thisAttribute.name; - const isMemo = isMemoThisAttribute(thisAttribute, castArrowFunctionExpression(node.right)); - this.scopes.push({ name, isMemo }); - } - - enter(node: arkts.AstNode): this { + enter(node: arkts.AstNode) { if (arkts.isMethodDefinition(node)) { - this.enterMethod(node); + const name = node.name.name; + const isMemo = isMemoMethodDefinition(node); + this.scopes.push({ name, isMemo }); } if (arkts.isClassProperty(node) && !!node.key && arkts.isIdentifier(node.key)) { - this.enterClassPropety(node); + const name = node.key.name; + const isMemo = isMemoClassProperty(node); + this.scopes.push({ name, isMemo }); } if (isStandaloneArrowFunction(node)) { - this.enterStandaloneArrowFunction(node); + const name = undefined; + const isMemo = isMemoArrowFunction(node); + this.scopes.push({ name, isMemo }); } if (arkts.isTSTypeAliasDeclaration(node) && !!node.id && !!node.typeAnnotation) { - this.enterTSTypeAliasDeclaration(node); - } - if (arkts.isVariableDeclarator(node)) { - this.enterVariableDeclarator(node); - } - if (arkts.isTSAsExpression(node) && !!node.expr && arkts.isArrowFunctionExpression(node.expr)) { - this.enterTSAsExpression(node); - } - if (isFunctionProperty(node)) { - this.enterFunctionProperty(node); - } - if (isThisAttributeAssignment(node) && !!node.right && arkts.isArrowFunctionExpression(node.right)) { - this.enterThisAttributeAssignment(node); + const name = node.id.name; + const isMemo = isMemoTSTypeAliasDeclaration(node); + this.scopes.push({ name, isMemo }); } if (arkts.isClassDefinition(node)) { if (hasMemoStableAnnotation(node)) { @@ -206,10 +210,13 @@ export class FunctionTransformer extends AbstractVisitor { } checkMemoCallInMethod(decl: arkts.MethodDefinition) { - const scope = this.scopes[this.scopes.length - 1]; - if (scope?.regardAsSameScope === false && scope?.isMemo === false) { - if (scope.name) { - console.error(`Attempt to call @memo-method ${decl.name.name} from non-@memo-method ${scope.name}`); + if (this.scopes[this.scopes.length - 1].isMemo == false) { + if (this.scopes[this.scopes.length - 1].name) { + console.error( + `Attempt to call @memo-method ${decl.name.name} from non-@memo-method ${ + this.scopes[this.scopes.length - 1].name + }` + ); throw 'Invalid @memo usage'; } else { console.error(`Attempt to call @memo-method ${decl.name.name} from anonymous non-@memo-method`); @@ -220,95 +227,67 @@ export class FunctionTransformer extends AbstractVisitor { } checkMemoCallInFunction() { - const scope = this.scopes[this.scopes.length - 1]; - if (scope?.regardAsSameScope === false && scope?.isMemo === false) { + if (this.scopes[this.scopes.length - 1]?.isMemo == false) { console.error(`Attempt to call @memo-function`); throw 'Invalid @memo usage'; } return this; } - updateInternalsInScriptFunction(scriptFunction: arkts.ScriptFunction): arkts.ScriptFunction { - if (!scriptFunction.body || !arkts.isBlockStatement(scriptFunction.body) || !this.internalsTransformer) { - return scriptFunction; - } - const afterInternalsTransformer = this.internalsTransformer.visitor( - scriptFunction.body - ) as arkts.BlockStatement; - return arkts.factory.updateScriptFunction( - scriptFunction, - afterInternalsTransformer, - arkts.factory.createFunctionSignature( - scriptFunction.typeParams, - scriptFunction.params, - scriptFunction.returnTypeAnnotation, - scriptFunction.hasReceiver - ), - scriptFunction.flags, - scriptFunction.modifiers - ); - } - updateScriptFunction(scriptFunction: arkts.ScriptFunction, name: string = ''): arkts.ScriptFunction { - if (!scriptFunction.body || !arkts.isBlockStatement(scriptFunction.body)) { - return scriptFunction; - } - if (this.parameterTransformer.isTracked(scriptFunction.body)) { - return this.updateInternalsInScriptFunction(scriptFunction); - } - if (hasMemoIntrinsicAnnotation(scriptFunction) || hasMemoEntryAnnotation(scriptFunction)) { - return this.updateInternalsInScriptFunction(scriptFunction); - } - const returnType = scriptFunction.returnTypeAnnotation; - const isStableThis = this.stable > 0 && returnType !== undefined && arkts.isTSThisType(returnType); - const returnTypeInfo: ReturnTypeInfo = buildReturnTypeInfo( - returnType, - findMemoFromTypeAnnotation(returnType), - isStableThis + const isStableThis = + this.stable > 0 && + scriptFunction.returnTypeAnnotation !== undefined && + arkts.isTSThisType(scriptFunction.returnTypeAnnotation); + const [body, memoParametersDeclaration, syntheticReturnStatement] = updateFunctionBody( + scriptFunction.body as arkts.BlockStatement, + castParameters(scriptFunction.params), + scriptFunction.returnTypeAnnotation, + isStableThis, + this.positionalIdTracker.id(name) ); - const [body, parameterIdentifiers, memoParametersDeclaration, syntheticReturnStatement] = - factory.updateFunctionBody( - scriptFunction.body, - castParameters(scriptFunction.params), - returnTypeInfo, - this.positionalIdTracker.id(name) - ); const afterParameterTransformer = this.parameterTransformer - .withParameters(parameterIdentifiers) + .withParameters(scriptFunction.params as arkts.ETSParameterExpression[]) .skip(memoParametersDeclaration) .visitor(body); const afterReturnTransformer = this.returnTransformer .skip(syntheticReturnStatement) - .registerReturnTypeInfo(returnTypeInfo) .rewriteThis(this.stable > 0) .visitor(afterParameterTransformer); - const updateScriptFunction = factory.updateScriptFunctionWithMemoParameters( + const updateScriptFunction = arkts.factory.updateScriptFunction( scriptFunction, afterReturnTransformer, - returnTypeInfo.node + arkts.FunctionSignature.createFunctionSignature( + scriptFunction.typeParams, + [ + ...factory.createHiddenParameters(), + ...scriptFunction.params, // we handle function params with signature-transformer + ], + scriptFunction.returnTypeAnnotation, + scriptFunction.hasReceiver + ), + scriptFunction.flags, + scriptFunction.modifiers ); - this.modified = true; - this.parameterTransformer.track(updateScriptFunction.body); - return this.updateInternalsInScriptFunction(updateScriptFunction); + return updateScriptFunction; } private updateMethodDefinition(node: arkts.MethodDefinition): arkts.MethodDefinition { let updateMethod: arkts.MethodDefinition; const that = this; const updateOverloads = node.overloads?.map((overload) => that.visitor(overload)) ?? undefined; - const isMemo = - hasMemoAnnotation(node.scriptFunction) || - hasMemoIntrinsicAnnotation(node.scriptFunction) || - hasMemoEntryAnnotation(node.scriptFunction); - if (isMemo && node.scriptFunction.body) { - const hasIntrinsic = hasMemoIntrinsicAnnotation(node.scriptFunction); + if ( + node.scriptFunction.body && + (hasMemoAnnotation(node.scriptFunction) || hasMemoIntrinsicAnnotation(node.scriptFunction)) + ) { updateMethod = arkts.factory.updateMethodDefinition( node, node.kind, node.name, - this.signatureTransformer.visitor( - removeMemoAnnotation(this.updateScriptFunction(node.scriptFunction, node.name.name)), - hasIntrinsic + arkts.factory.createFunctionExpression( + this.signatureTransformer.visitor( + removeMemoAnnotation(this.updateScriptFunction(node.scriptFunction, node.name.name)) + ) ), node.modifiers, false @@ -318,7 +297,7 @@ export class FunctionTransformer extends AbstractVisitor { node, node.kind, node.name, - this.signatureTransformer.visitor(node.scriptFunction), + arkts.factory.createFunctionExpression(this.signatureTransformer.visitor(node.scriptFunction)), node.modifiers, false ); @@ -326,149 +305,80 @@ export class FunctionTransformer extends AbstractVisitor { if (!!updateOverloads) { updateMethod.setOverloads(castOverloadsToMethods(updateOverloads)); } - this.modified ||= this.signatureTransformer.modified; return updateMethod; } - private updateDeclaredMethodMemoCall( - node: arkts.CallExpression, - decl: arkts.MethodDefinition, - ignoreSelf: boolean = false - ): arkts.CallExpression { - let updatedArguments: arkts.AstNode[] = node.arguments.map((it, index) => { - const param = decl.scriptFunction.params.at(index); - if (!param || !arkts.isEtsParameterExpression(param)) { - return it; - } - if (isMemoETSParameterExpression(param) && arkts.isArrowFunctionExpression(it)) { - this.enterAnonymousScope(it.scriptFunction); - const res = this.updateScriptFunction(it.scriptFunction); - this.exitAnonymousScope(); - this.modified = true; - return arkts.factory.updateArrowFunction(it, res); + private updateDeclaredMemoCall(node: arkts.CallExpression, decl: arkts.MethodDefinition): arkts.CallExpression { + this.checkMemoCallInMethod(decl); + const updatedArguments = node.arguments.map((it, index) => { + const type = (decl.scriptFunction.params[index] as arkts.ETSParameterExpression)?.type; + if (type && arkts.isETSFunctionType(type)) { + if ( + !hasMemoAnnotation(decl.scriptFunction.params[index] as arkts.ETSParameterExpression) && + !hasMemoIntrinsicAnnotation(decl.scriptFunction.params[index] as arkts.ETSParameterExpression) + ) { + return it; //factory.createComputeExpression(this.positionalIdTracker.id(decl.name.name), it) + } + if (arkts.isArrowFunctionExpression(it)) { + this.enterAnonymousScope(it.scriptFunction); + const res = this.updateScriptFunction(it.scriptFunction); + this.exitAnonymousScope(); + return arkts.factory.updateArrowFunction(it, res); + } } return it; }); - if (!ignoreSelf) { - this.checkMemoCallInMethod(decl); - updatedArguments = [ - ...factory.createHiddenArguments(this.positionalIdTracker.id(decl.name.name)), - ...updatedArguments, - ]; - } - const isMemo = - hasMemoAnnotation(decl.scriptFunction) || - hasMemoIntrinsicAnnotation(decl.scriptFunction) || - hasMemoEntryAnnotation(decl.scriptFunction); - if (parametrizedNodeHasReceiver(decl.scriptFunction) && isMemo) { - updatedArguments = moveToFront(updatedArguments, 2); - } - this.modified = true; - return arkts.factory.updateCallExpression(node, node.expression, node.typeArguments, updatedArguments); + return arkts.factory.updateCallExpression(node, node.expression, undefined, [ + ...factory.createHiddenArguments(this.positionalIdTracker.id(decl.name.name)), + ...updatedArguments, + ]); } - private updateDeclaredCallWithName(node: arkts.CallExpression, name: string): arkts.CallExpression { - this.modified = true; - return factory.insertHiddenArgumentsToCall(node, this.positionalIdTracker.id(name)); - } - - private updateAnonymousCallWithMemoParams(node: arkts.CallExpression): arkts.CallExpression { - let newExpression: arkts.AstNode = node.expression; - if (isStandaloneArrowFunction(node.expression)) { - newExpression = arkts.factory.updateArrowFunction( - node.expression, - this.signatureTransformer.visitor(node.expression.scriptFunction) - ); - } - const updatedArguments: arkts.AstNode[] = node.arguments.map((it) => { - if (arkts.isArrowFunctionExpression(it) && isMemoArrowFunction(it)) { - this.enterAnonymousScope(it.scriptFunction); - const res = this.updateScriptFunction(it.scriptFunction); - this.exitAnonymousScope(); - this.modified = true; - return arkts.factory.updateArrowFunction(it, res); - } - return it; - }); - this.modified ||= this.signatureTransformer.modified; - return arkts.factory.updateCallExpression(node, newExpression, node.typeArguments, updatedArguments); - } - - private updateAnonymousMemoCall( + private udpateAnonymousMemoCall( node: arkts.CallExpression, expression: arkts.ArrowFunctionExpression ): arkts.CallExpression { const scope = this.scopes[this.scopes.length - 1]; - const isValidScope = !!scope && scope.name === expression.scriptFunction.id?.name; - if (!isValidScope) { + if (!scope || !scope.isMemo || scope.name !== expression.scriptFunction.id?.name) { return node; } this.exitAnonymousScope(); - if (!scope.isMemo) { - return this.updateAnonymousCallWithMemoParams(node); - } this.checkMemoCallInFunction(); this.enterAnonymousScope(expression.scriptFunction); const res = this.updateScriptFunction(expression.scriptFunction, expression.scriptFunction.id?.name); this.exitAnonymousScope(); - const newNode = this.updateAnonymousCallWithMemoParams(node); - this.modified = true; return arkts.factory.updateCallExpression( node, arkts.factory.updateArrowFunction(expression, res), - newNode.typeArguments, - [...factory.createHiddenArguments(this.positionalIdTracker.id()), ...newNode.arguments] + node.typeArguments, + [...factory.createHiddenArguments(this.positionalIdTracker.id()), ...node.arguments] ); } - private updateCallExpressionWithNoDecl(node: arkts.CallExpression): arkts.CallExpression { - if (isStandaloneArrowFunction(node.expression)) { - return this.updateAnonymousMemoCall(node, node.expression); - } - return this.updateAnonymousCallWithMemoParams(node); - } - private updateCallExpression(node: arkts.CallExpression): arkts.CallExpression { const expr = node.expression; - const decl = getDeclResolveAlias(expr); - if (!decl) { - return this.updateCallExpressionWithNoDecl(node); - } - if (arkts.isMethodDefinition(decl) && isMemoDeclaredMethod(decl)) { - return this.updateDeclaredMethodMemoCall(node, decl); - } - if (arkts.isMethodDefinition(decl) && isDeclaredMethodWithMemoParams(decl)) { - return this.updateDeclaredMethodMemoCall(node, decl, true); - } - if (arkts.isIdentifier(decl) && isMemoDeclaredIdentifier(decl)) { - return this.updateDeclaredCallWithName(node, decl.name); - } + const decl = arkts.getDecl(expr); if ( - arkts.isClassProperty(decl) && - isMemoDeclaredClassProperty(decl) && - !!decl.key && - arkts.isIdentifier(decl.key) + decl && + arkts.isMethodDefinition(decl) && + (hasMemoAnnotation(decl.scriptFunction) || hasMemoIntrinsicAnnotation(decl.scriptFunction)) ) { - return this.updateDeclaredCallWithName(node, decl.key.name); + return this.updateDeclaredMemoCall(node, decl); } - if (arkts.isEtsParameterExpression(decl) && isMemoETSParameterExpression(decl)) { - return this.updateDeclaredCallWithName(node, decl.identifier.name); + if (isStandaloneArrowFunction(node.expression)) { + return this.udpateAnonymousMemoCall(node, node.expression); } - return this.updateCallExpressionWithNoDecl(node); + return node; } private updateClassProperty(node: arkts.ClassProperty, key: arkts.Identifier): arkts.ClassProperty { const scope = this.scopes[this.scopes.length - 1]; - const isValidScope = !!scope && scope.name === key.name; - if (!isValidScope) { + if (!scope || !scope.isMemo || scope.name !== key.name) { return node; } this.exitAnonymousScope(); - if (!scope.isMemo) { - return node; - } let res: arkts.ScriptFunction | undefined; if (!!node.value && arkts.isArrowFunctionExpression(node.value)) { @@ -478,12 +388,11 @@ export class FunctionTransformer extends AbstractVisitor { } let typeAnnotation: arkts.TypeNode | undefined; - if (!!node.typeAnnotation && !(typeAnnotation = factory.updateMemoTypeAnnotation(node.typeAnnotation))) { + if (!!node.typeAnnotation && !(typeAnnotation = updateMemoTypeAnnotation(node.typeAnnotation))) { console.error(`ETSFunctionType or ETSUnionType expected for @memo-property ${key.name}`); throw 'Invalid @memo usage'; } - this.modified = true; return arkts.factory.updateClassProperty( node, node.key, @@ -496,184 +405,32 @@ export class FunctionTransformer extends AbstractVisitor { private updateTSTypeAliasDeclaration(node: arkts.TSTypeAliasDeclaration): arkts.TSTypeAliasDeclaration { const scope = this.scopes[this.scopes.length - 1]; - const isValidScope = !!scope && scope.name === node.id?.name; - if (!isValidScope) { + if (!scope || !scope.isMemo || scope.name !== node.id?.name) { return node; } this.exitAnonymousScope(); - if (!scope.isMemo) { - if (!!node.typeAnnotation) { - const newNode = arkts.factory.updateTSTypeAliasDeclaration( - node, - node.id, - node.typeParams, - this.signatureTransformer.visitor(node.typeAnnotation) - ); - this.modified ||= this.signatureTransformer.modified; - return newNode; - } - return node; - } let typeAnnotation: arkts.TypeNode | undefined; - if (!(typeAnnotation = factory.updateMemoTypeAnnotation(node.typeAnnotation))) { + if (!(typeAnnotation = updateMemoTypeAnnotation(node.typeAnnotation))) { console.error(`ETSFunctionType or ETSUnionType expected for @memo-type ${node.id!.name}`); throw 'Invalid @memo usage'; } - this.modified = true; return arkts.factory.updateTSTypeAliasDeclaration(node, node.id, node.typeParams, typeAnnotation); } private updateStandaloneArrowFunction(node: arkts.ArrowFunctionExpression): arkts.ArrowFunctionExpression { const scope = this.scopes[this.scopes.length - 1]; - const isValidScope = !!scope && scope.name === node.scriptFunction.id?.name; - if (!isValidScope) { + if (!scope || !scope.isMemo || scope.name !== node.scriptFunction.id?.name) { return node; } this.exitAnonymousScope(); - if (!scope.isMemo) { - return arkts.factory.updateArrowFunction(node, this.signatureTransformer.visitor(node.scriptFunction)); - } this.enterAnonymousScope(node.scriptFunction); const res = this.updateScriptFunction(node.scriptFunction, node.scriptFunction.id?.name); this.exitAnonymousScope(); - this.modified = true; - return arkts.factory.updateArrowFunction(node, this.signatureTransformer.visitor(res)); - } - - private updateVariableDeclarator(node: arkts.VariableDeclarator): arkts.VariableDeclarator { - const scope = this.scopes[this.scopes.length - 1]; - const isValidScope = !!scope && scope.name === node.name.name; - if (!isValidScope) { - return node; - } - this.exitAnonymousScope(); - if (!scope.isMemo) { - if (!!node.initializer && arkts.isArrowFunctionExpression(node.initializer)) { - return arkts.factory.updateVariableDeclarator( - node, - node.flag, - node.name, - arkts.factory.updateArrowFunction( - node.initializer, - this.signatureTransformer.visitor(node.initializer.scriptFunction) - ) - ); - } - return node; - } - - let typeAnnotation: arkts.TypeNode | undefined; - if ( - !!node.name.typeAnnotation && - !(typeAnnotation = factory.updateMemoTypeAnnotation(node.name.typeAnnotation)) - ) { - console.error(`ETSFunctionType or ETSUnionType expected for @memo-variable-type ${node.name.name}`); - throw 'Invalid @memo usage'; - } - - let initializer: arkts.AstNode | undefined = node.initializer; - if (!!initializer && arkts.isArrowFunctionExpression(initializer)) { - this.enterAnonymousScope(initializer.scriptFunction); - const res = this.updateScriptFunction(initializer.scriptFunction, initializer.scriptFunction.id?.name); - this.exitAnonymousScope(); - initializer = arkts.factory.updateArrowFunction(initializer, res); - } - - this.modified = true; - return arkts.factory.updateVariableDeclarator( - node, - node.flag, - arkts.factory.updateIdentifier(node.name, node.name.name, typeAnnotation), - initializer - ); - } - - private updateTSAsExpression( - node: arkts.TSAsExpression, - expr: arkts.ArrowFunctionExpression - ): arkts.TSAsExpression { - const scope = this.scopes[this.scopes.length - 1]; - const isValidScope = !!scope; - if (!isValidScope) { - return node; - } - this.exitAnonymousScope(); - if (!scope.isMemo) { - return node; - } - - this.enterAnonymousScope(expr.scriptFunction); - const res = this.updateScriptFunction(expr.scriptFunction, expr.scriptFunction.id?.name); - this.exitAnonymousScope(); - - let typeAnnotation: arkts.TypeNode | undefined; - if (!(typeAnnotation = factory.updateMemoTypeAnnotation(node.typeAnnotation))) { - console.error(`ETSFunctionType or ETSUnionType expected for @memo-as-type`); - throw 'Invalid @memo usage'; - } - - this.modified = true; - return arkts.factory.updateTSAsExpression( - node, - arkts.factory.updateArrowFunction(expr, res), - typeAnnotation, - node.isConst - ); - } - - private updateProperty( - node: arkts.Property, - key: arkts.Identifier, - value: arkts.ArrowFunctionExpression - ): arkts.Property { - const scope = this.scopes[this.scopes.length - 1]; - const isValidScope = !!scope && scope.name === key.name; - if (!isValidScope) { - return node; - } - this.exitAnonymousScope(); - if (!scope.isMemo) { - return node; - } - - this.enterAnonymousScope(value.scriptFunction); - const res = this.updateScriptFunction(value.scriptFunction, value.scriptFunction.id?.name); - this.exitAnonymousScope(); - - this.modified = true; - return arkts.factory.updateProperty(node, key, arkts.factory.updateArrowFunction(value, res)); - } - - private updateThisAttributeAssignment( - node: arkts.AssignmentExpression, - thisAttribute: arkts.Identifier, - right: arkts.ArrowFunctionExpression - ): arkts.AssignmentExpression { - const scope = this.scopes[this.scopes.length - 1]; - const isValidScope = !!scope && scope.name === thisAttribute.name; - if (!isValidScope) { - return node; - } - this.exitAnonymousScope(); - if (!scope.isMemo) { - return node; - } - - this.enterAnonymousScope(right.scriptFunction); - const res = this.updateScriptFunction(right.scriptFunction, right.scriptFunction.id?.name); - this.exitAnonymousScope(); - - this.modified = true; - return arkts.factory.updateAssignmentExpression( - node, - node.left!, - node.operatorType, - arkts.factory.updateArrowFunction(right, res) - ); + return arkts.factory.updateArrowFunction(node, res); } visitor(beforeChildren: arkts.AstNode): arkts.AstNode { @@ -695,22 +452,6 @@ export class FunctionTransformer extends AbstractVisitor { if (isStandaloneArrowFunction(node)) { return this.updateStandaloneArrowFunction(node); } - if (arkts.isVariableDeclarator(node)) { - return this.updateVariableDeclarator(node); - } - if (arkts.isTSAsExpression(node) && node.expr && arkts.isArrowFunctionExpression(node.expr)) { - return this.updateTSAsExpression(node, node.expr); - } - if (isFunctionProperty(node)) { - return this.updateProperty(node, castIdentifier(node.key), castArrowFunctionExpression(node.value)); - } - if (isThisAttributeAssignment(node) && !!node.right && arkts.isArrowFunctionExpression(node.right)) { - const thisAttribute = findThisAttribute(node.left!)!; - return this.updateThisAttributeAssignment(node, thisAttribute, node.right); - } - if (arkts.isEtsScript(node) && this.modified) { - factory.createContextTypesImportDeclaration(this.program); - } return node; } } diff --git a/arkui-plugins/memo-plugins/index.ts b/arkui-plugins/memo-plugins/index.ts index beb7edff9..58f785dbd 100644 --- a/arkui-plugins/memo-plugins/index.ts +++ b/arkui-plugins/memo-plugins/index.ts @@ -20,97 +20,81 @@ import { PositionalIdTracker } from './utils'; import { ReturnTransformer } from './return-transformer'; import { ParameterTransformer } from './parameter-transformer'; import { ProgramVisitor } from '../common/program-visitor'; -import { EXTERNAL_SOURCE_PREFIX_NAMES, EXTERNAL_SOURCE_PREFIX_NAMES_FOR_FRAMEWORK } from '../common/predefines'; +import { EXTERNAL_SOURCE_PREFIX_NAMES } from '../common/predefines'; import { debugDump, debugLog, getDumpFileName } from '../common/debug'; import { SignatureTransformer } from './signature-transformer'; -import { InternalsTransformer } from './internal-transformer'; export function unmemoizeTransform(): Plugins { return { name: 'memo-plugin', - checked: checkedTransform, + checked(this: PluginContext) { + console.log('[MEMO PLUGIN] AFTER CHECKED ENTER'); + const contextPtr = arkts.arktsGlobal.compilerContext?.peer ?? this.getContextPtr(); + if (!!contextPtr) { + let program = arkts.getOrUpdateGlobalContext(contextPtr).program; + let script = program.astNode; + + debugLog('[BEFORE MEMO SCRIPT] script: ', script.dumpSrc()); + const cachePath: string | undefined = this.getProjectConfig()?.cachePath; + debugDump( + script.dumpSrc(), + getDumpFileName(0, 'SRC', 5, 'MEMO_AfterCheck_Begin'), + true, + cachePath, + program.programFileNameWithExtension + ); + + arkts.Performance.getInstance().createEvent('memo-checked'); + + const positionalIdTracker = new PositionalIdTracker(arkts.getFileName(), false); + const parameterTransformer = new ParameterTransformer({ + positionalIdTracker, + }); + const returnTransformer = new ReturnTransformer(); + const signatureTransformer = new SignatureTransformer(); + const functionTransformer = new FunctionTransformer({ + positionalIdTracker, + parameterTransformer, + returnTransformer, + signatureTransformer, + }); + + const programVisitor = new ProgramVisitor({ + pluginName: unmemoizeTransform.name, + state: arkts.Es2pandaContextState.ES2PANDA_STATE_CHECKED, + visitors: [functionTransformer], + skipPrefixNames: EXTERNAL_SOURCE_PREFIX_NAMES, + pluginContext: this, + }); + + program = programVisitor.programVisitor(program); + script = program.astNode; + + arkts.Performance.getInstance().stopEvent('memo-checked', true); + + debugLog('[AFTER MEMO SCRIPT] script: ', script.dumpSrc()); + debugDump( + script.dumpSrc(), + getDumpFileName(0, 'SRC', 6, 'MEMO_AfterCheck_End'), + true, + cachePath, + program.programFileNameWithExtension + ); + + arkts.Performance.getInstance().createEvent('memo-recheck'); + arkts.recheckSubtree(script); + arkts.Performance.getInstance().stopEvent('memo-recheck', true); + + arkts.Performance.getInstance().clearAllEvents(); + + this.setArkTSAst(script); + console.log('[MEMO PLUGIN] AFTER CHECKED EXIT'); + return script; + } + console.log('[MEMO PLUGIN] AFTER CHECKED EXIT WITH NO TRANSFORM'); + }, clean() { arkts.arktsGlobal.clearContext(); }, }; } - -function checkedTransform(this: PluginContext): arkts.EtsScript | undefined { - console.log('[MEMO PLUGIN] AFTER CHECKED ENTER'); - const contextPtr = arkts.arktsGlobal.compilerContext?.peer ?? this.getContextPtr(); - if (!!contextPtr) { - let program = arkts.getOrUpdateGlobalContext(contextPtr).program; - let script = program.astNode; - debugLog('[BEFORE MEMO SCRIPT] script: ', script.dumpSrc()); - const cachePath: string | undefined = this.getProjectConfig()?.cachePath; - const isFrameworkMode = !!this.getProjectConfig()?.frameworkMode; - const canSkipPhases = false; - debugDump( - script.dumpSrc(), - getDumpFileName(0, 'SRC', 5, 'MEMO_AfterCheck_Begin'), - true, - cachePath, - program.programFileNameWithExtension - ); - arkts.Performance.getInstance().createEvent('memo-checked'); - program = checkedProgramVisit(program, this, canSkipPhases, isFrameworkMode); - script = program.astNode; - arkts.Performance.getInstance().stopEvent('memo-checked', true); - debugLog('[AFTER MEMO SCRIPT] script: ', script.dumpSrc()); - debugDump( - script.dumpSrc(), - getDumpFileName(0, 'SRC', 6, 'MEMO_AfterCheck_End'), - true, - cachePath, - program.programFileNameWithExtension - ); - arkts.Performance.getInstance().createEvent('memo-recheck'); - arkts.recheckSubtree(script); - arkts.Performance.getInstance().stopEvent('memo-recheck', true); - arkts.Performance.getInstance().clearAllEvents(); - this.setArkTSAst(script); - console.log('[MEMO PLUGIN] AFTER CHECKED EXIT'); - return script; - } - console.log('[MEMO PLUGIN] AFTER CHECKED EXIT WITH NO TRANSFORM'); - return undefined; -} - -function checkedProgramVisit( - program: arkts.Program, - pluginContext: PluginContext, - canSkipPhases: boolean = false, - isFrameworkMode: boolean = false -): arkts.Program { - if (canSkipPhases) { - debugLog('[SKIP PHASE] phase: memo-checked, moduleName: ', program?.moduleName); - } else { - debugLog('[CANT SKIP PHASE] phase: memo-checked, moduleName: ', program?.moduleName); - const positionalIdTracker = new PositionalIdTracker(arkts.getFileName(), false); - const parameterTransformer = new ParameterTransformer({ - positionalIdTracker, - }); - const returnTransformer = new ReturnTransformer(); - const signatureTransformer = new SignatureTransformer(); - const internalsTransformer = new InternalsTransformer({ positionalIdTracker }); - const functionTransformer = new FunctionTransformer({ - positionalIdTracker, - parameterTransformer, - returnTransformer, - signatureTransformer, - internalsTransformer - }); - const skipPrefixNames = isFrameworkMode - ? EXTERNAL_SOURCE_PREFIX_NAMES_FOR_FRAMEWORK - : EXTERNAL_SOURCE_PREFIX_NAMES; - const programVisitor = new ProgramVisitor({ - pluginName: unmemoizeTransform.name, - state: arkts.Es2pandaContextState.ES2PANDA_STATE_CHECKED, - visitors: [functionTransformer], - skipPrefixNames, - pluginContext, - }); - program = programVisitor.programVisitor(program); - } - return program; -} \ No newline at end of file diff --git a/arkui-plugins/memo-plugins/internal-transformer.ts b/arkui-plugins/memo-plugins/internal-transformer.ts deleted file mode 100644 index 7419778b2..000000000 --- a/arkui-plugins/memo-plugins/internal-transformer.ts +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (c) 2022-2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as arkts from '@koalaui/libarkts'; -import { RuntimeNames, PositionalIdTracker } from './utils'; -import { AbstractVisitor, VisitorOptions } from '../common/abstract-visitor'; - -export interface InternalsTransformerOptions extends VisitorOptions { - positionalIdTracker: PositionalIdTracker; -} - -export class InternalsTransformer extends AbstractVisitor { - private readonly positionalIdTracker: PositionalIdTracker; - - constructor(options: InternalsTransformerOptions) { - super(options); - this.positionalIdTracker = options.positionalIdTracker; - } - - visitor(beforeChildren: arkts.AstNode): arkts.AstNode { - const node = this.visitEachChild(beforeChildren); - if (arkts.isCallExpression(node)) { - if (arkts.isIdentifier(node.expression)) { - if (node.expression.name === RuntimeNames.__CONTEXT) { - return arkts.factory.createIdentifier(RuntimeNames.CONTEXT, undefined); - } - if (node.expression.name === RuntimeNames.__ID) { - return arkts.factory.createIdentifier(RuntimeNames.ID, undefined); - } - if (node.expression.name === RuntimeNames.__KEY) { - return this.positionalIdTracker.id(RuntimeNames.__KEY); - } - } - } - return node; - } -} \ No newline at end of file diff --git a/arkui-plugins/memo-plugins/memo-factory.ts b/arkui-plugins/memo-plugins/memo-factory.ts index dac886843..9cef81c70 100644 --- a/arkui-plugins/memo-plugins/memo-factory.ts +++ b/arkui-plugins/memo-plugins/memo-factory.ts @@ -14,17 +14,7 @@ */ import * as arkts from '@koalaui/libarkts'; -import { - fixGensymParams, - buildeParamInfos, - isUnmemoizedInFunction, - mayAddLastReturn, - ParamInfo, - ReturnTypeInfo, - RuntimeNames, - parametrizedNodeHasReceiver -} from './utils'; -import { moveToFront } from '../common/arkts-utils'; +import { RuntimeNames } from './utils'; export class factory { // Importing @@ -40,15 +30,16 @@ export class factory { arkts.factory.createIdentifier(RuntimeNames.ID_TYPE) ); } - + // TODO: Currently, import declaration can only be inserted at after-parsed stage. static createContextTypesImportDeclaration(program?: arkts.Program): void { - const source: arkts.StringLiteral = arkts.factory.createStringLiteral(RuntimeNames.MEMO_IMPORT_NAME); + const source: arkts.StringLiteral = arkts.factory.createStringLiteral(RuntimeNames.CONTEXT_TYPE_DEFAULT_IMPORT); + // const resolvedSource: arkts.StringLiteral = arkts.factory.create1StringLiteral( + // arkts.ImportPathManager.create().resolvePath('', source.str) + // ); const importDecl: arkts.ETSImportDeclaration = arkts.factory.createImportDeclaration( source, [factory.createContextTypeImportSpecifier(), factory.createIdTypeImportSpecifier()], - arkts.Es2pandaImportKinds.IMPORT_KINDS_TYPE, - program!, - arkts.Es2pandaImportFlags.IMPORT_FLAGS_NONE + arkts.Es2pandaImportKinds.IMPORT_KINDS_TYPE ); // Insert this import at the top of the script's statements. if (!program) { @@ -84,50 +75,18 @@ export class factory { static createHiddenParameters(): arkts.ETSParameterExpression[] { return [factory.createContextParameter(), factory.createIdParameter()]; } - static createHiddenParameterIfNotAdded( - params: readonly arkts.Expression[], - hasReceiver: boolean = false - ): readonly arkts.Expression[] { - const _params = params ?? []; - if (isUnmemoizedInFunction(_params)) { - return _params; - } - let newParams: arkts.Expression[] = [...factory.createHiddenParameters(), ..._params]; - if (hasReceiver) { - newParams = moveToFront(newParams, 2); - } - return newParams; - } static updateFunctionTypeWithMemoParameters(type: arkts.ETSFunctionType): arkts.ETSFunctionType { return arkts.factory.updateFunctionType( type, arkts.factory.createFunctionSignature( undefined, - factory.createHiddenParameterIfNotAdded(type.params), + [...factory.createHiddenParameters(), ...type.params], type.returnType, false ), arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW ); } - static updateScriptFunctionWithMemoParameters( - func: arkts.ScriptFunction, - newBody?: arkts.AstNode | undefined, - returnType?: arkts.TypeNode | undefined - ): arkts.ScriptFunction { - return arkts.factory.updateScriptFunction( - func, - newBody ?? func.body, - arkts.factory.createFunctionSignature( - func.typeParams, - factory.createHiddenParameterIfNotAdded(func.params, parametrizedNodeHasReceiver(func)), - returnType ?? func.returnTypeAnnotation, - func.hasReceiver - ), - func.flags, - func.modifiers - ); - } // Arguments static createContextArgument(): arkts.AstNode { @@ -146,16 +105,9 @@ export class factory { // Memo parameters static createMemoParameterIdentifier(name: string): arkts.Identifier { - if (name === RuntimeNames.EQUAL_T) { - return arkts.factory.createIdentifier(`${RuntimeNames.PARAMETER}_${RuntimeNames.THIS}`, undefined); - } return arkts.factory.createIdentifier(`${RuntimeNames.PARAMETER}_${name}`); } static createMemoParameterDeclarator(id: number, name: string): arkts.VariableDeclarator { - const originalIdent = - name === RuntimeNames.THIS || name === RuntimeNames.EQUAL_T - ? arkts.factory.createThisExpression() - : arkts.factory.createIdentifier(name, undefined); return arkts.factory.createVariableDeclarator( arkts.Es2pandaVariableDeclaratorFlag.VARIABLE_DECLARATOR_FLAG_CONST, factory.createMemoParameterIdentifier(name), @@ -168,19 +120,10 @@ export class factory { false ), undefined, - [arkts.factory.createNumericLiteral(id), originalIdent] + [arkts.factory.createNumericLiteral(id), arkts.factory.createIdentifier(name)] ) ); } - static createMemoParameterDeclaration(parameters: string[]): arkts.VariableDeclaration { - return arkts.factory.createVariableDeclaration( - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, - arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_CONST, - parameters.map((name, id) => { - return factory.createMemoParameterDeclarator(id, name); - }) - ); - } static createMemoParameterAccess(name: string): arkts.MemberExpression { return arkts.factory.createMemberExpression( factory.createMemoParameterIdentifier(name), @@ -190,7 +133,40 @@ export class factory { false ); } - static createMemoParameterAccessCall(name: string, passArgs?: arkts.AstNode[]): arkts.CallExpression { + static createMemoParameterAccessMemoWithScope( + name: string, + hash: arkts.NumberLiteral | arkts.StringLiteral, + passArgs?: arkts.AstNode[] + ): arkts.CallExpression { + const updatedArgs = passArgs ? passArgs : []; + return arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + factory.createMemoParameterIdentifier(name), + arkts.factory.createIdentifier(RuntimeNames.VALUE), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_GETTER, + false, + false + ), + undefined, + [...factory.createHiddenArguments(hash), ...updatedArgs] + ); + } + static createMemoParameterAccessMemoWithoutScope( + name: string, + hash: arkts.NumberLiteral | arkts.StringLiteral, + passArgs?: arkts.AstNode[] + ): arkts.CallExpression { + const updatedArgs = passArgs ? passArgs : []; + return arkts.factory.createCallExpression(arkts.factory.createIdentifier(name), undefined, [ + ...factory.createHiddenArguments(hash), + ...updatedArgs, + ]); + } + static createMemoParameterAccessCall( + name: string, + hash: arkts.NumberLiteral | arkts.StringLiteral, + passArgs?: arkts.AstNode[] + ): arkts.CallExpression { const updatedArgs = passArgs ? passArgs : []; return arkts.factory.createCallExpression( arkts.factory.createMemberExpression( @@ -327,74 +303,4 @@ export class factory { [factory.createIdArgument(hash), factory.createLambdaWrapper(node)] ); } - - static updateFunctionBody( - node: arkts.BlockStatement, - parameters: arkts.ETSParameterExpression[], - returnTypeInfo: ReturnTypeInfo, - hash: arkts.NumberLiteral | arkts.StringLiteral - ): [ - arkts.BlockStatement, - ParamInfo[], - arkts.VariableDeclaration | undefined, - arkts.ReturnStatement | arkts.BlockStatement | undefined - ] { - const paramInfos = buildeParamInfos(parameters); - const gensymParamsCount = fixGensymParams(paramInfos, node); - const parameterNames = paramInfos.map((it) => it.ident.name); - const scopeDeclaration = factory.createScopeDeclaration(returnTypeInfo.node, hash, parameterNames.length); - const memoParametersDeclaration = parameterNames.length - ? factory.createMemoParameterDeclaration(parameterNames) - : undefined; - const syntheticReturnStatement = factory.createSyntheticReturnStatement(!!returnTypeInfo.isStableThis); - const isVoidValue = !!returnTypeInfo.isVoid; - const unchangedCheck = factory.createIfStatementWithSyntheticReturnStatement( - syntheticReturnStatement, - isVoidValue - ); - return [ - arkts.factory.updateBlock(node, [ - ...node.statements.slice(0, gensymParamsCount), - scopeDeclaration, - ...(memoParametersDeclaration ? [memoParametersDeclaration] : []), - unchangedCheck, - ...node.statements.slice(gensymParamsCount), - ...(mayAddLastReturn(node) ? [arkts.factory.createReturnStatement()] : []), - ]), - paramInfos, - memoParametersDeclaration, - syntheticReturnStatement, - ]; - } - - static updateMemoTypeAnnotation(typeAnnotation: arkts.AstNode | undefined): arkts.TypeNode | undefined { - if (!typeAnnotation || !arkts.isTypeNode(typeAnnotation)) { - return undefined; - } - - if (arkts.isETSFunctionType(typeAnnotation)) { - return factory.updateFunctionTypeWithMemoParameters(typeAnnotation); - } else if (arkts.isETSUnionType(typeAnnotation)) { - return arkts.factory.updateUnionType( - typeAnnotation, - typeAnnotation.types.map((it) => { - if (arkts.isETSFunctionType(it)) { - return factory.updateFunctionTypeWithMemoParameters(it); - } - return it; - }) - ); - } - return typeAnnotation; - } - - static insertHiddenArgumentsToCall( - node: arkts.CallExpression, - hash: arkts.NumberLiteral | arkts.StringLiteral - ): arkts.CallExpression { - return arkts.factory.updateCallExpression(node, node.expression, node.typeArguments, [ - ...factory.createHiddenArguments(hash), - ...node.arguments, - ]); - } } diff --git a/arkui-plugins/memo-plugins/parameter-transformer.ts b/arkui-plugins/memo-plugins/parameter-transformer.ts index 061e5b80b..757e45f77 100644 --- a/arkui-plugins/memo-plugins/parameter-transformer.ts +++ b/arkui-plugins/memo-plugins/parameter-transformer.ts @@ -17,73 +17,62 @@ import * as arkts from '@koalaui/libarkts'; import { factory } from './memo-factory'; import { AbstractVisitor, VisitorOptions } from '../common/abstract-visitor'; import { - buildReturnTypeInfo, - castParameters, - findReturnTypeFromTypeAnnotation, - isMemoETSParameterExpression, + hasMemoAnnotation, + hasMemoIntrinsicAnnotation, isMemoParametersDeclaration, - isUnmemoizedInFunction, - isVoidType, - MemoInfo, - ParamInfo, PositionalIdTracker, - ReturnTypeInfo, - RuntimeNames, } from './utils'; -import { ReturnTransformer } from './return-transformer'; export interface ParameterTransformerOptions extends VisitorOptions { positionalIdTracker: PositionalIdTracker; } -interface RewriteMemoInfo extends MemoInfo { - rewritePeer: number; -} - export class ParameterTransformer extends AbstractVisitor { private rewriteIdentifiers?: Map arkts.MemberExpression | arkts.Identifier>; - private rewriteCalls?: Map arkts.CallExpression>; - private rewriteMemoInfos?: Map; - private rewriteThis?: boolean; + private rewriteCalls?: Map arkts.CallExpression>; private skipNode?: arkts.VariableDeclaration; - private visited: Set; - - private positionalIdTracker: PositionalIdTracker; + private readonly positionalIdTracker: PositionalIdTracker; constructor(options: ParameterTransformerOptions) { super(options); this.positionalIdTracker = options.positionalIdTracker; - this.visited = new Set(); } reset(): void { super.reset(); this.rewriteIdentifiers = undefined; this.rewriteCalls = undefined; - this.rewriteMemoInfos = undefined; this.skipNode = undefined; - this.visited.clear(); } - withThis(flag: boolean): ParameterTransformer { - this.rewriteThis = flag; - return this; - } - - withParameters(parameters: ParamInfo[]): ParameterTransformer { + withParameters(parameters: arkts.ETSParameterExpression[]): ParameterTransformer { this.rewriteCalls = new Map( parameters - .filter( - (it) => - it.param.type && (arkts.isETSFunctionType(it.param.type) || arkts.isETSUnionType(it.param.type)) - ) + .filter((it) => it.type && (arkts.isETSFunctionType(it.type) || arkts.isETSUnionType(it.type))) .map((it) => { return [ - it.param.identifier.name.startsWith(RuntimeNames.GENSYM) - ? it.ident.originalPeer - : it.param.originalPeer, - (passArgs: arkts.Expression[]): arkts.CallExpression => { - return factory.createMemoParameterAccessCall(it.ident.name, passArgs); + it.peer, + (passArgs: arkts.AstNode[]) => { + if (hasMemoAnnotation(it) || hasMemoIntrinsicAnnotation(it)) { + if (it.type && arkts.isETSFunctionType(it.type) && !it.optional) { + return factory.createMemoParameterAccessMemoWithScope( + it.identifier.name, + this.positionalIdTracker?.id(), + passArgs + ); + } else { + return factory.createMemoParameterAccessMemoWithoutScope( + it.identifier.name, + this.positionalIdTracker?.id(), + passArgs + ); + } + } + return factory.createMemoParameterAccessCall( + it.identifier.name, + this.positionalIdTracker?.id(), + passArgs + ); }, ]; }) @@ -91,25 +80,12 @@ export class ParameterTransformer extends AbstractVisitor { this.rewriteIdentifiers = new Map( parameters.map((it) => { return [ - it.param.identifier.name.startsWith(RuntimeNames.GENSYM) - ? it.ident.originalPeer - : it.param.originalPeer, - (): arkts.MemberExpression => { - return factory.createMemoParameterAccess(it.ident.name); - }, - ]; - }) - ); - this.rewriteMemoInfos = new Map( - parameters.map((it) => { - return [ - it.param.identifier.name.startsWith(RuntimeNames.GENSYM) - ? it.ident.originalPeer - : it.param.originalPeer, - { - name: it.param.identifier.name, - rewritePeer: it.param.identifier.originalPeer, - isMemo: isMemoETSParameterExpression(it.param), + it.peer, + () => { + if ((it.type && arkts.isETSFunctionType(it.type)) || it.optional) { + return arkts.factory.createIdentifier(it.identifier.name); + } + return factory.createMemoParameterAccess(it.identifier.name); }, ]; }) @@ -122,189 +98,33 @@ export class ParameterTransformer extends AbstractVisitor { return this; } - track(node: arkts.AstNode | undefined): void { - if (!!node?.peer) { - this.visited.add(node.peer); - } - } - - isTracked(node: arkts.AstNode | undefined): boolean { - return !!node?.peer && this.visited.has(node.peer); - } - - private updateArrowFunctionFromVariableDeclareInit( - initializer: arkts.ArrowFunctionExpression, - returnType: arkts.TypeNode | undefined - ): arkts.ArrowFunctionExpression { - const scriptFunction = initializer.scriptFunction; - if (!scriptFunction.body || !arkts.isBlockStatement(scriptFunction.body)) { - return initializer; - } - if (isUnmemoizedInFunction(scriptFunction.params)) { - return initializer; - } - const returnTypeInfo: ReturnTypeInfo = buildReturnTypeInfo( - returnType ?? scriptFunction.returnTypeAnnotation, - true - ); - const [body, parameterIdentifiers, memoParametersDeclaration, syntheticReturnStatement] = - factory.updateFunctionBody( - scriptFunction.body, - castParameters(scriptFunction.params), - returnTypeInfo, - this.positionalIdTracker.id() - ); - const paramaterTransformer = new ParameterTransformer({ - positionalIdTracker: this.positionalIdTracker, - }); - const returnTransformer = new ReturnTransformer(); - const afterParameterTransformer = paramaterTransformer - .withParameters(parameterIdentifiers) - .skip(memoParametersDeclaration) - .visitor(body); - const afterReturnTransformer = returnTransformer - .skip(syntheticReturnStatement) - .registerReturnTypeInfo(returnTypeInfo) - .visitor(afterParameterTransformer); - const updateScriptFunction = factory.updateScriptFunctionWithMemoParameters( - scriptFunction, - afterReturnTransformer, - returnTypeInfo.node - ); - paramaterTransformer.reset(); - returnTransformer.reset(); - this.track(updateScriptFunction.body); - return arkts.factory.updateArrowFunction(initializer, updateScriptFunction); - } - - private updateVariableDeclareInit( - initializer: T | undefined, - returnType: arkts.TypeNode | undefined - ): T | undefined { - if (!initializer) { - return undefined; - } - if (arkts.isConditionalExpression(initializer)) { - return arkts.factory.updateConditionalExpression( - initializer, - initializer.test, - this.updateVariableDeclareInit(initializer.consequent, returnType), - this.updateVariableDeclareInit(initializer.alternate, returnType) - ) as unknown as T; - } - if (arkts.isTSAsExpression(initializer)) { - return arkts.factory.updateTSAsExpression( - initializer, - this.updateVariableDeclareInit(initializer.expr, returnType), - factory.updateMemoTypeAnnotation(initializer.typeAnnotation), - initializer.isConst - ) as unknown as T; - } - if (arkts.isArrowFunctionExpression(initializer)) { - return this.updateArrowFunctionFromVariableDeclareInit(initializer, returnType) as unknown as T; - } - return initializer; - } - - private updateParamReDeclare(node: arkts.VariableDeclarator, memoInfo: RewriteMemoInfo): arkts.VariableDeclarator { - const shouldUpdate: boolean = node.name.name !== memoInfo.name && memoInfo.isMemo; - if (!shouldUpdate) { - return node; - } - const decl = arkts.getPeerDecl(memoInfo.rewritePeer); - if (!decl || !arkts.isEtsParameterExpression(decl)) { - return node; - } - - let typeAnnotation: arkts.TypeNode | undefined; - if ( - !!node.name.typeAnnotation && - !(typeAnnotation = factory.updateMemoTypeAnnotation(node.name.typeAnnotation)) - ) { - console.error(`ETSFunctionType or ETSUnionType expected for @memo-variable-type ${node.name.name}`); - throw 'Invalid @memo usage'; - } - - const returnType = findReturnTypeFromTypeAnnotation(decl.type); - return arkts.factory.updateVariableDeclarator( - node, - node.flag, - arkts.factory.updateIdentifier(node.name, node.name.name, typeAnnotation), - this.updateVariableDeclareInit(node.initializer, returnType) - ); - } - - private updateVariableReDeclarationFromParam(node: arkts.VariableDeclaration): arkts.VariableDeclaration { - const that = this; - return arkts.factory.updateVariableDeclaration( - node, - node.modifiers, - node.declarationKind, - node.declarators.map((declarator) => { - if (that.rewriteMemoInfos?.has(declarator.name.originalPeer)) { - const memoInfo = that.rewriteMemoInfos.get(declarator.name.originalPeer)!; - return that.updateParamReDeclare(declarator, memoInfo); - } - if (!!declarator.initializer && arkts.isIdentifier(declarator.initializer)) { - const decl = arkts.getPeerDecl(declarator.initializer.originalPeer); - if (decl && that.rewriteIdentifiers?.has(decl.peer)) { - return arkts.factory.updateVariableDeclarator( - declarator, - declarator.flag, - declarator.name, - that.rewriteIdentifiers.get(decl.peer)!() - ); - } - } - return declarator; - }) - ); - } - - private updateCallReDeclare( - node: arkts.CallExpression, - oriName: arkts.Identifier, - memoInfo: RewriteMemoInfo - ): arkts.CallExpression { - const shouldUpdate: boolean = oriName.name !== memoInfo.name && memoInfo.isMemo; - if (!shouldUpdate) { - return node; - } - return factory.insertHiddenArgumentsToCall(node, this.positionalIdTracker.id(oriName.name)); - } - visitor(beforeChildren: arkts.AstNode): arkts.AstNode { // TODO: temporary checking skip nodes by comparison with expected skip nodes // Should be fixed when update procedure implemented properly - if (/* beforeChildren === this.skipNode */ isMemoParametersDeclaration(beforeChildren)) { + if (!beforeChildren) { return beforeChildren; } - if (arkts.isVariableDeclaration(beforeChildren)) { - return this.updateVariableReDeclarationFromParam(beforeChildren); + if (/* beforeChildren === this.skipNode */ isMemoParametersDeclaration(beforeChildren)) { + return beforeChildren; } - if (arkts.isCallExpression(beforeChildren) && arkts.isIdentifier(beforeChildren.expression)) { - const decl = arkts.getPeerDecl(beforeChildren.expression.originalPeer); - if (decl && this.rewriteCalls?.has(decl.peer)) { - const updateCall = this.rewriteCalls.get(decl.peer)!( - beforeChildren.arguments.map((it) => this.visitor(it) as arkts.Expression) - ); - if (this.rewriteMemoInfos?.has(decl.peer)) { - const memoInfo = this.rewriteMemoInfos.get(decl.peer)!; - return this.updateCallReDeclare(updateCall, beforeChildren.expression, memoInfo); + if (arkts.isCallExpression(beforeChildren)) { + if (arkts.isIdentifier(beforeChildren.expression)) { + const decl = arkts.getDecl(beforeChildren.expression); + if (decl && arkts.isEtsParameterExpression(decl) && this.rewriteCalls?.has(decl.peer)) { + return this.rewriteCalls.get(decl.peer)!(beforeChildren.arguments.map((it) => this.visitor(it))); } - return updateCall; } } const node = this.visitEachChild(beforeChildren); if (arkts.isIdentifier(node)) { - const decl = arkts.getPeerDecl(node.originalPeer); - if (decl && this.rewriteIdentifiers?.has(decl.peer)) { - return this.rewriteIdentifiers.get(decl.peer)!(); + const decl = arkts.getDecl(node); + if (decl && arkts.isEtsParameterExpression(decl) && this.rewriteIdentifiers?.has(decl.peer)) { + const res = this.rewriteIdentifiers.get(decl.peer)!(); + if (arkts.isMemberExpression(res)) { + return res; + } } } - if (arkts.isThisExpression(node) && this.rewriteThis) { - return factory.createMemoParameterAccess(RuntimeNames.THIS); - } return node; } } diff --git a/arkui-plugins/memo-plugins/return-transformer.ts b/arkui-plugins/memo-plugins/return-transformer.ts index c2c0fac2e..563d55621 100644 --- a/arkui-plugins/memo-plugins/return-transformer.ts +++ b/arkui-plugins/memo-plugins/return-transformer.ts @@ -16,18 +16,16 @@ import * as arkts from '@koalaui/libarkts'; import { factory } from './memo-factory'; import { AbstractVisitor } from '../common/abstract-visitor'; -import { isSyntheticReturnStatement, ReturnTypeInfo } from './utils'; +import { isSyntheticReturnStatement } from './utils'; export class ReturnTransformer extends AbstractVisitor { private skipNode?: arkts.ReturnStatement | arkts.BlockStatement; private stableThis: boolean = false; - private returnTypeInfo: ReturnTypeInfo | undefined; reset() { super.reset(); this.skipNode = undefined; this.stableThis = false; - this.returnTypeInfo = undefined; } skip(syntheticReturnStatement?: arkts.ReturnStatement | arkts.BlockStatement): ReturnTransformer { @@ -40,11 +38,6 @@ export class ReturnTransformer extends AbstractVisitor { return this; } - registerReturnTypeInfo(returnTypeInfo: ReturnTypeInfo): ReturnTransformer { - this.returnTypeInfo = returnTypeInfo; - return this; - } - visitor(beforeChildren: arkts.AstNode): arkts.AstNode { // TODO: temporary checking skip nodes by comparison with expected skip nodes // Should be fixed when update procedure implemented properly @@ -65,20 +58,7 @@ export class ReturnTransformer extends AbstractVisitor { node, ]); } - - let argument = node.argument; - if ( - !!this.returnTypeInfo?.node && - this.returnTypeInfo.isMemo && - arkts.isArrowFunctionExpression(argument) - ) { - argument = arkts.factory.updateArrowFunction( - argument, - factory.updateScriptFunctionWithMemoParameters(argument.scriptFunction) - ); - } - - return arkts.factory.updateReturnStatement(node, factory.createRecacheCall(argument)); + return arkts.factory.updateReturnStatement(node, factory.createRecacheCall(node.argument)); } return node; } diff --git a/arkui-plugins/memo-plugins/signature-transformer.ts b/arkui-plugins/memo-plugins/signature-transformer.ts index b7fa8a62d..985d57d5c 100644 --- a/arkui-plugins/memo-plugins/signature-transformer.ts +++ b/arkui-plugins/memo-plugins/signature-transformer.ts @@ -15,36 +15,10 @@ import * as arkts from '@koalaui/libarkts'; import { factory } from './memo-factory'; -import { - hasMemoAnnotation, - hasMemoIntrinsicAnnotation, - parametrizedNodeHasReceiver, - isMemoTSTypeAliasDeclaration, -} from './utils'; +import { hasMemoAnnotation, hasMemoIntrinsicAnnotation } from './utils'; import { AbstractVisitor } from '../common/abstract-visitor'; -function isScriptFunctionFromGetter(node: arkts.ScriptFunction): boolean { - return ( - !!node.parent && - !!node.parent.parent && - arkts.isFunctionExpression(node.parent) && - arkts.isMethodDefinition(node.parent.parent) && - node.parent.parent.kind === arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_GET - ); -} - -function isScriptFunctionFromSetter(node: arkts.ScriptFunction): boolean { - return ( - !!node.parent && - !!node.parent.parent && - arkts.isFunctionExpression(node.parent) && - arkts.isMethodDefinition(node.parent.parent) && - node.parent.parent.kind === arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_SET - ); -} - export class SignatureTransformer extends AbstractVisitor { - /* Tracking whether should import `__memo_context_type` and `__memo_id_type` */ public modified = false; reset(): void { @@ -58,25 +32,17 @@ export class SignatureTransformer extends AbstractVisitor { if (memo) { this.modified = true; } - const isFromGetter = isScriptFunctionFromGetter(node); - const isFromSetter = isScriptFunctionFromSetter(node); - const shouldAddMemoParam = memo && !isFromGetter && !isFromSetter; - const shouldApplyMemoToParamExpr = memo && isFromSetter; - const shouldApplyMemoToReturnType = memo && isFromGetter; - const newParams = node.params.map((it) => this.visitor(it, shouldApplyMemoToParamExpr)); return arkts.factory.updateScriptFunction( node, node.body, arkts.factory.createFunctionSignature( node.typeParams, - shouldAddMemoParam - ? factory.createHiddenParameterIfNotAdded(newParams, parametrizedNodeHasReceiver(node)) - : newParams, + [...(memo ? factory.createHiddenParameters() : []), ...node.params.map((it) => this.visitor(it))], node.returnTypeAnnotation - ? this.visitor(node.returnTypeAnnotation, shouldApplyMemoToReturnType) + ? this.visitor(node.returnTypeAnnotation) : memo - ? arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID) - : undefined, + ? arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID) + : undefined, node.hasReceiver ), node.flags, @@ -84,7 +50,7 @@ export class SignatureTransformer extends AbstractVisitor { ) as any as T; } if (arkts.isEtsParameterExpression(node)) { - const memo = hasMemoAnnotation(node) || hasMemoIntrinsicAnnotation(node) || applyMemo; + const memo = hasMemoAnnotation(node) || hasMemoIntrinsicAnnotation(node); if (!node.type) { if (memo) { console.error(`@memo parameter ${node.identifier.name} without type annotatation`); @@ -100,12 +66,11 @@ export class SignatureTransformer extends AbstractVisitor { if (memo) { this.modified = true; } - const newParams = node.params.map((it) => this.visitor(it)); return arkts.factory.updateFunctionType( node, arkts.factory.createFunctionSignature( undefined, - memo ? factory.createHiddenParameterIfNotAdded(newParams) : newParams, + [...(memo ? factory.createHiddenParameters() : []), ...node.params.map((it) => this.visitor(it))], this.visitor(node.returnType!), false ), @@ -121,26 +86,7 @@ export class SignatureTransformer extends AbstractVisitor { if (arkts.isETSUndefinedType(node)) { return node as any as T; } - if (arkts.isETSTypeReference(node) && applyMemo) { - if (!node.part || !node.part.name) { - console.error(`@memo parameter has no type reference`); - throw 'Invalid @memo usage'; - } - const expr = node.part.name; - const decl = arkts.getDecl(expr); - if (!decl || !arkts.isTSTypeAliasDeclaration(decl)) { - console.error(`@memo parameter's type has not been declared`); - throw 'Invalid @memo usage'; - } - const memoDecl = isMemoTSTypeAliasDeclaration(decl); - if (memoDecl) { - return node as any as T; - } - console.error(`@memo parameter type reference has no @memo type declaration`); - throw 'Invalid @memo usage'; - } if (applyMemo) { - console.error(`@memo parameter's signature has invalid type`); throw 'Invalid @memo usage'; } return node; diff --git a/arkui-plugins/memo-plugins/utils.ts b/arkui-plugins/memo-plugins/utils.ts index fea2bffad..cae4fa891 100644 --- a/arkui-plugins/memo-plugins/utils.ts +++ b/arkui-plugins/memo-plugins/utils.ts @@ -20,17 +20,13 @@ const UniqueId = common.UniqueId; export enum RuntimeNames { __CONTEXT = '__context', __ID = '__id', - __KEY = '__key', ANNOTATION = 'memo', - ANNOTATION_ENTRY = 'memo_entry', ANNOTATION_INTRINSIC = 'memo_intrinsic', ANNOTATION_STABLE = 'memo_stable', - ANNOTATION_SKIP = 'memo_skip', COMPUTE = 'compute', CONTEXT = '__memo_context', CONTEXT_TYPE = '__memo_context_type', - MEMO_IMPORT_NAME = 'arkui.stateManagement.runtime', - GENSYM = 'gensym%%_', + CONTEXT_TYPE_DEFAULT_IMPORT = '@ohos.arkui.StateManagement.runtime', ID = '__memo_id', ID_TYPE = '__memo_id_type', INTERNAL_PARAMETER_STATE = 'param', @@ -40,26 +36,7 @@ export enum RuntimeNames { INTERNAL_VALUE_OK = 'unchanged', PARAMETER = '__memo_parameter', SCOPE = '__memo_scope', - THIS = 'this', VALUE = 'value', - EQUAL_T = '=t' -} - -export interface ReturnTypeInfo { - node: arkts.TypeNode | undefined; - isMemo?: boolean; - isVoid?: boolean; - isStableThis?: boolean; -} - -export interface ParamInfo { - ident: arkts.Identifier; - param: arkts.ETSParameterExpression; -} - -export interface MemoInfo { - name?: string; - isMemo: boolean; } function baseName(path: string): string { @@ -111,9 +88,7 @@ export type MemoAstNode = | arkts.ClassProperty | arkts.TSTypeAliasDeclaration | arkts.ETSFunctionType - | arkts.ArrowFunctionExpression - | arkts.ETSTypeReference - | arkts.VariableDeclaration; + | arkts.ArrowFunctionExpression; export function hasMemoAnnotation(node: T): boolean { return node.annotations.some((it) => isMemoAnnotation(it, RuntimeNames.ANNOTATION)); @@ -123,21 +98,18 @@ export function hasMemoIntrinsicAnnotation(node: T): bool return node.annotations.some((it) => isMemoAnnotation(it, RuntimeNames.ANNOTATION_INTRINSIC)); } -export function hasMemoEntryAnnotation(node: T): boolean { - return node.annotations.some((it) => isMemoAnnotation(it, RuntimeNames.ANNOTATION_ENTRY)); -} - export function hasMemoStableAnnotation(node: arkts.ClassDefinition): boolean { - return node.annotations.some((it) => isMemoAnnotation(it, RuntimeNames.ANNOTATION_STABLE)); -} - -export function hasMemoSkipAnnotation(node: arkts.ETSParameterExpression): boolean { - return node.annotations.some((it) => isMemoAnnotation(it, RuntimeNames.ANNOTATION_SKIP)); + return node.annotations.some( + (it) => it.expr !== undefined && arkts.isIdentifier(it.expr) && it.expr.name === RuntimeNames.ANNOTATION_STABLE + ); } export function removeMemoAnnotation(node: T): T { const newAnnotations: arkts.AnnotationUsage[] = node.annotations.filter( - (it) => !isMemoAnnotation(it, RuntimeNames.ANNOTATION) && !isMemoAnnotation(it, RuntimeNames.ANNOTATION_STABLE) + (it) => + !isMemoAnnotation(it, RuntimeNames.ANNOTATION) && + !isMemoAnnotation(it, RuntimeNames.ANNOTATION_INTRINSIC) && + !isMemoAnnotation(it, RuntimeNames.ANNOTATION_STABLE) ); if (arkts.isEtsParameterExpression(node)) { node.annotations = newAnnotations; @@ -244,15 +216,6 @@ export function castArrowFunctionExpression(value: arkts.Expression | undefined) return value as unknown as arkts.ArrowFunctionExpression; } -/** - * es2panda API is weird here - * - * @deprecated - */ -export function castIdentifier(value: arkts.AstNode | undefined): arkts.Identifier { - return value as unknown as arkts.Identifier; -} - /** * es2panda API is weird here * @@ -266,65 +229,9 @@ export function isStandaloneArrowFunction(node: arkts.AstNode): node is arkts.Ar if (!arkts.isArrowFunctionExpression(node)) return false; // handling anonymous arrow function call - if (!!node.parent && arkts.isCallExpression(node.parent) && node.parent.expression.peer === node.peer) { - return true; - } - - return ( - !!node.parent && - !arkts.isVariableDeclarator(node.parent) && - !arkts.isClassProperty(node.parent) && - !(arkts.isCallExpression(node.parent) && node.parent.expression) - ); -} + if (arkts.isCallExpression(node.parent) && node.parent.expression.peer === node.peer) return true; -export function isFunctionProperty(node: arkts.AstNode): node is arkts.Property { - return ( - arkts.isProperty(node) && - !!node.key && - arkts.isIdentifier(node.key) && - !!node.value && - arkts.isArrowFunctionExpression(node.value) - ); -} - -export function isThisAttributeAssignment(node: arkts.AstNode): node is arkts.AssignmentExpression { - if (!arkts.isAssignmentExpression(node)) { - return false; - } - if (!node.left || !node.right) { - return false; - } - const isAssignOperator = node.operatorType === arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION; - const isThisAttribute = - arkts.isMemberExpression(node.left) && - arkts.isThisExpression(node.left.object) && - arkts.isIdentifier(node.left.property); - return isAssignOperator && isThisAttribute; -} - -export function findThisAttribute(node: arkts.AstNode): arkts.Identifier | undefined { - if (!arkts.isMemberExpression(node) || !arkts.isIdentifier(node.property)) { - return undefined; - } - return node.property; -} - -export function isMemoThisAttribute(node: arkts.Identifier, value: arkts.ArrowFunctionExpression): boolean { - let isMemo: boolean = isMemoArrowFunction(value); - if (isMemo) { - return true; - } - const decl: arkts.AstNode | undefined = getDeclResolveAlias(node); - if (!decl) { - return false; - } - if (arkts.isClassProperty(decl)) { - isMemo ||= isMemoClassProperty(decl); - } else if (arkts.isMethodDefinition(decl)) { - isMemo ||= isMemoDeclaredMethod(decl); - } - return isMemo; + return !arkts.isClassProperty(node.parent) && !(arkts.isCallExpression(node.parent) && node.parent.expression); } export function isMemoClassProperty(node: arkts.ClassProperty): boolean { @@ -339,11 +246,7 @@ export function isMemoClassProperty(node: arkts.ClassProperty): boolean { } export function isMemoMethodDefinition(node: arkts.MethodDefinition): boolean { - return ( - hasMemoAnnotation(node.scriptFunction) || - hasMemoIntrinsicAnnotation(node.scriptFunction) || - hasMemoEntryAnnotation(node.scriptFunction) - ); + return hasMemoAnnotation(node.scriptFunction) || hasMemoIntrinsicAnnotation(node.scriptFunction); } export function isMemoArrowFunction(node: arkts.ArrowFunctionExpression): boolean { @@ -356,110 +259,11 @@ export function isMemoTSTypeAliasDeclaration(node: arkts.TSTypeAliasDeclaration) return isMemo; } -export function isMemoETSParameterExpression(param: arkts.ETSParameterExpression): boolean { - const type = param.identifier.typeAnnotation; - if (!type) { - return false; - } - let isMemo: boolean = hasMemoAnnotation(param) || hasMemoIntrinsicAnnotation(param); - isMemo ||= findMemoFromTypeAnnotation(type); - let decl: arkts.AstNode | undefined; - if ( - arkts.isETSTypeReference(type) && - !!type.part && - !!type.part.name && - !!(decl = getDeclResolveAlias(type.part.name)) - ) { - if (arkts.isTSTypeAliasDeclaration(decl)) { - isMemo ||= hasMemoAnnotation(decl) || hasMemoIntrinsicAnnotation(decl); - isMemo ||= findMemoFromTypeAnnotation(decl.typeAnnotation); - return isMemo; - } - } - return isMemo; -} - -export function isMemoVariableDeclaration(node: arkts.VariableDeclaration): boolean { - return hasMemoAnnotation(node) || hasMemoIntrinsicAnnotation(node); -} - -export function isMemoVariableDeclarator(node: arkts.VariableDeclarator): boolean { - let isMemo: boolean = false; - if (!!node.name.typeAnnotation) { - isMemo ||= findMemoFromTypeAnnotation(node.name.typeAnnotation); - } - if (!!node.initializer && arkts.isArrowFunctionExpression(node.initializer)) { - isMemo ||= isMemoArrowFunction(node.initializer); - } - if (!!node.parent && arkts.isVariableDeclaration(node.parent)) { - isMemo ||= isMemoVariableDeclaration(node.parent); - } - return isMemo; -} - -export function isMemoProperty(node: arkts.Property, value: arkts.ArrowFunctionExpression): boolean { - let isMemo: boolean = isMemoArrowFunction(value); - if (isMemo) { - return true; - } - let decl: arkts.AstNode | undefined; - if (!node.key || !(decl = getDeclResolveAlias(node.key))) { - return false; - } - if (arkts.isMethodDefinition(decl)) { - isMemo ||= isMemoDeclaredMethod(decl); - } - return isMemo; -} - -export function isMemoDeclaredMethod(decl: arkts.MethodDefinition): boolean { - if ( - decl.kind === arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_GET && - findMemoFromTypeAnnotation(decl.scriptFunction.returnTypeAnnotation) - ) { - return true; - } - return !hasMemoEntryAnnotation(decl.scriptFunction) && isMemoMethodDefinition(decl); -} - -export function isDeclaredMethodWithMemoParams(decl: arkts.MethodDefinition): boolean { - if (decl.kind === arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_GET) { - return false; - } - return decl.scriptFunction.params.some((param) => { - return arkts.isEtsParameterExpression(param) && isMemoETSParameterExpression(param); - }); -} - -export function isMemoDeclaredIdentifier(decl: arkts.Identifier): boolean { - if (findMemoFromTypeAnnotation(decl.typeAnnotation)) { - return true; - } - if (!!decl.parent && arkts.isVariableDeclarator(decl.parent)) { - return isMemoVariableDeclarator(decl.parent); - } - return false; -} - -export function isMemoDeclaredClassProperty(decl: arkts.ClassProperty): boolean { - return isMemoClassProperty(decl); -} - -export function findMemoFromTypeAnnotation(typeAnnotation: arkts.AstNode | undefined): boolean { +export function findMemoFromTypeAnnotation(typeAnnotation: arkts.TypeNode | undefined): boolean { if (!typeAnnotation) { return false; } - if (arkts.isETSTypeReference(typeAnnotation) && !!typeAnnotation.part && !!typeAnnotation.part.name) { - let decl: arkts.AstNode | undefined = arkts.getDecl(typeAnnotation.part.name); - if (!decl || !arkts.isTSTypeAliasDeclaration(decl)) { - return false; - } - let isMemo: boolean = hasMemoAnnotation(decl) || hasMemoIntrinsicAnnotation(decl); - if (!isMemo && !!decl.typeAnnotation) { - isMemo = findMemoFromTypeAnnotation(decl.typeAnnotation); - } - return isMemo; - } else if (arkts.isETSFunctionType(typeAnnotation)) { + if (arkts.isETSFunctionType(typeAnnotation)) { return hasMemoAnnotation(typeAnnotation) || hasMemoIntrinsicAnnotation(typeAnnotation); } else if (arkts.isETSUnionType(typeAnnotation)) { return typeAnnotation.types.some( @@ -468,121 +272,3 @@ export function findMemoFromTypeAnnotation(typeAnnotation: arkts.AstNode | undef } return false; } - -export function findReturnTypeFromTypeAnnotation( - typeAnnotation: arkts.AstNode | undefined -): arkts.TypeNode | undefined { - if (!typeAnnotation) { - return undefined; - } - if (arkts.isETSTypeReference(typeAnnotation) && !!typeAnnotation.part && !!typeAnnotation.part.name) { - let decl: arkts.AstNode | undefined = arkts.getDecl(typeAnnotation.part.name); - if (!!decl && arkts.isTSTypeAliasDeclaration(decl)) { - return findReturnTypeFromTypeAnnotation(decl.typeAnnotation); - } - return undefined; - } - if (arkts.isETSFunctionType(typeAnnotation)) { - return typeAnnotation.returnType; - } - if (arkts.isETSUnionType(typeAnnotation)) { - return typeAnnotation.types.find((type) => arkts.isETSFunctionType(type))?.returnType; - } - return undefined; -} - -export function getDeclResolveAlias(node: arkts.AstNode): arkts.AstNode | undefined { - const decl = arkts.getDecl(node); - if (!!decl && !!decl.parent && arkts.isIdentifier(decl) && arkts.isVariableDeclarator(decl.parent)) { - if (!!decl.parent.initializer && arkts.isIdentifier(decl.parent.initializer)) { - return getDeclResolveAlias(decl.parent.initializer); - } - if (!!decl.parent.initializer && arkts.isMemberExpression(decl.parent.initializer)) { - return getDeclResolveAlias(decl.parent.initializer.property); - } - } - return decl; -} - -export function mayAddLastReturn(node: arkts.BlockStatement): boolean { - return ( - node.statements.length === 0 || - (!arkts.isReturnStatement(node.statements[node.statements.length - 1]) && - !arkts.isThrowStatement(node.statements[node.statements.length - 1])) - ); -} - -export function fixGensymParams(params: ParamInfo[], body: arkts.BlockStatement): number { - let gensymParamsCount = 0; - for (let i = 0; i < params.length; i++) { - if (params[i].ident.name.startsWith(RuntimeNames.GENSYM)) { - if (gensymParamsCount >= body.statements.length) { - throw new Error(`Expected ${params[i].ident.name} replacement to original parameter`); - } - const declaration = body.statements[gensymParamsCount]; - if (!arkts.isVariableDeclaration(declaration)) { - throw new Error(`Expected ${params[i].ident.name} replacement to original parameter`); - } - if (!arkts.isIdentifier(declaration.declarators[0].name)) { - throw new Error(`Expected ${params[i].ident.name} replacement to original parameter`); - } - params[i].ident = declaration.declarators[0].name; - gensymParamsCount++; - } - } - return gensymParamsCount; -} - -export function isUnmemoizedInFunction(params?: readonly arkts.Expression[]): boolean { - const _params = params ?? []; - const first = _params.at(0); - const isContextAdded = - !!first && arkts.isEtsParameterExpression(first) && first.identifier.name === RuntimeNames.CONTEXT; - const second = _params.at(1); - const isIdAdded = !!second && arkts.isEtsParameterExpression(second) && second.identifier.name === RuntimeNames.ID; - return isContextAdded && isIdAdded; -} - -export function buildReturnTypeInfo( - returnType: arkts.TypeNode | undefined, - isMemo?: boolean, - isStableThis?: boolean -): ReturnTypeInfo { - const newReturnType = !!returnType - ? returnType.clone() - : arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID); - return { - node: newReturnType, - isMemo, - isVoid: isVoidType(newReturnType), - isStableThis, - }; -} - -export function buildeParamInfos(parameters: readonly arkts.ETSParameterExpression[]): ParamInfo[] { - return [ - ...parameters - .filter((it) => !hasMemoSkipAnnotation(it)) - .map((it) => { - return { ident: it.identifier, param: it }; - }), - ]; -} - -export function parametersBlockHasReceiver(params: readonly arkts.Expression[]): boolean { - return params.length > 0 && arkts.isEtsParameterExpression(params[0]) && isThisParam(params[0]); -} - -export function parametrizedNodeHasReceiver(node: arkts.ScriptFunction | arkts.ETSFunctionType | undefined): boolean { - if (node === undefined) { - return false; - } - return parametersBlockHasReceiver(node.params); -} - -function isThisParam(node: arkts.Expression | undefined): boolean { - if (node === undefined || !arkts.isEtsParameterExpression(node)) { - return false; - } - return node.identifier?.isReceiver ?? false; -} diff --git a/arkui-plugins/package.json b/arkui-plugins/package.json index 0267fb00d..20078aeb0 100644 --- a/arkui-plugins/package.json +++ b/arkui-plugins/package.json @@ -10,9 +10,7 @@ "local:install": "chmod 777 ./npm_preinstall.sh && ./npm_preinstall.sh --init", "compile:plugins": "./node_modules/.bin/babel . --out-dir lib --extensions .ts", "compile:clean": "rm -rf lib", - "clean:test": "rm -rf dist && rm -rf coverage", - "prepare:test": "cp -rf $INIT_CWD/../../../out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/koala-wrapper/build/native/ ../koala-wrapper/build/", - "test": "npm run clean:test && npm run prepare:test && LD_LIBRARY_PATH=$INIT_CWD/../../../out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/ets2panda/lib jest --coverage --logHeapUsage --config ./jest-test.config.js --silent", + "test": "jest --config ./jest-test.config.ts", "compile": "npm run compile:clean && npm run compile:plugins && cp -rf ./lib $INIT_CWD/../../../../out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/ui-plugins/" }, "devDependencies": { diff --git a/arkui-plugins/test/demo/interop/1.2State-1.1Link-example.ets b/arkui-plugins/test/demo/interop/1.2State-1.1Link-example.ets deleted file mode 100644 index f11af005f..000000000 --- a/arkui-plugins/test/demo/interop/1.2State-1.1Link-example.ets +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright (C) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -// ArkTS1.2 -import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" // should be insert by ui-plugins -import { ArkUICompatible, InteropComponent, Text, TextAttribute, Column, Component, Button, ButtonAttribute, ClickEvent, UserView, } from "@ohos.arkui.component" // TextAttribute should be insert by ui-plugins -import { State, StateDecoratedVariable, MutableState, stateOf, observableProxy, Observed, Track, Provide, Consume } from "@ohos.arkui.stateManagement" // should be insert by ui-plugins -import { MyText } from 'har2/src/main/ets/components/MainPage' -import { Child1 } from 'har1' - - -@Component -struct MyStateSample { - @State stateVar: new MyText(); - build() { - Column() { - Button(this.stateVar.text) - .onClick((e: ClickEvent) => { - this.stateVar.text += '~'; - }) - Child1({stateVar: this.stateVar, text: this.stateVar}) - } - } -} - -class MyText { - text: string = 'MyText'; -} - - -//ArkT1.1 -import { MyText } from 'har2/src/main/ets/components/MainPage' - -@Component -export struct Child1{ - @Link stateVar: MyText; - @Link text: MyText; - build() { - Column() { - Button(this.stateVar.text) - .onClick(() => { - this.stateVar.text += '~'; - }) - Button(this.text.text) - .onClick(() => { - this.text.text = 'ArkTS1.1'; - }) - } - } -} - - -//transform 1.1struct 'Child1' to ArkUICompatible - -ArkUICompatible(__memo_context, ((__memo_id) + (252133223)), (() => { - let global = ESValue.getGlobal(); - let param = ESValue.instantiateEmptyObject(); - let createState = global.getProperty("createStateVariable"); - let stateVar_SetSource = ((value: B) => { - (this).stateVar = value; - }); - let stateVar_ProxyState = createState.invoke(ESValue.wrap((this).stateVar), ESValue.wrap(stateVar_SetSource)); - (this).__backing_stateVar!.setProxy(stateVar_ProxyState); - let stateVar_SetProxy = ((value: B) => { - stateVar_ProxyState.invokeMethod("set", ESValue.wrap(value)); - }); - (this).__backing_stateVar!.setProxyValue = stateVar_SetProxy; - let stateVar_NotifyCallback = ((propertyName: string) => { - stateVar_ProxyState.invokeMethod("notifyPropertyHasChangedPU"); - }); - (this).__backing_stateVar!.setNotifyCallback(stateVar_NotifyCallback); - param.setProperty("stateVar", stateVar_ProxyState); - param.setProperty("text", stateVar_ProxyState); - let extraInfo = ESValue.instantiateEmptyObject(); - extraInfo.setProperty("page", "har1/src/main/ets/components/MainPage"); - let esundefined = ESValue.wrap(undefined); - let blank = (() => {}); - let esblank = ESValue.wrap((blank as object)); - let viewStackProcessor = global.getProperty("ViewStackProcessor"); - let createId = viewStackProcessor.getProperty("AllocateNewElmetIdForNextComponent"); - let elmtId = createId.invoke(); - let har1 = ESValue.load("@normalized:N&entry&com.example.Interop2use1&har1/src/main/ets/components/MainPage&1.0.0"); - let structObject = har1.getProperty("Child1"); - let component = structObject.instantiate(esundefined, param, esundefined, elmtId, esblank, extraInfo); - let create = structObject.getProperty("create"); - create.invoke(component); - return { - component: component, - name: "Child1", - }; -}), ((instance: ESValue) => {})); \ No newline at end of file diff --git a/arkui-plugins/test/demo/localtest/build_config_template.json b/arkui-plugins/test/demo/localtest/build_config_template.json index 3855891d1..aa3de2c82 100755 --- a/arkui-plugins/test/demo/localtest/build_config_template.json +++ b/arkui-plugins/test/demo/localtest/build_config_template.json @@ -1,6 +1,5 @@ { "plugins": { - "ui-syntax-plugin": "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/ui-plugins/lib/ui-syntax-plugins/index", "ui_plugin": "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/ui-plugins/lib/ui-plugins/index", "memo_plugin": "workspace/out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/ui-plugins/lib/memo-plugins/index" }, diff --git a/arkui-plugins/test/demo/localtest/entry/new.ets b/arkui-plugins/test/demo/localtest/entry/new.ets index acdb7c3c3..551759239 100755 --- a/arkui-plugins/test/demo/localtest/entry/new.ets +++ b/arkui-plugins/test/demo/localtest/entry/new.ets @@ -15,13 +15,9 @@ import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" // should be insert by ui-plugins import { Text, TextAttribute, Column, Component, Button, ButtonAttribute, ClickEvent, UserView } from "@ohos.arkui.component" // TextAttribute should be insert by ui-plugins -import { State, Link, StateDecoratedVariable, LinkDecoratedVariable,MutableState, stateOf, observableProxy } from "@ohos.arkui.stateManagement" // should be insert by ui-plugins +import { State, Link, StateDecoratedVariable, LinkDecoratedVariable,MutableState, stateOf, observableProxy, DecoratedMutableVariable } from "@ohos.arkui.stateManagement" // should be insert by ui-plugins import hilog from '@ohos.hilog' -function ArkUICompatible(init:(elmtId: number, instance: ESObject) => void, update: ((elmtId: number, instance: ESObject) => void)) { - -} - @Component struct MyStateSample { @State stateVar: string = "Parent"; @@ -42,6 +38,7 @@ struct MyStateSample { } } + @Component struct ChildLink { @Link stateVar: string = "Child"; diff --git a/arkui-plugins/test/demo/mock/animation/animation-basic.ets b/arkui-plugins/test/demo/mock/animation/animation-basic.ets deleted file mode 100644 index 35c26e459..000000000 --- a/arkui-plugins/test/demo/mock/animation/animation-basic.ets +++ /dev/null @@ -1,17 +0,0 @@ -import { Text, Column, Component, Color, Curve } from "@ohos.arkui.component" -import { Entry } from "@ohos.arkui.component" - -@Entry -@Component -struct AnimatablePropertyExample { - build() { - Column() { - Text("AnimatableProperty") - .backgroundColor(Color.Red) - .animation({ duration: 2000, curve: Curve.Ease }) - .fontSize(20) - .animation({ duration: 2000, curve: Curve.Ease }) - .width("100%") - } - } -} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/builder-lambda/custom-component/custom-component-call.ets b/arkui-plugins/test/demo/mock/builder-lambda/custom-component/custom-component-call.ets deleted file mode 100644 index 4da86661b..000000000 --- a/arkui-plugins/test/demo/mock/builder-lambda/custom-component/custom-component-call.ets +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (C) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { Text, Column, Component, Builder, BuilderParam } from "@ohos.arkui.component" - -@Component -struct CustomContainer { - @Builder closerBuilder(){}; - @BuilderParam closer: () => void = this.closerBuilder; - - build() {} -} - -@Component -struct CustomContainerUser { - - build() { - Column() { - CustomContainer() { - Column() { - Text('hello') - } - } - CustomContainer({}) { - Column() {} - } - CustomContainer(undefined) {} - CustomContainer() - } - } -} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/builder-lambda/simple-component.ets b/arkui-plugins/test/demo/mock/builder-lambda/simple-component.ets deleted file mode 100644 index 4f0f3b5cf..000000000 --- a/arkui-plugins/test/demo/mock/builder-lambda/simple-component.ets +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" -import { Column, UIColumnAttribute } from "arkui.component.column" - -class MyStateSample { - @memo build() { - Column(undefined) {} - } -} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/builder-lambda/style-with-receiver.ets b/arkui-plugins/test/demo/mock/builder-lambda/style-with-receiver.ets deleted file mode 100644 index 92d842ff5..000000000 --- a/arkui-plugins/test/demo/mock/builder-lambda/style-with-receiver.ets +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { memo } from "@ohos.arkui.stateManagement" // should be insert by ui-plugins -import { Text, UITextAttribute, Column, Component} from "@ohos.arkui.component" -import hilog from '@ohos.hilog' - -@memo function cardStyle(this: UITextAttribute, num: number, str: string): this { - this.fontSize(num); - this.backgroundColor(num); - return this; -} - -@memo function style22(this: UITextAttribute): this { - this.fontWeight(700); - return this; -} - -@Component -struct MM { - build() { - Column() { - Text('hello world') - .height(200) - .fontColor('#000000') - .cardStyle(600, '#eeeeee') - .fontSize(60) - .fontWeight(400) - .style22() - .width(900) - Text('hello world') - .cardStyle(600, '#eeeeee') - } - } -} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/decorators/builder-param/builder-param-passing.ets b/arkui-plugins/test/demo/mock/decorators/builder-param/builder-param-passing.ets deleted file mode 100644 index c679899b2..000000000 --- a/arkui-plugins/test/demo/mock/decorators/builder-param/builder-param-passing.ets +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (C) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { Component, Entry, Builder, BuilderParam, Column, Text } from "@ohos.arkui.component" - -@Component -struct Child { - @Builder customBuilder() {}; - @BuilderParam customBuilderParam: () => void = this.customBuilder; - - build() { - this.customBuilderParam() - } -} - -@Component -struct Parent { - @Builder componentBuilder() { - Text('Parent builder') - } - - build() { - Column() { - Child({ customBuilderParam: this.componentBuilder }) - Child({ customBuilderParam: () => { this.componentBuilder() } }) - Child() { Text('Parent builder') } - } - } -} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/decorators/builder-param/init-with-local-builder.ets b/arkui-plugins/test/demo/mock/decorators/builder-param/init-with-local-builder.ets deleted file mode 100644 index e1e2b46c9..000000000 --- a/arkui-plugins/test/demo/mock/decorators/builder-param/init-with-local-builder.ets +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (C) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { Component, Builder, BuilderParam } from "@ohos.arkui.component" - -@Component -struct Child { - @Builder doNothingBuilder() {}; - @Builder doNothingBuilder2(str: string) {}; - @BuilderParam customBuilderParam: () => void = this.doNothingBuilder; - @BuilderParam customBuilderParam2: (str: string) => void = this.doNothingBuilder2; - - build(){ - this.customBuilderParam() - this.customBuilderParam2('hello') - } -} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/decorators/builder/global-builder.ets b/arkui-plugins/test/demo/mock/decorators/builder/global-builder.ets deleted file mode 100644 index bba1e6ee0..000000000 --- a/arkui-plugins/test/demo/mock/decorators/builder/global-builder.ets +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (C) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { Component, Row, Builder, Text } from "@ohos.arkui.component" - -@Builder -function showTextBuilder() { - Text('Hello World') -} - -class Tmp { - paramA1: string = ''; -} - -@Builder function overBuilder(params: Tmp) { - Row() { - Text('UseStateVarByReference: ' + params.paramA1) - } -} - -@Component -struct BuilderDemo { - build() { - Row() { - showTextBuilder() - overBuilder({ paramA1: 'Hello' }) - } - } -} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/decorators/builder/local-builder.ets b/arkui-plugins/test/demo/mock/decorators/builder/local-builder.ets deleted file mode 100644 index 01da4671a..000000000 --- a/arkui-plugins/test/demo/mock/decorators/builder/local-builder.ets +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (C) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { Component, Column, Builder, Text } from "@ohos.arkui.component" - -@Component -struct BuilderDemo { - @Builder - showTextBuilder() { - Text('Hello World') - .fontSize(30) - } - @Builder - showTextValueBuilder(param: string) { - Text(param) - .fontSize(30) - } - build() { - Column() { - this.showTextBuilder() - this.showTextValueBuilder('Hello @Builder') - } - } -} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/decorators/link/link-basic-type.ets b/arkui-plugins/test/demo/mock/decorators/link/link-basic-type.ets deleted file mode 100644 index 9c97005bc..000000000 --- a/arkui-plugins/test/demo/mock/decorators/link/link-basic-type.ets +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (C) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { Component } from "@ohos.arkui.component" -import { Link } from "@ohos.arkui.stateManagement" - -@Component -struct LinkParent { - @Link linkVar1: string; - @Link linkVar2: number; - @Link linkVar3: boolean; - @Link linkVar4: undefined; - @Link linkVar5: null; - - build() { - } -} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/decorators/link/link-complex-type.ets b/arkui-plugins/test/demo/mock/decorators/link/link-complex-type.ets deleted file mode 100644 index 512968ab3..000000000 --- a/arkui-plugins/test/demo/mock/decorators/link/link-complex-type.ets +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (C) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { Component } from "@ohos.arkui.component" -import { Link } from "@ohos.arkui.stateManagement" - -class Per { - num: number; - constructor(num: number) { - this.num = num; - } -} - -enum LinkType { - TYPE1 = 0, - TYPE2 = 1, - TYPE3 = 3 -} - -@Component -struct Parent { - @Link linkVar1: Per; - @Link linkVar2: Array; - @Link linkVar3: LinkType; - @Link linkVar4: Set; - @Link linkVar5: boolean[]; - @Link linkVar6: Array; - @Link linkVar7: Per[]; - @Link linkVar8: (sr: string)=>void; - @Link linkVar9: Date; - @Link linkVar10: Map; - @Link linkVar11: string | number; - @Link linkVar12: Set | Per; - - build() { - } -} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/decorators/link/link-to-link-prop-state.ets b/arkui-plugins/test/demo/mock/decorators/link/link-to-link-prop-state.ets deleted file mode 100644 index b04d84e93..000000000 --- a/arkui-plugins/test/demo/mock/decorators/link/link-to-link-prop-state.ets +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (C) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { Component, Column, TextInput } from "@ohos.arkui.component" -import { Link, State, Prop } from "@ohos.arkui.stateManagement" - -@Component -struct Parant { - @Link text1: string; - - build() { - Column() { - TextInput({ text: this.text1 }) - Child({ childText: this.text1, childText2: this.text1, childText3: this.text1, childText4: this.text1 }) - } - } -} - -@Component -struct Child { - @Link childText: string; - @State childText2: string = 'sss'; - @Prop childText3: string; - @Prop childText4: string = 'cc'; - - build() { - TextInput({ text: this.childText }) - } -} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/decorators/link/state-to-link.ets b/arkui-plugins/test/demo/mock/decorators/link/state-to-link.ets deleted file mode 100644 index a3e02b8b7..000000000 --- a/arkui-plugins/test/demo/mock/decorators/link/state-to-link.ets +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (C) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { Component, Entry, Column, Button, DatePicker, ClickEvent } from "@ohos.arkui.component" -import { Link, State } from "@ohos.arkui.stateManagement" - -@Component -struct DateComponent { - @Link selectedDate: Date; - - build() { - Column() { - Button('child increase the year by 1') - .onClick((e: ClickEvent) => { - this.selectedDate.setFullYear(this.selectedDate.getFullYear() + 1); - }) - Button('child update the new date') - .margin(10) - .onClick((e: ClickEvent) => { - this.selectedDate = new Date('2023-09-09'); - }) - DatePicker({ - start: new Date('1970-1-1'), - end: new Date('2100-1-1'), - selected: this.selectedDate - }) - } - - } -} - -@Entry -@Component -struct ParentComponent { - @State parentSelectedDate: Date = new Date('2021-08-08'); - - build() { - Column() { - Button('parent increase the month by 1') - .margin(10) - .onClick((e: ClickEvent) => { - this.parentSelectedDate.setMonth(this.parentSelectedDate.getMonth() + 1); - }) - Button('parent update the new date') - .margin(10) - .onClick((e: ClickEvent) => { - this.parentSelectedDate = new Date('2023-07-07'); - }) - DatePicker({ - start: new Date('1970-1-1'), - end: new Date('2100-1-1'), - selected: this.parentSelectedDate - }) - - DateComponent({ selectedDate:this.parentSelectedDate }) - } - } -} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/decorators/objectlink/objectlink-basic.ets b/arkui-plugins/test/demo/mock/decorators/objectlink/objectlink-basic.ets deleted file mode 100644 index 273a00f46..000000000 --- a/arkui-plugins/test/demo/mock/decorators/objectlink/objectlink-basic.ets +++ /dev/null @@ -1,13 +0,0 @@ -import { Component } from "@ohos.arkui.component" -import { Observed, ObjectLink } from "@ohos.arkui.stateManagement" - -@Observed -class A {} - -@Component -struct MyStateSample { - - @ObjectLink objectlinkvar: A; - - build() {} -} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/decorators/objectlink/objectlink-observed.ets b/arkui-plugins/test/demo/mock/decorators/objectlink/objectlink-observed.ets deleted file mode 100644 index 54dc8f89b..000000000 --- a/arkui-plugins/test/demo/mock/decorators/objectlink/objectlink-observed.ets +++ /dev/null @@ -1,54 +0,0 @@ -import { Component, Entry, Column, Button, ClickEvent } from "@ohos.arkui.component" -import { State, ObjectLink, Observed } from "@ohos.arkui.stateManagement" - -@Observed -class DateClass extends Date { - constructor(args: number | string) { - super(args); - } -} - -@Observed -class NewDate { - public data: DateClass; - - constructor(data: DateClass) { - this.data = data; - } -} - -@Component -struct Child { - label: string = 'date'; - @ObjectLink data: DateClass; - - build() { - Column() { - Button(`child increase the day by 1`) - .onClick((e: ClickEvent) => { - this.data.setDate(this.data.getDate() + 1); - }) - } - } -} - -@Entry -@Component -struct Parent { - @State newData: NewDate = new NewDate(new DateClass('2023-1-1')); - - build() { - Column() { - Child({ label: 'date', data: this.newData.data }) - - Button(`parent update the new date`) - .onClick(() => { - this.newData.data = new DateClass('2023-07-07'); - }) - Button(`ViewB: this.newData = new NewDate(new DateClass('2023-08-20'))`) - .onClick(() => { - this.newData = new NewDate(new DateClass('2023-08-20')); - }) - } - } -} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/decorators/observed-track/observed-only.ets b/arkui-plugins/test/demo/mock/decorators/observed-track/observed-only.ets deleted file mode 100644 index 3890ea9ec..000000000 --- a/arkui-plugins/test/demo/mock/decorators/observed-track/observed-only.ets +++ /dev/null @@ -1,13 +0,0 @@ -import { Component } from "@ohos.arkui.component" -import { Observed } from "@ohos.arkui.stateManagement" - -@Observed -class A { - propA: number = 1 - trackA: number = 2 -} - -@Component -struct MyStateSample { - build() {} -} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/decorators/observed-track/observed-track-class-property.ets b/arkui-plugins/test/demo/mock/decorators/observed-track/observed-track-class-property.ets deleted file mode 100644 index 48a3cd405..000000000 --- a/arkui-plugins/test/demo/mock/decorators/observed-track/observed-track-class-property.ets +++ /dev/null @@ -1,19 +0,0 @@ -import { Component } from "@ohos.arkui.component" -import { Observed, Track } from "@ohos.arkui.stateManagement" - -class Info{} -class E { - propE: Info = new Info() - @Track trackE: Info = new Info() -} - -@Observed -class E1 { - propE1: Info = new Info() - trackE1: Info = new Info() -} - -@Component -struct MyStateSample { - build() {} -} diff --git a/arkui-plugins/test/demo/mock/decorators/observed-track/observed-track-complex-type.ets b/arkui-plugins/test/demo/mock/decorators/observed-track/observed-track-complex-type.ets deleted file mode 100644 index bf59d6d51..000000000 --- a/arkui-plugins/test/demo/mock/decorators/observed-track/observed-track-complex-type.ets +++ /dev/null @@ -1,76 +0,0 @@ -import { Component, Entry } from "@ohos.arkui.component" -import { Observed, Track } from "@ohos.arkui.stateManagement" - -class Person{ -} - -enum Status { - Success = 200, - NotFound = 404, - ServerError = 500 -} - -@Observed -class mixed1 { - @Track numA: number = 33; - @Track stringA: string = 'AA'; - @Track booleanA: boolean = true; - @Track arrayA: number[] = [1,2,3]; - @Track objectA: Object = {}; - @Track dateA: Date = new Date('2021-08-08'); - @Track setA: Set = new Set(); - @Track mapA: Map = new Map(); - @Track unionA: string | undefined = ""; - @Track classA: Person = new Person(); - @Track enumA: Status = Status.NotFound; - - numB: number = 33; - stringB: string = 'AA'; - booleanB: boolean = true; - arrayB: number[] = [1,2,3]; - objectB: Object = {}; - dateB: Date = new Date('2021-08-08'); - setB: Set = new Set(); - mapB: Map = new Map(); - unionB: string | undefined = ""; - classB: Person = new Person(); - enumB: Status = Status.NotFound; -} - -@Observed -class mixed2 { - numA: number = 33; - stringA: string = 'AA'; - booleanA: boolean = true; - arrayA: number[] = [1,2,3]; - objectA: Object = {}; - dateA: Date = new Date('2021-08-08'); - setA: Set = new Set(); - mapA: Map = new Map(); - unionA: string | undefined = ""; - classA: Person = new Person(); - enumA: Status = Status.NotFound; -} - -class mixed3 { - @Track numA: number = 33; - @Track stringA: string = 'AA'; - @Track booleanA: boolean = true; - @Track arrayA: number[] = [1,2,3]; - @Track objectA: Object = {}; - @Track dateA: Date = new Date('2021-08-08'); - @Track setA: Set = new Set(); - @Track mapA: Map = new Map(); - @Track unionA: string | undefined = ""; - @Track classA: Person = new Person(); - @Track enumA: Status = Status.NotFound; -} - - -@Entry -@Component -struct MyStateSample { - build() { - - } -} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/decorators/observed-track/observed-track-extends.ets b/arkui-plugins/test/demo/mock/decorators/observed-track/observed-track-extends.ets deleted file mode 100644 index 66135926a..000000000 --- a/arkui-plugins/test/demo/mock/decorators/observed-track/observed-track-extends.ets +++ /dev/null @@ -1,23 +0,0 @@ -import { Component } from "@ohos.arkui.component" -import { Observed, Track } from "@ohos.arkui.stateManagement" - -@Observed -class A { - propA: number = 1 - trackA: number = 2 -} - - -class G extends A { - propG: number = 1; -} - -@Observed -class H extends G { - @Track propG: number = 1; -} - -@Component -struct MyStateSample { - build() {} -} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/decorators/observed-track/observed-track-implements.ets b/arkui-plugins/test/demo/mock/decorators/observed-track/observed-track-implements.ets deleted file mode 100644 index 5be8bd871..000000000 --- a/arkui-plugins/test/demo/mock/decorators/observed-track/observed-track-implements.ets +++ /dev/null @@ -1,20 +0,0 @@ -import { Component } from "@ohos.arkui.component" -import { Observed } from "@ohos.arkui.stateManagement" - interface PropInterface { - propF: number -} - -interface trackInterface { - trackF: number -} - -@Observed -class F implements PropInterface, trackInterface { - propF: number = 1 - trackF: number = 2 -} - -@Component -struct MyStateSample { - build() {} -} diff --git a/arkui-plugins/test/demo/mock/decorators/observed-track/observed-track.ets b/arkui-plugins/test/demo/mock/decorators/observed-track/observed-track.ets deleted file mode 100644 index 3d15c071a..000000000 --- a/arkui-plugins/test/demo/mock/decorators/observed-track/observed-track.ets +++ /dev/null @@ -1,13 +0,0 @@ -import { Component } from "@ohos.arkui.component" -import { Observed, Track } from "@ohos.arkui.stateManagement" - -@Observed -class B { - propB: number = 1 - @Track trackB: number = 2 -} - -@Component -struct MyStateSample { - build() {} -} diff --git a/arkui-plugins/test/demo/mock/decorators/observed-track/track-only.ets b/arkui-plugins/test/demo/mock/decorators/observed-track/track-only.ets deleted file mode 100644 index fea1df86e..000000000 --- a/arkui-plugins/test/demo/mock/decorators/observed-track/track-only.ets +++ /dev/null @@ -1,12 +0,0 @@ -import { Component } from "@ohos.arkui.component" -import { Track } from "@ohos.arkui.stateManagement" - -class C { - propC: number = 1 - @Track trackC: number = 2 -} - -@Component -struct MyStateSample { - build() {} -} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/decorators/prop/prop-basic-type.ets b/arkui-plugins/test/demo/mock/decorators/prop/prop-basic-type.ets deleted file mode 100644 index bcfff2d58..000000000 --- a/arkui-plugins/test/demo/mock/decorators/prop/prop-basic-type.ets +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (C) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { Component } from "@ohos.arkui.component" -import { Prop } from "@ohos.arkui.stateManagement" - -@Component -struct PropParent { - @Prop propVar1: string = 'propVar1'; - @Prop propVar2: number = 50; - @Prop propVar3: boolean = true; - @Prop propVar4: undefined = undefined; - @Prop propVar5: null = null; - - build() { - } -} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/decorators/prop/prop-complex-type.ets b/arkui-plugins/test/demo/mock/decorators/prop/prop-complex-type.ets deleted file mode 100644 index a2fbdc9d2..000000000 --- a/arkui-plugins/test/demo/mock/decorators/prop/prop-complex-type.ets +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (C) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { Component } from "@ohos.arkui.component" -import { Prop } from "@ohos.arkui.stateManagement" - -class Per { - num: number; - constructor(num: number) { - this.num = num; - } -} - -enum PropType { - TYPE1 = 0, - TYPE2 = 1, - TYPE3 = 3 -} - -@Component -struct Parent { - @Prop propVar1: Per = new Per(6); - @Prop propVar2: Array = new Array(3,6,8); - @Prop propVar3: PropType = PropType.TYPE3; - @Prop propVar4: Set = new Set(new Array('aa', 'bb')); - @Prop propVar5: boolean[] = [true, false]; - @Prop propVar6: Array = new Array(new Per(7), new Per(11)); - @Prop propVar7: Per[] = [new Per(7), new Per(11)]; - @Prop propVar8: (sr: string)=>void = (sr: string)=>{}; - @Prop propVar9: Date = new Date('2025-4-23'); - @Prop propVar10: Map = new Map([[0, new Per(7)], [1, new Per(10)]]); - @Prop propVar11: string | number = 0.0; - @Prop propVar12: Set | Per = new Per(6); - - build() { - } -} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/decorators/prop/state-to-prop.ets b/arkui-plugins/test/demo/mock/decorators/prop/state-to-prop.ets deleted file mode 100644 index 38af709df..000000000 --- a/arkui-plugins/test/demo/mock/decorators/prop/state-to-prop.ets +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (C) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { Component, Text, Button, Column, ClickEvent } from "@ohos.arkui.component" -import { Prop, State } from "@ohos.arkui.stateManagement" - -@Component -struct CountDownComponent { - @Prop count: number = 0; - costOfOneAttempt: number = 1; - - build() { - Column() { - if (this.count > 0) { - Text('You have'+ this.count + 'Nuggets left') - } else { - Text('Game over!') - } - Button('Try again').onClick((e: ClickEvent) => { - this.count -= this.costOfOneAttempt; - }) - } - } -} - -@Component -struct ParentComponent { - @State countDownStartValue: number = 10; - - build() { - Column() { - Text('Grant' + this.countDownStartValue + 'nuggets to play.') - Button('+1 - Nuggets in New Game').onClick((e: ClickEvent) => { - this.countDownStartValue += 1; - }) - Button('-1 - Nuggets in New Game').onClick((e: ClickEvent) => { - this.countDownStartValue -= 1; - }) - CountDownComponent({ count: this.countDownStartValue, costOfOneAttempt: 2 }) - } - } -} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/decorators/provide-and-consume/provide-annotation-usage.ets b/arkui-plugins/test/demo/mock/decorators/provide-and-consume/provide-annotation-usage.ets deleted file mode 100644 index 74afaf8f9..000000000 --- a/arkui-plugins/test/demo/mock/decorators/provide-and-consume/provide-annotation-usage.ets +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (C) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { Component } from "@ohos.arkui.component" -import { Provide } from "@ohos.arkui.stateManagement" - -@Component -struct Ancestors { - @Provide count: string | undefined = 'Child0'; - @Provide({ alias: 'prov1' }) count1: string | undefined = 'Child1'; - @Provide({ alias: 'prov2', allowOverride: false }) count2: string | undefined = 'Child2'; - @Provide({ alias: 'prov3', allowOverride: true }) count3: string | undefined = 'Child3'; - @Provide({ allowOverride: false }) count4: string | undefined = 'Child4'; - @Provide({ allowOverride: true }) count5: string | undefined = 'Child5'; - @Provide({ alias: "", allowOverride: true }) count6: string | undefined = 'Child6'; - @Provide({ alias: "" }) count7: string | undefined = 'Child7'; - - build() { - } -} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/decorators/provide-and-consume/provide-basic-type.ets b/arkui-plugins/test/demo/mock/decorators/provide-and-consume/provide-basic-type.ets deleted file mode 100644 index 06c9ddea3..000000000 --- a/arkui-plugins/test/demo/mock/decorators/provide-and-consume/provide-basic-type.ets +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (C) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { Component } from "@ohos.arkui.component" -import { Provide } from "@ohos.arkui.stateManagement" - -@Component -struct PropParent { - @Provide provideVar1: string = 'propVar1'; - @Provide provideVar2: number = 50; - @Provide provideVar3: boolean = true; - @Provide provideVar4: undefined = undefined; - @Provide provideVar5: null = null; - - build() { - } -} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/decorators/provide-and-consume/provide-complex-type.ets b/arkui-plugins/test/demo/mock/decorators/provide-and-consume/provide-complex-type.ets deleted file mode 100644 index 6395a981b..000000000 --- a/arkui-plugins/test/demo/mock/decorators/provide-and-consume/provide-complex-type.ets +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (C) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { Component } from "@ohos.arkui.component" -import { Provide } from "@ohos.arkui.stateManagement" - -class Per { - num: number; - constructor(num: number) { - this.num = num; - } -} - -enum PropType { - TYPE1 = 0, - TYPE2 = 1, - TYPE3 = 3 -} - -@Component -struct Parent { - @Provide provideVar1: Per = new Per(6); - @Provide provideVar2: Array = new Array(3,6,8); - @Provide provideVar3: PropType = PropType.TYPE3; - @Provide provideVar4: Set = new Set(new Array('aa', 'bb')); - @Provide provideVar5: boolean[] = [true, false]; - @Provide provideVar6: Array = new Array(new Per(7), new Per(11)); - @Provide provideVar7: Per[] = [new Per(7), new Per(11)]; - @Provide provideVar8: (sr: string)=>void = (sr: string)=>{}; - @Provide provideVar9: Date = new Date('2025-4-23'); - @Provide provideVar10: Map = new Map([[0, new Per(7)], [1, new Per(10)]]); - @Provide provideVar11: string | number = 0.0; - @Provide provideVar12: Set | Per = new Per(6); - - build() { - } -} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/decorators/resource/resource-in-build.ets b/arkui-plugins/test/demo/mock/decorators/resource/resource-in-build.ets deleted file mode 100644 index 49331e647..000000000 --- a/arkui-plugins/test/demo/mock/decorators/resource/resource-in-build.ets +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (C) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { Component, $r, $rawfile, Column, Text, Image, TextInput, Select, SelectOption, Margin, ImageAnimator } from "@ohos.arkui.component" - -@Component -struct ResourceComponent { - str1: string = 'app.media.ri' - str2: string = 'app.photo2.png' - build() { - Column() { - Text($r('app.string.app_name')) - Image($rawfile('app.photo.png')) - TextInput({ text: $r('app.string.input_content') }) - Text($r(this.str1)) - Text($r(this.str2)) - Select(new Array( - { value: 'aaa', icon: $r("app.media.selection") }, - { value: 'bbb', icon: $r("app.media.selection") }, - { value: 'ccc', icon: $r("app.media.selection") }, - { value: 'ddd', icon: $r("app.media.selection") } - )) - Image($r('app.media.app_icon')) - .margin({ - top: $r('app.float.elements_margin_horizontal_m'), - bottom: $r('app.float.elements_margin_horizontal_l') - } as Margin) - ImageAnimator().images([ - { - src: $r('app.media.aaa') - }, - { - src: $r('app.media.bbb') - }, - ]) - } - } -} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/decorators/resource/resource-in-property.ets b/arkui-plugins/test/demo/mock/decorators/resource/resource-in-property.ets deleted file mode 100644 index 591311c7d..000000000 --- a/arkui-plugins/test/demo/mock/decorators/resource/resource-in-property.ets +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (C) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { Component, $r, $rawfile, Column, Text, Image, Resource } from "@ohos.arkui.component" - -let i: Resource = $r('app.string.app_name'); - -@Component -struct ResourceComponent { - private str: Resource = $r('app.string.app_name'); - private icon: Resource = $rawfile('app.photo.png'); - build() { - Column() { - Text(this.str) - Text(i) - Image(this.icon) - } - } -} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/decorators/reusable/reusable-basic.ets b/arkui-plugins/test/demo/mock/decorators/reusable/reusable-basic.ets deleted file mode 100644 index 755a647b3..000000000 --- a/arkui-plugins/test/demo/mock/decorators/reusable/reusable-basic.ets +++ /dev/null @@ -1,19 +0,0 @@ -import { Component, Reusable} from "@ohos.arkui.component" -import { State, Link } from "@ohos.arkui.stateManagement" - -@Component -struct MyStateSample { - build() { - Child({ num: 5 } ) - } -} - -@Component -@Reusable -struct Child { - @Link num: number = 1 - @State num1: number = 2 - build() { - - } -} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/decorators/reusable/reusable-complex.ets b/arkui-plugins/test/demo/mock/decorators/reusable/reusable-complex.ets deleted file mode 100644 index d66fe5451..000000000 --- a/arkui-plugins/test/demo/mock/decorators/reusable/reusable-complex.ets +++ /dev/null @@ -1,53 +0,0 @@ -import { Component, Entry, Reusable, Column, Text, Button, ClickEvent, FontWeight} from "@ohos.arkui.component" -import { State } from "@ohos.arkui.stateManagement" - -class Message { - value: string | undefined; - - constructor(value: string) { - this.value = value; - } -} - -@Entry -@Component -struct Index { - @State display: boolean = true; - - build() { - Column() { - Button('Hello') - .fontSize(30) - .fontWeight(FontWeight.Bold) - .onClick((e: ClickEvent) => { - this.display = !this.display; - }) - if (this.display) { - // 如果只有一个复用的组件,可以不用设置reuseId - Child({ message: new Message('Child') }) - } - } - .height("100%") - .width('100%') - } -} - -@Reusable -@Component -struct Child { - @State message: Message = new Message('AboutToReuse'); - - aboutToReuse(params: Record) { - console.info("Recycle ====Child=="); - //this.message = params.message as Message; - } - - build() { - Column() { - Text(this.message.value) - .fontSize(30) - } - .borderWidth(1) - .height(100) - } -} diff --git a/arkui-plugins/test/demo/mock/decorators/state/state-basic-type.ets b/arkui-plugins/test/demo/mock/decorators/state/state-basic-type.ets deleted file mode 100644 index b7e039a77..000000000 --- a/arkui-plugins/test/demo/mock/decorators/state/state-basic-type.ets +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (C) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { Component } from "@ohos.arkui.component" -import { State} from "@ohos.arkui.stateManagement" - -@Component -struct Parent { - @State stateVar1: string = 'stateVar1'; - @State stateVar2: number = 50; - @State stateVar3: boolean = true; - @State stateVar4: undefined = undefined; - @State stateVar5: null = null; - - build() { - } -} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/decorators/state/state-complex-type.ets b/arkui-plugins/test/demo/mock/decorators/state/state-complex-type.ets deleted file mode 100644 index 5ffe6f50a..000000000 --- a/arkui-plugins/test/demo/mock/decorators/state/state-complex-type.ets +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (C) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { Component } from "@ohos.arkui.component" -import { State} from "@ohos.arkui.stateManagement" - -class Per { - num: number; - constructor(num: number) { - this.num = num; - } -} - -enum StateType { - TYPE1 = 0, - TYPE2 = 1, - TYPE3 = 3 -} - -@Component -struct Parent { - @State stateVar1: Per = new Per(6); - @State stateVar2: Array = new Array(3,6,8); - @State stateVar3: StateType = StateType.TYPE3; - @State stateVar4: Set = new Set(new Array('aa', 'bb')); - @State stateVar5: boolean[] = [true, false]; - @State stateVar6: Array = new Array(new Per(7), new Per(11)); - @State stateVar7: Per[] = [new Per(7), new Per(11)]; - @State stateVar8: (sr: string)=>void = (sr: string)=>{}; - @State stateVar9: Date = new Date('2025-4-23'); - @State stateVar10: Map = new Map([[0, new Per(7)], [1, new Per(10)]]); - @State stateVar11: string | number = 0.0; - @State stateVar12: Set | Per = new Per(6); - - build() { - } -} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/decorators/state/state-to-state.ets b/arkui-plugins/test/demo/mock/decorators/state/state-to-state.ets deleted file mode 100644 index 8beb2e452..000000000 --- a/arkui-plugins/test/demo/mock/decorators/state/state-to-state.ets +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (C) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { Component, Column, Text } from "@ohos.arkui.component" -import { State } from "@ohos.arkui.stateManagement" - -class Per { - str: string; - constructor(str: string) { - this.str = str; - } -} - -@Component -struct Parent { - @State parentVar1: Per = new Per('hello'); - build() { - Column() { - Child({ childVar1: this.parentVar1 }) - } - } -} - -@Component -struct Child { - @State childVar1: Per = new Per('ccc'); - build() { - Text(this.childVar1.str) - } -} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/decorators/storagelink/storagelink-appstorage.ets b/arkui-plugins/test/demo/mock/decorators/storagelink/storagelink-appstorage.ets deleted file mode 100644 index 298dc8955..000000000 --- a/arkui-plugins/test/demo/mock/decorators/storagelink/storagelink-appstorage.ets +++ /dev/null @@ -1,35 +0,0 @@ -import { Component, Entry, Column, Text, ClickEvent } from "@ohos.arkui.component" -import { StorageLink, AppStorage } from "@ohos.arkui.stateManagement" - -class Data { - code: number; - - constructor(code: number) { - this.code = code; - } -} - -AppStorage.setOrCreate('PropA', 47); -AppStorage.setOrCreate('PropB', new Data(50)); - - -@Entry -@Component -struct Index { - @StorageLink('PropA') storageLink: number = 1; - @StorageLink('PropB') storageLinkObject: Data = new Data(1); - - build() { - Column() { - Text(`From AppStorage ${this.storageLink}`) - .onClick((e: ClickEvent) => { - this.storageLink += 1; - }) - - Text(`From AppStorage ${this.storageLinkObject.code}`) - .onClick((e: ClickEvent) => { - this.storageLinkObject.code += 1; - }) - } - } -} diff --git a/arkui-plugins/test/demo/mock/decorators/storagelink/storagelink-complex-type.ets b/arkui-plugins/test/demo/mock/decorators/storagelink/storagelink-complex-type.ets deleted file mode 100644 index 9aed6364d..000000000 --- a/arkui-plugins/test/demo/mock/decorators/storagelink/storagelink-complex-type.ets +++ /dev/null @@ -1,28 +0,0 @@ -import { Component, Entry } from "@ohos.arkui.component" -import { StorageLink } from "@ohos.arkui.stateManagement" - -class Person{ - name: string = '' - constructor(name: string){} -} - -enum Status { - Success = 200, - NotFound = 404, - ServerError = 500 -} - -@Entry -@Component -struct MyStateSample { - @StorageLink('Prop1') arrayA: number[] = [1,2,3]; - @StorageLink('Prop2') objectA: Object = {}; - @StorageLink('Prop3') dateA: Date = new Date('2021-08-08'); - @StorageLink('Prop4') setA: Set = new Set(); - @StorageLink('Prop5') mapA: Map = new Map(); - @StorageLink('Prop6') unionA: string | undefined = ""; - @StorageLink('Prop7') classA: Person = new Person("John"); - @StorageLink('Prop8') enumA: Status = Status.NotFound; - - build() {} -} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/decorators/storagelink/storagelink-primitive-type.ets b/arkui-plugins/test/demo/mock/decorators/storagelink/storagelink-primitive-type.ets deleted file mode 100644 index e5afb4d19..000000000 --- a/arkui-plugins/test/demo/mock/decorators/storagelink/storagelink-primitive-type.ets +++ /dev/null @@ -1,12 +0,0 @@ -import { Component, Entry } from "@ohos.arkui.component" -import { StorageLink } from "@ohos.arkui.stateManagement" - -@Entry -@Component -struct MyStateSample { - @StorageLink('Prop1') numA: number = 33; - @StorageLink('Prop2') stringA: string = 'AA'; - @StorageLink('Prop3') booleanA: boolean = true; - - build() {} -} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/decorators/storageprop/storageprop-appstorage.ets b/arkui-plugins/test/demo/mock/decorators/storageprop/storageprop-appstorage.ets deleted file mode 100644 index bff353a17..000000000 --- a/arkui-plugins/test/demo/mock/decorators/storageprop/storageprop-appstorage.ets +++ /dev/null @@ -1,34 +0,0 @@ -import { Component, Entry, Column, Text, ClickEvent } from "@ohos.arkui.component" -import { StorageProp, AppStorage } from "@ohos.arkui.stateManagement" - -class Data { - code: number; - - constructor(code: number) { - this.code = code; - } -} - -AppStorage.setOrCreate('PropA', 47); -AppStorage.setOrCreate('PropB', new Data(50)); - -@Entry -@Component -struct Index { - @StorageProp('PropA') storageProp: number = 1; - @StorageProp('PropB') storagePropObject: Data = new Data(1); - - build() { - Column() { - Text(`From AppStorage ${this.storageProp}`) - .onClick((e: ClickEvent) => { - this.storageProp += 1; - }) - - Text(`From AppStorage ${this.storagePropObject.code}`) - .onClick((e: ClickEvent) => { - this.storagePropObject.code += 1; - }) - } - } -} diff --git a/arkui-plugins/test/demo/mock/decorators/storageprop/storageprop-complex-type.ets b/arkui-plugins/test/demo/mock/decorators/storageprop/storageprop-complex-type.ets deleted file mode 100644 index 5a770cf6e..000000000 --- a/arkui-plugins/test/demo/mock/decorators/storageprop/storageprop-complex-type.ets +++ /dev/null @@ -1,28 +0,0 @@ -import { Component, Entry } from "@ohos.arkui.component" // TextAttribute should be insert by ui-plugins -import { StorageProp } from "@ohos.arkui.stateManagement" - -class Person{ - name: string = '' - constructor(name: string){} -} - -enum Status { - Success = 200, - NotFound = 404, - ServerError = 500 -} - -@Entry -@Component -struct MyStateSample { - @StorageProp('Prop1') arrayB: number[] = [1,2,3]; - @StorageProp('Prop2') objectB: Object = {}; - @StorageProp('Prop3') dateB: Date = new Date('2021-09-09'); - @StorageProp('Prop4') setB: Set = new Set(); - @StorageProp('Prop5') mapB: Map = new Map(); - @StorageProp('Prop6') unionB: string | undefined = ""; - @StorageProp('Prop7') classB: Person = new Person("Kevin"); - @StorageProp('Prop8') enumB: Status = Status.NotFound; - - build() {} -} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/decorators/storageprop/storageprop-primitive-type.ets b/arkui-plugins/test/demo/mock/decorators/storageprop/storageprop-primitive-type.ets deleted file mode 100644 index d82a28552..000000000 --- a/arkui-plugins/test/demo/mock/decorators/storageprop/storageprop-primitive-type.ets +++ /dev/null @@ -1,12 +0,0 @@ -import { Component, Entry } from "@ohos.arkui.component" // TextAttribute should be insert by ui-plugins -import { StorageProp } from "@ohos.arkui.stateManagement" - -@Entry -@Component -struct MyStateSample { - @StorageProp('Prop1') numB: number = 43; - @StorageProp('Prop2') stringB: string = 'BB'; - @StorageProp('Prop3') booleanB: boolean = false; - - build() {} -} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/decorators/watch/watch-basic.ets b/arkui-plugins/test/demo/mock/decorators/watch/watch-basic.ets deleted file mode 100644 index 6a85ab00a..000000000 --- a/arkui-plugins/test/demo/mock/decorators/watch/watch-basic.ets +++ /dev/null @@ -1,41 +0,0 @@ -import { Component, Entry } from "@ohos.arkui.component" -import { State, Prop, StorageLink, StorageProp, Link, Watch, ObjectLink, Observed, Track, Provide, Consume } from "@ohos.arkui.stateManagement" - -@Observed -class A { - propA: string = 'hello' - @Track trackA: string = 'world' -} - -@Entry -@Component -struct MyStateSample { - @State @Watch('stateOnChange') statevar: string = 'Hello World'; - @Prop @Watch('propOnChange') propvar: string = 'Hello World'; - // @Link @Watch('linkOnChange') linkvar: string; - @StorageLink('prop1') @Watch('storageLinkOnChange') storagelinkvar: string = 'Hello World'; - @StorageProp('prop2') @Watch('storagePropOnChange') storagepropvar: string = 'Hello World'; - // @ObjectLink @Watch('objectLinkOnChange') objectlinkvar: A; - @Provide @Watch('ProvideOnChange') providevar: string = 'Hello World'; - - stateOnChange(propName: string) {} - propOnChange(propName: string) {} - // linkOnChange(propName: string) {} - storageLinkOnChange(propName: string) {} - storagePropOnChange(propName: string) {} - // objectLinkOnChange(propName: string) {} - ProvideOnChange(propName: string) {} - - build() { - Child() - } -} - -@Component -struct Child { - // @Consume @Watch('ConsumeOnChange') providevar: string; - - // ConsumeOnChange(propName: string) {} - - build() {} -} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/memo/functions/argument-call.ets b/arkui-plugins/test/demo/mock/memo/functions/argument-call.ets deleted file mode 100644 index 54263a552..000000000 --- a/arkui-plugins/test/demo/mock/memo/functions/argument-call.ets +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (C) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" - -@memo function memo_arg_call( - arg1: number, - arg2: (x: number) => number, - @memo arg3: (x: number) => number, - arg4?: (x: number) => number, - @memo arg5?: (x: number) => number, -) { - arg2(arg1) - arg3(arg1) - arg4?.(arg1) - arg5?.(arg1) -} - -@memo -function memo_arg_call_with_lowering( - arg1: number, - arg4?: (x: number) => number, - @memo arg5?: (x: number) => number, -) { - {let gensym___1 = arg4; - ((gensym___1 == null) ? undefined : gensym___1(arg1))}; - {let gensym___2 = arg5; - ((gensym___2 == null) ? undefined : gensym___2(arg1))}; -} - -@memo -function args_with_default_values( - arg1: int = 10, - @memo arg2: () => int = () => { return 20 }, - arg3: int = arg1, - arg4?: int -): void { - console.log(arg1, arg2, arg3, arg4) - console.log(arg2()) -} diff --git a/arkui-plugins/test/demo/mock/memo/functions/declare-and-call.ets b/arkui-plugins/test/demo/mock/memo/functions/declare-and-call.ets deleted file mode 100644 index ac8324d22..000000000 --- a/arkui-plugins/test/demo/mock/memo/functions/declare-and-call.ets +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (C) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" - -@memo -declare function funcA(): void; - -class A { - @memo foo() { - funcA(); - } -} - -@memo -function funcB(): void { - funcA(); -} - -@memo -() => { - funcA(); -} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/memo/functions/inner-functions.ets b/arkui-plugins/test/demo/mock/memo/functions/inner-functions.ets deleted file mode 100644 index 313164b28..000000000 --- a/arkui-plugins/test/demo/mock/memo/functions/inner-functions.ets +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (C) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" - -@memo -function foo() { } - -@memo -function bar() { - const qux = @memo () => { - foo(); - } - - const other = () => {} -} - -class A { - @memo goo() { - let func = () => {}; - let func2 = @memo () => { - foo(); - } - } -} diff --git a/arkui-plugins/test/demo/mock/memo/functions/non-void-return-type.ets b/arkui-plugins/test/demo/mock/memo/functions/non-void-return-type.ets deleted file mode 100644 index cc0f993ec..000000000 --- a/arkui-plugins/test/demo/mock/memo/functions/non-void-return-type.ets +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (C) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" - -@memo -function funcNum(): number { - return 1; -} - -@memo -function funcStr(): string { - return "1"; -} - -@memo -function funcBool(): boolean { - return false; -} - -interface A { - str: string; -} - -@memo -function funcA(): A { - return { str: "1" }; -} - -type B = (str: string) => void; - -@memo -function funcB(): B { - return (str: string) => {}; -} - -class C { - str: string; - constructor(str: string) { - this.str = str; - } -} - -@memo -function funcC(): C { - return new C("1"); -} - -@memo -function funcD(): () => void { - return () => {}; -} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/memo/functions/type-reference.ets b/arkui-plugins/test/demo/mock/memo/functions/type-reference.ets deleted file mode 100644 index be715df95..000000000 --- a/arkui-plugins/test/demo/mock/memo/functions/type-reference.ets +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (C) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" - -@memo type ItemBuilder = (item: Item) => void; - -interface Item { - item: T; -} - -interface Attribute { - @memo each(@memo itemGenerator: ItemBuilder): Attribute; -} - -@memo -export declare function A(): Attribute - -@memo -function func(): ItemBuilder { - return (item: Item): void => {}; -} - -class B { - @memo build() { - A().each((ri: Item) => {}) - } -} diff --git a/arkui-plugins/test/demo/mock/memo/functions/void-return-type.ets b/arkui-plugins/test/demo/mock/memo/functions/void-return-type.ets deleted file mode 100644 index 840c84aaf..000000000 --- a/arkui-plugins/test/demo/mock/memo/functions/void-return-type.ets +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright (C) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" - -@memo -function func(): void { - return; -} diff --git a/arkui-plugins/test/demo/mock/memo/lambdas/argument-call.ets b/arkui-plugins/test/demo/mock/memo/lambdas/argument-call.ets deleted file mode 100644 index def28807a..000000000 --- a/arkui-plugins/test/demo/mock/memo/lambdas/argument-call.ets +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (C) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" - -(arg: (()=>void)) => {}(() => {}); - -(arg: @memo (()=>void)) => {}(@memo () => {}); - -(arg: @memo (()=>void) = () => {}) => {}(@memo () => {}); - -@memo -() => { - (@memo (arg: @memo (()=>void) = () => {}) => {})(@memo () => {}); -} - -@memo -() => { - let goo = @memo (name: string = "old") => {} - - goo(); -} - -() => { - let foo = (arg: @memo (()=>void) = () => {}) => {} - - foo(@memo () => {}); -} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/memo/lambdas/function-with-receiver.ets b/arkui-plugins/test/demo/mock/memo/lambdas/function-with-receiver.ets deleted file mode 100644 index 36bc7d82f..000000000 --- a/arkui-plugins/test/demo/mock/memo/lambdas/function-with-receiver.ets +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (C) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { memo } from "@ohos.arkui.stateManagement" - -class B { - @memo internal_call(): B { - this.foo1('morning'); - return this.foo2('afternoon') - } -} - -@memo function foo1(this: B, str: string): void { - console.log('Good', str); -} - -@memo function foo2(this: B, str: string): this { - console.log('Good', str); - return this; -} diff --git a/arkui-plugins/test/demo/mock/memo/lambdas/trailing-lambdas.ets b/arkui-plugins/test/demo/mock/memo/lambdas/trailing-lambdas.ets deleted file mode 100644 index 08d252f58..000000000 --- a/arkui-plugins/test/demo/mock/memo/lambdas/trailing-lambdas.ets +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (C) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" - -class A { - @memo foo(p?: ()=>void): void {} - - goo(@memo p?: ()=>void): void {} - - @memo koo(@memo p?: ()=>void): void {} -} - -@memo -function bar(f?: ()=>void): void {} - -function par(f?: @memo ()=>void): void {} - -@memo -function kar(@memo f?: ()=>void): void {} - -@memo -() => { - let a = new A(); - a.foo() { console.log(); } - a.goo() { console.log(); } - a.koo() { console.log(); } - - bar() { console.log(); } - par() { console.log(); } - kar() { console.log(); } -} diff --git a/arkui-plugins/test/demo/mock/memo/lambdas/void-lambda.ets b/arkui-plugins/test/demo/mock/memo/lambdas/void-lambda.ets deleted file mode 100644 index fb757d8b6..000000000 --- a/arkui-plugins/test/demo/mock/memo/lambdas/void-lambda.ets +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright (C) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" - -@memo -(): void => { - return; -} - -@memo -(arg?: () => string): void => { - return; -} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/memo/lambdas/with-receiver.ets b/arkui-plugins/test/demo/mock/memo/lambdas/with-receiver.ets deleted file mode 100644 index b54c9c6c2..000000000 --- a/arkui-plugins/test/demo/mock/memo/lambdas/with-receiver.ets +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (C) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" - -class Person { - constructor() {} -} - -function fullName(this: Person, @memo arg?: () => void): void { - return; -} - -class A {} - -type F1 = (this: A, @memo arg?: () => void) => void; -type F2 = (a: A, @memo arg?: () => void) => void; - -function foo(this: A, @memo arg?: () => void): void {} -function goo(a: A, @memo arg?: () => void): void {} - -@memo -() => { - let x = new Person(); - x.fullName(() => {}); - - let f1: F1 = foo; - f1 = goo; - - let f2: F2 = goo; - f2 = foo; - f1 = f2; - - let a = new A(); - a.f1(() => {}); - f1(a, () => {}); - - f2(a, () => {}); -} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/memo/methods/argument-call.ets b/arkui-plugins/test/demo/mock/memo/methods/argument-call.ets deleted file mode 100644 index 5f799140f..000000000 --- a/arkui-plugins/test/demo/mock/memo/methods/argument-call.ets +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (C) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" - -class Test { - @memo lambda_arg(@memo arg: () => void) { - - } - - @memo lambda_arg_with_arg(@memo arg: (value: string) => string) { - - } - - @memo memo_content(@memo content: () => void) { - content() - } - - @memo compute_test( - @memo arg1: (() => void) | undefined, - arg2: (() => void) | undefined, - content: (() => void) | undefined - ): void { - - } -} - -class Use { - @memo test() { - const test = new Test() - - test.lambda_arg((): void => {}) - test.lambda_arg_with_arg((value: string): string => value) - - test.compute_test(() => {}, () => {}, () => {}) - } -} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/memo/methods/callable.ets b/arkui-plugins/test/demo/mock/memo/methods/callable.ets deleted file mode 100644 index 2f4e2a401..000000000 --- a/arkui-plugins/test/demo/mock/memo/methods/callable.ets +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (C) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" - -class A { - @memo - static $_invoke(): void {} -} - -class B { - static $_invoke(@memo p?: () => void): void {} -} - -class C { - @memo - static $_instantiate(factory: () => C): C { - return factory(); - } -} - -class D { - static $_instantiate(factory: () => D, @memo content?: () => void): D { - return factory(); - } -} - -@memo -() => { - A(); - B(() => {}); - - let x: C | D = C(); - x = D(); -} diff --git a/arkui-plugins/test/demo/mock/memo/methods/declare-and-call.ets b/arkui-plugins/test/demo/mock/memo/methods/declare-and-call.ets deleted file mode 100644 index e28c85361..000000000 --- a/arkui-plugins/test/demo/mock/memo/methods/declare-and-call.ets +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (C) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" - -declare abstract class A { - @memo - x(): void; - - test_signature( - @memo arg1: () => void, - @memo arg2: (() => void) | undefined, - @memo arg3: ((() => void) | undefined) | ((() => int) | undefined), - @memo x: (y: (z: @memo () => void) => void) => void, - ): @memo () => void; -} - -class AA extends A { - @memo x(): void {} -} - -@memo -() => { - new AA().x(); - - const a: A = new AA(); - a.x(); -} - diff --git a/arkui-plugins/test/demo/mock/memo/methods/internal-calls.ets b/arkui-plugins/test/demo/mock/memo/methods/internal-calls.ets deleted file mode 100644 index 7ef4cdb0e..000000000 --- a/arkui-plugins/test/demo/mock/memo/methods/internal-calls.ets +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (C) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" - -export declare function __context(): __memo_context_type -export declare function __id(): __memo_id_type -type MemoType = @memo () => void - -class Test { - @memo void_method(): void { - } - - @memo internal_call() { - this.void_method() - } - - @memo method_with_internals() { - __context() - __id() - } - - memo_lambda() { - @memo () => { - - } - } - - @memo memo_variables() { - @memo const f = (): number => { - return 123 - }, g = (x: number): number => { - return 123 + x - } - - const h = @memo (): number => { - return 1 - } - - f() - g(1) - h() - } - - @memo args_with_default_values( - arg1: int = 10, - arg2: () => int = () => { return 20 }, - arg3: int = arg1, - arg4?: int - ): void { - console.log(arg1, arg2, arg3, arg4) - console.log(arg2()) - } - - @memo optional_args( - arg1?: int, - arg2?: () => int - ) { - console.log(arg1) - console.log(arg2) - console.log(arg2?.()) - } - - @memo type_alias( - arg: MemoType - ) { - arg() - } -} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/memo/methods/non-void-method.ets b/arkui-plugins/test/demo/mock/memo/methods/non-void-method.ets deleted file mode 100644 index 06df30297..000000000 --- a/arkui-plugins/test/demo/mock/memo/methods/non-void-method.ets +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (C) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" - -@Retention({policy:"SOURCE"}) @interface memo_intrinsic {} -@Retention({policy:"SOURCE"}) @interface memo_entry {} - -export declare function __context(): __memo_context_type -export declare function __id(): __memo_id_type - -class Test { - @memo void_method(): void { - } - - @memo string_method_with_return(arg: string): string { - return arg - } - - @memo method_with_type_parameter(arg: T): T { - return arg - } - - @memo_intrinsic intrinsic_method(): int { - return 0 - } - - @memo_intrinsic intrinsic_method_with_this(): int { - this.void_method() - return 0 - } - - @memo_entry memoEntry(__memo_context: __memo_context_type, __memo_id: __memo_id_type, @memo entry: () => R): R { - const getContext = () => { - return __context() - } - const getId = () => { - return __id() - } - { - const __memo_context = getContext() - const __memo_id = getId() - return entry() - } - } -} - -class Use { - @memo test() { - const test = new Test() - - test.string_method_with_return("a string") - test.method_with_type_parameter("I'm string") - } -} diff --git a/arkui-plugins/test/demo/mock/memo/methods/void-method.ets b/arkui-plugins/test/demo/mock/memo/methods/void-method.ets deleted file mode 100644 index ed3339dd1..000000000 --- a/arkui-plugins/test/demo/mock/memo/methods/void-method.ets +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (C) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" - -class A { - x: int - y: int -} - -class Test { - @memo void_method(): void { - } - - @memo a_method_with_implicit_return_type() { - } - - @memo void_method_with_arg(arg: string) { - } - - @memo void_method_with_return(arg: string) { - return - } - - @memo static static_method_with_type_parameter(arg: T): void { - return - } - - @memo obj_arg(arg: A) { - - } -} - -class Use { - @memo test() { - const test = new Test() - - test.void_method() - test.void_method_with_arg("an arg") - test.void_method_with_return("a value") - Test.static_method_with_type_parameter("I'm static") - - test.obj_arg({ x: 1, y: 2 }) - } -} diff --git a/arkui-plugins/test/demo/mock/memo/properties/class-constructor.ets b/arkui-plugins/test/demo/mock/memo/properties/class-constructor.ets deleted file mode 100644 index 725d2702b..000000000 --- a/arkui-plugins/test/demo/mock/memo/properties/class-constructor.ets +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (C) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" - -interface A { - @memo a: () => void -} - -class AA { - - @memo a: (() => void) | undefined - - constructor(arg?: A) { - this.a = arg?.a; - } - - @memo - build() { - this.a?.(); - } -} - -@memo -() => { - let a = new AA({ a: () => {} }) ; -} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/memo/properties/class-properties.ets b/arkui-plugins/test/demo/mock/memo/properties/class-properties.ets deleted file mode 100644 index 9fe1e5dc4..000000000 --- a/arkui-plugins/test/demo/mock/memo/properties/class-properties.ets +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (C) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" - -class A { - arg: () => void - @memo memo_arg: () => void - @memo memo_optional_arg?: () => void - @memo memo_union_arg: (() => void) | undefined = () => {} - - arg_memo_type: @memo () => void - - constructor() { - this.arg = () => {}; - this.memo_arg = () => {}; - this.arg_memo_type = () => {}; - } - - @memo - build() { - this.arg(); - this.memo_arg(); - this.arg_memo_type(); - } - -} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/memo/properties/implements.ets b/arkui-plugins/test/demo/mock/memo/properties/implements.ets deleted file mode 100644 index ad61b2a7a..000000000 --- a/arkui-plugins/test/demo/mock/memo/properties/implements.ets +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright (C) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" - -interface A { - @memo prop: (() => void) | undefined -} - -class AA implements A { - @memo prop: (() => void) | undefined -} \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/memo/properties/interfaces.ets b/arkui-plugins/test/demo/mock/memo/properties/interfaces.ets deleted file mode 100644 index c46a181e5..000000000 --- a/arkui-plugins/test/demo/mock/memo/properties/interfaces.ets +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (C) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { memo, __memo_context_type, __memo_id_type } from "@ohos.arkui.stateManagement" - -interface A { - arg: () => void - @memo memo_arg: () => void - @memo memo_optional_arg?: () => void - @memo memo_union_arg: (() => void) | undefined - - arg_memo_type: @memo () => void -} - -@memo() (() => { - let a: A = { - arg: (() => {}), - memo_arg: (() => {}), - memo_union_arg: (() => {}), - arg_memo_type: (() => {}), - }; -}); \ No newline at end of file diff --git a/arkui-plugins/test/demo/mock/xcomponent/xcomponent-basic.ets b/arkui-plugins/test/demo/mock/xcomponent/xcomponent-basic.ets deleted file mode 100644 index aa644d5ed..000000000 --- a/arkui-plugins/test/demo/mock/xcomponent/xcomponent-basic.ets +++ /dev/null @@ -1,19 +0,0 @@ -import {Component, Flex, XComponent, FlexDirection, XComponentType, Entry, XComponentController, ItemAlign, FlexAlign, XComponentParameter} from '@ohos.arkui.component' - -@Entry -@Component -struct Index { - myXComponentController: XComponentController = new XComponentController(); - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Start }) { - XComponent({ - id: 'xComponentId', - type: XComponentType.TEXTURE, - libraryname: 'nativerender', - controller: this.myXComponentController - } as XComponentParameter) - } - .width('100%') - .height('100%') - } -} \ No newline at end of file diff --git a/arkui-plugins/test/package.json b/arkui-plugins/test/package.json index 07123fbd7..51154bd39 100644 --- a/arkui-plugins/test/package.json +++ b/arkui-plugins/test/package.json @@ -6,11 +6,7 @@ "scripts": { "compile:ohos": "node $INIT_CWD/../../../../arkcompiler/ets_frontend/ets2panda/driver/build-system/dist/entry.js ./demo/hello_world/build_config.json", "compile:gdb": "gdb --args node $INIT_CWD/../../../../out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/driver/build-system/dist/entry.js ./demo/hello_world/build_config.json", - "compile:plugins": "npm run compile --prefix ..", - "clean:localtest": "rm -rf dist", - "clean:test": "rm -rf generated", - "clean:all": "npm run clean:localtest && npm run clean:test", - "test": "npm run clean:all && npm run compile:plugins && cd .. && npm run test", + "compile:plugins": "npm run compile --prefix .. ", "localtest": "rm -rf dist && node localtest_config.js && npm run compile:plugins && LD_LIBRARY_PATH=$INIT_CWD/../../../../out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/ets2panda/lib node $INIT_CWD/../../../../out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/driver/build-system/dist/entry.js ./demo/localtest/build_config.json", "localtest_gdb": "LD_LIBRARY_PATH=$INIT_CWD/../../../../out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/ets2panda/lib gdb --args node $INIT_CWD/../../../../out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/driver/build-system/dist/entry.js ./demo/localtest/build_config.json", "localtest_decl": "rm -rf dist && node localtest_decl_config.js && npm run compile:plugins && LD_LIBRARY_PATH=$INIT_CWD/../../../../out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/ets2panda/lib node $INIT_CWD/../../../../out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/driver/build-system/dist/entry.js ./demo/localtest/build_decl_config.json", diff --git a/arkui-plugins/test/ut/common/annotation.test.ts b/arkui-plugins/test/ut/common/annotation.test.ts index cf9f7d191..7091e7d52 100644 --- a/arkui-plugins/test/ut/common/annotation.test.ts +++ b/arkui-plugins/test/ut/common/annotation.test.ts @@ -13,16 +13,16 @@ * limitations under the License. */ +import * as arkts from '@koalaui/libarkts'; import { PluginTestContext, PluginTester } from '../../utils/plugin-tester'; import { annotation } from '../../../common/arkts-utils'; -import * as arkts from '@koalaui/libarkts'; const pluginTester = new PluginTester('test arkts-utils'); function testAnnotation(this: PluginTestContext): void { const anno: arkts.AnnotationUsage = annotation('State'); expect(arkts.isAnnotationUsage(anno)).toBeTruthy(); - expect(anno.dumpSrc()).toBe('@State() '); + expect(anno.dumpSrc()).toBe('@State()'); } pluginTester.run( @@ -34,5 +34,17 @@ pluginTester.run( }, { stopAfter: 'checked', + }, + { + beforeEach: [ + () => { + jest.spyOn(console, 'warn').mockImplementation(() => {}); + }, + ], + afterEach: [ + () => { + jest.spyOn(console, 'warn').mockRestore(); + }, + ], } ); diff --git a/arkui-plugins/test/ut/memo-plugins/function-declarations/argument-call.test.ts b/arkui-plugins/test/ut/memo-plugins/function-declarations/argument-call.test.ts deleted file mode 100644 index a3d7d2909..000000000 --- a/arkui-plugins/test/ut/memo-plugins/function-declarations/argument-call.test.ts +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; -import { parseDumpSrc } from '../../../utils/parse-string'; -import { memoNoRecheck } from '../../../utils/plugins'; - -const FUNCTION_DIR_PATH: string = 'memo/functions'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, FUNCTION_DIR_PATH, 'argument-call.ets')]; - -const pluginTester = new PluginTester('test memo function', buildConfig); - -const expectedScript: string = ` -import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; -function main() {} -@functions.OptionalParametersAnnotation({minArgCount:3}) function memo_arg_call(__memo_context: __memo_context_type, __memo_id: __memo_id_type, arg1: number, arg2: ((x: number)=> number), @memo() arg3: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type, x: number)=> number), arg4?: ((x: number)=> number), @memo() arg5?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type, x: number)=> number)): void { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 5); - const __memo_parameter_arg1 = __memo_scope.param(0, arg1), __memo_parameter_arg2 = __memo_scope.param(1, arg2), __memo_parameter_arg3 = __memo_scope.param(2, arg3), __memo_parameter_arg4 = __memo_scope.param(3, arg4), __memo_parameter_arg5 = __memo_scope.param(4, arg5); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - __memo_parameter_arg2.value(__memo_parameter_arg1.value); - __memo_parameter_arg3.value(__memo_context, ((__memo_id) + ()), __memo_parameter_arg1.value); - ({let gensym%%_ = __memo_parameter_arg4.value; - (((gensym%%_) == (null)) ? undefined : gensym%%_(__memo_parameter_arg1.value))}); - ({let gensym%%_ = __memo_parameter_arg5.value; - (((gensym%%_) == (null)) ? undefined : gensym%%_(__memo_context, ((__memo_id) + ()), __memo_parameter_arg1.value))}); - { - __memo_scope.recache(); - return; - } -} -@functions.OptionalParametersAnnotation({minArgCount:1}) function memo_arg_call_with_lowering(__memo_context: __memo_context_type, __memo_id: __memo_id_type, arg1: number, arg4?: ((x: number)=> number), @memo() arg5?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type, x: number)=> number)): void { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 3); - const __memo_parameter_arg1 = __memo_scope.param(0, arg1), __memo_parameter_arg4 = __memo_scope.param(1, arg4), __memo_parameter_arg5 = __memo_scope.param(2, arg5); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - { - let gensym___ = __memo_parameter_arg4.value; - (((gensym___) == (null)) ? undefined : gensym___(__memo_parameter_arg1.value)); - } - { - let gensym___ = __memo_parameter_arg5.value; - (((gensym___) == (null)) ? undefined : gensym___(__memo_context, ((__memo_id) + ()), __memo_parameter_arg1.value)); - } - { - __memo_scope.recache(); - return; - } -} -@functions.OptionalParametersAnnotation({minArgCount:0}) function args_with_default_values(__memo_context: __memo_context_type, __memo_id: __memo_id_type, gensym%%_?: int, @memo() gensym%%_?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> int), gensym%%_?: int, arg4?: int): void { - let arg1: int = (((gensym%%_) !== (undefined)) ? gensym%%_ : (10 as int)); - let arg2: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> int) = (((gensym%%_) !== (undefined)) ? gensym%%_ : (((__memo_context: __memo_context_type, __memo_id: __memo_id_type): int => { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - return __memo_scope.cached; - } - return __memo_scope.recache(20); - }) as ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> int))); - let arg3: int = (((gensym%%_) !== (undefined)) ? gensym%%_ : (arg1 as int)); - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 4); - const __memo_parameter_arg1 = __memo_scope.param(0, arg1), __memo_parameter_arg2 = __memo_scope.param(1, arg2), __memo_parameter_arg3 = __memo_scope.param(2, arg3), __memo_parameter_arg4 = __memo_scope.param(3, arg4); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - console.log(__memo_parameter_arg1.value, __memo_parameter_arg2.value, __memo_parameter_arg3.value, __memo_parameter_arg4.value); - console.log(__memo_parameter_arg2.value(__memo_context, ((__memo_id) + ()))); - { - __memo_scope.recache(); - return; - } -} -`; - -function testMemoTransformer(this: PluginTestContext): void { - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'transform argument calls in functions', - [memoNoRecheck], - { - 'checked:memo-no-recheck': [testMemoTransformer], - }, - { - stopAfter: 'checked', - } -); diff --git a/arkui-plugins/test/ut/memo-plugins/function-declarations/declare-and-call.test.ts b/arkui-plugins/test/ut/memo-plugins/function-declarations/declare-and-call.test.ts deleted file mode 100644 index db15946ae..000000000 --- a/arkui-plugins/test/ut/memo-plugins/function-declarations/declare-and-call.test.ts +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; -import { parseDumpSrc } from '../../../utils/parse-string'; -import { memoNoRecheck } from '../../../utils/plugins'; - -const FUNCTION_DIR_PATH: string = 'memo/functions'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [ - path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, FUNCTION_DIR_PATH, 'declare-and-call.ets'), -]; - -const pluginTester = new PluginTester('test memo function', buildConfig); - -const expectedScript: string = ` -import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; -function main() {} -@memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - funcA(__memo_context, ((__memo_id) + ())); - { - __memo_scope.recache(); - return; - } -}); -@memo() function funcA(__memo_context: __memo_context_type, __memo_id: __memo_id_type): void -function funcB(__memo_context: __memo_context_type, __memo_id: __memo_id_type): void { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - funcA(__memo_context, ((__memo_id) + ())); - { - __memo_scope.recache(); - return; - } -} -class A { - public foo(__memo_context: __memo_context_type, __memo_id: __memo_id_type): void { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - funcA(__memo_context, ((__memo_id) + ())); - { - __memo_scope.recache(); - return; - } - } - public constructor() {} -} -`; - -function testMemoTransformer(this: PluginTestContext): void { - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'transform declare functions and calls', - [memoNoRecheck], - { - 'checked:memo-no-recheck': [testMemoTransformer], - }, - { - stopAfter: 'checked', - } -); diff --git a/arkui-plugins/test/ut/memo-plugins/function-declarations/inner-functions.test.ts b/arkui-plugins/test/ut/memo-plugins/function-declarations/inner-functions.test.ts deleted file mode 100644 index 8e5494643..000000000 --- a/arkui-plugins/test/ut/memo-plugins/function-declarations/inner-functions.test.ts +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; -import { parseDumpSrc } from '../../../utils/parse-string'; -import { memoNoRecheck } from '../../../utils/plugins'; - -const FUNCTION_DIR_PATH: string = 'memo/functions'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [ - path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, FUNCTION_DIR_PATH, 'inner-functions.ets'), -]; - -const pluginTester = new PluginTester('test memo function', buildConfig); - -const expectedScript: string = ` -import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; -function main() {} -function foo(__memo_context: __memo_context_type, __memo_id: __memo_id_type): void { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - { - __memo_scope.recache(); - return; - } -} -function bar(__memo_context: __memo_context_type, __memo_id: __memo_id_type): void { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - const qux = @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - foo(__memo_context, ((__memo_id) + ())); - { - __memo_scope.recache(); - return; - } - }); - const other = (() => {}); - { - __memo_scope.recache(); - return; - } -} -class A { - public goo(__memo_context: __memo_context_type, __memo_id: __memo_id_type): void { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - let func = (() => {}); - let func2 = @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - foo(__memo_context, ((__memo_id) + ())); - { - __memo_scope.recache(); - return; - } - }); - { - __memo_scope.recache(); - return; - } - } - public constructor() {} -} -`; - -function testMemoTransformer(this: PluginTestContext): void { - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'transform inner functions', - [memoNoRecheck], - { - 'checked:memo-no-recheck': [testMemoTransformer], - }, - { - stopAfter: 'checked', - } -); diff --git a/arkui-plugins/test/ut/memo-plugins/function-declarations/non-void-return-type.test.ts b/arkui-plugins/test/ut/memo-plugins/function-declarations/non-void-return-type.test.ts deleted file mode 100644 index 19b061ad6..000000000 --- a/arkui-plugins/test/ut/memo-plugins/function-declarations/non-void-return-type.test.ts +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; -import { parseDumpSrc } from '../../../utils/parse-string'; -import { memoNoRecheck } from '../../../utils/plugins'; - -const FUNCTION_DIR_PATH: string = 'memo/functions'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [ - path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, FUNCTION_DIR_PATH, 'non-void-return-type.ets'), -]; - -const pluginTester = new PluginTester('test memo function', buildConfig); - -const expectedScript: string = ` -import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; -function main() {} -function funcNum(__memo_context: __memo_context_type, __memo_id: __memo_id_type): number { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - return __memo_scope.cached; - } - return __memo_scope.recache(1); -} -function funcStr(__memo_context: __memo_context_type, __memo_id: __memo_id_type): string { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - return __memo_scope.cached; - } - return __memo_scope.recache(\"1\"); -} -function funcBool(__memo_context: __memo_context_type, __memo_id: __memo_id_type): boolean { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - return __memo_scope.cached; - } - return __memo_scope.recache(false); -} -function funcA(__memo_context: __memo_context_type, __memo_id: __memo_id_type): A { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - return __memo_scope.cached; - } - return __memo_scope.recache({ - str: \"1\", - }); -} -function funcB(__memo_context: __memo_context_type, __memo_id: __memo_id_type): B { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - return __memo_scope.cached; - } - return __memo_scope.recache(((str: string) => {})); -} -function funcC(__memo_context: __memo_context_type, __memo_id: __memo_id_type): C { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - return __memo_scope.cached; - } - return __memo_scope.recache(new C(\"1\")); -} -function funcD(__memo_context: __memo_context_type, __memo_id: __memo_id_type): (()=> void) { - const __memo_scope = __memo_context.scope<(()=> void)>(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - return __memo_scope.cached; - } - return __memo_scope.recache((() => {})); -} -interface A { - set str(str: string) - get str(): string -} -type B = ((str: string)=> void); -class C { - public str: string; - public constructor(str: string) { - this.str = str; - } -} -`; - -function testMemoTransformer(this: PluginTestContext): void { - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'transform functions with non-void return type', - [memoNoRecheck], - { - 'checked:memo-no-recheck': [testMemoTransformer], - }, - { - stopAfter: 'checked', - } -); diff --git a/arkui-plugins/test/ut/memo-plugins/function-declarations/type-reference.test.ts b/arkui-plugins/test/ut/memo-plugins/function-declarations/type-reference.test.ts deleted file mode 100644 index 7db7cd676..000000000 --- a/arkui-plugins/test/ut/memo-plugins/function-declarations/type-reference.test.ts +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; -import { parseDumpSrc } from '../../../utils/parse-string'; -import { memoNoRecheck } from '../../../utils/plugins'; - -const FUNCTION_DIR_PATH: string = 'memo/functions'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [ - path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, FUNCTION_DIR_PATH, 'type-reference.ets'), -]; - -const pluginTester = new PluginTester('test memo function', buildConfig); - -const expectedScript: string = ` -import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; -function main() {} -@memo() function A(__memo_context: __memo_context_type, __memo_id: __memo_id_type): Attribute -function func(__memo_context: __memo_context_type, __memo_id: __memo_id_type): ItemBuilder { - const __memo_scope = __memo_context.scope>(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - return __memo_scope.cached; - } - return __memo_scope.recache(((__memo_context: __memo_context_type, __memo_id: __memo_id_type, item: Item): void => {})); -} -@memo() type ItemBuilder = ((__memo_context: __memo_context_type, __memo_id: __memo_id_type, item: Item)=> void); -interface Item { - set item(item: T) - get item(): T -} -interface Attribute { - @memo() each(__memo_context: __memo_context_type, __memo_id: __memo_id_type, @memo() itemGenerator: ItemBuilder): Attribute -} -class B { - public build(__memo_context: __memo_context_type, __memo_id: __memo_id_type): void { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - A(__memo_context, ((__memo_id) + ())).each(__memo_context, ((__memo_id) + ()), ((__memo_context: __memo_context_type, __memo_id: __memo_id_type, ri: Item): void => { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 1); - const __memo_parameter_ri = __memo_scope.param(0, ri); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - { - __memo_scope.recache(); - return; - } - })); - { - __memo_scope.recache(); - return; - } - } - public constructor() {} -} -`; - -function testMemoTransformer(this: PluginTestContext): void { - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'transform functions with type reference', - [memoNoRecheck], - { - 'checked:memo-no-recheck': [testMemoTransformer], - }, - { - stopAfter: 'checked', - } -); diff --git a/arkui-plugins/test/ut/memo-plugins/function-declarations/void-return-type.test.ts b/arkui-plugins/test/ut/memo-plugins/function-declarations/void-return-type.test.ts deleted file mode 100644 index 08c0eb3bd..000000000 --- a/arkui-plugins/test/ut/memo-plugins/function-declarations/void-return-type.test.ts +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; -import { parseDumpSrc } from '../../../utils/parse-string'; -import { memoNoRecheck } from '../../../utils/plugins'; - -const FUNCTION_DIR_PATH: string = 'memo/functions'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [ - path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, FUNCTION_DIR_PATH, 'void-return-type.ets'), -]; - -const pluginTester = new PluginTester('test memo function', buildConfig); - -const expectedScript: string = ` -import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; -function main() {} -function func(__memo_context: __memo_context_type, __memo_id: __memo_id_type): void { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - { - __memo_scope.recache(); - return; - } -} -`; - -function testMemoTransformer(this: PluginTestContext): void { - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'transform functions with void return type', - [memoNoRecheck], - { - 'checked:memo-no-recheck': [testMemoTransformer], - }, - { - stopAfter: 'checked', - } -); diff --git a/arkui-plugins/test/ut/memo-plugins/lambda-literals/argument-call.test.ts b/arkui-plugins/test/ut/memo-plugins/lambda-literals/argument-call.test.ts deleted file mode 100644 index f23a8d252..000000000 --- a/arkui-plugins/test/ut/memo-plugins/lambda-literals/argument-call.test.ts +++ /dev/null @@ -1,173 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; -import { parseDumpSrc } from '../../../utils/parse-string'; -import { memoNoRecheck } from '../../../utils/plugins'; - -const LAMBDA_DIR_PATH: string = 'memo/lambdas'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, LAMBDA_DIR_PATH, 'argument-call.ets')]; - -const pluginTester = new PluginTester('test memo lambda', buildConfig); - -const expectedScript: string = ` -import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; -function main() {} -((arg: (()=> void)) => {})((() => {})); - -((arg: @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)) => {})(@memo() (() => {})); - -((gensym%%_1?: @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)) => { - let arg: @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void) = (((gensym%%_1) !== (undefined)) ? gensym%%_1 : (((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { - const __memo_scope = __memo_context.scope(((__memo_id) + (201676739)), 0); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - { - __memo_scope.recache(); - return; - } - }) as @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void))); -})(@memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { - const __memo_scope = __memo_context.scope(((__memo_id) + (209782503)), 0); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - { - __memo_scope.recache(); - return; - } -})); - -@memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type, gensym%%_?: @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): void => { - let arg: @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void) = (((gensym%%_) !== (undefined)) ? gensym%%_ : (((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - { - __memo_scope.recache(); - return; - } - }) as @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void))); - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 1); - const __memo_parameter_arg = __memo_scope.param(0, arg); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - { - __memo_scope.recache(); - return; - } - })(__memo_context, ((__memo_id) + ()), @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - { - __memo_scope.recache(); - return; - } - })); - { - __memo_scope.recache(); - return; - } -}); - -@memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - let goo = @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type, gensym%%_?: string): void => { - let name: string = (((gensym%%_) !== (undefined)) ? gensym%%_ : (\"old\" as string)); - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 1); - const __memo_parameter_name = __memo_scope.param(0, name); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - { - __memo_scope.recache(); - return; - } - }); - goo(__memo_context, ((__memo_id) + ())); - { - __memo_scope.recache(); - return; - } -}); - -(() => { - let foo = ((gensym%%_?: @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)) => { - let arg: @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void) = (((gensym%%_) !== (undefined)) ? gensym%%_ : (((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - { - __memo_scope.recache(); - return; - } - }) as @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void))); - }); - foo(@memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - { - __memo_scope.recache(); - return; - } - })); -}); -`; - -function testMemoTransformer(this: PluginTestContext): void { - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'transform argument calls in lambdas', - [memoNoRecheck], - { - 'checked:memo-no-recheck': [testMemoTransformer], - }, - { - stopAfter: 'checked', - } -); diff --git a/arkui-plugins/test/ut/memo-plugins/lambda-literals/function-with-receiver.test.ts b/arkui-plugins/test/ut/memo-plugins/lambda-literals/function-with-receiver.test.ts deleted file mode 100644 index be488294a..000000000 --- a/arkui-plugins/test/ut/memo-plugins/lambda-literals/function-with-receiver.test.ts +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; -import { parseDumpSrc } from '../../../utils/parse-string'; -import { memoNoRecheck } from '../../../utils/plugins'; -import { Plugins } from '../../../../common/plugin-context'; -import { uiTransform } from '../../../../ui-plugins'; - -const LAMBDA_DIR_PATH: string = 'memo/lambdas'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [ - path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, LAMBDA_DIR_PATH, 'function-with-receiver.ets'), -]; - -const parsedTransform: Plugins = { - name: 'state-complex-type', - parsed: uiTransform().parsed -}; - -const pluginTester = new PluginTester('test memo lambda', buildConfig); - -const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; -import { memo as memo } from "@ohos.arkui.stateManagement"; - -function main() {} - -function foo1(this: B, __memo_context: __memo_context_type, __memo_id: __memo_id_type, str: string): void { - const __memo_scope = __memo_context.scope(((__memo_id) + (38567515)), 2); - const __memo_parameter_this = __memo_scope.param(0, this), __memo_parameter_str = __memo_scope.param(1, str); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - console.log("Good", __memo_parameter_str.value); - { - __memo_scope.recache(); - return; - } -} - -function foo2(this: B, __memo_context: __memo_context_type, __memo_id: __memo_id_type, str: string): B { - const __memo_scope = __memo_context.scope(((__memo_id) + (167482260)), 2); - const __memo_parameter_this = __memo_scope.param(0, this), __memo_parameter_str = __memo_scope.param(1, str); - if (__memo_scope.unchanged) { - return __memo_scope.cached; - } - console.log("Good", __memo_parameter_str.value); - return __memo_scope.recache(this); -} - -class B { - public internal_call(__memo_context: __memo_context_type, __memo_id: __memo_id_type): B { - const __memo_scope = __memo_context.scope(((__memo_id) + (146437675)), 0); - if (__memo_scope.unchanged) { - return __memo_scope.cached; - } - foo1(this, __memo_context, ((__memo_id) + (119664703)), "morning"); - return __memo_scope.recache(foo2(this, __memo_context, ((__memo_id) + (181969214)), "afternoon")); - } - - public constructor() {} -} -`; - -function testMemoTransformer(this: PluginTestContext): void { - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'transform lambdas about function with receiver feature', - [parsedTransform, memoNoRecheck], - { - 'checked:memo-no-recheck': [testMemoTransformer], - }, - { - stopAfter: 'checked', - } -); diff --git a/arkui-plugins/test/ut/memo-plugins/lambda-literals/trailing-lambdas.test.ts b/arkui-plugins/test/ut/memo-plugins/lambda-literals/trailing-lambdas.test.ts deleted file mode 100644 index f023fef13..000000000 --- a/arkui-plugins/test/ut/memo-plugins/lambda-literals/trailing-lambdas.test.ts +++ /dev/null @@ -1,169 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; -import { parseDumpSrc } from '../../../utils/parse-string'; -import { memoNoRecheck } from '../../../utils/plugins'; - -const LAMBDA_DIR_PATH: string = 'memo/lambdas'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [ - path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, LAMBDA_DIR_PATH, 'trailing-lambdas.ets'), -]; - -const pluginTester = new PluginTester('test memo lambda', buildConfig); - -const expectedScript: string = ` -import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; -function main() {} -@memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - let a = new A(); - a.foo(__memo_context, ((__memo_id) + ()), (() => { - console.log(); - })); - a.goo(((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - console.log(); - { - __memo_scope.recache(); - return; - } - })); - a.koo(__memo_context, ((__memo_id) + ()), ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - console.log(); - { - __memo_scope.recache(); - return; - } - })); - bar(__memo_context, ((__memo_id) + ()), (() => { - console.log(); - })); - par(((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - console.log(); - { - __memo_scope.recache(); - return; - } - })); - kar(__memo_context, ((__memo_id) + ()), ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - console.log(); - { - __memo_scope.recache(); - return; - } - })); - { - __memo_scope.recache(); - return; - } -}); -@functions.OptionalParametersAnnotation({minArgCount:0}) function bar(__memo_context: __memo_context_type, __memo_id: __memo_id_type, f?: (()=> void)): void { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 1); - const __memo_parameter_f = __memo_scope.param(0, f); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - { - __memo_scope.recache(); - return; - } -} -@functions.OptionalParametersAnnotation({minArgCount:0}) function par(f?: @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): void {} -@functions.OptionalParametersAnnotation({minArgCount:0}) function kar(__memo_context: __memo_context_type, __memo_id: __memo_id_type, @memo() f?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): void { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 1); - const __memo_parameter_f = __memo_scope.param(0, f); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - { - __memo_scope.recache(); - return; - } -} -class A { - @functions.OptionalParametersAnnotation({minArgCount:0}) public foo(__memo_context: __memo_context_type, __memo_id: __memo_id_type, p?: (()=> void)): void { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 1); - const __memo_parameter_p = __memo_scope.param(0, p); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - { - __memo_scope.recache(); - return; - } - } - @functions.OptionalParametersAnnotation({minArgCount:0}) public goo(@memo() p?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): void {} - @functions.OptionalParametersAnnotation({minArgCount:0}) public koo(__memo_context: __memo_context_type, __memo_id: __memo_id_type, @memo() p?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): void { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 1); - const __memo_parameter_p = __memo_scope.param(0, p); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - { - __memo_scope.recache(); - return; - } - } - public constructor() {} -} -`; - -function testMemoTransformer(this: PluginTestContext): void { - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'transform trailing lambdas', - [memoNoRecheck], - { - 'checked:memo-no-recheck': [testMemoTransformer], - }, - { - stopAfter: 'checked', - } -); diff --git a/arkui-plugins/test/ut/memo-plugins/lambda-literals/void-lambda.test.ts b/arkui-plugins/test/ut/memo-plugins/lambda-literals/void-lambda.test.ts deleted file mode 100644 index 59b48a024..000000000 --- a/arkui-plugins/test/ut/memo-plugins/lambda-literals/void-lambda.test.ts +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; -import { parseDumpSrc } from '../../../utils/parse-string'; -import { memoNoRecheck } from '../../../utils/plugins'; - -const LAMBDA_DIR_PATH: string = 'memo/lambdas'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [ - path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, LAMBDA_DIR_PATH, 'void-lambda.ets'), -]; - -const pluginTester = new PluginTester('test memo lambda', buildConfig); - -const expectedScript: string = ` -import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; -function main() {} -@memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - { - __memo_scope.recache(); - return; - } -}); -@memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type, arg?: (()=> string)): void => { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 1); - const __memo_parameter_arg = __memo_scope.param(0, arg); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - { - __memo_scope.recache(); - return; - } -}); -`; - -function testMemoTransformer(this: PluginTestContext): void { - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'transform lambdas with void return type', - [memoNoRecheck], - { - 'checked:memo-no-recheck': [testMemoTransformer], - }, - { - stopAfter: 'checked', - } -); diff --git a/arkui-plugins/test/ut/memo-plugins/lambda-literals/with-receiver.test.ts b/arkui-plugins/test/ut/memo-plugins/lambda-literals/with-receiver.test.ts deleted file mode 100644 index 4f6e3fa92..000000000 --- a/arkui-plugins/test/ut/memo-plugins/lambda-literals/with-receiver.test.ts +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; -import { parseDumpSrc } from '../../../utils/parse-string'; -import { memoNoRecheck } from '../../../utils/plugins'; - -const LAMBDA_DIR_PATH: string = 'memo/lambdas'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [ - path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, LAMBDA_DIR_PATH, 'with-receiver.ets'), -]; - -const pluginTester = new PluginTester('test memo lambda', buildConfig); - -const expectedScript: string = ` -import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; -function main() {} -@memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - let x = new Person(); - fullName(x, ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - { - __memo_scope.recache(); - return; - } - })); - let f1: F1 = foo; - f1 = goo; - let f2: F2 = goo; - f2 = foo; - f1 = f2; - let a = new A(); - f1(a, ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - { - __memo_scope.recache(); - return; - } - })); - f1(a, ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - { - __memo_scope.recache(); - return; - } - })); - f2(a, ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - { - __memo_scope.recache(); - return; - } - })); - { - __memo_scope.recache(); - return; - } -}); -@functions.OptionalParametersAnnotation({minArgCount:1}) function fullName(this: Person, @memo() arg?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): void { - return; -} -@functions.OptionalParametersAnnotation({minArgCount:1}) function foo(this: A, @memo() arg?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): void {} -@functions.OptionalParametersAnnotation({minArgCount:1}) function goo(a: A, @memo() arg?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): void {} -class Person { - public constructor() {} -} -class A { - public constructor() {} -} -type F1 = ((this: A, @memo() arg?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void))=> void); -type F2 = ((a: A, @memo() arg?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void))=> void); -`; - -function testMemoTransformer(this: PluginTestContext): void { - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'transform lambdas with receiver', - [memoNoRecheck], - { - 'checked:memo-no-recheck': [testMemoTransformer], - }, - { - stopAfter: 'checked', - } -); diff --git a/arkui-plugins/test/ut/memo-plugins/method-declarations/argument-call.test.ts b/arkui-plugins/test/ut/memo-plugins/method-declarations/argument-call.test.ts deleted file mode 100644 index de72519e7..000000000 --- a/arkui-plugins/test/ut/memo-plugins/method-declarations/argument-call.test.ts +++ /dev/null @@ -1,145 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; -import { parseDumpSrc } from '../../../utils/parse-string'; -import { memoNoRecheck } from '../../../utils/plugins'; - -const METHOD_DIR_PATH: string = 'memo/methods'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, METHOD_DIR_PATH, 'argument-call.ets')]; - -const pluginTester = new PluginTester('test memo method', buildConfig); - -const expectedScript: string = ` -import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; -function main() {} -class Test { - public lambda_arg(__memo_context: __memo_context_type, __memo_id: __memo_id_type, @memo() arg: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): void { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 1); - const __memo_parameter_arg = __memo_scope.param(0, arg); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - { - __memo_scope.recache(); - return; - } - } - public lambda_arg_with_arg(__memo_context: __memo_context_type, __memo_id: __memo_id_type, @memo() arg: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type, value: string)=> string)): void { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 1); - const __memo_parameter_arg = __memo_scope.param(0, arg); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - { - __memo_scope.recache(); - return; - } - } - public memo_content(__memo_context: __memo_context_type, __memo_id: __memo_id_type, @memo() content: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): void { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 1); - const __memo_parameter_content = __memo_scope.param(0, content); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - __memo_parameter_content.value(__memo_context, ((__memo_id) + ())); - { - __memo_scope.recache(); - return; - } - } - public compute_test(__memo_context: __memo_context_type, __memo_id: __memo_id_type, @memo() arg1: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void) | undefined, arg2: (()=> void) | undefined, content: (()=> void) | undefined): void { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 3); - const __memo_parameter_arg1 = __memo_scope.param(0, arg1), __memo_parameter_arg2 = __memo_scope.param(1, arg2), __memo_parameter_content = __memo_scope.param(2, content); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - { - __memo_scope.recache(); - return; - } - } - public constructor() {} -} -class Use { - public test(__memo_context: __memo_context_type, __memo_id: __memo_id_type): void { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - const test = new Test(); - test.lambda_arg(__memo_context, ((__memo_id) + ()), ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - { - __memo_scope.recache(); - return; - } - })); - test.lambda_arg_with_arg(__memo_context, ((__memo_id) + ()), ((__memo_context: __memo_context_type, __memo_id: __memo_id_type, value: string): string => { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 1); - const __memo_parameter_value = __memo_scope.param(0, value); - if (__memo_scope.unchanged) { - return __memo_scope.cached; - } - return __memo_scope.recache(__memo_parameter_value.value); - })); - test.compute_test(__memo_context, ((__memo_id) + ()), ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - { - __memo_scope.recache(); - return; - } - }), (() => {}), (() => {})); - { - __memo_scope.recache(); - return; - } - } - public constructor() {} -} -`; - -function testMemoTransformer(this: PluginTestContext): void { - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'transform argument calls in methods', - [memoNoRecheck], - { - 'checked:memo-no-recheck': [testMemoTransformer], - }, - { - stopAfter: 'checked', - } -); diff --git a/arkui-plugins/test/ut/memo-plugins/method-declarations/callable.test.ts b/arkui-plugins/test/ut/memo-plugins/method-declarations/callable.test.ts deleted file mode 100644 index 7657e1dd0..000000000 --- a/arkui-plugins/test/ut/memo-plugins/method-declarations/callable.test.ts +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; -import { parseDumpSrc } from '../../../utils/parse-string'; -import { memoNoRecheck } from '../../../utils/plugins'; - -const METHOD_DIR_PATH: string = 'memo/methods'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, METHOD_DIR_PATH, 'callable.ets')]; - -const pluginTester = new PluginTester('test memo method', buildConfig); - -const expectedScript: string = ` -import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; -function main() {} -@memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - A.$_invoke(__memo_context, ((__memo_id) + ())); - B.$_invoke(((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - { - __memo_scope.recache(); - return; - } - })); - let x: C | D = C.$_instantiate(__memo_context, ((__memo_id) + ()), (() => { - return new C(); - })); - x = D.$_instantiate((() => { - return new D(); - })); - { - __memo_scope.recache(); - return; - } -}); -class A { - public static $_invoke(__memo_context: __memo_context_type, __memo_id: __memo_id_type): void { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - { - __memo_scope.recache(); - return; - } - } - public constructor() {} -} -class B { - @functions.OptionalParametersAnnotation({minArgCount:0}) public static $_invoke(@memo() p?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): void {} - public constructor() {} -} -class C { - public static $_instantiate(__memo_context: __memo_context_type, __memo_id: __memo_id_type, factory: (()=> C)): C { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 1); - const __memo_parameter_factory = __memo_scope.param(0, factory); - if (__memo_scope.unchanged) { - return __memo_scope.cached; - } - return __memo_scope.recache(__memo_parameter_factory.value()); - } - public constructor() {} -} -class D { - @functions.OptionalParametersAnnotation({minArgCount:1}) public static $_instantiate(factory: (()=> D), @memo() content?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): D { - return factory(); - } - public constructor() {} -} -`; - -function testMemoTransformer(this: PluginTestContext): void { - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'transform callable class', - [memoNoRecheck], - { - 'checked:memo-no-recheck': [testMemoTransformer], - }, - { - stopAfter: 'checked', - } -); diff --git a/arkui-plugins/test/ut/memo-plugins/method-declarations/declare-and-call.test.ts b/arkui-plugins/test/ut/memo-plugins/method-declarations/declare-and-call.test.ts deleted file mode 100644 index 0a669b4c0..000000000 --- a/arkui-plugins/test/ut/memo-plugins/method-declarations/declare-and-call.test.ts +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; -import { parseDumpSrc } from '../../../utils/parse-string'; -import { memoNoRecheck } from '../../../utils/plugins'; - -const METHOD_DIR_PATH: string = 'memo/methods'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [ - path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, METHOD_DIR_PATH, 'declare-and-call.ets'), -]; - -const pluginTester = new PluginTester('test memo method', buildConfig); - -const expectedScript: string = ` -import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; -function main() {} -@memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - new AA().x(__memo_context, ((__memo_id) + ())); - const a: A = new AA(); - a.x(__memo_context, ((__memo_id) + ())); - { - __memo_scope.recache(); - return; - } -}); -declare abstract class A { - @memo() public x(__memo_context: __memo_context_type, __memo_id: __memo_id_type): void - public test_signature(@memo() arg1: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void), @memo() arg2: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void) | undefined, @memo() arg3: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void) | undefined | ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> int) | undefined, @memo() x: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type, y: ((z: @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void))=> void))=> void)): @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void) - public constructor() {} -} -class AA extends A { - public x(__memo_context: __memo_context_type, __memo_id: __memo_id_type): void { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - { - __memo_scope.recache(); - return; - } - } - public constructor() {} -} -`; - -function testMemoTransformer(this: PluginTestContext): void { - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'transform declare methods and calls', - [memoNoRecheck], - { - 'checked:memo-no-recheck': [testMemoTransformer], - }, - { - stopAfter: 'checked', - } -); diff --git a/arkui-plugins/test/ut/memo-plugins/method-declarations/internal-calls.test.ts b/arkui-plugins/test/ut/memo-plugins/method-declarations/internal-calls.test.ts deleted file mode 100644 index 11dae0f7e..000000000 --- a/arkui-plugins/test/ut/memo-plugins/method-declarations/internal-calls.test.ts +++ /dev/null @@ -1,186 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; -import { parseDumpSrc } from '../../../utils/parse-string'; -import { memoNoRecheck } from '../../../utils/plugins'; - -const METHOD_DIR_PATH: string = 'memo/methods'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, METHOD_DIR_PATH, 'internal-calls.ets')]; - -const pluginTester = new PluginTester('test memo method', buildConfig); - -const expectedScript: string = ` -import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; -function main() {} -function __context(): __memo_context_type -function __id(): __memo_id_type -type MemoType = @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void); -class Test { - public void_method(__memo_context: __memo_context_type, __memo_id: __memo_id_type): void { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - { - __memo_scope.recache(); - return; - } - } - public internal_call(__memo_context: __memo_context_type, __memo_id: __memo_id_type): void { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - this.void_method(__memo_context, ((__memo_id) + ())); - { - __memo_scope.recache(); - return; - } - } - public method_with_internals(__memo_context: __memo_context_type, __memo_id: __memo_id_type): void { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - __context(); - __id(); - { - __memo_scope.recache(); - return; - } - } - public memo_lambda() { - @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - { - __memo_scope.recache(); - return; - } - }); - } - public memo_variables(__memo_context: __memo_context_type, __memo_id: __memo_id_type): void { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - @memo() const f = ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): number => { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - return __memo_scope.cached; - } - return __memo_scope.recache(123); - }), g = ((__memo_context: __memo_context_type, __memo_id: __memo_id_type, x: number): number => { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 1); - const __memo_parameter_x = __memo_scope.param(0, x); - if (__memo_scope.unchanged) { - return __memo_scope.cached; - } - return __memo_scope.recache(((123) + (__memo_parameter_x.value))); - }); - const h = @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): number => { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - return __memo_scope.cached; - } - return __memo_scope.recache(1); - }); - f(__memo_context, ((__memo_id) + ())); - g(__memo_context, ((__memo_id) + ()), 1); - h(__memo_context, ((__memo_id) + ())); - { - __memo_scope.recache(); - return; - } - } - @functions.OptionalParametersAnnotation({minArgCount:0}) public args_with_default_values(__memo_context: __memo_context_type, __memo_id: __memo_id_type, gensym%%_1?: int, gensym%%_2?: (()=> int), gensym%%_3?: int, arg4?: int): void { - let arg1: int = (((gensym%%_1) !== (undefined)) ? gensym%%_1 : (10 as int)); - let arg2: (()=> int) = (((gensym%%_2) !== (undefined)) ? gensym%%_2 : ((() => { - return 20; - }) as (()=> int))); - let arg3: int = (((gensym%%_3) !== (undefined)) ? gensym%%_3 : (arg1 as int)); - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 4); - const __memo_parameter_arg1 = __memo_scope.param(0, arg1), __memo_parameter_arg2 = __memo_scope.param(1, arg2), __memo_parameter_arg3 = __memo_scope.param(2, arg3), __memo_parameter_arg4 = __memo_scope.param(3, arg4); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - console.log(__memo_parameter_arg1.value, __memo_parameter_arg2.value, __memo_parameter_arg3.value, __memo_parameter_arg4.value); - console.log(__memo_parameter_arg2.value()); - { - __memo_scope.recache(); - return; - } - } - @functions.OptionalParametersAnnotation({minArgCount:0}) public optional_args(__memo_context: __memo_context_type, __memo_id: __memo_id_type, arg1?: int, arg2?: (()=> int)): void { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 2); - const __memo_parameter_arg1 = __memo_scope.param(0, arg1), __memo_parameter_arg2 = __memo_scope.param(1, arg2); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - console.log(__memo_parameter_arg1.value); - console.log(__memo_parameter_arg2.value); - console.log(({let gensym%%_166 = __memo_parameter_arg2.value; - (((gensym%%_166) == (null)) ? undefined : gensym%%_166())})); - { - __memo_scope.recache(); - return; - } - } - public type_alias(__memo_context: __memo_context_type, __memo_id: __memo_id_type, arg: MemoType): void { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 1); - const __memo_parameter_arg = __memo_scope.param(0, arg); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - __memo_parameter_arg.value(__memo_context, ((__memo_id) + ())); - { - __memo_scope.recache(); - return; - } - } - public constructor() {} -} -`; - -function testMemoTransformer(this: PluginTestContext): void { - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'transform inner calls in methods', - [memoNoRecheck], - { - 'checked:memo-no-recheck': [testMemoTransformer], - }, - { - stopAfter: 'checked', - } -); diff --git a/arkui-plugins/test/ut/memo-plugins/method-declarations/non-void-method.test.ts b/arkui-plugins/test/ut/memo-plugins/method-declarations/non-void-method.test.ts deleted file mode 100644 index a8ddef791..000000000 --- a/arkui-plugins/test/ut/memo-plugins/method-declarations/non-void-method.test.ts +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; -import { parseDumpSrc } from '../../../utils/parse-string'; -import { memoNoRecheck } from '../../../utils/plugins'; - -const METHOD_DIR_PATH: string = 'memo/methods'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, METHOD_DIR_PATH, 'non-void-method.ets')]; - -const pluginTester = new PluginTester('test memo method', buildConfig); - -const expectedScript: string = ` -import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; -function main() {} -function __context(): __memo_context_type -function __id(): __memo_id_type -@Retention({policy:"SOURCE"}) @interface memo_intrinsic {} -@Retention({policy:"SOURCE"}) @interface memo_entry {} -class Test { - public void_method(__memo_context: __memo_context_type, __memo_id: __memo_id_type): void { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - { - __memo_scope.recache(); - return; - } - } - public string_method_with_return(__memo_context: __memo_context_type, __memo_id: __memo_id_type, arg: string): string { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 1); - const __memo_parameter_arg = __memo_scope.param(0, arg); - if (__memo_scope.unchanged) { - return __memo_scope.cached; - } - return __memo_scope.recache(__memo_parameter_arg.value); - } - public method_with_type_parameter(__memo_context: __memo_context_type, __memo_id: __memo_id_type, arg: T): T { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 1); - const __memo_parameter_arg = __memo_scope.param(0, arg); - if (__memo_scope.unchanged) { - return __memo_scope.cached; - } - return __memo_scope.recache(__memo_parameter_arg.value); - } - public intrinsic_method(): int { - return 0; - } - public intrinsic_method_with_this(): int { - this.void_method(__memo_context, ((__memo_id) + ())); - return 0; - } - public memoEntry(__memo_context: __memo_context_type, __memo_id: __memo_id_type, @memo() entry: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> R)): R { - const getContext = (() => { - return __context(); - }); - const getId = (() => { - return __id(); - }); - { - const __memo_context = getContext(); - const __memo_id = getId(); - return entry(__memo_context, ((__memo_id) + ())); - } - } - public constructor() {} -} -class Use { - public test(__memo_context: __memo_context_type, __memo_id: __memo_id_type): void { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - const test = new Test(); - test.string_method_with_return(__memo_context, ((__memo_id) + ()), "a string"); - test.method_with_type_parameter(__memo_context, ((__memo_id) + ()), "I'm string"); - { - __memo_scope.recache(); - return; - } - } - public constructor() {} -} -`; - -function testMemoTransformer(this: PluginTestContext): void { - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'transform methods with non-void return type', - [memoNoRecheck], - { - 'checked:memo-no-recheck': [testMemoTransformer], - }, - { - stopAfter: 'checked', - } -); diff --git a/arkui-plugins/test/ut/memo-plugins/method-declarations/void-method.test.ts b/arkui-plugins/test/ut/memo-plugins/method-declarations/void-method.test.ts deleted file mode 100644 index 953742b8a..000000000 --- a/arkui-plugins/test/ut/memo-plugins/method-declarations/void-method.test.ts +++ /dev/null @@ -1,151 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; -import { parseDumpSrc } from '../../../utils/parse-string'; -import { memoNoRecheck } from '../../../utils/plugins'; - -const METHOD_DIR_PATH: string = 'memo/methods'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [ - path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, METHOD_DIR_PATH, 'void-method.ets'), -]; - -const pluginTester = new PluginTester('test memo method', buildConfig); - -const expectedScript: string = ` -import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; -function main() {} -class A { - public x: int; - public y: int; - public constructor() {} -} -class Test { - public void_method(__memo_context: __memo_context_type, __memo_id: __memo_id_type): void { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - { - __memo_scope.recache(); - return; - } - } - public a_method_with_implicit_return_type(__memo_context: __memo_context_type, __memo_id: __memo_id_type): void { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - { - __memo_scope.recache(); - return; - } - } - public void_method_with_arg(__memo_context: __memo_context_type, __memo_id: __memo_id_type, arg: string): void { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 1); - const __memo_parameter_arg = __memo_scope.param(0, arg); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - { - __memo_scope.recache(); - return; - } - } - public void_method_with_return(__memo_context: __memo_context_type, __memo_id: __memo_id_type, arg: string): void { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 1); - const __memo_parameter_arg = __memo_scope.param(0, arg); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - { - __memo_scope.recache(); - return; - } - } - public static static_method_with_type_parameter(__memo_context: __memo_context_type, __memo_id: __memo_id_type, arg: T): void { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 1); - const __memo_parameter_arg = __memo_scope.param(0, arg); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - { - __memo_scope.recache(); - return; - } - } - public obj_arg(__memo_context: __memo_context_type, __memo_id: __memo_id_type, arg: A): void { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 1); - const __memo_parameter_arg = __memo_scope.param(0, arg); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - { - __memo_scope.recache(); - return; - } - } - public constructor() {} -} -class Use { - public test(__memo_context: __memo_context_type, __memo_id: __memo_id_type): void { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - const test = new Test(); - test.void_method(__memo_context, ((__memo_id) + ())); - test.void_method_with_arg(__memo_context, ((__memo_id) + ()), "an arg"); - test.void_method_with_return(__memo_context, ((__memo_id) + ()), "a value"); - Test.static_method_with_type_parameter(__memo_context, ((__memo_id) + ()), "I'm static"); - test.obj_arg(__memo_context, ((__memo_id) + ()), { - x: 1, - y: 2, - }); - { - __memo_scope.recache(); - return; - } - } - public constructor() {} -} -`; - -function testMemoTransformer(this: PluginTestContext): void { - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'transform methods with void return type', - [memoNoRecheck], - { - 'checked:memo-no-recheck': [testMemoTransformer], - }, - { - stopAfter: 'checked', - } -); diff --git a/arkui-plugins/test/ut/memo-plugins/property-declarations/class-constructor.test.ts b/arkui-plugins/test/ut/memo-plugins/property-declarations/class-constructor.test.ts deleted file mode 100644 index 28671e700..000000000 --- a/arkui-plugins/test/ut/memo-plugins/property-declarations/class-constructor.test.ts +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; -import { parseDumpSrc } from '../../../utils/parse-string'; -import { memoNoRecheck } from '../../../utils/plugins'; - -const PROPERTY_DIR_PATH: string = 'memo/properties'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [ - path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, PROPERTY_DIR_PATH, 'class-constructor.ets'), -]; - -const pluginTester = new PluginTester('test memo property', buildConfig); - -const expectedScript: string = ` -import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; -function main() {} -@memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - let a = new AA({ - a: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - { - __memo_scope.recache(); - return; - } - }), - }); - { - __memo_scope.recache(); - return; - } -}); -interface A { - @memo() set a(a: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): void - @memo() get a(): ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void) -} -class AA { - @memo() public a: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void) | undefined; - constructor() { - this(undefined); - } - public constructor(arg: A | undefined) { - this.a = ({let gensym%%_ = arg; - (((gensym%%_) == (null)) ? undefined : gensym%%_.a)}); - } - public build(__memo_context: __memo_context_type, __memo_id: __memo_id_type): void { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - ({let gensym%%_ = this.a; - (((gensym%%_) == (null)) ? undefined : gensym%%_(__memo_context, ((__memo_id) + ())))}); - { - __memo_scope.recache(); - return; - } - } -} -`; - -function testMemoTransformer(this: PluginTestContext): void { - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'transform properties in class constructor', - [memoNoRecheck], - { - 'checked:memo-no-recheck': [testMemoTransformer], - }, - { - stopAfter: 'checked', - } -); diff --git a/arkui-plugins/test/ut/memo-plugins/property-declarations/class-properties.test.ts b/arkui-plugins/test/ut/memo-plugins/property-declarations/class-properties.test.ts deleted file mode 100644 index c98720039..000000000 --- a/arkui-plugins/test/ut/memo-plugins/property-declarations/class-properties.test.ts +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; -import { parseDumpSrc } from '../../../utils/parse-string'; -import { memoNoRecheck } from '../../../utils/plugins'; - -const PROPERTY_DIR_PATH: string = 'memo/properties'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [ - path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, PROPERTY_DIR_PATH, 'class-properties.ets'), -]; - -const pluginTester = new PluginTester('test memo property', buildConfig); - -const expectedScript: string = ` -import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; -function main() {} -class A { - public arg: (()=> void); - @memo() public memo_arg: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void); - @memo() public memo_optional_arg?: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void) | undefined; - @memo() public memo_union_arg: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void) | undefined = ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - { - __memo_scope.recache(); - return; - } - }); - public arg_memo_type: @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void); - public constructor() { - this.arg = (() => {}); - this.memo_arg = ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - { - __memo_scope.recache(); - return; - } - }); - this.arg_memo_type = ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - { - __memo_scope.recache(); - return; - } - }); - } - public build(__memo_context: __memo_context_type, __memo_id: __memo_id_type): void { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - this.arg(); - this.memo_arg(__memo_context, ((__memo_id) + ())); - this.arg_memo_type(__memo_context, ((__memo_id) + ())); - { - __memo_scope.recache(); - return; - } - } -} -`; - -function testMemoTransformer(this: PluginTestContext): void { - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'transform properties in class', - [memoNoRecheck], - { - 'checked:memo-no-recheck': [testMemoTransformer], - }, - { - stopAfter: 'checked', - } -); diff --git a/arkui-plugins/test/ut/memo-plugins/property-declarations/interfaces.test.ts b/arkui-plugins/test/ut/memo-plugins/property-declarations/interfaces.test.ts deleted file mode 100644 index 99053d0ef..000000000 --- a/arkui-plugins/test/ut/memo-plugins/property-declarations/interfaces.test.ts +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; -import { parseDumpSrc } from '../../../utils/parse-string'; -import { memoNoRecheck } from '../../../utils/plugins'; - -const PROPERTY_DIR_PATH: string = 'memo/properties'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, PROPERTY_DIR_PATH, 'interfaces.ets')]; - -const pluginTester = new PluginTester('test memo property', buildConfig); - -const expectedScript: string = ` -import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; -function main() {} -@memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - let a: A = { - arg: (() => {}), - memo_arg: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - { - __memo_scope.recache(); - return; - } - }), - memo_union_arg: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - { - __memo_scope.recache(); - return; - } - }), - arg_memo_type: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { - const __memo_scope = __memo_context.scope(((__memo_id) + ()), 0); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - { - __memo_scope.recache(); - return; - } - }), - }; - { - __memo_scope.recache(); - return; - } -}); -interface A { - set arg(arg: (()=> void)) - get arg(): (()=> void) - @memo() set memo_arg(memo_arg: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)): void - @memo() get memo_arg(): ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void) - @memo() set memo_optional_arg(memo_optional_arg: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void) | undefined): void - @memo() get memo_optional_arg(): ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void) | undefined - @memo() set memo_union_arg(memo_union_arg: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void) | undefined): void - @memo() get memo_union_arg(): ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void) | undefined - set arg_memo_type(arg_memo_type: @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)) - get arg_memo_type(): @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void) -} -`; - -function testMemoTransformer(this: PluginTestContext): void { - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'transform interface properties', - [memoNoRecheck], - { - 'checked:memo-no-recheck': [testMemoTransformer], - }, - { - stopAfter: 'checked', - } -); diff --git a/arkui-plugins/test/ut/ui-plugins/animation/animation-basic.test.ts b/arkui-plugins/test/ut/ui-plugins/animation/animation-basic.test.ts deleted file mode 100644 index dd4678db6..000000000 --- a/arkui-plugins/test/ut/ui-plugins/animation/animation-basic.test.ts +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; -import { parseDumpSrc } from '../../../utils/parse-string'; -import { uiNoRecheck } from '../../../utils/plugins'; -import { uiTransform } from '../../../../ui-plugins'; -import { Plugins } from '../../../../common/plugin-context'; - -const ANIMATION_DIR_PATH: string = 'animation'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [ - path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, ANIMATION_DIR_PATH, 'animation-basic.ets'), -]; - -const animationTransform: Plugins = { - name: 'animation', - parsed: uiTransform().parsed, -} - -const pluginTester = new PluginTester('test basic animation transform', buildConfig); - -const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; - -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; - -import { memo as memo } from "arkui.stateManagement.runtime"; - -import { UIColumnAttribute as UIColumnAttribute } from "@ohos.arkui.component"; - -import { UITextAttribute as UITextAttribute } from "@ohos.arkui.component"; - -import { EntryPoint as EntryPoint } from "arkui.UserView"; - -import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; - -import { Text as Text, Column as Column, Component as Component, Color as Color, Curve as Curve } from "@ohos.arkui.component"; - -import { Entry as Entry } from "@ohos.arkui.component"; - -function main() {} - - - -@Entry({useSharedStorage:false,storage:"",routeName:""}) @Component({freezeWhenInactive:false}) final class AnimatablePropertyExample extends CustomComponent { - public __initializeStruct(initializers: __Options_AnimatablePropertyExample | undefined, @memo() content: (()=> void) | undefined): void {} - - public __updateStruct(initializers: __Options_AnimatablePropertyExample | undefined): void {} - - @memo() public _build(@memo() style: ((instance: AnimatablePropertyExample)=> AnimatablePropertyExample) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_AnimatablePropertyExample | undefined): void { - Column(undefined, undefined, (() => { - Text(@memo() ((instance: UITextAttribute): void => { - instance.animationStart({ - duration: 2000, - curve: Curve.Ease, - }).backgroundColor(Color.Red).animationStop({ - duration: 2000, - curve: Curve.Ease, - }).animationStart({ - duration: 2000, - curve: Curve.Ease, - }).fontSize(20).animationStop({ - duration: 2000, - curve: Curve.Ease, - }).width("100%"); - return; - }), "AnimatableProperty", undefined, undefined); - })); - } - - public constructor() {} - -} - -interface __Options_AnimatablePropertyExample { - -} - -class __EntryWrapper extends EntryPoint { - @memo() public entry(): void { - AnimatablePropertyExample._instantiateImpl(undefined, (() => { - return new AnimatablePropertyExample(); - }), undefined, undefined, undefined); - } - - public constructor() {} - -} -`; - -function testAnimationTransformer(this: PluginTestContext): void { - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'test basic animation transform', - [animationTransform, uiNoRecheck], - { - checked: [testAnimationTransformer], - }, - { - stopAfter: 'checked', - } -); diff --git a/arkui-plugins/test/ut/ui-plugins/builder-lambda/custom-component/custom-component-call.test.ts b/arkui-plugins/test/ut/ui-plugins/builder-lambda/custom-component/custom-component-call.test.ts deleted file mode 100644 index b9a0d5943..000000000 --- a/arkui-plugins/test/ut/ui-plugins/builder-lambda/custom-component/custom-component-call.test.ts +++ /dev/null @@ -1,166 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; -import { parseDumpSrc } from '../../../../utils/parse-string'; -import { recheck, uiNoRecheck } from '../../../../utils/plugins'; -import { uiTransform } from '../../../../../ui-plugins'; -import { Plugins } from '../../../../../common/plugin-context'; - -const BUILDER_LAMBDA_DIR_PATH: string = 'builder-lambda'; -const CUSTOM_COMPONENT_DIR_PATH: string = 'custom-component'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [ - path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, BUILDER_LAMBDA_DIR_PATH, CUSTOM_COMPONENT_DIR_PATH, 'custom-component-call.ets'), -]; - -const pluginTester = new PluginTester('test custom component call transformation', buildConfig); - -const parsedTransform: Plugins = { - name: 'custom-component-call', - parsed: uiTransform().parsed -}; - -const expectedParsedScript: string = ` -import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; -import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; -import { memo as memo } from "@ohos.arkui.stateManagement"; -import { UIColumnAttribute as UIColumnAttribute } from "@ohos.arkui.component"; -import { UITextAttribute as UITextAttribute } from "@ohos.arkui.component"; -import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; -import { Text as Text, Column as Column, Component as Component, Builder as Builder, BuilderParam as BuilderParam } from "@ohos.arkui.component"; - -@Component() final class CustomContainer extends CustomComponent { - @Builder() public closerBuilder() {} - @BuilderParam() public closer: (()=> void) = (this).closerBuilder; - public build() {} - public constructor() {} -} - -@Component() final class CustomContainerUser extends CustomComponent { - public build() { - Column(undefined){ - CustomContainer(undefined){ - Column(undefined){ - Text("hello", undefined); - }; - }; - CustomContainer(({} as __Options_CustomContainer)){ - Column(undefined){}; - }; - CustomContainer(undefined){}; - CustomContainer(); - }; - } - public constructor() {} -} - -interface __Options_CustomContainer { - closer?: @memo() (()=> void); -} - -interface __Options_CustomContainerUser { -} -`; - -function testParedTransformer(this: PluginTestContext): void { - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedParsedScript)); -} - -const expectedBuilderLambdaScript: string = ` -import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; -import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; -import { memo as memo } from "@ohos.arkui.stateManagement"; -import { UIColumnAttribute as UIColumnAttribute } from "@ohos.arkui.component"; -import { UITextAttribute as UITextAttribute } from "@ohos.arkui.component"; -import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; -import { Text as Text, Column as Column, Component as Component, Builder as Builder, BuilderParam as BuilderParam } from "@ohos.arkui.component"; - -function main() {} - -@Component({freezeWhenInactive:false}) final class CustomContainer extends CustomComponent { - public __initializeStruct(initializers: __Options_CustomContainer | undefined, @memo() content: (()=> void) | undefined): void { - (this).__backing_closer = ((((({let gensym___38813563 = initializers; - (((gensym___38813563) == (null)) ? undefined : gensym___38813563.closer)})) ?? (content))) ?? ((this).closerBuilder)) - } - public __updateStruct(initializers: __Options_CustomContainer | undefined): void {} - private __backing_closer?: @memo() (()=> void); - public get closer(): @memo() (()=> void) { - return (this).__backing_closer!; - } - public set closer(@memo() value: (()=> void)) { - (this).__backing_closer = value; - } - @memo() public closerBuilder() {} - @memo() public _build(@memo() style: ((instance: CustomContainer)=> CustomContainer) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_CustomContainer | undefined): void {} - public constructor() {} -} - -@Component({freezeWhenInactive:false}) final class CustomContainerUser extends CustomComponent { - public __initializeStruct(initializers: __Options_CustomContainerUser | undefined, @memo() content: (()=> void) | undefined): void {} - public __updateStruct(initializers: __Options_CustomContainerUser | undefined): void {} - @memo() public _build(@memo() style: ((instance: CustomContainerUser)=> CustomContainerUser) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_CustomContainerUser | undefined): void { - Column(undefined, undefined, (() => { - CustomContainer._instantiateImpl(undefined, (() => { - return new CustomContainer(); - }), undefined, (() => { - Column(undefined, undefined, (() => { - Text(undefined, "hello", undefined, undefined); - })); - }), undefined); - CustomContainer._instantiateImpl(undefined, (() => { - return new CustomContainer(); - }), ({} as __Options_CustomContainer), (() => { - Column(undefined, undefined, (() => {})); - }), undefined); - CustomContainer._instantiateImpl(undefined, (() => { - return new CustomContainer(); - }), undefined, (() => {}), undefined); - CustomContainer._instantiateImpl(undefined, (() => { - return new CustomContainer(); - }), undefined, undefined, undefined); - })); - } - public constructor() {} -} - -interface __Options_CustomContainer { - set closer(closer: @memo() (()=> void) | undefined) - get closer(): @memo() (()=> void) | undefined -} - -interface __Options_CustomContainerUser { -} -`; - -function testCustomComponentTransformer(this: PluginTestContext): void { - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedBuilderLambdaScript)); -} - -pluginTester.run( - 'test custom component call transformation', - [parsedTransform, recheck, uiNoRecheck], - { - parsed: [testParedTransformer], - 'checked:builder-lambda-no-recheck': [testCustomComponentTransformer], - }, - { - stopAfter: 'checked', - } -); diff --git a/arkui-plugins/test/ut/ui-plugins/builder-lambda/simple-component.test.ts b/arkui-plugins/test/ut/ui-plugins/builder-lambda/simple-component.test.ts deleted file mode 100644 index 37b4605ad..000000000 --- a/arkui-plugins/test/ut/ui-plugins/builder-lambda/simple-component.test.ts +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; -import { parseDumpSrc } from '../../../utils/parse-string'; -import { builderLambdaNoRecheck, memoNoRecheck, recheck } from '../../../utils/plugins'; - -const BUILDER_LAMBDA_DIR_PATH: string = 'builder-lambda'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [ - path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, BUILDER_LAMBDA_DIR_PATH, 'simple-component.ets'), -]; - -const pluginTester = new PluginTester('test builder-lambda simple component', buildConfig); - -function testBuilderLambdaTransformer(this: PluginTestContext): void { - const expectedScript: string = ` -import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; -import { Column as Column, UIColumnAttribute as UIColumnAttribute } from \"arkui.component.column\"; -function main() {} -class MyStateSample { - @memo() public build() { - Column(undefined, undefined, (() => {})); - } - public constructor() {} -} -`; - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); -} - -function testMemoTransformer(this: PluginTestContext): void { - const expectedScript: string = ` -import { memo as memo, __memo_context_type as __memo_context_type, __memo_id_type as __memo_id_type } from \"@ohos.arkui.stateManagement\"; -import { Column as Column, UIColumnAttribute as UIColumnAttribute } from \"arkui.component.column\"; -function main() {} -class MyStateSample { - public build(__memo_context: __memo_context_type, __memo_id: __memo_id_type): void { - const __memo_scope = __memo_context.scope(((__memo_id) + (263357132)), 0); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - Column(__memo_context, ((__memo_id) + (65509320)), undefined, undefined, ((__memo_context: __memo_context_type, __memo_id: __memo_id_type): void => { - const __memo_scope = __memo_context.scope(((__memo_id) + (147296800)), 0); - if (__memo_scope.unchanged) { - __memo_scope.cached; - return; - } - { - __memo_scope.recache(); - return; - } - })); - { - __memo_scope.recache(); - return; - } - } - public constructor() {} -} -`; - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'transform simple component', - [builderLambdaNoRecheck, recheck, memoNoRecheck], - { - 'checked:builder-lambda-no-recheck': [testBuilderLambdaTransformer], - 'checked:memo-no-recheck': [testMemoTransformer], - }, - { - stopAfter: 'checked', - } -); diff --git a/arkui-plugins/test/ut/ui-plugins/builder-lambda/style-with-receiver.test.ts b/arkui-plugins/test/ut/ui-plugins/builder-lambda/style-with-receiver.test.ts deleted file mode 100644 index 1c64f1cdb..000000000 --- a/arkui-plugins/test/ut/ui-plugins/builder-lambda/style-with-receiver.test.ts +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; -import { parseDumpSrc } from '../../../utils/parse-string'; -import { builderLambdaNoRecheck, structNoRecheck, uiNoRecheck } from '../../../utils/plugins'; -import { uiTransform } from '../../../../ui-plugins'; -import { Plugins } from '../../../../common/plugin-context'; - -const BUILDER_LAMBDA_DIR_PATH: string = 'builder-lambda'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [ - path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, BUILDER_LAMBDA_DIR_PATH, 'style-with-receiver.ets'), -]; - -const pluginTester = new PluginTester('test function with receiver style transformstion', buildConfig); - -const parsedTransform: Plugins = { - name: 'style-with-receiver', - parsed: uiTransform().parsed -}; - -const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; -import { UIColumnAttribute as UIColumnAttribute } from "@ohos.arkui.component"; -import { UITextAttribute as UITextAttribute } from "@ohos.arkui.component"; -import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; -import { memo as memo } from "@ohos.arkui.stateManagement"; -import { Text as Text, UITextAttribute as UITextAttribute, Column as Column, Component as Component } from "@ohos.arkui.component"; -import hilog from "@ohos.hilog"; - -function main() {} - -@memo() function cardStyle(this: UITextAttribute, num: number, str: string): UITextAttribute { - this.fontSize(num); - this.backgroundColor(num); - return this; -} - -@memo() function style22(this: UITextAttribute): UITextAttribute { - this.fontWeight(700); - return this; -} - -@Component({freezeWhenInactive:false}) final class MM extends CustomComponent { - public __initializeStruct(initializers: __Options_MM | undefined, @memo() content: (()=> void) | undefined): void {} - - public __updateStruct(initializers: __Options_MM | undefined): void {} - - @memo() public _build(@memo() style: ((instance: MM)=> MM) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_MM | undefined): void { - Column(undefined, undefined, (() => { - Text(@memo() ((instance: UITextAttribute): void => { - style22(cardStyle(instance.height(200).fontColor("#000000"), 600, "#eeeeee").fontSize(60).fontWeight(400)).width(900); - return; - }), "hello world", undefined, undefined); - Text(@memo() ((instance: UITextAttribute): void => { - cardStyle(instance, 600, "#eeeeee"); - return; - }), "hello world", undefined, undefined); - })); - } - - public constructor() {} - -} - -interface __Options_MM { - -} -`; - -function testParsedAndCheckedTransformer(this: PluginTestContext): void { - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'test function with receiver style transformstion', - [parsedTransform, uiNoRecheck], - { - checked: [testParsedAndCheckedTransformer], - }, - { - stopAfter: 'checked', - } -); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/builder-param/builder-param-passing.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/builder-param/builder-param-passing.test.ts deleted file mode 100644 index ba63b9e2d..000000000 --- a/arkui-plugins/test/ut/ui-plugins/decorators/builder-param/builder-param-passing.test.ts +++ /dev/null @@ -1,133 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; -import { parseDumpSrc } from '../../../../utils/parse-string'; -import { uiNoRecheck } from '../../../../utils/plugins'; -import { uiTransform } from '../../../../../ui-plugins'; -import { Plugins } from '../../../../../common/plugin-context'; - -const FUNCTION_DIR_PATH: string = 'decorators/builder-param'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [ - path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, FUNCTION_DIR_PATH, 'builder-param-passing.ets'), -]; - -const pluginTester = new PluginTester('test builder param variable passing', buildConfig); - -const parsedTransform: Plugins = { - name: 'builder-param-passing', - parsed: uiTransform().parsed -}; - -const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "@ohos.arkui.stateManagement"; -import { __memo_context_type as __memo_context_type } from "@ohos.arkui.stateManagement"; -import { memo as memo } from "@ohos.arkui.stateManagement"; -import { UITextAttribute as UITextAttribute } from "@ohos.arkui.component"; -import { UIColumnAttribute as UIColumnAttribute } from "@ohos.arkui.component"; -import { CustomComponent as CustomComponent } from "@ohos.arkui.component"; -import { Component as Component, Entry as Entry, Builder as Builder, BuilderParam as BuilderParam, Column as Column, Text as Text } from "@ohos.arkui.component"; - -function main() {} - -@Component({freezeWhenInactive:false}) final class Child extends CustomComponent { - public __initializeStruct(initializers: __Options_Child | undefined, @memo() content: (()=> void) | undefined): void { - (this).__backing_customBuilderParam = ((((({let gensym___169376706 = initializers; - (((gensym___169376706) == (null)) ? undefined : gensym___169376706.customBuilderParam)})) ?? (content))) ?? ((this).customBuilder)) - } - - public __updateStruct(initializers: __Options_Child | undefined): void {} - - private __backing_customBuilderParam?: @memo() (()=> void); - - public get customBuilderParam(): @memo() (()=> void) { - return (this).__backing_customBuilderParam!; - } - - public set customBuilderParam(@memo() value: (()=> void)) { - (this).__backing_customBuilderParam = value; - } - - @memo() public customBuilder() {} - - @memo() public _build(@memo() style: ((instance: Child)=> Child) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Child | undefined): void { - (this).customBuilderParam(); - } - - public constructor() {} - -} - -@Component({freezeWhenInactive:false}) final class Parent extends CustomComponent { - public __initializeStruct(initializers: __Options_Parent | undefined, @memo() content: (()=> void) | undefined): void {} - - public __updateStruct(initializers: __Options_Parent | undefined): void {} - - @memo() public componentBuilder() { - Text(undefined, "Parent builder", undefined, undefined); - } - - @memo() public _build(@memo() style: ((instance: Parent)=> Parent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Parent | undefined): void { - Column(undefined, undefined, (() => { - Child._instantiateImpl(undefined, (() => { - return new Child(); - }), ({ - customBuilderParam: (this).componentBuilder, - } as __Options_Child), undefined, undefined); - Child._instantiateImpl(undefined, (() => { - return new Child(); - }), ({ - customBuilderParam: @memo() (() => { - (this).componentBuilder(); - }), - } as __Options_Child), undefined, undefined); - Child._instantiateImpl(undefined, (() => { - return new Child(); - }), undefined, (() => { - Text(undefined, "Parent builder", undefined, undefined); - }), undefined); - })); - } - public constructor() {} -} - -interface __Options_Child { - set customBuilderParam(customBuilderParam: @memo() (()=> void) | undefined) - get customBuilderParam(): @memo() (()=> void) | undefined -} - -interface __Options_Parent { -} -`; - -function testCheckedTransformer(this: PluginTestContext): void { - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'test builder param variable passing', - [parsedTransform, uiNoRecheck], - { - 'checked:ui-no-recheck': [testCheckedTransformer], - }, - { - stopAfter: 'checked', - } -); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/builder-param/init-with-local-builder.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/builder-param/init-with-local-builder.test.ts deleted file mode 100644 index 21e7f2bb4..000000000 --- a/arkui-plugins/test/ut/ui-plugins/decorators/builder-param/init-with-local-builder.test.ts +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; -import { parseDumpSrc } from '../../../../utils/parse-string'; -import { uiNoRecheck } from '../../../../utils/plugins'; -import { uiTransform } from '../../../../../ui-plugins'; -import { Plugins } from '../../../../../common/plugin-context'; - -const FUNCTION_DIR_PATH: string = 'decorators/builder-param'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [ - path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, FUNCTION_DIR_PATH, 'init-with-local-builder.ets'), -]; - -const pluginTester = new PluginTester('test builder param init with local builder', buildConfig); - -const parsedTransform: Plugins = { - name: 'init-with-local-builder', - parsed: uiTransform().parsed -}; - -const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; -import { memo as memo } from "arkui.stateManagement.runtime"; -import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; -import { Component as Component, Builder as Builder, BuilderParam as BuilderParam } from "@ohos.arkui.component"; - -function main() {} - -@Component({freezeWhenInactive:false}) final class Child extends CustomComponent { - public __initializeStruct(initializers: __Options_Child | undefined, @memo() content: (()=> void) | undefined): void { - this.__backing_customBuilderParam = ((((({let gensym___169376706 = initializers; - (((gensym___169376706) == (null)) ? undefined : gensym___169376706.customBuilderParam)})) ?? (content))) ?? (this.doNothingBuilder)) - this.__backing_customBuilderParam2 = ((((({let gensym___14041256 = initializers; - (((gensym___14041256) == (null)) ? undefined : gensym___14041256.customBuilderParam2)})) ?? (content))) ?? (this.doNothingBuilder2)) - } - public __updateStruct(initializers: __Options_Child | undefined): void {} - private __backing_customBuilderParam?: @memo() (()=> void); - public get customBuilderParam(): @memo() (()=> void) { - return this.__backing_customBuilderParam!; - } - public set customBuilderParam(@memo() value: (()=> void)) { - this.__backing_customBuilderParam = value; - } - private __backing_customBuilderParam2?: @memo() ((str: string)=> void); - public get customBuilderParam2(): @memo() ((str: string)=> void) { - return this.__backing_customBuilderParam2!; - } - public set customBuilderParam2(@memo() value: ((str: string)=> void)) { - this.__backing_customBuilderParam2 = value; - } - @memo() public doNothingBuilder() {} - @memo() public doNothingBuilder2(str: string) {} - @memo() public _build(@memo() style: ((instance: Child)=> Child) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Child | undefined): void { - this.customBuilderParam(); - this.customBuilderParam2("hello"); - } - public constructor() {} -} - -interface __Options_Child { - set customBuilderParam(customBuilderParam: @memo() (()=> void) | undefined) - get customBuilderParam(): @memo() (()=> void) | undefined - set customBuilderParam2(customBuilderParam2: @memo() ((str: string)=> void) | undefined) - get customBuilderParam2(): @memo() ((str: string)=> void) | undefined -} -`; - -function testCheckedTransformer(this: PluginTestContext): void { - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'test builder param init with local builder', - [parsedTransform, uiNoRecheck], - { - 'checked:ui-no-recheck': [testCheckedTransformer], - }, - { - stopAfter: 'checked', - } -); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/builder/global-builder.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/builder/global-builder.test.ts deleted file mode 100644 index 95740a1d5..000000000 --- a/arkui-plugins/test/ut/ui-plugins/decorators/builder/global-builder.test.ts +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; -import { parseDumpSrc } from '../../../../utils/parse-string'; -import { uiNoRecheck } from '../../../../utils/plugins'; -import { uiTransform } from '../../../../../ui-plugins'; -import { Plugins } from '../../../../../common/plugin-context'; - -const FUNCTION_DIR_PATH: string = 'decorators/builder'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [ - path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, FUNCTION_DIR_PATH, 'global-builder.ets'), -]; - -const pluginTester = new PluginTester('test global builder', buildConfig); - -const parsedTransform: Plugins = { - name: 'global-builder', - parsed: uiTransform().parsed -}; - -const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; -import { memo as memo } from "arkui.stateManagement.runtime"; -import { UITextAttribute as UITextAttribute } from "@ohos.arkui.component"; -import { UIRowAttribute as UIRowAttribute } from "@ohos.arkui.component"; -import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; -import { Component as Component, Row as Row, Builder as Builder, Text as Text } from "@ohos.arkui.component"; - -function main() {} - -@memo() function showTextBuilder() { - Text(undefined, "Hello World", undefined, undefined); -} - -@memo() function overBuilder(params: Tmp) { - Row(undefined, undefined, (() => { - Text(undefined, (("UseStateVarByReference: ") + (params.paramA1)), undefined, undefined); - })); -} - -class Tmp { - public paramA1: string = ""; - public constructor() {} -} - -@Component({freezeWhenInactive:false}) final class BuilderDemo extends CustomComponent { - public __initializeStruct(initializers: __Options_BuilderDemo | undefined, @memo() content: (()=> void) | undefined): void {} - public __updateStruct(initializers: __Options_BuilderDemo | undefined): void {} - @memo() public _build(@memo() style: ((instance: BuilderDemo)=> BuilderDemo) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_BuilderDemo | undefined): void { - Row(undefined, undefined, @memo() (() => { - showTextBuilder(); - overBuilder({ - paramA1: "Hello", - }); - })); - } - public constructor() {} -} - -interface __Options_BuilderDemo { - -} -`; - -function testCheckedTransformer(this: PluginTestContext): void { - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'global builder', - [parsedTransform, uiNoRecheck], - { - 'checked:ui-no-recheck': [testCheckedTransformer], - }, - { - stopAfter: 'checked', - } -); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/builder/local-builder.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/builder/local-builder.test.ts deleted file mode 100644 index 9769285c5..000000000 --- a/arkui-plugins/test/ut/ui-plugins/decorators/builder/local-builder.test.ts +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; -import { parseDumpSrc } from '../../../../utils/parse-string'; -import { uiNoRecheck } from '../../../../utils/plugins'; -import { uiTransform } from '../../../../../ui-plugins'; -import { Plugins } from '../../../../../common/plugin-context'; - -const FUNCTION_DIR_PATH: string = 'decorators/builder'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [ - path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, FUNCTION_DIR_PATH, 'local-builder.ets'), -]; - -const pluginTester = new PluginTester('test local builder', buildConfig); - -const parsedTransform: Plugins = { - name: 'local-builder', - parsed: uiTransform().parsed -}; - -const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; -import { memo as memo } from "arkui.stateManagement.runtime"; -import { UITextAttribute as UITextAttribute } from "@ohos.arkui.component"; -import { UIColumnAttribute as UIColumnAttribute } from "@ohos.arkui.component"; -import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; -import { Component as Component, Column as Column, Builder as Builder, Text as Text } from "@ohos.arkui.component"; - -function main() {} - -@Component({freezeWhenInactive:false}) final class BuilderDemo extends CustomComponent { - public __initializeStruct(initializers: __Options_BuilderDemo | undefined, @memo() content: (()=> void) | undefined): void {} - public __updateStruct(initializers: __Options_BuilderDemo | undefined): void {} - @memo() public showTextBuilder() { - Text(@memo() ((instance: UITextAttribute): void => { - instance.fontSize(30); - return; - }), "Hello World", undefined, undefined); - } - @memo() public showTextValueBuilder(param: string) { - Text(@memo() ((instance: UITextAttribute): void => { - instance.fontSize(30); - return; - }), param, undefined, undefined); - } - @memo() public _build(@memo() style: ((instance: BuilderDemo)=> BuilderDemo) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_BuilderDemo | undefined): void { - Column(undefined, undefined, @memo() (() => { - this.showTextBuilder(); - this.showTextValueBuilder("Hello @Builder"); - })); - } - public constructor() {} -} - -interface __Options_BuilderDemo { - -} -`; - -function testCheckedTransformer(this: PluginTestContext): void { - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'local builder', - [parsedTransform, uiNoRecheck], - { - 'checked:ui-no-recheck': [testCheckedTransformer], - }, - { - stopAfter: 'checked', - } -); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/link/link-basic-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/link/link-basic-type.test.ts deleted file mode 100644 index 340db6a9e..000000000 --- a/arkui-plugins/test/ut/ui-plugins/decorators/link/link-basic-type.test.ts +++ /dev/null @@ -1,151 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; -import { parseDumpSrc } from '../../../../utils/parse-string'; -import { structNoRecheck } from '../../../../utils/plugins'; -import { uiTransform } from '../../../../../ui-plugins'; -import { Plugins } from '../../../../../common/plugin-context'; - -const BUILDER_LAMBDA_DIR_PATH: string = 'decorators/link'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [ - path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, BUILDER_LAMBDA_DIR_PATH, 'link-basic-type.ets'), -]; - -const pluginTester = new PluginTester('test basic type @Link decorated variables transformation', buildConfig); - -const parsedTransform: Plugins = { - name: 'link-basic-type', - parsed: uiTransform().parsed -}; - -const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; -import { memo as memo } from "arkui.stateManagement.runtime"; -import { DecoratedV1VariableBase as DecoratedV1VariableBase } from "@ohos.arkui.stateManagement"; -import { LinkDecoratedVariable as LinkDecoratedVariable } from "@ohos.arkui.stateManagement"; -import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; -import { Component as Component } from "@ohos.arkui.component"; -import { Link as Link } from "@ohos.arkui.stateManagement"; - -function main() {} - -@Component({freezeWhenInactive:false}) final class LinkParent extends CustomComponent { - public __initializeStruct(initializers: __Options_LinkParent | undefined, @memo() content: (()=> void) | undefined): void { - if (({let gensym___11910109 = initializers; - (((gensym___11910109) == (null)) ? undefined : gensym___11910109.__backing_linkVar1)})) { - this.__backing_linkVar1 = new LinkDecoratedVariable("linkVar1", initializers!.__backing_linkVar1!); - }; - if (({let gensym___181684045 = initializers; - (((gensym___181684045) == (null)) ? undefined : gensym___181684045.__backing_linkVar2)})) { - this.__backing_linkVar2 = new LinkDecoratedVariable("linkVar2", initializers!.__backing_linkVar2!); - }; - if (({let gensym___24446313 = initializers; - (((gensym___24446313) == (null)) ? undefined : gensym___24446313.__backing_linkVar3)})) { - this.__backing_linkVar3 = new LinkDecoratedVariable("linkVar3", initializers!.__backing_linkVar3!); - }; - if (({let gensym___167989826 = initializers; - (((gensym___167989826) == (null)) ? undefined : gensym___167989826.__backing_linkVar4)})) { - this.__backing_linkVar4 = new LinkDecoratedVariable("linkVar4", initializers!.__backing_linkVar4!); - }; - if (({let gensym___157566097 = initializers; - (((gensym___157566097) == (null)) ? undefined : gensym___157566097.__backing_linkVar5)})) { - this.__backing_linkVar5 = new LinkDecoratedVariable("linkVar5", initializers!.__backing_linkVar5!); - }; - } - public __updateStruct(initializers: __Options_LinkParent | undefined): void {} - private __backing_linkVar1?: LinkDecoratedVariable; - public get linkVar1(): string { - return this.__backing_linkVar1!.get(); - } - public set linkVar1(value: string) { - this.__backing_linkVar1!.set(value); - } - private __backing_linkVar2?: LinkDecoratedVariable; - public get linkVar2(): number { - return this.__backing_linkVar2!.get(); - } - public set linkVar2(value: number) { - this.__backing_linkVar2!.set(value); - } - private __backing_linkVar3?: LinkDecoratedVariable; - public get linkVar3(): boolean { - return this.__backing_linkVar3!.get(); - } - public set linkVar3(value: boolean) { - this.__backing_linkVar3!.set(value); - } - private __backing_linkVar4?: LinkDecoratedVariable; - public get linkVar4(): undefined { - return this.__backing_linkVar4!.get(); - } - public set linkVar4(value: undefined) { - this.__backing_linkVar4!.set(value); - } - private __backing_linkVar5?: LinkDecoratedVariable; - public get linkVar5(): null { - return this.__backing_linkVar5!.get(); - } - public set linkVar5(value: null) { - this.__backing_linkVar5!.set(value); - } - @memo() public _build(@memo() style: ((instance: LinkParent)=> LinkParent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_LinkParent | undefined): void {} - public constructor() {} -} - -interface __Options_LinkParent { - set linkVar1(linkVar1: string | undefined) - get linkVar1(): string | undefined - set __backing_linkVar1(__backing_linkVar1: DecoratedV1VariableBase | undefined) - get __backing_linkVar1(): DecoratedV1VariableBase | undefined - set linkVar2(linkVar2: number | undefined) - get linkVar2(): number | undefined - set __backing_linkVar2(__backing_linkVar2: DecoratedV1VariableBase | undefined) - get __backing_linkVar2(): DecoratedV1VariableBase | undefined - set linkVar3(linkVar3: boolean | undefined) - get linkVar3(): boolean | undefined - set __backing_linkVar3(__backing_linkVar3: DecoratedV1VariableBase | undefined) - get __backing_linkVar3(): DecoratedV1VariableBase | undefined - set linkVar4(linkVar4: undefined | undefined) - get linkVar4(): undefined | undefined - set __backing_linkVar4(__backing_linkVar4: DecoratedV1VariableBase | undefined) - get __backing_linkVar4(): DecoratedV1VariableBase | undefined - set linkVar5(linkVar5: null | undefined) - get linkVar5(): null | undefined - set __backing_linkVar5(__backing_linkVar5: DecoratedV1VariableBase | undefined) - get __backing_linkVar5(): DecoratedV1VariableBase | undefined -} -`; - -function testParsedAndCheckedTransformer(this: PluginTestContext): void { - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'test basic type @Link decorated variables transformation', - [parsedTransform, structNoRecheck], - { - checked: [testParsedAndCheckedTransformer], - }, - { - stopAfter: 'checked', - } -); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/link/link-complex-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/link/link-complex-type.test.ts deleted file mode 100644 index 486097a84..000000000 --- a/arkui-plugins/test/ut/ui-plugins/decorators/link/link-complex-type.test.ts +++ /dev/null @@ -1,314 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; -import { parseDumpSrc } from '../../../../utils/parse-string'; -import { structNoRecheck } from '../../../../utils/plugins'; -import { uiTransform } from '../../../../../ui-plugins'; -import { Plugins } from '../../../../../common/plugin-context'; - -const BUILDER_LAMBDA_DIR_PATH: string = 'decorators/link'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [ - path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, BUILDER_LAMBDA_DIR_PATH, 'link-complex-type.ets'), -]; - -const pluginTester = new PluginTester('test complex type @Link decorated variables transformation', buildConfig); - -const parsedTransform: Plugins = { - name: 'link-complex-type', - parsed: uiTransform().parsed -}; - -const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; -import { memo as memo } from "arkui.stateManagement.runtime"; -import { DecoratedV1VariableBase as DecoratedV1VariableBase } from "@ohos.arkui.stateManagement"; -import { LinkDecoratedVariable as LinkDecoratedVariable } from "@ohos.arkui.stateManagement"; -import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; -import { Component as Component } from "@ohos.arkui.component"; -import { Link as Link } from "@ohos.arkui.stateManagement"; - -function main() {} - -class Per { - public num: number; - public constructor(num: number) { - this.num = num; - } -} - -final class LinkType extends BaseEnum { - private readonly #ordinal: int; - private static () {} - public constructor(ordinal: int, value: int) { - super(value); - this.#ordinal = ordinal; - } - public static readonly TYPE1: LinkType = new LinkType(0, 0); - public static readonly TYPE2: LinkType = new LinkType(1, 1); - public static readonly TYPE3: LinkType = new LinkType(2, 3); - private static readonly #NamesArray: String[] = ["TYPE1", "TYPE2", "TYPE3"]; - private static readonly #ValuesArray: int[] = [0, 1, 3]; - private static readonly #StringValuesArray: String[] = ["0", "1", "3"]; - private static readonly #ItemsArray: LinkType[] = [LinkType.TYPE1, LinkType.TYPE2, LinkType.TYPE3]; - public getName(): String { - return LinkType.#NamesArray[this.#ordinal]; - } - public static getValueOf(name: String): LinkType { - for (let i = 0;((i) < (LinkType.#NamesArray.length));(++i)) { - if (((name) == (LinkType.#NamesArray[i]))) { - return LinkType.#ItemsArray[i]; - } - } - throw new Error((("No enum constant LinkType.") + (name))); - } - - public static fromValue(value: int): LinkType { - for (let i = 0;((i) < (LinkType.#ValuesArray.length));(++i)) { - if (((value) == (LinkType.#ValuesArray[i]))) { - return LinkType.#ItemsArray[i]; - } - } - throw new Error((("No enum LinkType with value ") + (value))); - } - public valueOf(): int { - return LinkType.#ValuesArray[this.#ordinal]; - } - public toString(): String { - return LinkType.#StringValuesArray[this.#ordinal]; - } - public static values(): LinkType[] { - return LinkType.#ItemsArray; - } - public getOrdinal(): int { - return this.#ordinal; - } - public static $_get(e: LinkType): String { - return e.getName(); - } -} - -@Component({freezeWhenInactive:false}) final class Parent extends CustomComponent { - public __initializeStruct(initializers: __Options_Parent | undefined, @memo() content: (()=> void) | undefined): void { - if (({let gensym___11910109 = initializers; - (((gensym___11910109) == (null)) ? undefined : gensym___11910109.__backing_linkVar1)})) { - this.__backing_linkVar1 = new LinkDecoratedVariable("linkVar1", initializers!.__backing_linkVar1!); - }; - if (({let gensym___181684045 = initializers; - (((gensym___181684045) == (null)) ? undefined : gensym___181684045.__backing_linkVar2)})) { - this.__backing_linkVar2 = new LinkDecoratedVariable>("linkVar2", initializers!.__backing_linkVar2!); - }; - if (({let gensym___24446313 = initializers; - (((gensym___24446313) == (null)) ? undefined : gensym___24446313.__backing_linkVar3)})) { - this.__backing_linkVar3 = new LinkDecoratedVariable("linkVar3", initializers!.__backing_linkVar3!); - }; - if (({let gensym___167989826 = initializers; - (((gensym___167989826) == (null)) ? undefined : gensym___167989826.__backing_linkVar4)})) { - this.__backing_linkVar4 = new LinkDecoratedVariable>("linkVar4", initializers!.__backing_linkVar4!); - }; - if (({let gensym___157566097 = initializers; - (((gensym___157566097) == (null)) ? undefined : gensym___157566097.__backing_linkVar5)})) { - this.__backing_linkVar5 = new LinkDecoratedVariable>("linkVar5", initializers!.__backing_linkVar5!); - }; - if (({let gensym___60105491 = initializers; - (((gensym___60105491) == (null)) ? undefined : gensym___60105491.__backing_linkVar6)})) { - this.__backing_linkVar6 = new LinkDecoratedVariable>("linkVar6", initializers!.__backing_linkVar6!); - }; - if (({let gensym___3429048 = initializers; - (((gensym___3429048) == (null)) ? undefined : gensym___3429048.__backing_linkVar7)})) { - this.__backing_linkVar7 = new LinkDecoratedVariable>("linkVar7", initializers!.__backing_linkVar7!); - }; - if (({let gensym___139916435 = initializers; - (((gensym___139916435) == (null)) ? undefined : gensym___139916435.__backing_linkVar8)})) { - this.__backing_linkVar8 = new LinkDecoratedVariable<((sr: string)=> void)>("linkVar8", initializers!.__backing_linkVar8!); - }; - if (({let gensym___145003260 = initializers; - (((gensym___145003260) == (null)) ? undefined : gensym___145003260.__backing_linkVar9)})) { - this.__backing_linkVar9 = new LinkDecoratedVariable("linkVar9", initializers!.__backing_linkVar9!); - }; - if (({let gensym___122643185 = initializers; - (((gensym___122643185) == (null)) ? undefined : gensym___122643185.__backing_linkVar10)})) { - this.__backing_linkVar10 = new LinkDecoratedVariable>("linkVar10", initializers!.__backing_linkVar10!); - }; - if (({let gensym___222468503 = initializers; - (((gensym___222468503) == (null)) ? undefined : gensym___222468503.__backing_linkVar11)})) { - this.__backing_linkVar11 = new LinkDecoratedVariable("linkVar11", initializers!.__backing_linkVar11!); - }; - if (({let gensym___243301539 = initializers; - (((gensym___243301539) == (null)) ? undefined : gensym___243301539.__backing_linkVar12)})) { - this.__backing_linkVar12 = new LinkDecoratedVariable | Per>("linkVar12", initializers!.__backing_linkVar12!); - }; - } - public __updateStruct(initializers: __Options_Parent | undefined): void {} - private __backing_linkVar1?: LinkDecoratedVariable; - public get linkVar1(): Per { - return this.__backing_linkVar1!.get(); - } - public set linkVar1(value: Per) { - this.__backing_linkVar1!.set(value); - } - private __backing_linkVar2?: LinkDecoratedVariable>; - public get linkVar2(): Array { - return this.__backing_linkVar2!.get(); - } - public set linkVar2(value: Array) { - this.__backing_linkVar2!.set(value); - } - private __backing_linkVar3?: LinkDecoratedVariable; - public get linkVar3(): LinkType { - return this.__backing_linkVar3!.get(); - } - public set linkVar3(value: LinkType) { - this.__backing_linkVar3!.set(value); - } - private __backing_linkVar4?: LinkDecoratedVariable>; - public get linkVar4(): Set { - return this.__backing_linkVar4!.get(); - } - public set linkVar4(value: Set) { - this.__backing_linkVar4!.set(value); - } - private __backing_linkVar5?: LinkDecoratedVariable>; - public get linkVar5(): Array { - return this.__backing_linkVar5!.get(); - } - public set linkVar5(value: Array) { - this.__backing_linkVar5!.set(value); - } - private __backing_linkVar6?: LinkDecoratedVariable>; - public get linkVar6(): Array { - return this.__backing_linkVar6!.get(); - } - public set linkVar6(value: Array) { - this.__backing_linkVar6!.set(value); - } - private __backing_linkVar7?: LinkDecoratedVariable>; - public get linkVar7(): Array { - return this.__backing_linkVar7!.get(); - } - public set linkVar7(value: Array) { - this.__backing_linkVar7!.set(value); - } - private __backing_linkVar8?: LinkDecoratedVariable<((sr: string)=> void)>; - public get linkVar8(): ((sr: string)=> void) { - return this.__backing_linkVar8!.get(); - } - public set linkVar8(value: ((sr: string)=> void)) { - this.__backing_linkVar8!.set(value); - } - private __backing_linkVar9?: LinkDecoratedVariable; - public get linkVar9(): Date { - return this.__backing_linkVar9!.get(); - } - public set linkVar9(value: Date) { - this.__backing_linkVar9!.set(value); - } - private __backing_linkVar10?: LinkDecoratedVariable>; - public get linkVar10(): Map { - return this.__backing_linkVar10!.get(); - } - public set linkVar10(value: Map) { - this.__backing_linkVar10!.set(value); - } - private __backing_linkVar11?: LinkDecoratedVariable; - public get linkVar11(): string | number { - return this.__backing_linkVar11!.get(); - } - public set linkVar11(value: string | number) { - this.__backing_linkVar11!.set(value); - } - private __backing_linkVar12?: LinkDecoratedVariable | Per>; - public get linkVar12(): Set | Per { - return this.__backing_linkVar12!.get(); - } - public set linkVar12(value: Set | Per) { - this.__backing_linkVar12!.set(value); - } - @memo() public _build(@memo() style: ((instance: Parent)=> Parent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Parent | undefined): void {} - public constructor() {} -} - -interface __Options_Parent { - set linkVar1(linkVar1: Per | undefined) - get linkVar1(): Per | undefined - set __backing_linkVar1(__backing_linkVar1: DecoratedV1VariableBase | undefined) - get __backing_linkVar1(): DecoratedV1VariableBase | undefined - set linkVar2(linkVar2: Array | undefined) - get linkVar2(): Array | undefined - set __backing_linkVar2(__backing_linkVar2: DecoratedV1VariableBase> | undefined) - get __backing_linkVar2(): DecoratedV1VariableBase> | undefined - set linkVar3(linkVar3: LinkType | undefined) - get linkVar3(): LinkType | undefined - set __backing_linkVar3(__backing_linkVar3: DecoratedV1VariableBase | undefined) - get __backing_linkVar3(): DecoratedV1VariableBase | undefined - set linkVar4(linkVar4: Set | undefined) - get linkVar4(): Set | undefined - set __backing_linkVar4(__backing_linkVar4: DecoratedV1VariableBase> | undefined) - get __backing_linkVar4(): DecoratedV1VariableBase> | undefined - set linkVar5(linkVar5: Array | undefined) - get linkVar5(): Array | undefined - set __backing_linkVar5(__backing_linkVar5: DecoratedV1VariableBase> | undefined) - get __backing_linkVar5(): DecoratedV1VariableBase> | undefined - set linkVar6(linkVar6: Array | undefined) - get linkVar6(): Array | undefined - set __backing_linkVar6(__backing_linkVar6: DecoratedV1VariableBase> | undefined) - get __backing_linkVar6(): DecoratedV1VariableBase> | undefined - set linkVar7(linkVar7: Array | undefined) - get linkVar7(): Array | undefined - set __backing_linkVar7(__backing_linkVar7: DecoratedV1VariableBase> | undefined) - get __backing_linkVar7(): DecoratedV1VariableBase> | undefined - set linkVar8(linkVar8: ((sr: string)=> void) | undefined) - get linkVar8(): ((sr: string)=> void) | undefined - set __backing_linkVar8(__backing_linkVar8: DecoratedV1VariableBase<((sr: string)=> void)> | undefined) - get __backing_linkVar8(): DecoratedV1VariableBase<((sr: string)=> void)> | undefined - set linkVar9(linkVar9: Date | undefined) - get linkVar9(): Date | undefined - set __backing_linkVar9(__backing_linkVar9: DecoratedV1VariableBase | undefined) - get __backing_linkVar9(): DecoratedV1VariableBase | undefined - set linkVar10(linkVar10: Map | undefined) - get linkVar10(): Map | undefined - set __backing_linkVar10(__backing_linkVar10: DecoratedV1VariableBase> | undefined) - get __backing_linkVar10(): DecoratedV1VariableBase> | undefined - set linkVar11(linkVar11: string | number | undefined) - get linkVar11(): string | number | undefined - set __backing_linkVar11(__backing_linkVar11: DecoratedV1VariableBase | undefined) - get __backing_linkVar11(): DecoratedV1VariableBase | undefined - set linkVar12(linkVar12: Set | Per | undefined) - get linkVar12(): Set | Per | undefined - set __backing_linkVar12(__backing_linkVar12: DecoratedV1VariableBase | Per> | undefined) - get __backing_linkVar12(): DecoratedV1VariableBase | Per> | undefined -} -`; - -function testParsedAndCheckedTransformer(this: PluginTestContext): void { - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'test complex type @Link decorated variables transformation', - [parsedTransform, structNoRecheck], - { - checked: [testParsedAndCheckedTransformer], - }, - { - stopAfter: 'checked', - } -); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/link/link-to-link-prop-state.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/link/link-to-link-prop-state.test.ts deleted file mode 100644 index 01a8275f9..000000000 --- a/arkui-plugins/test/ut/ui-plugins/decorators/link/link-to-link-prop-state.test.ts +++ /dev/null @@ -1,186 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; -import { parseDumpSrc } from '../../../../utils/parse-string'; -import { uiNoRecheck } from '../../../../utils/plugins'; -import { uiTransform } from '../../../../../ui-plugins'; -import { Plugins } from '../../../../../common/plugin-context'; - -const BUILDER_LAMBDA_DIR_PATH: string = 'decorators/link'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [ - path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, BUILDER_LAMBDA_DIR_PATH, 'link-to-link-prop-state.ets'), -]; - -const pluginTester = new PluginTester('test @Link decorated variables passing to other variables', buildConfig); - -const parsedTransform: Plugins = { - name: 'link-to-link-prop-state', - parsed: uiTransform().parsed -}; - -const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; -import { memo as memo } from "arkui.stateManagement.runtime"; -import { PropDecoratedVariable as PropDecoratedVariable } from "@ohos.arkui.stateManagement"; -import { StateDecoratedVariable as StateDecoratedVariable } from "@ohos.arkui.stateManagement"; -import { DecoratedV1VariableBase as DecoratedV1VariableBase } from "@ohos.arkui.stateManagement"; -import { LinkDecoratedVariable as LinkDecoratedVariable } from "@ohos.arkui.stateManagement"; -import { UITextInputAttribute as UITextInputAttribute } from "@ohos.arkui.component"; -import { UIColumnAttribute as UIColumnAttribute } from "@ohos.arkui.component"; -import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; -import { Component as Component, Column as Column, TextInput as TextInput } from "@ohos.arkui.component"; -import { Link as Link, State as State, Prop as Prop } from "@ohos.arkui.stateManagement"; - -function main() {} - -@Component({freezeWhenInactive:false}) final class Parant extends CustomComponent { - public __initializeStruct(initializers: __Options_Parant | undefined, @memo() content: (()=> void) | undefined): void { - if (({let gensym___10127521 = initializers; - (((gensym___10127521) == (null)) ? undefined : gensym___10127521.__backing_text1)})) { - this.__backing_text1 = new LinkDecoratedVariable("text1", initializers!.__backing_text1!); - }; - } - public __updateStruct(initializers: __Options_Parant | undefined): void {} - private __backing_text1?: LinkDecoratedVariable; - public get text1(): string { - return this.__backing_text1!.get(); - } - public set text1(value: string) { - this.__backing_text1!.set(value); - } - @memo() public _build(@memo() style: ((instance: Parant)=> Parant) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Parant | undefined): void { - Column(undefined, undefined, (() => { - TextInput(undefined, { - text: this.text1, - }, undefined); - Child._instantiateImpl(undefined, (() => { - return new Child(); - }), ({ - __backing_childText: this.__backing_text1, - childText2: this.text1, - childText3: this.text1, - childText4: this.text1, - } as __Options_Child), undefined, undefined); - })); - } - public constructor() {} -} - -@Component({freezeWhenInactive:false}) final class Child extends CustomComponent { - public __initializeStruct(initializers: __Options_Child | undefined, @memo() content: (()=> void) | undefined): void { - if (({let gensym___161337494 = initializers; - (((gensym___161337494) == (null)) ? undefined : gensym___161337494.__backing_childText)})) { - this.__backing_childText = new LinkDecoratedVariable("childText", initializers!.__backing_childText!); - }; - this.__backing_childText2 = new StateDecoratedVariable("childText2", ((({let gensym___95513066 = initializers; - (((gensym___95513066) == (null)) ? undefined : gensym___95513066.childText2)})) ?? ("sss"))); - this.__backing_childText3 = new PropDecoratedVariable("childText3", (initializers!.childText3 as string)); - this.__backing_childText4 = new PropDecoratedVariable("childText4", ((({let gensym___162028107 = initializers; - (((gensym___162028107) == (null)) ? undefined : gensym___162028107.childText4)})) ?? ("cc"))); - } - public __updateStruct(initializers: __Options_Child | undefined): void { - if (((({let gensym___77632518 = initializers; - (((gensym___77632518) == (null)) ? undefined : gensym___77632518.childText3)})) !== (undefined))) { - this.__backing_childText3!.update((initializers!.childText3 as string)); - } - if (((({let gensym___250510741 = initializers; - (((gensym___250510741) == (null)) ? undefined : gensym___250510741.childText4)})) !== (undefined))) { - this.__backing_childText4!.update((initializers!.childText4 as string)); - } - } - private __backing_childText?: LinkDecoratedVariable; - public get childText(): string { - return this.__backing_childText!.get(); - } - public set childText(value: string) { - this.__backing_childText!.set(value); - } - private __backing_childText2?: StateDecoratedVariable; - public get childText2(): string { - return this.__backing_childText2!.get(); - } - public set childText2(value: string) { - this.__backing_childText2!.set(value); - } - private __backing_childText3?: PropDecoratedVariable; - public get childText3(): string { - return this.__backing_childText3!.get(); - } - public set childText3(value: string) { - this.__backing_childText3!.set(value); - } - private __backing_childText4?: PropDecoratedVariable; - public get childText4(): string { - return this.__backing_childText4!.get(); - } - public set childText4(value: string) { - this.__backing_childText4!.set(value); - } - @memo() public _build(@memo() style: ((instance: Child)=> Child) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Child | undefined): void { - TextInput(undefined, { - text: this.childText, - }, undefined); - } - public constructor() {} -} - -interface __Options_Parant { - set text1(text1: string | undefined) - get text1(): string | undefined - set __backing_text1(__backing_text1: DecoratedV1VariableBase | undefined) - get __backing_text1(): DecoratedV1VariableBase | undefined -} - -interface __Options_Child { - set childText(childText: string | undefined) - get childText(): string | undefined - set __backing_childText(__backing_childText: DecoratedV1VariableBase | undefined) - get __backing_childText(): DecoratedV1VariableBase | undefined - set childText2(childText2: string | undefined) - get childText2(): string | undefined - set __backing_childText2(__backing_childText2: StateDecoratedVariable | undefined) - get __backing_childText2(): StateDecoratedVariable | undefined - set childText3(childText3: string | undefined) - get childText3(): string | undefined - set __backing_childText3(__backing_childText3: PropDecoratedVariable | undefined) - get __backing_childText3(): PropDecoratedVariable | undefined - set childText4(childText4: string | undefined) - get childText4(): string | undefined - set __backing_childText4(__backing_childText4: PropDecoratedVariable | undefined) - get __backing_childText4(): PropDecoratedVariable | undefined -} -`; - -function testParsedAndCheckedTransformer(this: PluginTestContext): void { - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'test @Link decorated variables passing to other variables', - [parsedTransform, uiNoRecheck], - { - checked: [testParsedAndCheckedTransformer], - }, - { - stopAfter: 'checked', - } -); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/link/state-to-link.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/link/state-to-link.test.ts deleted file mode 100644 index cd9424e90..000000000 --- a/arkui-plugins/test/ut/ui-plugins/decorators/link/state-to-link.test.ts +++ /dev/null @@ -1,175 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; -import { parseDumpSrc } from '../../../../utils/parse-string'; -import { uiNoRecheck } from '../../../../utils/plugins'; -import { uiTransform } from '../../../../../ui-plugins'; -import { Plugins } from '../../../../../common/plugin-context'; - -const BUILDER_LAMBDA_DIR_PATH: string = 'decorators/link'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [ - path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, BUILDER_LAMBDA_DIR_PATH, 'state-to-link.ets'), -]; - -const pluginTester = new PluginTester('test @Link decorated variables passing', buildConfig); - -const parsedTransform: Plugins = { - name: 'state-to-link', - parsed: uiTransform().parsed -}; - -const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; -import { memo as memo } from "arkui.stateManagement.runtime"; -import { StateDecoratedVariable as StateDecoratedVariable } from "@ohos.arkui.stateManagement"; -import { DecoratedV1VariableBase as DecoratedV1VariableBase } from "@ohos.arkui.stateManagement"; -import { LinkDecoratedVariable as LinkDecoratedVariable } from "@ohos.arkui.stateManagement"; -import { UIDatePickerAttribute as UIDatePickerAttribute } from "@ohos.arkui.component"; -import { UIButtonAttribute as UIButtonAttribute } from "@ohos.arkui.component"; -import { UIColumnAttribute as UIColumnAttribute } from "@ohos.arkui.component"; -import { EntryPoint as EntryPoint } from "arkui.UserView"; -import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; -import { Component as Component, Entry as Entry, Column as Column, Button as Button, DatePicker as DatePicker, ClickEvent as ClickEvent } from "@ohos.arkui.component"; -import { Link as Link, State as State } from "@ohos.arkui.stateManagement"; - -function main() {} - -@Component({freezeWhenInactive:false}) final class DateComponent extends CustomComponent { - public __initializeStruct(initializers: __Options_DateComponent | undefined, @memo() content: (()=> void) | undefined): void { - if (({let gensym___164314175 = initializers; - (((gensym___164314175) == (null)) ? undefined : gensym___164314175.__backing_selectedDate)})) { - this.__backing_selectedDate = new LinkDecoratedVariable("selectedDate", initializers!.__backing_selectedDate!); - }; - } - public __updateStruct(initializers: __Options_DateComponent | undefined): void {} - private __backing_selectedDate?: LinkDecoratedVariable; - public get selectedDate(): Date { - return this.__backing_selectedDate!.get(); - } - public set selectedDate(value: Date) { - this.__backing_selectedDate!.set(value); - } - @memo() public _build(@memo() style: ((instance: DateComponent)=> DateComponent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_DateComponent | undefined): void { - Column(undefined, undefined, (() => { - Button(@memo() ((instance: UIButtonAttribute): void => { - instance.onClick(((e: ClickEvent) => { - this.selectedDate.setFullYear(((this.selectedDate.getFullYear()) + (1))); - })); - return; - }), "child increase the year by 1", undefined, undefined); - Button(@memo() ((instance: UIButtonAttribute): void => { - instance.margin(10).onClick(((e: ClickEvent) => { - this.selectedDate = new Date("2023-09-09"); - })); - return; - }), "child update the new date", undefined, undefined); - DatePicker(undefined, { - start: new Date("1970-1-1"), - end: new Date("2100-1-1"), - selected: this.selectedDate, - }, undefined); - })); - } - public constructor() {} - -} - -@Entry({useSharedStorage:false,storage:"",routeName:""}) @Component({freezeWhenInactive:false}) final class ParentComponent extends CustomComponent { - public __initializeStruct(initializers: __Options_ParentComponent | undefined, @memo() content: (()=> void) | undefined): void { - this.__backing_parentSelectedDate = new StateDecoratedVariable("parentSelectedDate", ((({let gensym___80922148 = initializers; - (((gensym___80922148) == (null)) ? undefined : gensym___80922148.parentSelectedDate)})) ?? (new Date("2021-08-08")))); - } - public __updateStruct(initializers: __Options_ParentComponent | undefined): void {} - private __backing_parentSelectedDate?: StateDecoratedVariable; - public get parentSelectedDate(): Date { - return this.__backing_parentSelectedDate!.get(); - } - public set parentSelectedDate(value: Date) { - this.__backing_parentSelectedDate!.set(value); - } - @memo() public _build(@memo() style: ((instance: ParentComponent)=> ParentComponent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_ParentComponent | undefined): void { - Column(undefined, undefined, (() => { - Button(@memo() ((instance: UIButtonAttribute): void => { - instance.margin(10).onClick(((e: ClickEvent) => { - this.parentSelectedDate.setMonth(((this.parentSelectedDate.getMonth()) + (1))); - })); - return; - }), "parent increase the month by 1", undefined, undefined); - Button(@memo() ((instance: UIButtonAttribute): void => { - instance.margin(10).onClick(((e: ClickEvent) => { - this.parentSelectedDate = new Date("2023-07-07"); - })); - return; - }), "parent update the new date", undefined, undefined); - DatePicker(undefined, { - start: new Date("1970-1-1"), - end: new Date("2100-1-1"), - selected: this.parentSelectedDate, - }, undefined); - DateComponent._instantiateImpl(undefined, (() => { - return new DateComponent(); - }), ({ - __backing_selectedDate: this.__backing_parentSelectedDate, - } as __Options_DateComponent), undefined, undefined); - })); - } - public constructor() {} -} - -interface __Options_DateComponent { - set selectedDate(selectedDate: Date | undefined) - get selectedDate(): Date | undefined - set __backing_selectedDate(__backing_selectedDate: DecoratedV1VariableBase | undefined) - get __backing_selectedDate(): DecoratedV1VariableBase | undefined -} - -interface __Options_ParentComponent { - set parentSelectedDate(parentSelectedDate: Date | undefined) - get parentSelectedDate(): Date | undefined - set __backing_parentSelectedDate(__backing_parentSelectedDate: StateDecoratedVariable | undefined) - get __backing_parentSelectedDate(): StateDecoratedVariable | undefined -} - -class __EntryWrapper extends EntryPoint { - @memo() public entry(): void { - ParentComponent._instantiateImpl(undefined, (() => { - return new ParentComponent(); - }), undefined, undefined, undefined); - } - public constructor() {} -} -`; - -function testParsedAndCheckedTransformer(this: PluginTestContext): void { - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'test @Link decorated variables passing', - [parsedTransform, uiNoRecheck], - { - checked: [testParsedAndCheckedTransformer], - }, - { - stopAfter: 'checked', - } -); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-only.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-only.test.ts deleted file mode 100644 index 08e0ec65b..000000000 --- a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-only.test.ts +++ /dev/null @@ -1,157 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; -import { parseDumpSrc } from '../../../../utils/parse-string'; -import { uiNoRecheck } from '../../../../utils/plugins'; -import { uiTransform } from '../../../../../ui-plugins'; -import { Plugins } from '../../../../../common/plugin-context'; - -const OBSERVED_DIR_PATH: string = 'decorators/observed-track'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [ - path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, OBSERVED_DIR_PATH, 'observed-only.ets'), -]; - -const observedTrackTransform: Plugins = { - name: 'observedTrack', - parsed: uiTransform().parsed, -} - -const pluginTester = new PluginTester('test observed only transform', buildConfig); - -const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; - -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; - -import { memo as memo } from "arkui.stateManagement.runtime"; - -import { SubscribedWatches as SubscribedWatches } from "@ohos.arkui.stateManagement"; - -import { WatchIdType as WatchIdType } from "@ohos.arkui.stateManagement"; - -import { int32 as int32 } from "@ohos.arkui.stateManagement"; - -import { IObservedObject as IObservedObject } from "@ohos.arkui.stateManagement"; - -import { setObservationDepth as setObservationDepth } from "@ohos.arkui.stateManagement"; - -import { BackingValue as BackingValue } from "@ohos.arkui.stateManagement"; - -import { MutableStateMeta as MutableStateMeta } from "@ohos.arkui.stateManagement"; - -import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; - -import { Component as Component } from "@ohos.arkui.component"; - -import { Observed as Observed } from "@ohos.arkui.stateManagement"; - -function main() {} - - - -@Observed() class A implements IObservedObject { - private subscribedWatches: SubscribedWatches = new SubscribedWatches(); - - public addWatchSubscriber(watchId: WatchIdType): void { - this.subscribedWatches.addWatchSubscriber(watchId); - } - - public removeWatchSubscriber(watchId: WatchIdType): boolean { - return this.subscribedWatches.removeWatchSubscriber(watchId); - } - - public executeOnSubscribingWatches(propertyName: string): void { - this.subscribedWatches.executeOnSubscribingWatches(propertyName); - } - - public _permissibleAddRefDepth: int32 = 0; - - private __meta: MutableStateMeta = new MutableStateMeta("@Observe properties (no @Track)"); - - private __backing_propA: number = 1; - - private __backing_trackA: number = 2; - - public constructor() {} - - public get propA(): number { - if (((this._permissibleAddRefDepth) > (0))) { - this.__meta.addRef(); - } - return this.__backing_propA; - } - - public set propA(newValue: number) { - if (((this.__backing_propA) !== (newValue))) { - this.__backing_propA = newValue; - this.__meta.fireChange(); - this.executeOnSubscribingWatches("propA"); - } - } - - public get trackA(): number { - if (((this._permissibleAddRefDepth) > (0))) { - this.__meta.addRef(); - } - return this.__backing_trackA; - } - - public set trackA(newValue: number) { - if (((this.__backing_trackA) !== (newValue))) { - this.__backing_trackA = newValue; - this.__meta.fireChange(); - this.executeOnSubscribingWatches("trackA"); - } - } - -} - -@Component({freezeWhenInactive:false}) final class MyStateSample extends CustomComponent { - public __initializeStruct(initializers: __Options_MyStateSample | undefined, @memo() content: (()=> void) | undefined): void {} - - public __updateStruct(initializers: __Options_MyStateSample | undefined): void {} - - @memo() public _build(@memo() style: ((instance: MyStateSample)=> MyStateSample) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_MyStateSample | undefined): void {} - - public constructor() {} - -} - -interface __Options_MyStateSample { - -} - -`; - -function testObservedOnlyTransformer(this: PluginTestContext): void { - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'test observed only transform', - [observedTrackTransform, uiNoRecheck], - { - checked: [testObservedOnlyTransformer], - }, - { - stopAfter: 'checked', - } -); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-class-property.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-class-property.test.ts deleted file mode 100644 index 5bd7f7551..000000000 --- a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-class-property.test.ts +++ /dev/null @@ -1,206 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; -import { parseDumpSrc } from '../../../../utils/parse-string'; -import { uiNoRecheck } from '../../../../utils/plugins'; -import { uiTransform } from '../../../../../ui-plugins'; -import { Plugins } from '../../../../../common/plugin-context'; - -const OBSERVED_DIR_PATH: string = 'decorators/observed-track'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [ - path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, OBSERVED_DIR_PATH, 'observed-track-class-property.ets'), -]; - -const observedTrackTransform: Plugins = { - name: 'observedTrack', - parsed: uiTransform().parsed, -} - -const pluginTester = new PluginTester('test observed track transform with class property', buildConfig); - -const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; - -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; - -import { memo as memo } from "arkui.stateManagement.runtime"; - -import { SubscribedWatches as SubscribedWatches } from "@ohos.arkui.stateManagement"; - -import { WatchIdType as WatchIdType } from "@ohos.arkui.stateManagement"; - -import { int32 as int32 } from "@ohos.arkui.stateManagement"; - -import { IObservedObject as IObservedObject } from "@ohos.arkui.stateManagement"; - -import { setObservationDepth as setObservationDepth } from "@ohos.arkui.stateManagement"; - -import { BackingValue as BackingValue } from "@ohos.arkui.stateManagement"; - -import { MutableStateMeta as MutableStateMeta } from "@ohos.arkui.stateManagement"; - -import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; - -import { Component as Component } from "@ohos.arkui.component"; - -import { Observed as Observed, Track as Track } from "@ohos.arkui.stateManagement"; - -function main() {} - - - -class Info { - public constructor() {} - -} - -class E implements IObservedObject { - private subscribedWatches: SubscribedWatches = new SubscribedWatches(); - - public addWatchSubscriber(watchId: WatchIdType): void { - this.subscribedWatches.addWatchSubscriber(watchId); - } - - public removeWatchSubscriber(watchId: WatchIdType): boolean { - return this.subscribedWatches.removeWatchSubscriber(watchId); - } - - public executeOnSubscribingWatches(propertyName: string): void { - this.subscribedWatches.executeOnSubscribingWatches(propertyName); - } - - public _permissibleAddRefDepth: int32 = 0; - - public propE: Info = new Info(); - - private __backing_trackE: BackingValue = new BackingValue(new Info()); - - private __meta_trackE: MutableStateMeta = new MutableStateMeta("@Track"); - - public constructor() {} - - public get trackE(): Info { - if (((this._permissibleAddRefDepth) > (0))) { - this.__meta_trackE.addRef(); - } - setObservationDepth(this.__backing_trackE.value, ((this._permissibleAddRefDepth) - (1))); - return this.__backing_trackE.value; - } - - public set trackE(newValue: Info) { - if (((this.__backing_trackE.value) !== (newValue))) { - this.__backing_trackE.value = newValue; - this.__meta_trackE.fireChange(); - this.executeOnSubscribingWatches("trackE"); - } - } - -} - -@Observed() class E1 implements IObservedObject { - private subscribedWatches: SubscribedWatches = new SubscribedWatches(); - - public addWatchSubscriber(watchId: WatchIdType): void { - this.subscribedWatches.addWatchSubscriber(watchId); - } - - public removeWatchSubscriber(watchId: WatchIdType): boolean { - return this.subscribedWatches.removeWatchSubscriber(watchId); - } - - public executeOnSubscribingWatches(propertyName: string): void { - this.subscribedWatches.executeOnSubscribingWatches(propertyName); - } - - public _permissibleAddRefDepth: int32 = 0; - - private __meta: MutableStateMeta = new MutableStateMeta("@Observe properties (no @Track)"); - - private __backing_propE1: BackingValue = new BackingValue(new Info()); - - private __backing_trackE1: BackingValue = new BackingValue(new Info()); - - public constructor() {} - - public get propE1(): Info { - if (((this._permissibleAddRefDepth) > (0))) { - this.__meta.addRef(); - } - setObservationDepth(this.__backing_propE1.value, ((this._permissibleAddRefDepth) - (1))); - return this.__backing_propE1.value; - } - - public set propE1(newValue: Info) { - if (((this.__backing_propE1.value) !== (newValue))) { - this.__backing_propE1.value = newValue; - this.__meta.fireChange(); - this.executeOnSubscribingWatches("propE1"); - } - } - - public get trackE1(): Info { - if (((this._permissibleAddRefDepth) > (0))) { - this.__meta.addRef(); - } - setObservationDepth(this.__backing_trackE1.value, ((this._permissibleAddRefDepth) - (1))); - return this.__backing_trackE1.value; - } - - public set trackE1(newValue: Info) { - if (((this.__backing_trackE1.value) !== (newValue))) { - this.__backing_trackE1.value = newValue; - this.__meta.fireChange(); - this.executeOnSubscribingWatches("trackE1"); - } - } - -} - -@Component({freezeWhenInactive:false}) final class MyStateSample extends CustomComponent { - public __initializeStruct(initializers: __Options_MyStateSample | undefined, @memo() content: (()=> void) | undefined): void {} - - public __updateStruct(initializers: __Options_MyStateSample | undefined): void {} - - @memo() public _build(@memo() style: ((instance: MyStateSample)=> MyStateSample) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_MyStateSample | undefined): void {} - - public constructor() {} - -} - -interface __Options_MyStateSample { - -} -`; - -function testObservedOnlyTransformer(this: PluginTestContext): void { - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'test observed track transform with class property', - [observedTrackTransform, uiNoRecheck], - { - checked: [testObservedOnlyTransformer], - }, - { - stopAfter: 'checked', - } -); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-complex-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-complex-type.test.ts deleted file mode 100644 index 371c48a6c..000000000 --- a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-complex-type.test.ts +++ /dev/null @@ -1,898 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; -import { parseDumpSrc } from '../../../../utils/parse-string'; -import { uiNoRecheck } from '../../../../utils/plugins'; -import { uiTransform } from '../../../../../ui-plugins'; -import { Plugins } from '../../../../../common/plugin-context'; - -const OBSERVED_DIR_PATH: string = 'decorators/observed-track'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [ - path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, OBSERVED_DIR_PATH, 'observed-track-complex-type.ets'), -]; - -const observedTrackTransform: Plugins = { - name: 'observedTrack', - parsed: uiTransform().parsed, -} - -const pluginTester = new PluginTester('test observed track transform with complex type', buildConfig); - -const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; - -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; - -import { memo as memo } from "arkui.stateManagement.runtime"; - -import { SubscribedWatches as SubscribedWatches } from "@ohos.arkui.stateManagement"; - -import { WatchIdType as WatchIdType } from "@ohos.arkui.stateManagement"; - -import { int32 as int32 } from "@ohos.arkui.stateManagement"; - -import { IObservedObject as IObservedObject } from "@ohos.arkui.stateManagement"; - -import { setObservationDepth as setObservationDepth } from "@ohos.arkui.stateManagement"; - -import { BackingValue as BackingValue } from "@ohos.arkui.stateManagement"; - -import { MutableStateMeta as MutableStateMeta } from "@ohos.arkui.stateManagement"; - -import { EntryPoint as EntryPoint } from "arkui.UserView"; - -import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; - -import { Component as Component, Entry as Entry } from "@ohos.arkui.component"; - -import { Observed as Observed, Track as Track } from "@ohos.arkui.stateManagement"; - -function main() {} - - - -class Person { - public constructor() {} - -} - -final class Status extends BaseEnum { - private readonly #ordinal: int; - - private static () {} - - public constructor(ordinal: int, value: int) { - super(value); - this.#ordinal = ordinal; - } - - public static readonly Success: Status = new Status(0, 200); - - public static readonly NotFound: Status = new Status(1, 404); - - public static readonly ServerError: Status = new Status(2, 500); - - private static readonly #NamesArray: String[] = ["Success", "NotFound", "ServerError"]; - - private static readonly #ValuesArray: int[] = [200, 404, 500]; - - private static readonly #StringValuesArray: String[] = ["200", "404", "500"]; - - private static readonly #ItemsArray: Status[] = [Status.Success, Status.NotFound, Status.ServerError]; - - public getName(): String { - return Status.#NamesArray[this.#ordinal]; - } - - public static getValueOf(name: String): Status { - for (let i = 0;((i) < (Status.#NamesArray.length));(++i)) { - if (((name) == (Status.#NamesArray[i]))) { - return Status.#ItemsArray[i]; - } - } - throw new Error((("No enum constant Status.") + (name))); - } - - public static fromValue(value: int): Status { - for (let i = 0;((i) < (Status.#ValuesArray.length));(++i)) { - if (((value) == (Status.#ValuesArray[i]))) { - return Status.#ItemsArray[i]; - } - } - throw new Error((("No enum Status with value ") + (value))); - } - - public valueOf(): int { - return Status.#ValuesArray[this.#ordinal]; - } - - public toString(): String { - return Status.#StringValuesArray[this.#ordinal]; - } - - public static values(): Status[] { - return Status.#ItemsArray; - } - - public getOrdinal(): int { - return this.#ordinal; - } - - public static $_get(e: Status): String { - return e.getName(); - } - -} - -@Observed() class mixed1 implements IObservedObject { - private subscribedWatches: SubscribedWatches = new SubscribedWatches(); - - public addWatchSubscriber(watchId: WatchIdType): void { - this.subscribedWatches.addWatchSubscriber(watchId); - } - - public removeWatchSubscriber(watchId: WatchIdType): boolean { - return this.subscribedWatches.removeWatchSubscriber(watchId); - } - - public executeOnSubscribingWatches(propertyName: string): void { - this.subscribedWatches.executeOnSubscribingWatches(propertyName); - } - - public _permissibleAddRefDepth: int32 = 0; - - private __backing_numA: number = 33; - - private __meta_numA: MutableStateMeta = new MutableStateMeta("@Track"); - - private __backing_stringA: string = "AA"; - - private __meta_stringA: MutableStateMeta = new MutableStateMeta("@Track"); - - private __backing_booleanA: boolean = true; - - private __meta_booleanA: MutableStateMeta = new MutableStateMeta("@Track"); - - private __backing_arrayA: BackingValue> = new BackingValue>([1, 2, 3]); - - private __meta_arrayA: MutableStateMeta = new MutableStateMeta("@Track"); - - private __backing_objectA: BackingValue = new BackingValue({}); - - private __meta_objectA: MutableStateMeta = new MutableStateMeta("@Track"); - - private __backing_dateA: BackingValue = new BackingValue(new Date("2021-08-08")); - - private __meta_dateA: MutableStateMeta = new MutableStateMeta("@Track"); - - private __backing_setA: BackingValue> = new BackingValue>(new Set()); - - private __meta_setA: MutableStateMeta = new MutableStateMeta("@Track"); - - private __backing_mapA: BackingValue> = new BackingValue>(new Map()); - - private __meta_mapA: MutableStateMeta = new MutableStateMeta("@Track"); - - private __backing_unionA: string | undefined = ""; - - private __meta_unionA: MutableStateMeta = new MutableStateMeta("@Track"); - - private __backing_classA: BackingValue = new BackingValue(new Person()); - - private __meta_classA: MutableStateMeta = new MutableStateMeta("@Track"); - - private __backing_enumA: BackingValue = new BackingValue(Status.NotFound); - - private __meta_enumA: MutableStateMeta = new MutableStateMeta("@Track"); - - public numB: number = 33; - - public stringB: string = "AA"; - - public booleanB: boolean = true; - - public arrayB: Array = [1, 2, 3]; - - public objectB: Object = {}; - - public dateB: Date = new Date("2021-08-08"); - - public setB: Set = new Set(); - - public mapB: Map = new Map(); - - public unionB: string | undefined = ""; - - public classB: Person = new Person(); - - public enumB: Status = Status.NotFound; - - public constructor() {} - - public get numA(): number { - if (((this._permissibleAddRefDepth) > (0))) { - this.__meta_numA.addRef(); - } - return this.__backing_numA; - } - - public set numA(newValue: number) { - if (((this.__backing_numA) !== (newValue))) { - this.__backing_numA = newValue; - this.__meta_numA.fireChange(); - this.executeOnSubscribingWatches("numA"); - } - } - - public get stringA(): string { - if (((this._permissibleAddRefDepth) > (0))) { - this.__meta_stringA.addRef(); - } - return this.__backing_stringA; - } - - public set stringA(newValue: string) { - if (((this.__backing_stringA) !== (newValue))) { - this.__backing_stringA = newValue; - this.__meta_stringA.fireChange(); - this.executeOnSubscribingWatches("stringA"); - } - } - - public get booleanA(): boolean { - if (((this._permissibleAddRefDepth) > (0))) { - this.__meta_booleanA.addRef(); - } - return this.__backing_booleanA; - } - - public set booleanA(newValue: boolean) { - if (((this.__backing_booleanA) !== (newValue))) { - this.__backing_booleanA = newValue; - this.__meta_booleanA.fireChange(); - this.executeOnSubscribingWatches("booleanA"); - } - } - - public get arrayA(): Array { - if (((this._permissibleAddRefDepth) > (0))) { - this.__meta_arrayA.addRef(); - } - setObservationDepth(this.__backing_arrayA.value, ((this._permissibleAddRefDepth) - (1))); - return this.__backing_arrayA.value; - } - - public set arrayA(newValue: Array) { - if (((this.__backing_arrayA.value) !== (newValue))) { - this.__backing_arrayA.value = newValue; - this.__meta_arrayA.fireChange(); - this.executeOnSubscribingWatches("arrayA"); - } - } - - public get objectA(): Object { - if (((this._permissibleAddRefDepth) > (0))) { - this.__meta_objectA.addRef(); - } - setObservationDepth(this.__backing_objectA.value, ((this._permissibleAddRefDepth) - (1))); - return this.__backing_objectA.value; - } - - public set objectA(newValue: Object) { - if (((this.__backing_objectA.value) !== (newValue))) { - this.__backing_objectA.value = newValue; - this.__meta_objectA.fireChange(); - this.executeOnSubscribingWatches("objectA"); - } - } - - public get dateA(): Date { - if (((this._permissibleAddRefDepth) > (0))) { - this.__meta_dateA.addRef(); - } - setObservationDepth(this.__backing_dateA.value, ((this._permissibleAddRefDepth) - (1))); - return this.__backing_dateA.value; - } - - public set dateA(newValue: Date) { - if (((this.__backing_dateA.value) !== (newValue))) { - this.__backing_dateA.value = newValue; - this.__meta_dateA.fireChange(); - this.executeOnSubscribingWatches("dateA"); - } - } - - public get setA(): Set { - if (((this._permissibleAddRefDepth) > (0))) { - this.__meta_setA.addRef(); - } - setObservationDepth(this.__backing_setA.value, ((this._permissibleAddRefDepth) - (1))); - return this.__backing_setA.value; - } - - public set setA(newValue: Set) { - if (((this.__backing_setA.value) !== (newValue))) { - this.__backing_setA.value = newValue; - this.__meta_setA.fireChange(); - this.executeOnSubscribingWatches("setA"); - } - } - - public get mapA(): Map { - if (((this._permissibleAddRefDepth) > (0))) { - this.__meta_mapA.addRef(); - } - setObservationDepth(this.__backing_mapA.value, ((this._permissibleAddRefDepth) - (1))); - return this.__backing_mapA.value; - } - - public set mapA(newValue: Map) { - if (((this.__backing_mapA.value) !== (newValue))) { - this.__backing_mapA.value = newValue; - this.__meta_mapA.fireChange(); - this.executeOnSubscribingWatches("mapA"); - } - } - - public get unionA(): string | undefined { - if (((this._permissibleAddRefDepth) > (0))) { - this.__meta_unionA.addRef(); - } - return this.__backing_unionA; - } - - public set unionA(newValue: string | undefined) { - if (((this.__backing_unionA) !== (newValue))) { - this.__backing_unionA = newValue; - this.__meta_unionA.fireChange(); - this.executeOnSubscribingWatches("unionA"); - } - } - - public get classA(): Person { - if (((this._permissibleAddRefDepth) > (0))) { - this.__meta_classA.addRef(); - } - setObservationDepth(this.__backing_classA.value, ((this._permissibleAddRefDepth) - (1))); - return this.__backing_classA.value; - } - - public set classA(newValue: Person) { - if (((this.__backing_classA.value) !== (newValue))) { - this.__backing_classA.value = newValue; - this.__meta_classA.fireChange(); - this.executeOnSubscribingWatches("classA"); - } - } - - public get enumA(): Status { - if (((this._permissibleAddRefDepth) > (0))) { - this.__meta_enumA.addRef(); - } - setObservationDepth(this.__backing_enumA.value, ((this._permissibleAddRefDepth) - (1))); - return this.__backing_enumA.value; - } - - public set enumA(newValue: Status) { - if (((this.__backing_enumA.value) !== (newValue))) { - this.__backing_enumA.value = newValue; - this.__meta_enumA.fireChange(); - this.executeOnSubscribingWatches("enumA"); - } - } - -} - -@Observed() class mixed2 implements IObservedObject { - private subscribedWatches: SubscribedWatches = new SubscribedWatches(); - - public addWatchSubscriber(watchId: WatchIdType): void { - this.subscribedWatches.addWatchSubscriber(watchId); - } - - public removeWatchSubscriber(watchId: WatchIdType): boolean { - return this.subscribedWatches.removeWatchSubscriber(watchId); - } - - public executeOnSubscribingWatches(propertyName: string): void { - this.subscribedWatches.executeOnSubscribingWatches(propertyName); - } - - public _permissibleAddRefDepth: int32 = 0; - - private __meta: MutableStateMeta = new MutableStateMeta("@Observe properties (no @Track)"); - - private __backing_numA: number = 33; - - private __backing_stringA: string = "AA"; - - private __backing_booleanA: boolean = true; - - private __backing_arrayA: BackingValue> = new BackingValue>([1, 2, 3]); - - private __backing_objectA: BackingValue = new BackingValue({}); - - private __backing_dateA: BackingValue = new BackingValue(new Date("2021-08-08")); - - private __backing_setA: BackingValue> = new BackingValue>(new Set()); - - private __backing_mapA: BackingValue> = new BackingValue>(new Map()); - - private __backing_unionA: string | undefined = ""; - - private __backing_classA: BackingValue = new BackingValue(new Person()); - - private __backing_enumA: BackingValue = new BackingValue(Status.NotFound); - - public constructor() {} - - public get numA(): number { - if (((this._permissibleAddRefDepth) > (0))) { - this.__meta.addRef(); - } - return this.__backing_numA; - } - - public set numA(newValue: number) { - if (((this.__backing_numA) !== (newValue))) { - this.__backing_numA = newValue; - this.__meta.fireChange(); - this.executeOnSubscribingWatches("numA"); - } - } - - public get stringA(): string { - if (((this._permissibleAddRefDepth) > (0))) { - this.__meta.addRef(); - } - return this.__backing_stringA; - } - - public set stringA(newValue: string) { - if (((this.__backing_stringA) !== (newValue))) { - this.__backing_stringA = newValue; - this.__meta.fireChange(); - this.executeOnSubscribingWatches("stringA"); - } - } - - public get booleanA(): boolean { - if (((this._permissibleAddRefDepth) > (0))) { - this.__meta.addRef(); - } - return this.__backing_booleanA; - } - - public set booleanA(newValue: boolean) { - if (((this.__backing_booleanA) !== (newValue))) { - this.__backing_booleanA = newValue; - this.__meta.fireChange(); - this.executeOnSubscribingWatches("booleanA"); - } - } - - public get arrayA(): Array { - if (((this._permissibleAddRefDepth) > (0))) { - this.__meta.addRef(); - } - setObservationDepth(this.__backing_arrayA.value, ((this._permissibleAddRefDepth) - (1))); - return this.__backing_arrayA.value; - } - - public set arrayA(newValue: Array) { - if (((this.__backing_arrayA.value) !== (newValue))) { - this.__backing_arrayA.value = newValue; - this.__meta.fireChange(); - this.executeOnSubscribingWatches("arrayA"); - } - } - - public get objectA(): Object { - if (((this._permissibleAddRefDepth) > (0))) { - this.__meta.addRef(); - } - setObservationDepth(this.__backing_objectA.value, ((this._permissibleAddRefDepth) - (1))); - return this.__backing_objectA.value; - } - - public set objectA(newValue: Object) { - if (((this.__backing_objectA.value) !== (newValue))) { - this.__backing_objectA.value = newValue; - this.__meta.fireChange(); - this.executeOnSubscribingWatches("objectA"); - } - } - - public get dateA(): Date { - if (((this._permissibleAddRefDepth) > (0))) { - this.__meta.addRef(); - } - setObservationDepth(this.__backing_dateA.value, ((this._permissibleAddRefDepth) - (1))); - return this.__backing_dateA.value; - } - - public set dateA(newValue: Date) { - if (((this.__backing_dateA.value) !== (newValue))) { - this.__backing_dateA.value = newValue; - this.__meta.fireChange(); - this.executeOnSubscribingWatches("dateA"); - } - } - - public get setA(): Set { - if (((this._permissibleAddRefDepth) > (0))) { - this.__meta.addRef(); - } - setObservationDepth(this.__backing_setA.value, ((this._permissibleAddRefDepth) - (1))); - return this.__backing_setA.value; - } - - public set setA(newValue: Set) { - if (((this.__backing_setA.value) !== (newValue))) { - this.__backing_setA.value = newValue; - this.__meta.fireChange(); - this.executeOnSubscribingWatches("setA"); - } - } - - public get mapA(): Map { - if (((this._permissibleAddRefDepth) > (0))) { - this.__meta.addRef(); - } - setObservationDepth(this.__backing_mapA.value, ((this._permissibleAddRefDepth) - (1))); - return this.__backing_mapA.value; - } - - public set mapA(newValue: Map) { - if (((this.__backing_mapA.value) !== (newValue))) { - this.__backing_mapA.value = newValue; - this.__meta.fireChange(); - this.executeOnSubscribingWatches("mapA"); - } - } - - public get unionA(): string | undefined { - if (((this._permissibleAddRefDepth) > (0))) { - this.__meta.addRef(); - } - return this.__backing_unionA; - } - - public set unionA(newValue: string | undefined) { - if (((this.__backing_unionA) !== (newValue))) { - this.__backing_unionA = newValue; - this.__meta.fireChange(); - this.executeOnSubscribingWatches("unionA"); - } - } - - public get classA(): Person { - if (((this._permissibleAddRefDepth) > (0))) { - this.__meta.addRef(); - } - setObservationDepth(this.__backing_classA.value, ((this._permissibleAddRefDepth) - (1))); - return this.__backing_classA.value; - } - - public set classA(newValue: Person) { - if (((this.__backing_classA.value) !== (newValue))) { - this.__backing_classA.value = newValue; - this.__meta.fireChange(); - this.executeOnSubscribingWatches("classA"); - } - } - - public get enumA(): Status { - if (((this._permissibleAddRefDepth) > (0))) { - this.__meta.addRef(); - } - setObservationDepth(this.__backing_enumA.value, ((this._permissibleAddRefDepth) - (1))); - return this.__backing_enumA.value; - } - - public set enumA(newValue: Status) { - if (((this.__backing_enumA.value) !== (newValue))) { - this.__backing_enumA.value = newValue; - this.__meta.fireChange(); - this.executeOnSubscribingWatches("enumA"); - } - } - -} - -class mixed3 implements IObservedObject { - private subscribedWatches: SubscribedWatches = new SubscribedWatches(); - - public addWatchSubscriber(watchId: WatchIdType): void { - this.subscribedWatches.addWatchSubscriber(watchId); - } - - public removeWatchSubscriber(watchId: WatchIdType): boolean { - return this.subscribedWatches.removeWatchSubscriber(watchId); - } - - public executeOnSubscribingWatches(propertyName: string): void { - this.subscribedWatches.executeOnSubscribingWatches(propertyName); - } - - public _permissibleAddRefDepth: int32 = 0; - - private __backing_numA: number = 33; - - private __meta_numA: MutableStateMeta = new MutableStateMeta("@Track"); - - private __backing_stringA: string = "AA"; - - private __meta_stringA: MutableStateMeta = new MutableStateMeta("@Track"); - - private __backing_booleanA: boolean = true; - - private __meta_booleanA: MutableStateMeta = new MutableStateMeta("@Track"); - - private __backing_arrayA: BackingValue> = new BackingValue>([1, 2, 3]); - - private __meta_arrayA: MutableStateMeta = new MutableStateMeta("@Track"); - - private __backing_objectA: BackingValue = new BackingValue({}); - - private __meta_objectA: MutableStateMeta = new MutableStateMeta("@Track"); - - private __backing_dateA: BackingValue = new BackingValue(new Date("2021-08-08")); - - private __meta_dateA: MutableStateMeta = new MutableStateMeta("@Track"); - - private __backing_setA: BackingValue> = new BackingValue>(new Set()); - - private __meta_setA: MutableStateMeta = new MutableStateMeta("@Track"); - - private __backing_mapA: BackingValue> = new BackingValue>(new Map()); - - private __meta_mapA: MutableStateMeta = new MutableStateMeta("@Track"); - - private __backing_unionA: string | undefined = ""; - - private __meta_unionA: MutableStateMeta = new MutableStateMeta("@Track"); - - private __backing_classA: BackingValue = new BackingValue(new Person()); - - private __meta_classA: MutableStateMeta = new MutableStateMeta("@Track"); - - private __backing_enumA: BackingValue = new BackingValue(Status.NotFound); - - private __meta_enumA: MutableStateMeta = new MutableStateMeta("@Track"); - - public constructor() {} - - public get numA(): number { - if (((this._permissibleAddRefDepth) > (0))) { - this.__meta_numA.addRef(); - } - return this.__backing_numA; - } - - public set numA(newValue: number) { - if (((this.__backing_numA) !== (newValue))) { - this.__backing_numA = newValue; - this.__meta_numA.fireChange(); - this.executeOnSubscribingWatches("numA"); - } - } - - public get stringA(): string { - if (((this._permissibleAddRefDepth) > (0))) { - this.__meta_stringA.addRef(); - } - return this.__backing_stringA; - } - - public set stringA(newValue: string) { - if (((this.__backing_stringA) !== (newValue))) { - this.__backing_stringA = newValue; - this.__meta_stringA.fireChange(); - this.executeOnSubscribingWatches("stringA"); - } - } - - public get booleanA(): boolean { - if (((this._permissibleAddRefDepth) > (0))) { - this.__meta_booleanA.addRef(); - } - return this.__backing_booleanA; - } - - public set booleanA(newValue: boolean) { - if (((this.__backing_booleanA) !== (newValue))) { - this.__backing_booleanA = newValue; - this.__meta_booleanA.fireChange(); - this.executeOnSubscribingWatches("booleanA"); - } - } - - public get arrayA(): Array { - if (((this._permissibleAddRefDepth) > (0))) { - this.__meta_arrayA.addRef(); - } - setObservationDepth(this.__backing_arrayA.value, ((this._permissibleAddRefDepth) - (1))); - return this.__backing_arrayA.value; - } - - public set arrayA(newValue: Array) { - if (((this.__backing_arrayA.value) !== (newValue))) { - this.__backing_arrayA.value = newValue; - this.__meta_arrayA.fireChange(); - this.executeOnSubscribingWatches("arrayA"); - } - } - - public get objectA(): Object { - if (((this._permissibleAddRefDepth) > (0))) { - this.__meta_objectA.addRef(); - } - setObservationDepth(this.__backing_objectA.value, ((this._permissibleAddRefDepth) - (1))); - return this.__backing_objectA.value; - } - - public set objectA(newValue: Object) { - if (((this.__backing_objectA.value) !== (newValue))) { - this.__backing_objectA.value = newValue; - this.__meta_objectA.fireChange(); - this.executeOnSubscribingWatches("objectA"); - } - } - - public get dateA(): Date { - if (((this._permissibleAddRefDepth) > (0))) { - this.__meta_dateA.addRef(); - } - setObservationDepth(this.__backing_dateA.value, ((this._permissibleAddRefDepth) - (1))); - return this.__backing_dateA.value; - } - - public set dateA(newValue: Date) { - if (((this.__backing_dateA.value) !== (newValue))) { - this.__backing_dateA.value = newValue; - this.__meta_dateA.fireChange(); - this.executeOnSubscribingWatches("dateA"); - } - } - - public get setA(): Set { - if (((this._permissibleAddRefDepth) > (0))) { - this.__meta_setA.addRef(); - } - setObservationDepth(this.__backing_setA.value, ((this._permissibleAddRefDepth) - (1))); - return this.__backing_setA.value; - } - - public set setA(newValue: Set) { - if (((this.__backing_setA.value) !== (newValue))) { - this.__backing_setA.value = newValue; - this.__meta_setA.fireChange(); - this.executeOnSubscribingWatches("setA"); - } - } - - public get mapA(): Map { - if (((this._permissibleAddRefDepth) > (0))) { - this.__meta_mapA.addRef(); - } - setObservationDepth(this.__backing_mapA.value, ((this._permissibleAddRefDepth) - (1))); - return this.__backing_mapA.value; - } - - public set mapA(newValue: Map) { - if (((this.__backing_mapA.value) !== (newValue))) { - this.__backing_mapA.value = newValue; - this.__meta_mapA.fireChange(); - this.executeOnSubscribingWatches("mapA"); - } - } - - public get unionA(): string | undefined { - if (((this._permissibleAddRefDepth) > (0))) { - this.__meta_unionA.addRef(); - } - return this.__backing_unionA; - } - - public set unionA(newValue: string | undefined) { - if (((this.__backing_unionA) !== (newValue))) { - this.__backing_unionA = newValue; - this.__meta_unionA.fireChange(); - this.executeOnSubscribingWatches("unionA"); - } - } - - public get classA(): Person { - if (((this._permissibleAddRefDepth) > (0))) { - this.__meta_classA.addRef(); - } - setObservationDepth(this.__backing_classA.value, ((this._permissibleAddRefDepth) - (1))); - return this.__backing_classA.value; - } - - public set classA(newValue: Person) { - if (((this.__backing_classA.value) !== (newValue))) { - this.__backing_classA.value = newValue; - this.__meta_classA.fireChange(); - this.executeOnSubscribingWatches("classA"); - } - } - - public get enumA(): Status { - if (((this._permissibleAddRefDepth) > (0))) { - this.__meta_enumA.addRef(); - } - setObservationDepth(this.__backing_enumA.value, ((this._permissibleAddRefDepth) - (1))); - return this.__backing_enumA.value; - } - - public set enumA(newValue: Status) { - if (((this.__backing_enumA.value) !== (newValue))) { - this.__backing_enumA.value = newValue; - this.__meta_enumA.fireChange(); - this.executeOnSubscribingWatches("enumA"); - } - } - -} - -@Entry({useSharedStorage:false,storage:"",routeName:""}) @Component({freezeWhenInactive:false}) final class MyStateSample extends CustomComponent { - public __initializeStruct(initializers: __Options_MyStateSample | undefined, @memo() content: (()=> void) | undefined): void {} - - public __updateStruct(initializers: __Options_MyStateSample | undefined): void {} - - @memo() public _build(@memo() style: ((instance: MyStateSample)=> MyStateSample) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_MyStateSample | undefined): void {} - - public constructor() {} - -} - -interface __Options_MyStateSample { - -} - -class __EntryWrapper extends EntryPoint { - @memo() public entry(): void { - MyStateSample._instantiateImpl(undefined, (() => { - return new MyStateSample(); - }), undefined, undefined, undefined); - } - - public constructor() {} - -} -`; - -function testObservedOnlyTransformer(this: PluginTestContext): void { - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'test observed track transform with complex type', - [observedTrackTransform, uiNoRecheck], - { - checked: [testObservedOnlyTransformer], - }, - { - stopAfter: 'checked', - } -); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-extends.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-extends.test.ts deleted file mode 100644 index f3f3a001e..000000000 --- a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-extends.test.ts +++ /dev/null @@ -1,204 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; -import { parseDumpSrc } from '../../../../utils/parse-string'; -import { uiNoRecheck } from '../../../../utils/plugins'; -import { uiTransform } from '../../../../../ui-plugins'; -import { Plugins } from '../../../../../common/plugin-context'; - -const OBSERVED_DIR_PATH: string = 'decorators/observed-track'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [ - path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, OBSERVED_DIR_PATH, 'observed-track-extends.ets'), -]; - -const observedTrackTransform: Plugins = { - name: 'observedTrack', - parsed: uiTransform().parsed, -} - -const pluginTester = new PluginTester('test observed track transform with extends', buildConfig); - -const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; - -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; - -import { memo as memo } from "arkui.stateManagement.runtime"; - -import { SubscribedWatches as SubscribedWatches } from "@ohos.arkui.stateManagement"; - -import { WatchIdType as WatchIdType } from "@ohos.arkui.stateManagement"; - -import { int32 as int32 } from "@ohos.arkui.stateManagement"; - -import { IObservedObject as IObservedObject } from "@ohos.arkui.stateManagement"; - -import { setObservationDepth as setObservationDepth } from "@ohos.arkui.stateManagement"; - -import { BackingValue as BackingValue } from "@ohos.arkui.stateManagement"; - -import { MutableStateMeta as MutableStateMeta } from "@ohos.arkui.stateManagement"; - -import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; - -import { Component as Component } from "@ohos.arkui.component"; - -import { Observed as Observed, Track as Track } from "@ohos.arkui.stateManagement"; - -function main() {} - - - -@Observed() class A implements IObservedObject { - private subscribedWatches: SubscribedWatches = new SubscribedWatches(); - - public addWatchSubscriber(watchId: WatchIdType): void { - this.subscribedWatches.addWatchSubscriber(watchId); - } - - public removeWatchSubscriber(watchId: WatchIdType): boolean { - return this.subscribedWatches.removeWatchSubscriber(watchId); - } - - public executeOnSubscribingWatches(propertyName: string): void { - this.subscribedWatches.executeOnSubscribingWatches(propertyName); - } - - public _permissibleAddRefDepth: int32 = 0; - - private __meta: MutableStateMeta = new MutableStateMeta("@Observe properties (no @Track)"); - - private __backing_propA: number = 1; - - private __backing_trackA: number = 2; - - public constructor() {} - - public get propA(): number { - if (((this._permissibleAddRefDepth) > (0))) { - this.__meta.addRef(); - } - return this.__backing_propA; - } - - public set propA(newValue: number) { - if (((this.__backing_propA) !== (newValue))) { - this.__backing_propA = newValue; - this.__meta.fireChange(); - this.executeOnSubscribingWatches("propA"); - } - } - - public get trackA(): number { - if (((this._permissibleAddRefDepth) > (0))) { - this.__meta.addRef(); - } - return this.__backing_trackA; - } - - public set trackA(newValue: number) { - if (((this.__backing_trackA) !== (newValue))) { - this.__backing_trackA = newValue; - this.__meta.fireChange(); - this.executeOnSubscribingWatches("trackA"); - } - } - -} - -class G extends A { - public propG: number = 1; - - public constructor() {} - -} - -@Observed() class H extends G implements IObservedObject { - private subscribedWatches: SubscribedWatches = new SubscribedWatches(); - - public addWatchSubscriber(watchId: WatchIdType): void { - this.subscribedWatches.addWatchSubscriber(watchId); - } - - public removeWatchSubscriber(watchId: WatchIdType): boolean { - return this.subscribedWatches.removeWatchSubscriber(watchId); - } - - public executeOnSubscribingWatches(propertyName: string): void { - this.subscribedWatches.executeOnSubscribingWatches(propertyName); - } - - public _permissibleAddRefDepth: int32 = 0; - - private __backing_propG: number = 1; - - private __meta_propG: MutableStateMeta = new MutableStateMeta("@Track"); - - public constructor() {} - - public get propG(): number { - if (((this._permissibleAddRefDepth) > (0))) { - this.__meta_propG.addRef(); - } - return this.__backing_propG; - } - - public set propG(newValue: number) { - if (((this.__backing_propG) !== (newValue))) { - this.__backing_propG = newValue; - this.__meta_propG.fireChange(); - this.executeOnSubscribingWatches("propG"); - } - } - -} - -@Component({freezeWhenInactive:false}) final class MyStateSample extends CustomComponent { - public __initializeStruct(initializers: __Options_MyStateSample | undefined, @memo() content: (()=> void) | undefined): void {} - - public __updateStruct(initializers: __Options_MyStateSample | undefined): void {} - - @memo() public _build(@memo() style: ((instance: MyStateSample)=> MyStateSample) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_MyStateSample | undefined): void {} - - public constructor() {} - -} - -interface __Options_MyStateSample { - -} - -`; - -function testObservedOnlyTransformer(this: PluginTestContext): void { - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'test observed track transform with extends', - [observedTrackTransform, uiNoRecheck], - { - checked: [testObservedOnlyTransformer], - }, - { - stopAfter: 'checked', - } -); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-implements.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-implements.test.ts deleted file mode 100644 index f71a5e922..000000000 --- a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track-implements.test.ts +++ /dev/null @@ -1,171 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; -import { parseDumpSrc } from '../../../../utils/parse-string'; -import { uiNoRecheck } from '../../../../utils/plugins'; -import { uiTransform } from '../../../../../ui-plugins'; -import { Plugins } from '../../../../../common/plugin-context'; - -const OBSERVED_DIR_PATH: string = 'decorators/observed-track'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [ - path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, OBSERVED_DIR_PATH, 'observed-track-implements.ets'), -]; - -const observedTrackTransform: Plugins = { - name: 'observedTrack', - parsed: uiTransform().parsed, -} - -const pluginTester = new PluginTester('test observed track transform with implements', buildConfig); - -const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; - -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; - -import { memo as memo } from "arkui.stateManagement.runtime"; - -import { SubscribedWatches as SubscribedWatches } from "@ohos.arkui.stateManagement"; - -import { WatchIdType as WatchIdType } from "@ohos.arkui.stateManagement"; - -import { int32 as int32 } from "@ohos.arkui.stateManagement"; - -import { IObservedObject as IObservedObject } from "@ohos.arkui.stateManagement"; - -import { setObservationDepth as setObservationDepth } from "@ohos.arkui.stateManagement"; - -import { BackingValue as BackingValue } from "@ohos.arkui.stateManagement"; - -import { MutableStateMeta as MutableStateMeta } from "@ohos.arkui.stateManagement"; - -import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; - -import { Component as Component } from "@ohos.arkui.component"; - -import { Observed as Observed } from "@ohos.arkui.stateManagement"; - -function main() {} - - - -interface PropInterface { - set propF(propF: number) - - get propF(): number - -} - -interface trackInterface { - set trackF(trackF: number) - - get trackF(): number - -} - -@Observed() class F implements PropInterface, trackInterface, IObservedObject { - private subscribedWatches: SubscribedWatches = new SubscribedWatches(); - - public addWatchSubscriber(watchId: WatchIdType): void { - this.subscribedWatches.addWatchSubscriber(watchId); - } - - public removeWatchSubscriber(watchId: WatchIdType): boolean { - return this.subscribedWatches.removeWatchSubscriber(watchId); - } - - public executeOnSubscribingWatches(propertyName: string): void { - this.subscribedWatches.executeOnSubscribingWatches(propertyName); - } - - public _permissibleAddRefDepth: int32 = 0; - - private __meta: MutableStateMeta = new MutableStateMeta("@Observe properties (no @Track)"); - - private __backing_propF: number = 1; - - private __backing_trackF: number = 2; - - public constructor() {} - - public set propF(newValue: number) { - if (((this.__backing_propF) !== (newValue))) { - this.__backing_propF = newValue; - this.__meta.fireChange(); - this.executeOnSubscribingWatches("propF"); - } - } - - public get propF(): number { - if (((this._permissibleAddRefDepth) > (0))) { - this.__meta.addRef(); - } - return this.__backing_propF; - } - - public set trackF(newValue: number) { - if (((this.__backing_trackF) !== (newValue))) { - this.__backing_trackF = newValue; - this.__meta.fireChange(); - this.executeOnSubscribingWatches("trackF"); - } - } - - public get trackF(): number { - if (((this._permissibleAddRefDepth) > (0))) { - this.__meta.addRef(); - } - return this.__backing_trackF; - } - -} - -@Component({freezeWhenInactive:false}) final class MyStateSample extends CustomComponent { - public __initializeStruct(initializers: __Options_MyStateSample | undefined, @memo() content: (()=> void) | undefined): void {} - - public __updateStruct(initializers: __Options_MyStateSample | undefined): void {} - - @memo() public _build(@memo() style: ((instance: MyStateSample)=> MyStateSample) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_MyStateSample | undefined): void {} - - public constructor() {} - -} - -interface __Options_MyStateSample { - -} - -`; - -function testObservedOnlyTransformer(this: PluginTestContext): void { - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'test observed track transform with implements', - [observedTrackTransform, uiNoRecheck], - { - checked: [testObservedOnlyTransformer], - }, - { - stopAfter: 'checked', - } -); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track.test.ts deleted file mode 100644 index 9f28609dc..000000000 --- a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/observed-track.test.ts +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; -import { parseDumpSrc } from '../../../../utils/parse-string'; -import { uiNoRecheck } from '../../../../utils/plugins'; -import { uiTransform } from '../../../../../ui-plugins'; -import { Plugins } from '../../../../../common/plugin-context'; - -const OBSERVED_DIR_PATH: string = 'decorators/observed-track'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [ - path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, OBSERVED_DIR_PATH, 'observed-track.ets'), -]; - -const observedTrackTransform: Plugins = { - name: 'observedTrack', - parsed: uiTransform().parsed, -} - -const pluginTester = new PluginTester('test observed with track transform', buildConfig); - -const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; - -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; - -import { memo as memo } from "arkui.stateManagement.runtime"; - -import { SubscribedWatches as SubscribedWatches } from "@ohos.arkui.stateManagement"; - -import { WatchIdType as WatchIdType } from "@ohos.arkui.stateManagement"; - -import { int32 as int32 } from "@ohos.arkui.stateManagement"; - -import { IObservedObject as IObservedObject } from "@ohos.arkui.stateManagement"; - -import { setObservationDepth as setObservationDepth } from "@ohos.arkui.stateManagement"; - -import { BackingValue as BackingValue } from "@ohos.arkui.stateManagement"; - -import { MutableStateMeta as MutableStateMeta } from "@ohos.arkui.stateManagement"; - -import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; - -import { Component as Component } from "@ohos.arkui.component"; - -import { Observed as Observed, Track as Track } from "@ohos.arkui.stateManagement"; - -function main() {} - - - -@Observed() class B implements IObservedObject { - private subscribedWatches: SubscribedWatches = new SubscribedWatches(); - - public addWatchSubscriber(watchId: WatchIdType): void { - this.subscribedWatches.addWatchSubscriber(watchId); - } - - public removeWatchSubscriber(watchId: WatchIdType): boolean { - return this.subscribedWatches.removeWatchSubscriber(watchId); - } - - public executeOnSubscribingWatches(propertyName: string): void { - this.subscribedWatches.executeOnSubscribingWatches(propertyName); - } - - public _permissibleAddRefDepth: int32 = 0; - - public propB: number = 1; - - private __backing_trackB: number = 2; - - private __meta_trackB: MutableStateMeta = new MutableStateMeta("@Track"); - - public constructor() {} - - public get trackB(): number { - if (((this._permissibleAddRefDepth) > (0))) { - this.__meta_trackB.addRef(); - } - return this.__backing_trackB; - } - - public set trackB(newValue: number) { - if (((this.__backing_trackB) !== (newValue))) { - this.__backing_trackB = newValue; - this.__meta_trackB.fireChange(); - this.executeOnSubscribingWatches("trackB"); - } - } - -} - -@Component({freezeWhenInactive:false}) final class MyStateSample extends CustomComponent { - public __initializeStruct(initializers: __Options_MyStateSample | undefined, @memo() content: (()=> void) | undefined): void {} - - public __updateStruct(initializers: __Options_MyStateSample | undefined): void {} - - @memo() public _build(@memo() style: ((instance: MyStateSample)=> MyStateSample) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_MyStateSample | undefined): void {} - - public constructor() {} - -} - -interface __Options_MyStateSample { - -} - -`; - -function testObservedOnlyTransformer(this: PluginTestContext): void { - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'test observed with track transform', - [observedTrackTransform, uiNoRecheck], - { - checked: [testObservedOnlyTransformer], - }, - { - stopAfter: 'checked', - } -); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/track-only.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/track-only.test.ts deleted file mode 100644 index a1e60b0fa..000000000 --- a/arkui-plugins/test/ut/ui-plugins/decorators/observed-track/track-only.test.ts +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; -import { parseDumpSrc } from '../../../../utils/parse-string'; -import { uiNoRecheck } from '../../../../utils/plugins'; -import { uiTransform } from '../../../../../ui-plugins'; -import { Plugins } from '../../../../../common/plugin-context'; - -const OBSERVED_DIR_PATH: string = 'decorators/observed-track'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [ - path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, OBSERVED_DIR_PATH, 'track-only.ets'), -]; - -const observedTrackTransform: Plugins = { - name: 'observedTrack', - parsed: uiTransform().parsed, -} - -const pluginTester = new PluginTester('test track only transform', buildConfig); - -const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; - -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; - -import { memo as memo } from "arkui.stateManagement.runtime"; - -import { SubscribedWatches as SubscribedWatches } from "@ohos.arkui.stateManagement"; - -import { WatchIdType as WatchIdType } from "@ohos.arkui.stateManagement"; - -import { int32 as int32 } from "@ohos.arkui.stateManagement"; - -import { IObservedObject as IObservedObject } from "@ohos.arkui.stateManagement"; - -import { setObservationDepth as setObservationDepth } from "@ohos.arkui.stateManagement"; - -import { BackingValue as BackingValue } from "@ohos.arkui.stateManagement"; - -import { MutableStateMeta as MutableStateMeta } from "@ohos.arkui.stateManagement"; - -import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; - -import { Component as Component } from "@ohos.arkui.component"; - -import { Track as Track } from "@ohos.arkui.stateManagement"; - -function main() {} - - - -class C implements IObservedObject { - private subscribedWatches: SubscribedWatches = new SubscribedWatches(); - - public addWatchSubscriber(watchId: WatchIdType): void { - this.subscribedWatches.addWatchSubscriber(watchId); - } - - public removeWatchSubscriber(watchId: WatchIdType): boolean { - return this.subscribedWatches.removeWatchSubscriber(watchId); - } - - public executeOnSubscribingWatches(propertyName: string): void { - this.subscribedWatches.executeOnSubscribingWatches(propertyName); - } - - public _permissibleAddRefDepth: int32 = 0; - - public propC: number = 1; - - private __backing_trackC: number = 2; - - private __meta_trackC: MutableStateMeta = new MutableStateMeta("@Track"); - - public constructor() {} - - public get trackC(): number { - if (((this._permissibleAddRefDepth) > (0))) { - this.__meta_trackC.addRef(); - } - return this.__backing_trackC; - } - - public set trackC(newValue: number) { - if (((this.__backing_trackC) !== (newValue))) { - this.__backing_trackC = newValue; - this.__meta_trackC.fireChange(); - this.executeOnSubscribingWatches("trackC"); - } - } - -} - -@Component({freezeWhenInactive:false}) final class MyStateSample extends CustomComponent { - public __initializeStruct(initializers: __Options_MyStateSample | undefined, @memo() content: (()=> void) | undefined): void {} - - public __updateStruct(initializers: __Options_MyStateSample | undefined): void {} - - @memo() public _build(@memo() style: ((instance: MyStateSample)=> MyStateSample) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_MyStateSample | undefined): void {} - - public constructor() {} - -} - -interface __Options_MyStateSample { - -} - -`; - -function testObservedOnlyTransformer(this: PluginTestContext): void { - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'test track only transform', - [observedTrackTransform, uiNoRecheck], - { - checked: [testObservedOnlyTransformer], - }, - { - stopAfter: 'checked', - } -); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/prop/prop-basic-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/prop/prop-basic-type.test.ts deleted file mode 100644 index 9ed163723..000000000 --- a/arkui-plugins/test/ut/ui-plugins/decorators/prop/prop-basic-type.test.ts +++ /dev/null @@ -1,161 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; -import { parseDumpSrc } from '../../../../utils/parse-string'; -import { structNoRecheck } from '../../../../utils/plugins'; -import { uiTransform } from '../../../../../ui-plugins'; -import { Plugins } from '../../../../../common/plugin-context'; - -const BUILDER_LAMBDA_DIR_PATH: string = 'decorators/prop'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [ - path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, BUILDER_LAMBDA_DIR_PATH, 'prop-basic-type.ets'), -]; - -const pluginTester = new PluginTester('test basic type @Prop decorated variables transformation', buildConfig); - -const parsedTransform: Plugins = { - name: 'prop-basic-type', - parsed: uiTransform().parsed -}; - -const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; -import { memo as memo } from "arkui.stateManagement.runtime"; -import { PropDecoratedVariable as PropDecoratedVariable } from "@ohos.arkui.stateManagement"; -import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; -import { Component as Component } from "@ohos.arkui.component"; -import { Prop as Prop } from "@ohos.arkui.stateManagement"; - -function main() {} - -@Component({freezeWhenInactive:false}) final class PropParent extends CustomComponent { - public __initializeStruct(initializers: __Options_PropParent | undefined, @memo() content: (()=> void) | undefined): void { - this.__backing_propVar1 = new PropDecoratedVariable("propVar1", ((({let gensym___95172135 = initializers; - (((gensym___95172135) == (null)) ? undefined : gensym___95172135.propVar1)})) ?? ("propVar1"))); - this.__backing_propVar2 = new PropDecoratedVariable("propVar2", ((({let gensym___222490386 = initializers; - (((gensym___222490386) == (null)) ? undefined : gensym___222490386.propVar2)})) ?? (50))); - this.__backing_propVar3 = new PropDecoratedVariable("propVar3", ((({let gensym___201781257 = initializers; - (((gensym___201781257) == (null)) ? undefined : gensym___201781257.propVar3)})) ?? (true))); - this.__backing_propVar4 = new PropDecoratedVariable("propVar4", ((({let gensym___22028950 = initializers; - (((gensym___22028950) == (null)) ? undefined : gensym___22028950.propVar4)})) ?? (undefined))); - this.__backing_propVar5 = new PropDecoratedVariable("propVar5", ((({let gensym___54872258 = initializers; - (((gensym___54872258) == (null)) ? undefined : gensym___54872258.propVar5)})) ?? (null))); - } - public __updateStruct(initializers: __Options_PropParent | undefined): void { - if (((({let gensym___67969738 = initializers; - (((gensym___67969738) == (null)) ? undefined : gensym___67969738.propVar1)})) !== (undefined))) { - this.__backing_propVar1!.update((initializers!.propVar1 as string)); - } - if (((({let gensym___52350476 = initializers; - (((gensym___52350476) == (null)) ? undefined : gensym___52350476.propVar2)})) !== (undefined))) { - this.__backing_propVar2!.update((initializers!.propVar2 as number)); - } - if (((({let gensym___103864283 = initializers; - (((gensym___103864283) == (null)) ? undefined : gensym___103864283.propVar3)})) !== (undefined))) { - this.__backing_propVar3!.update((initializers!.propVar3 as boolean)); - } - if (((({let gensym___175155715 = initializers; - (((gensym___175155715) == (null)) ? undefined : gensym___175155715.propVar4)})) !== (undefined))) { - this.__backing_propVar4!.update((initializers!.propVar4 as undefined)); - } - if (((({let gensym___134530703 = initializers; - (((gensym___134530703) == (null)) ? undefined : gensym___134530703.propVar5)})) !== (undefined))) { - this.__backing_propVar5!.update((initializers!.propVar5 as null)); - } - } - private __backing_propVar1?: PropDecoratedVariable; - public get propVar1(): string { - return this.__backing_propVar1!.get(); - } - public set propVar1(value: string) { - this.__backing_propVar1!.set(value); - } - private __backing_propVar2?: PropDecoratedVariable; - public get propVar2(): number { - return this.__backing_propVar2!.get(); - } - public set propVar2(value: number) { - this.__backing_propVar2!.set(value); - } - private __backing_propVar3?: PropDecoratedVariable; - public get propVar3(): boolean { - return this.__backing_propVar3!.get(); - } - public set propVar3(value: boolean) { - this.__backing_propVar3!.set(value); - } - private __backing_propVar4?: PropDecoratedVariable; - public get propVar4(): undefined { - return this.__backing_propVar4!.get(); - } - public set propVar4(value: undefined) { - this.__backing_propVar4!.set(value); - } - private __backing_propVar5?: PropDecoratedVariable; - public get propVar5(): null { - return this.__backing_propVar5!.get(); - } - public set propVar5(value: null) { - this.__backing_propVar5!.set(value); - } - @memo() public _build(@memo() style: ((instance: PropParent)=> PropParent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_PropParent | undefined): void {} - public constructor() {} -} - -interface __Options_PropParent { - set propVar1(propVar1: string | undefined) - get propVar1(): string | undefined - set __backing_propVar1(__backing_propVar1: PropDecoratedVariable | undefined) - get __backing_propVar1(): PropDecoratedVariable | undefined - set propVar2(propVar2: number | undefined) - get propVar2(): number | undefined - set __backing_propVar2(__backing_propVar2: PropDecoratedVariable | undefined) - get __backing_propVar2(): PropDecoratedVariable | undefined - set propVar3(propVar3: boolean | undefined) - get propVar3(): boolean | undefined - set __backing_propVar3(__backing_propVar3: PropDecoratedVariable | undefined) - get __backing_propVar3(): PropDecoratedVariable | undefined - set propVar4(propVar4: undefined | undefined) - get propVar4(): undefined | undefined - set __backing_propVar4(__backing_propVar4: PropDecoratedVariable | undefined) - get __backing_propVar4(): PropDecoratedVariable | undefined - set propVar5(propVar5: null | undefined) - get propVar5(): null | undefined - set __backing_propVar5(__backing_propVar5: PropDecoratedVariable | undefined) - get __backing_propVar5(): PropDecoratedVariable | undefined -} -`; - -function testParsedAndCheckedTransformer(this: PluginTestContext): void { - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'test basic type @Prop decorated variables transformation', - [parsedTransform, structNoRecheck], - { - checked: [testParsedAndCheckedTransformer], - }, - { - stopAfter: 'checked', - } -); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/prop/prop-complex-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/prop/prop-complex-type.test.ts deleted file mode 100644 index 7db445781..000000000 --- a/arkui-plugins/test/ut/ui-plugins/decorators/prop/prop-complex-type.test.ts +++ /dev/null @@ -1,337 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; -import { parseDumpSrc } from '../../../../utils/parse-string'; -import { structNoRecheck } from '../../../../utils/plugins'; -import { uiTransform } from '../../../../../ui-plugins'; -import { Plugins } from '../../../../../common/plugin-context'; - -const BUILDER_LAMBDA_DIR_PATH: string = 'decorators/prop'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [ - path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, BUILDER_LAMBDA_DIR_PATH, 'prop-complex-type.ets'), -]; - -const pluginTester = new PluginTester('test complex type @Prop decorated variables transformation', buildConfig); - -const parsedTransform: Plugins = { - name: 'prop-complex-type', - parsed: uiTransform().parsed -}; - -const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; -import { memo as memo } from "arkui.stateManagement.runtime"; -import { PropDecoratedVariable as PropDecoratedVariable } from "@ohos.arkui.stateManagement"; -import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; -import { Component as Component } from "@ohos.arkui.component"; -import { Prop as Prop } from "@ohos.arkui.stateManagement"; - -function main() {} - -class Per { - public num: number; - public constructor(num: number) { - this.num = num; - } -} - -final class PropType extends BaseEnum { - private readonly #ordinal: int; - private static () {} - public constructor(ordinal: int, value: int) { - super(value); - this.#ordinal = ordinal; - } - public static readonly TYPE1: PropType = new PropType(0, 0); - public static readonly TYPE2: PropType = new PropType(1, 1); - public static readonly TYPE3: PropType = new PropType(2, 3); - private static readonly #NamesArray: String[] = ["TYPE1", "TYPE2", "TYPE3"]; - private static readonly #ValuesArray: int[] = [0, 1, 3]; - private static readonly #StringValuesArray: String[] = ["0", "1", "3"]; - private static readonly #ItemsArray: PropType[] = [PropType.TYPE1, PropType.TYPE2, PropType.TYPE3]; - public getName(): String { - return PropType.#NamesArray[this.#ordinal]; - } - public static getValueOf(name: String): PropType { - for (let i = 0;((i) < (PropType.#NamesArray.length));(++i)) { - if (((name) == (PropType.#NamesArray[i]))) { - return PropType.#ItemsArray[i]; - } - } - throw new Error((("No enum constant PropType.") + (name))); - } - public static fromValue(value: int): PropType { - for (let i = 0;((i) < (PropType.#ValuesArray.length));(++i)) { - if (((value) == (PropType.#ValuesArray[i]))) { - return PropType.#ItemsArray[i]; - } - } - throw new Error((("No enum PropType with value ") + (value))); - } - public valueOf(): int { - return PropType.#ValuesArray[this.#ordinal]; - } - public toString(): String { - return PropType.#StringValuesArray[this.#ordinal]; - } - public static values(): PropType[] { - return PropType.#ItemsArray; - } - public getOrdinal(): int { - return this.#ordinal; - } - public static $_get(e: PropType): String { - return e.getName(); - } -} - -@Component({freezeWhenInactive:false}) final class Parent extends CustomComponent { - public __initializeStruct(initializers: __Options_Parent | undefined, @memo() content: (()=> void) | undefined): void { - this.__backing_propVar1 = new PropDecoratedVariable("propVar1", ((({let gensym___95172135 = initializers; - (((gensym___95172135) == (null)) ? undefined : gensym___95172135.propVar1)})) ?? (new Per(6)))); - this.__backing_propVar2 = new PropDecoratedVariable>("propVar2", ((({let gensym___222490386 = initializers; - (((gensym___222490386) == (null)) ? undefined : gensym___222490386.propVar2)})) ?? (new Array(3, 6, 8)))); - this.__backing_propVar3 = new PropDecoratedVariable("propVar3", ((({let gensym___201781257 = initializers; - (((gensym___201781257) == (null)) ? undefined : gensym___201781257.propVar3)})) ?? (PropType.TYPE3))); - this.__backing_propVar4 = new PropDecoratedVariable>("propVar4", ((({let gensym___22028950 = initializers; - (((gensym___22028950) == (null)) ? undefined : gensym___22028950.propVar4)})) ?? (new Set(new Array("aa", "bb"))))); - this.__backing_propVar5 = new PropDecoratedVariable>("propVar5", ((({let gensym___54872258 = initializers; - (((gensym___54872258) == (null)) ? undefined : gensym___54872258.propVar5)})) ?? ([true, false]))); - this.__backing_propVar6 = new PropDecoratedVariable>("propVar6", ((({let gensym___128760941 = initializers; - (((gensym___128760941) == (null)) ? undefined : gensym___128760941.propVar6)})) ?? (new Array(new Per(7), new Per(11))))); - this.__backing_propVar7 = new PropDecoratedVariable>("propVar7", ((({let gensym___30534085 = initializers; - (((gensym___30534085) == (null)) ? undefined : gensym___30534085.propVar7)})) ?? ([new Per(7), new Per(11)]))); - this.__backing_propVar8 = new PropDecoratedVariable<((sr: string)=> void)>("propVar8", ((({let gensym___12471776 = initializers; - (((gensym___12471776) == (null)) ? undefined : gensym___12471776.propVar8)})) ?? (((sr: string) => {})))); - this.__backing_propVar9 = new PropDecoratedVariable("propVar9", ((({let gensym___123472108 = initializers; - (((gensym___123472108) == (null)) ? undefined : gensym___123472108.propVar9)})) ?? (new Date("2025-4-23")))); - this.__backing_propVar10 = new PropDecoratedVariable>("propVar10", ((({let gensym___147847012 = initializers; - (((gensym___147847012) == (null)) ? undefined : gensym___147847012.propVar10)})) ?? (new Map([[0, new Per(7)], [1, new Per(10)]])))); - this.__backing_propVar11 = new PropDecoratedVariable("propVar11", ((({let gensym___117026760 = initializers; - (((gensym___117026760) == (null)) ? undefined : gensym___117026760.propVar11)})) ?? (0.0))); - this.__backing_propVar12 = new PropDecoratedVariable | Per>("propVar12", ((({let gensym___220245132 = initializers; - (((gensym___220245132) == (null)) ? undefined : gensym___220245132.propVar12)})) ?? (new Per(6)))); - } - public __updateStruct(initializers: __Options_Parent | undefined): void { - if (((({let gensym___67969738 = initializers; - (((gensym___67969738) == (null)) ? undefined : gensym___67969738.propVar1)})) !== (undefined))) { - this.__backing_propVar1!.update((initializers!.propVar1 as Per)); - } - if (((({let gensym___52350476 = initializers; - (((gensym___52350476) == (null)) ? undefined : gensym___52350476.propVar2)})) !== (undefined))) { - this.__backing_propVar2!.update((initializers!.propVar2 as Array)); - } - if (((({let gensym___103864283 = initializers; - (((gensym___103864283) == (null)) ? undefined : gensym___103864283.propVar3)})) !== (undefined))) { - this.__backing_propVar3!.update((initializers!.propVar3 as PropType)); - } - if (((({let gensym___175155715 = initializers; - (((gensym___175155715) == (null)) ? undefined : gensym___175155715.propVar4)})) !== (undefined))) { - this.__backing_propVar4!.update((initializers!.propVar4 as Set)); - } - if (((({let gensym___134530703 = initializers; - (((gensym___134530703) == (null)) ? undefined : gensym___134530703.propVar5)})) !== (undefined))) { - this.__backing_propVar5!.update((initializers!.propVar5 as Array)); - } - if (((({let gensym___211600890 = initializers; - (((gensym___211600890) == (null)) ? undefined : gensym___211600890.propVar6)})) !== (undefined))) { - this.__backing_propVar6!.update((initializers!.propVar6 as Array)); - } - if (((({let gensym___124229427 = initializers; - (((gensym___124229427) == (null)) ? undefined : gensym___124229427.propVar7)})) !== (undefined))) { - this.__backing_propVar7!.update((initializers!.propVar7 as Array)); - } - if (((({let gensym___248056380 = initializers; - (((gensym___248056380) == (null)) ? undefined : gensym___248056380.propVar8)})) !== (undefined))) { - this.__backing_propVar8!.update((initializers!.propVar8 as ((sr: string)=> void))); - } - if (((({let gensym___55399278 = initializers; - (((gensym___55399278) == (null)) ? undefined : gensym___55399278.propVar9)})) !== (undefined))) { - this.__backing_propVar9!.update((initializers!.propVar9 as Date)); - } - if (((({let gensym___125042885 = initializers; - (((gensym___125042885) == (null)) ? undefined : gensym___125042885.propVar10)})) !== (undefined))) { - this.__backing_propVar10!.update((initializers!.propVar10 as Map)); - } - if (((({let gensym___2015283 = initializers; - (((gensym___2015283) == (null)) ? undefined : gensym___2015283.propVar11)})) !== (undefined))) { - this.__backing_propVar11!.update((initializers!.propVar11 as string | number)); - } - if (((({let gensym___39009414 = initializers; - (((gensym___39009414) == (null)) ? undefined : gensym___39009414.propVar12)})) !== (undefined))) { - this.__backing_propVar12!.update((initializers!.propVar12 as Set | Per)); - } - } - private __backing_propVar1?: PropDecoratedVariable; - public get propVar1(): Per { - return this.__backing_propVar1!.get(); - } - public set propVar1(value: Per) { - this.__backing_propVar1!.set(value); - } - private __backing_propVar2?: PropDecoratedVariable>; - public get propVar2(): Array { - return this.__backing_propVar2!.get(); - } - public set propVar2(value: Array) { - this.__backing_propVar2!.set(value); - } - private __backing_propVar3?: PropDecoratedVariable; - public get propVar3(): PropType { - return this.__backing_propVar3!.get(); - } - public set propVar3(value: PropType) { - this.__backing_propVar3!.set(value); - } - private __backing_propVar4?: PropDecoratedVariable>; - public get propVar4(): Set { - return this.__backing_propVar4!.get(); - } - public set propVar4(value: Set) { - this.__backing_propVar4!.set(value); - } - private __backing_propVar5?: PropDecoratedVariable>; - public get propVar5(): Array { - return this.__backing_propVar5!.get(); - } - public set propVar5(value: Array) { - this.__backing_propVar5!.set(value); - } - private __backing_propVar6?: PropDecoratedVariable>; - public get propVar6(): Array { - return this.__backing_propVar6!.get(); - } - public set propVar6(value: Array) { - this.__backing_propVar6!.set(value); - } - private __backing_propVar7?: PropDecoratedVariable>; - public get propVar7(): Array { - return this.__backing_propVar7!.get(); - } - public set propVar7(value: Array) { - this.__backing_propVar7!.set(value); - } - private __backing_propVar8?: PropDecoratedVariable<((sr: string)=> void)>; - public get propVar8(): ((sr: string)=> void) { - return this.__backing_propVar8!.get(); - } - public set propVar8(value: ((sr: string)=> void)) { - this.__backing_propVar8!.set(value); - } - private __backing_propVar9?: PropDecoratedVariable; - public get propVar9(): Date { - return this.__backing_propVar9!.get(); - } - public set propVar9(value: Date) { - this.__backing_propVar9!.set(value); - } - private __backing_propVar10?: PropDecoratedVariable>; - public get propVar10(): Map { - return this.__backing_propVar10!.get(); - } - public set propVar10(value: Map) { - this.__backing_propVar10!.set(value); - } - private __backing_propVar11?: PropDecoratedVariable; - public get propVar11(): string | number { - return this.__backing_propVar11!.get(); - } - public set propVar11(value: string | number) { - this.__backing_propVar11!.set(value); - } - private __backing_propVar12?: PropDecoratedVariable | Per>; - public get propVar12(): Set | Per { - return this.__backing_propVar12!.get(); - } - public set propVar12(value: Set | Per) { - this.__backing_propVar12!.set(value); - } - @memo() public _build(@memo() style: ((instance: Parent)=> Parent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Parent | undefined): void {} - public constructor() {} -} - -interface __Options_Parent { - set propVar1(propVar1: Per | undefined) - get propVar1(): Per | undefined - set __backing_propVar1(__backing_propVar1: PropDecoratedVariable | undefined) - get __backing_propVar1(): PropDecoratedVariable | undefined - set propVar2(propVar2: Array | undefined) - get propVar2(): Array | undefined - set __backing_propVar2(__backing_propVar2: PropDecoratedVariable> | undefined) - get __backing_propVar2(): PropDecoratedVariable> | undefined - set propVar3(propVar3: PropType | undefined) - get propVar3(): PropType | undefined - set __backing_propVar3(__backing_propVar3: PropDecoratedVariable | undefined) - get __backing_propVar3(): PropDecoratedVariable | undefined - set propVar4(propVar4: Set | undefined) - get propVar4(): Set | undefined - set __backing_propVar4(__backing_propVar4: PropDecoratedVariable> | undefined) - get __backing_propVar4(): PropDecoratedVariable> | undefined - set propVar5(propVar5: Array | undefined) - get propVar5(): Array | undefined - set __backing_propVar5(__backing_propVar5: PropDecoratedVariable> | undefined) - get __backing_propVar5(): PropDecoratedVariable> | undefined - set propVar6(propVar6: Array | undefined) - get propVar6(): Array | undefined - set __backing_propVar6(__backing_propVar6: PropDecoratedVariable> | undefined) - get __backing_propVar6(): PropDecoratedVariable> | undefined - set propVar7(propVar7: Array | undefined) - get propVar7(): Array | undefined - set __backing_propVar7(__backing_propVar7: PropDecoratedVariable> | undefined) - get __backing_propVar7(): PropDecoratedVariable> | undefined - set propVar8(propVar8: ((sr: string)=> void) | undefined) - get propVar8(): ((sr: string)=> void) | undefined - set __backing_propVar8(__backing_propVar8: PropDecoratedVariable<((sr: string)=> void)> | undefined) - get __backing_propVar8(): PropDecoratedVariable<((sr: string)=> void)> | undefined - set propVar9(propVar9: Date | undefined) - get propVar9(): Date | undefined - set __backing_propVar9(__backing_propVar9: PropDecoratedVariable | undefined) - get __backing_propVar9(): PropDecoratedVariable | undefined - set propVar10(propVar10: Map | undefined) - get propVar10(): Map | undefined - set __backing_propVar10(__backing_propVar10: PropDecoratedVariable> | undefined) - get __backing_propVar10(): PropDecoratedVariable> | undefined - set propVar11(propVar11: string | number | undefined) - get propVar11(): string | number | undefined - set __backing_propVar11(__backing_propVar11: PropDecoratedVariable | undefined) - get __backing_propVar11(): PropDecoratedVariable | undefined - set propVar12(propVar12: Set | Per | undefined) - get propVar12(): Set | Per | undefined - set __backing_propVar12(__backing_propVar12: PropDecoratedVariable | Per> | undefined) - get __backing_propVar12(): PropDecoratedVariable | Per> | undefined -} -`; - -function testParsedAndCheckedTransformer(this: PluginTestContext): void { - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'test complex type @Prop decorated variables transformation', - [parsedTransform, structNoRecheck], - { - checked: [testParsedAndCheckedTransformer], - }, - { - stopAfter: 'checked', - } -); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/prop/state-to-prop.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/prop/state-to-prop.test.ts deleted file mode 100644 index 0809c2d46..000000000 --- a/arkui-plugins/test/ut/ui-plugins/decorators/prop/state-to-prop.test.ts +++ /dev/null @@ -1,169 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; -import { parseDumpSrc } from '../../../../utils/parse-string'; -import { uiNoRecheck } from '../../../../utils/plugins'; -import { uiTransform } from '../../../../../ui-plugins'; -import { Plugins } from '../../../../../common/plugin-context'; - -const BUILDER_LAMBDA_DIR_PATH: string = 'decorators/prop'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [ - path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, BUILDER_LAMBDA_DIR_PATH, 'state-to-prop.ets'), -]; - -const pluginTester = new PluginTester('test @Prop decorated variables passing', buildConfig); - -const parsedTransform: Plugins = { - name: 'state-to-prop', - parsed: uiTransform().parsed -}; - -const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; -import { memo as memo } from "arkui.stateManagement.runtime"; -import { StateDecoratedVariable as StateDecoratedVariable } from "@ohos.arkui.stateManagement"; -import { PropDecoratedVariable as PropDecoratedVariable } from "@ohos.arkui.stateManagement"; -import { UIColumnAttribute as UIColumnAttribute } from "@ohos.arkui.component"; -import { UIButtonAttribute as UIButtonAttribute } from "@ohos.arkui.component"; -import { UITextAttribute as UITextAttribute } from "@ohos.arkui.component"; -import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; -import { Component as Component, Text as Text, Button as Button, Column as Column, ClickEvent as ClickEvent } from "@ohos.arkui.component"; -import { Prop as Prop, State as State } from "@ohos.arkui.stateManagement"; - -function main() {} - -@Component({freezeWhenInactive:false}) final class CountDownComponent extends CustomComponent { - public __initializeStruct(initializers: __Options_CountDownComponent | undefined, @memo() content: (()=> void) | undefined): void { - this.__backing_count = new PropDecoratedVariable("count", ((({let gensym___58710805 = initializers; - (((gensym___58710805) == (null)) ? undefined : gensym___58710805.count)})) ?? (0))); - this.__backing_costOfOneAttempt = ((({let gensym___88948111 = initializers; - (((gensym___88948111) == (null)) ? undefined : gensym___88948111.costOfOneAttempt)})) ?? (1)); - } - public __updateStruct(initializers: __Options_CountDownComponent | undefined): void { - if (((({let gensym___188547633 = initializers; - (((gensym___188547633) == (null)) ? undefined : gensym___188547633.count)})) !== (undefined))) { - this.__backing_count!.update((initializers!.count as number)); - } - } - private __backing_count?: PropDecoratedVariable; - public get count(): number { - return this.__backing_count!.get(); - } - public set count(value: number) { - this.__backing_count!.set(value); - } - private __backing_costOfOneAttempt?: number; - public get costOfOneAttempt(): number { - return (this.__backing_costOfOneAttempt as number); - } - public set costOfOneAttempt(value: number) { - this.__backing_costOfOneAttempt = value; - } - - @memo() public _build(@memo() style: ((instance: CountDownComponent)=> CountDownComponent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_CountDownComponent | undefined): void { - Column(undefined, undefined, (() => { - if (((this.count) > (0))) { - Text(undefined, (((("You have") + (this.count))) + ("Nuggets left")), undefined, undefined); - } else { - Text(undefined, "Game over!", undefined, undefined); - } - Button(@memo() ((instance: UIButtonAttribute): void => { - instance.onClick(((e: ClickEvent) => { - this.count -= this.costOfOneAttempt; - })); - return; - }), "Try again", undefined, undefined); - })); - } - public constructor() {} -} - -@Component({freezeWhenInactive:false}) final class ParentComponent extends CustomComponent { - public __initializeStruct(initializers: __Options_ParentComponent | undefined, @memo() content: (()=> void) | undefined): void { - this.__backing_countDownStartValue = new StateDecoratedVariable("countDownStartValue", ((({let gensym___249912438 = initializers; - (((gensym___249912438) == (null)) ? undefined : gensym___249912438.countDownStartValue)})) ?? (10))); - } - public __updateStruct(initializers: __Options_ParentComponent | undefined): void {} - private __backing_countDownStartValue?: StateDecoratedVariable; - public get countDownStartValue(): number { - return this.__backing_countDownStartValue!.get(); - } - public set countDownStartValue(value: number) { - this.__backing_countDownStartValue!.set(value); - } - @memo() public _build(@memo() style: ((instance: ParentComponent)=> ParentComponent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_ParentComponent | undefined): void { - Column(undefined, undefined, (() => { - Text(undefined, (((("Grant") + (this.countDownStartValue))) + ("nuggets to play.")), undefined, undefined); - Button(@memo() ((instance: UIButtonAttribute): void => { - instance.onClick(((e: ClickEvent) => { - this.countDownStartValue += 1; - })); - return; - }), "+1 - Nuggets in New Game", undefined, undefined); - Button(@memo() ((instance: UIButtonAttribute): void => { - instance.onClick(((e: ClickEvent) => { - this.countDownStartValue -= 1; - })); - return; - }), "-1 - Nuggets in New Game", undefined, undefined); - CountDownComponent._instantiateImpl(undefined, (() => { - return new CountDownComponent(); - }), ({ - count: this.countDownStartValue, - costOfOneAttempt: 2, - } as __Options_CountDownComponent), undefined, undefined); - })); - } - public constructor() {} -} - -interface __Options_CountDownComponent { - set count(count: number | undefined) - get count(): number | undefined - set __backing_count(__backing_count: PropDecoratedVariable | undefined) - get __backing_count(): PropDecoratedVariable | undefined - set costOfOneAttempt(costOfOneAttempt: number | undefined) - get costOfOneAttempt(): number | undefined -} - -interface __Options_ParentComponent { - set countDownStartValue(countDownStartValue: number | undefined) - get countDownStartValue(): number | undefined - set __backing_countDownStartValue(__backing_countDownStartValue: StateDecoratedVariable | undefined) - get __backing_countDownStartValue(): StateDecoratedVariable | undefined -} -`; - -function testParsedAndCheckedTransformer(this: PluginTestContext): void { - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'test @Prop decorated variables passing', - [parsedTransform, uiNoRecheck], - { - checked: [testParsedAndCheckedTransformer], - }, - { - stopAfter: 'checked', - } -); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-annotation-usage.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-annotation-usage.test.ts deleted file mode 100644 index 9f5787762..000000000 --- a/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-annotation-usage.test.ts +++ /dev/null @@ -1,179 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; -import { parseDumpSrc } from '../../../../utils/parse-string'; -import { structNoRecheck } from '../../../../utils/plugins'; -import { uiTransform } from '../../../../../ui-plugins'; -import { Plugins } from '../../../../../common/plugin-context'; - -const BUILDER_LAMBDA_DIR_PATH: string = 'decorators/provide-and-consume'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [ - path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, BUILDER_LAMBDA_DIR_PATH, 'provide-annotation-usage.ets'), -]; - -const pluginTester = new PluginTester('test different @Provide annotation usage transformation', buildConfig); - -const parsedTransform: Plugins = { - name: 'provide-annotation-usage', - parsed: uiTransform().parsed -}; - -const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; -import { memo as memo } from "arkui.stateManagement.runtime"; -import { ProvideDecoratedVariable as ProvideDecoratedVariable } from "@ohos.arkui.stateManagement"; -import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; -import { Component as Component } from "@ohos.arkui.component"; -import { Provide as Provide } from "@ohos.arkui.stateManagement"; - -function main() {} - -@Component({freezeWhenInactive:false}) final class Ancestors extends CustomComponent { - public __initializeStruct(initializers: __Options_Ancestors | undefined, @memo() content: (()=> void) | undefined): void { - this.__backing_count = this.addProvidedVar("count", "count", ((({let gensym___58710805 = initializers; - (((gensym___58710805) == (null)) ? undefined : gensym___58710805.count)})) ?? ("Child0")), false); - this.__backing_count1 = this.addProvidedVar("count1", "prov1", ((({let gensym___84874570 = initializers; - (((gensym___84874570) == (null)) ? undefined : gensym___84874570.count1)})) ?? ("Child1")), false); - this.__backing_count2 = this.addProvidedVar("count2", "prov2", ((({let gensym___124037738 = initializers; - (((gensym___124037738) == (null)) ? undefined : gensym___124037738.count2)})) ?? ("Child2")), false); - this.__backing_count3 = this.addProvidedVar("count3", "prov3", ((({let gensym___199202238 = initializers; - (((gensym___199202238) == (null)) ? undefined : gensym___199202238.count3)})) ?? ("Child3")), true); - this.__backing_count4 = this.addProvidedVar("count4", "count4", ((({let gensym___4359740 = initializers; - (((gensym___4359740) == (null)) ? undefined : gensym___4359740.count4)})) ?? ("Child4")), false); - this.__backing_count5 = this.addProvidedVar("count5", "count5", ((({let gensym___208755050 = initializers; - (((gensym___208755050) == (null)) ? undefined : gensym___208755050.count5)})) ?? ("Child5")), true); - this.__backing_count6 = this.addProvidedVar("count6", "", ((({let gensym___37571585 = initializers; - (((gensym___37571585) == (null)) ? undefined : gensym___37571585.count6)})) ?? ("Child6")), true); - this.__backing_count7 = this.addProvidedVar("count7", "", ((({let gensym___2162781 = initializers; - (((gensym___2162781) == (null)) ? undefined : gensym___2162781.count7)})) ?? ("Child7")), false); - } - public __updateStruct(initializers: __Options_Ancestors | undefined): void {} - private __backing_count?: ProvideDecoratedVariable; - public get count(): string | undefined { - return this.__backing_count!.get(); - } - public set count(value: string | undefined) { - this.__backing_count!.set(value); - } - private __backing_count1?: ProvideDecoratedVariable; - public get count1(): string | undefined { - return this.__backing_count1!.get(); - } - public set count1(value: string | undefined) { - this.__backing_count1!.set(value); - } - private __backing_count2?: ProvideDecoratedVariable; - public get count2(): string | undefined { - return this.__backing_count2!.get(); - } - public set count2(value: string | undefined) { - this.__backing_count2!.set(value); - } - private __backing_count3?: ProvideDecoratedVariable; - public get count3(): string | undefined { - return this.__backing_count3!.get(); - } - public set count3(value: string | undefined) { - this.__backing_count3!.set(value); - } - private __backing_count4?: ProvideDecoratedVariable; - public get count4(): string | undefined { - return this.__backing_count4!.get(); - } - public set count4(value: string | undefined) { - this.__backing_count4!.set(value); - } - private __backing_count5?: ProvideDecoratedVariable; - public get count5(): string | undefined { - return this.__backing_count5!.get(); - } - public set count5(value: string | undefined) { - this.__backing_count5!.set(value); - } - private __backing_count6?: ProvideDecoratedVariable; - public get count6(): string | undefined { - return this.__backing_count6!.get(); - } - public set count6(value: string | undefined) { - this.__backing_count6!.set(value); - } - private __backing_count7?: ProvideDecoratedVariable; - public get count7(): string | undefined { - return this.__backing_count7!.get(); - } - public set count7(value: string | undefined) { - this.__backing_count7!.set(value); - } - @memo() public _build(@memo() style: ((instance: Ancestors)=> Ancestors) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Ancestors | undefined): void {} - public constructor() {} -} - -interface __Options_Ancestors { - set count(count: string | undefined | undefined) - get count(): string | undefined | undefined - set __backing_count(__backing_count: ProvideDecoratedVariable | undefined) - get __backing_count(): ProvideDecoratedVariable | undefined - set count1(count1: string | undefined | undefined) - get count1(): string | undefined | undefined - set __backing_count1(__backing_count1: ProvideDecoratedVariable | undefined) - get __backing_count1(): ProvideDecoratedVariable | undefined - set count2(count2: string | undefined | undefined) - get count2(): string | undefined | undefined - set __backing_count2(__backing_count2: ProvideDecoratedVariable | undefined) - get __backing_count2(): ProvideDecoratedVariable | undefined - set count3(count3: string | undefined | undefined) - get count3(): string | undefined | undefined - set __backing_count3(__backing_count3: ProvideDecoratedVariable | undefined) - get __backing_count3(): ProvideDecoratedVariable | undefined - set count4(count4: string | undefined | undefined) - get count4(): string | undefined | undefined - set __backing_count4(__backing_count4: ProvideDecoratedVariable | undefined) - get __backing_count4(): ProvideDecoratedVariable | undefined - set count5(count5: string | undefined | undefined) - get count5(): string | undefined | undefined - set __backing_count5(__backing_count5: ProvideDecoratedVariable | undefined) - get __backing_count5(): ProvideDecoratedVariable | undefined - set count6(count6: string | undefined | undefined) - get count6(): string | undefined | undefined - set __backing_count6(__backing_count6: ProvideDecoratedVariable | undefined) - get __backing_count6(): ProvideDecoratedVariable | undefined - set count7(count7: string | undefined | undefined) - get count7(): string | undefined | undefined - set __backing_count7(__backing_count7: ProvideDecoratedVariable | undefined) - get __backing_count7(): ProvideDecoratedVariable | undefined -} -`; - -function testParsedAndCheckedTransformer(this: PluginTestContext): void { - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'test different @Provide annotation usage transformation', - [parsedTransform, structNoRecheck], - { - checked: [testParsedAndCheckedTransformer], - }, - { - stopAfter: 'checked', - } -); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-basic-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-basic-type.test.ts deleted file mode 100644 index dffbb429f..000000000 --- a/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-basic-type.test.ts +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; -import { parseDumpSrc } from '../../../../utils/parse-string'; -import { structNoRecheck } from '../../../../utils/plugins'; -import { uiTransform } from '../../../../../ui-plugins'; -import { Plugins } from '../../../../../common/plugin-context'; - -const BUILDER_LAMBDA_DIR_PATH: string = 'decorators/provide-and-consume'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [ - path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, BUILDER_LAMBDA_DIR_PATH, 'provide-basic-type.ets'), -]; - -const pluginTester = new PluginTester('test basic type @Provide decorated variables transformation', buildConfig); - -const parsedTransform: Plugins = { - name: 'provide-basic-type', - parsed: uiTransform().parsed -}; - -const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; -import { memo as memo } from "arkui.stateManagement.runtime"; -import { ProvideDecoratedVariable as ProvideDecoratedVariable } from "@ohos.arkui.stateManagement"; -import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; -import { Component as Component } from "@ohos.arkui.component"; -import { Provide as Provide } from "@ohos.arkui.stateManagement"; - -function main() {} - -@Component({freezeWhenInactive:false}) final class PropParent extends CustomComponent { - public __initializeStruct(initializers: __Options_PropParent | undefined, @memo() content: (()=> void) | undefined): void { - this.__backing_provideVar1 = this.addProvidedVar("provideVar1", "provideVar1", ((({let gensym___181030638 = initializers; - (((gensym___181030638) == (null)) ? undefined : gensym___181030638.provideVar1)})) ?? ("propVar1")), false); - this.__backing_provideVar2 = this.addProvidedVar("provideVar2", "provideVar2", ((({let gensym___143944235 = initializers; - (((gensym___143944235) == (null)) ? undefined : gensym___143944235.provideVar2)})) ?? (50)), false); - this.__backing_provideVar3 = this.addProvidedVar("provideVar3", "provideVar3", ((({let gensym___262195977 = initializers; - (((gensym___262195977) == (null)) ? undefined : gensym___262195977.provideVar3)})) ?? (true)), false); - this.__backing_provideVar4 = this.addProvidedVar("provideVar4", "provideVar4", ((({let gensym___85711435 = initializers; - (((gensym___85711435) == (null)) ? undefined : gensym___85711435.provideVar4)})) ?? (undefined)), false); - this.__backing_provideVar5 = this.addProvidedVar("provideVar5", "provideVar5", ((({let gensym___139253630 = initializers; - (((gensym___139253630) == (null)) ? undefined : gensym___139253630.provideVar5)})) ?? (null)), false); - } - public __updateStruct(initializers: __Options_PropParent | undefined): void {} - private __backing_provideVar1?: ProvideDecoratedVariable; - public get provideVar1(): string { - return this.__backing_provideVar1!.get(); - } - public set provideVar1(value: string) { - this.__backing_provideVar1!.set(value); - } - private __backing_provideVar2?: ProvideDecoratedVariable; - public get provideVar2(): number { - return this.__backing_provideVar2!.get(); - } - public set provideVar2(value: number) { - this.__backing_provideVar2!.set(value); - } - private __backing_provideVar3?: ProvideDecoratedVariable; - public get provideVar3(): boolean { - return this.__backing_provideVar3!.get(); - } - public set provideVar3(value: boolean) { - this.__backing_provideVar3!.set(value); - } - private __backing_provideVar4?: ProvideDecoratedVariable; - public get provideVar4(): undefined { - return this.__backing_provideVar4!.get(); - } - public set provideVar4(value: undefined) { - this.__backing_provideVar4!.set(value); - } - private __backing_provideVar5?: ProvideDecoratedVariable; - public get provideVar5(): null { - return this.__backing_provideVar5!.get(); - } - public set provideVar5(value: null) { - this.__backing_provideVar5!.set(value); - } - @memo() public _build(@memo() style: ((instance: PropParent)=> PropParent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_PropParent | undefined): void {} - public constructor() {} -} - -interface __Options_PropParent { - set provideVar1(provideVar1: string | undefined) - get provideVar1(): string | undefined - set __backing_provideVar1(__backing_provideVar1: ProvideDecoratedVariable | undefined) - get __backing_provideVar1(): ProvideDecoratedVariable | undefined - set provideVar2(provideVar2: number | undefined) - get provideVar2(): number | undefined - set __backing_provideVar2(__backing_provideVar2: ProvideDecoratedVariable | undefined) - get __backing_provideVar2(): ProvideDecoratedVariable | undefined - set provideVar3(provideVar3: boolean | undefined) - get provideVar3(): boolean | undefined - set __backing_provideVar3(__backing_provideVar3: ProvideDecoratedVariable | undefined) - get __backing_provideVar3(): ProvideDecoratedVariable | undefined - set provideVar4(provideVar4: undefined | undefined) - get provideVar4(): undefined | undefined - set __backing_provideVar4(__backing_provideVar4: ProvideDecoratedVariable | undefined) - get __backing_provideVar4(): ProvideDecoratedVariable | undefined - set provideVar5(provideVar5: null | undefined) - get provideVar5(): null | undefined - set __backing_provideVar5(__backing_provideVar5: ProvideDecoratedVariable | undefined) - get __backing_provideVar5(): ProvideDecoratedVariable | undefined -} -`; - -function testParsedAndCheckedTransformer(this: PluginTestContext): void { - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'test basic type @Provide decorated variables transformation', - [parsedTransform, structNoRecheck], - { - checked: [testParsedAndCheckedTransformer], - }, - { - stopAfter: 'checked', - } -); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-complex-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-complex-type.test.ts deleted file mode 100644 index 6684a83fe..000000000 --- a/arkui-plugins/test/ut/ui-plugins/decorators/provide-and-consume/provide-complex-type.test.ts +++ /dev/null @@ -1,288 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; -import { parseDumpSrc } from '../../../../utils/parse-string'; -import { structNoRecheck } from '../../../../utils/plugins'; -import { uiTransform } from '../../../../../ui-plugins'; -import { Plugins } from '../../../../../common/plugin-context'; - -const BUILDER_LAMBDA_DIR_PATH: string = 'decorators/provide-and-consume'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [ - path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, BUILDER_LAMBDA_DIR_PATH, 'provide-complex-type.ets'), -]; - -const pluginTester = new PluginTester('test complex type @Provide decorated variables transformation', buildConfig); - -const parsedTransform: Plugins = { - name: 'provide-complex-type', - parsed: uiTransform().parsed -}; - -const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; -import { memo as memo } from "arkui.stateManagement.runtime"; -import { ProvideDecoratedVariable as ProvideDecoratedVariable } from "@ohos.arkui.stateManagement"; -import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; -import { Component as Component } from "@ohos.arkui.component"; -import { Provide as Provide } from "@ohos.arkui.stateManagement"; - -function main() {} - -class Per { - public num: number; - public constructor(num: number) { - this.num = num; - } -} - -final class PropType extends BaseEnum { - private readonly #ordinal: int; - private static () {} - public constructor(ordinal: int, value: int) { - super(value); - this.#ordinal = ordinal; - } - public static readonly TYPE1: PropType = new PropType(0, 0); - public static readonly TYPE2: PropType = new PropType(1, 1); - public static readonly TYPE3: PropType = new PropType(2, 3); - private static readonly #NamesArray: String[] = ["TYPE1", "TYPE2", "TYPE3"]; - private static readonly #ValuesArray: int[] = [0, 1, 3]; - private static readonly #StringValuesArray: String[] = ["0", "1", "3"]; - private static readonly #ItemsArray: PropType[] = [PropType.TYPE1, PropType.TYPE2, PropType.TYPE3]; - public getName(): String { - return PropType.#NamesArray[this.#ordinal]; - } - public static getValueOf(name: String): PropType { - for (let i = 0;((i) < (PropType.#NamesArray.length));(++i)) { - if (((name) == (PropType.#NamesArray[i]))) { - return PropType.#ItemsArray[i]; - } - } - throw new Error((("No enum constant PropType.") + (name))); - } - public static fromValue(value: int): PropType { - for (let i = 0;((i) < (PropType.#ValuesArray.length));(++i)) { - if (((value) == (PropType.#ValuesArray[i]))) { - return PropType.#ItemsArray[i]; - } - } - throw new Error((("No enum PropType with value ") + (value))); - } - public valueOf(): int { - return PropType.#ValuesArray[this.#ordinal]; - } - public toString(): String { - return PropType.#StringValuesArray[this.#ordinal]; - } - public static values(): PropType[] { - return PropType.#ItemsArray; - } - public getOrdinal(): int { - return this.#ordinal; - } - public static $_get(e: PropType): String { - return e.getName(); - } -} - -@Component({freezeWhenInactive:false}) final class Parent extends CustomComponent { - public __initializeStruct(initializers: __Options_Parent | undefined, @memo() content: (()=> void) | undefined): void { - this.__backing_provideVar1 = this.addProvidedVar("provideVar1", "provideVar1", ((({let gensym___181030638 = initializers; - (((gensym___181030638) == (null)) ? undefined : gensym___181030638.provideVar1)})) ?? (new Per(6))), false); - this.__backing_provideVar2 = this.addProvidedVar>("provideVar2", "provideVar2", ((({let gensym___143944235 = initializers; - (((gensym___143944235) == (null)) ? undefined : gensym___143944235.provideVar2)})) ?? (new Array(3, 6, 8))), false); - this.__backing_provideVar3 = this.addProvidedVar("provideVar3", "provideVar3", ((({let gensym___262195977 = initializers; - (((gensym___262195977) == (null)) ? undefined : gensym___262195977.provideVar3)})) ?? (PropType.TYPE3)), false); - this.__backing_provideVar4 = this.addProvidedVar>("provideVar4", "provideVar4", ((({let gensym___85711435 = initializers; - (((gensym___85711435) == (null)) ? undefined : gensym___85711435.provideVar4)})) ?? (new Set(new Array("aa", "bb")))), false); - this.__backing_provideVar5 = this.addProvidedVar>("provideVar5", "provideVar5", ((({let gensym___139253630 = initializers; - (((gensym___139253630) == (null)) ? undefined : gensym___139253630.provideVar5)})) ?? ([true, false])), false); - this.__backing_provideVar6 = this.addProvidedVar>("provideVar6", "provideVar6", ((({let gensym___146872112 = initializers; - (((gensym___146872112) == (null)) ? undefined : gensym___146872112.provideVar6)})) ?? (new Array(new Per(7), new Per(11)))), false); - this.__backing_provideVar7 = this.addProvidedVar>("provideVar7", "provideVar7", ((({let gensym___174412117 = initializers; - (((gensym___174412117) == (null)) ? undefined : gensym___174412117.provideVar7)})) ?? ([new Per(7), new Per(11)])), false); - this.__backing_provideVar8 = this.addProvidedVar<((sr: string)=> void)>("provideVar8", "provideVar8", ((({let gensym___253467853 = initializers; - (((gensym___253467853) == (null)) ? undefined : gensym___253467853.provideVar8)})) ?? (((sr: string) => {}))), false); - this.__backing_provideVar9 = this.addProvidedVar("provideVar9", "provideVar9", ((({let gensym___179115605 = initializers; - (((gensym___179115605) == (null)) ? undefined : gensym___179115605.provideVar9)})) ?? (new Date("2025-4-23"))), false); - this.__backing_provideVar10 = this.addProvidedVar>("provideVar10", "provideVar10", ((({let gensym___209671248 = initializers; - (((gensym___209671248) == (null)) ? undefined : gensym___209671248.provideVar10)})) ?? (new Map([[0, new Per(7)], [1, new Per(10)]]))), false); - this.__backing_provideVar11 = this.addProvidedVar("provideVar11", "provideVar11", ((({let gensym___150211849 = initializers; - (((gensym___150211849) == (null)) ? undefined : gensym___150211849.provideVar11)})) ?? (0.0)), false); - this.__backing_provideVar12 = this.addProvidedVar | Per>("provideVar12", "provideVar12", ((({let gensym___256025818 = initializers; - (((gensym___256025818) == (null)) ? undefined : gensym___256025818.provideVar12)})) ?? (new Per(6))), false); - } - public __updateStruct(initializers: __Options_Parent | undefined): void {} - private __backing_provideVar1?: ProvideDecoratedVariable; - public get provideVar1(): Per { - return this.__backing_provideVar1!.get(); - } - public set provideVar1(value: Per) { - this.__backing_provideVar1!.set(value); - } - private __backing_provideVar2?: ProvideDecoratedVariable>; - public get provideVar2(): Array { - return this.__backing_provideVar2!.get(); - } - public set provideVar2(value: Array) { - this.__backing_provideVar2!.set(value); - } - private __backing_provideVar3?: ProvideDecoratedVariable; - public get provideVar3(): PropType { - return this.__backing_provideVar3!.get(); - } - public set provideVar3(value: PropType) { - this.__backing_provideVar3!.set(value); - } - private __backing_provideVar4?: ProvideDecoratedVariable>; - public get provideVar4(): Set { - return this.__backing_provideVar4!.get(); - } - public set provideVar4(value: Set) { - this.__backing_provideVar4!.set(value); - } - private __backing_provideVar5?: ProvideDecoratedVariable>; - public get provideVar5(): Array { - return this.__backing_provideVar5!.get(); - } - public set provideVar5(value: Array) { - this.__backing_provideVar5!.set(value); - } - private __backing_provideVar6?: ProvideDecoratedVariable>; - public get provideVar6(): Array { - return this.__backing_provideVar6!.get(); - } - public set provideVar6(value: Array) { - this.__backing_provideVar6!.set(value); - } - private __backing_provideVar7?: ProvideDecoratedVariable>; - public get provideVar7(): Array { - return this.__backing_provideVar7!.get(); - } - public set provideVar7(value: Array) { - this.__backing_provideVar7!.set(value); - } - private __backing_provideVar8?: ProvideDecoratedVariable<((sr: string)=> void)>; - public get provideVar8(): ((sr: string)=> void) { - return this.__backing_provideVar8!.get(); - } - public set provideVar8(value: ((sr: string)=> void)) { - this.__backing_provideVar8!.set(value); - } - private __backing_provideVar9?: ProvideDecoratedVariable; - public get provideVar9(): Date { - return this.__backing_provideVar9!.get(); - } - public set provideVar9(value: Date) { - this.__backing_provideVar9!.set(value); - } - private __backing_provideVar10?: ProvideDecoratedVariable>; - public get provideVar10(): Map { - return this.__backing_provideVar10!.get(); - } - public set provideVar10(value: Map) { - this.__backing_provideVar10!.set(value); - } - private __backing_provideVar11?: ProvideDecoratedVariable; - public get provideVar11(): string | number { - return this.__backing_provideVar11!.get(); - } - public set provideVar11(value: string | number) { - this.__backing_provideVar11!.set(value); - } - private __backing_provideVar12?: ProvideDecoratedVariable | Per>; - public get provideVar12(): Set | Per { - return this.__backing_provideVar12!.get(); - } - public set provideVar12(value: Set | Per) { - this.__backing_provideVar12!.set(value); - } - @memo() public _build(@memo() style: ((instance: Parent)=> Parent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Parent | undefined): void {} - public constructor() {} -} - -interface __Options_Parent { - set provideVar1(provideVar1: Per | undefined) - get provideVar1(): Per | undefined - set __backing_provideVar1(__backing_provideVar1: ProvideDecoratedVariable | undefined) - get __backing_provideVar1(): ProvideDecoratedVariable | undefined - set provideVar2(provideVar2: Array | undefined) - get provideVar2(): Array | undefined - set __backing_provideVar2(__backing_provideVar2: ProvideDecoratedVariable> | undefined) - get __backing_provideVar2(): ProvideDecoratedVariable> | undefined - set provideVar3(provideVar3: PropType | undefined) - get provideVar3(): PropType | undefined - set __backing_provideVar3(__backing_provideVar3: ProvideDecoratedVariable | undefined) - get __backing_provideVar3(): ProvideDecoratedVariable | undefined - set provideVar4(provideVar4: Set | undefined) - get provideVar4(): Set | undefined - set __backing_provideVar4(__backing_provideVar4: ProvideDecoratedVariable> | undefined) - get __backing_provideVar4(): ProvideDecoratedVariable> | undefined - set provideVar5(provideVar5: Array | undefined) - get provideVar5(): Array | undefined - set __backing_provideVar5(__backing_provideVar5: ProvideDecoratedVariable> | undefined) - get __backing_provideVar5(): ProvideDecoratedVariable> | undefined - set provideVar6(provideVar6: Array | undefined) - get provideVar6(): Array | undefined - set __backing_provideVar6(__backing_provideVar6: ProvideDecoratedVariable> | undefined) - get __backing_provideVar6(): ProvideDecoratedVariable> | undefined - set provideVar7(provideVar7: Array | undefined) - get provideVar7(): Array | undefined - set __backing_provideVar7(__backing_provideVar7: ProvideDecoratedVariable> | undefined) - get __backing_provideVar7(): ProvideDecoratedVariable> | undefined - set provideVar8(provideVar8: ((sr: string)=> void) | undefined) - get provideVar8(): ((sr: string)=> void) | undefined - set __backing_provideVar8(__backing_provideVar8: ProvideDecoratedVariable<((sr: string)=> void)> | undefined) - get __backing_provideVar8(): ProvideDecoratedVariable<((sr: string)=> void)> | undefined - set provideVar9(provideVar9: Date | undefined) - get provideVar9(): Date | undefined - set __backing_provideVar9(__backing_provideVar9: ProvideDecoratedVariable | undefined) - get __backing_provideVar9(): ProvideDecoratedVariable | undefined - set provideVar10(provideVar10: Map | undefined) - get provideVar10(): Map | undefined - set __backing_provideVar10(__backing_provideVar10: ProvideDecoratedVariable> | undefined) - get __backing_provideVar10(): ProvideDecoratedVariable> | undefined - set provideVar11(provideVar11: string | number | undefined) - get provideVar11(): string | number | undefined - set __backing_provideVar11(__backing_provideVar11: ProvideDecoratedVariable | undefined) - get __backing_provideVar11(): ProvideDecoratedVariable | undefined - set provideVar12(provideVar12: Set | Per | undefined) - get provideVar12(): Set | Per | undefined - set __backing_provideVar12(__backing_provideVar12: ProvideDecoratedVariable | Per> | undefined) - get __backing_provideVar12(): ProvideDecoratedVariable | Per> | undefined -} -`; - -function testParsedAndCheckedTransformer(this: PluginTestContext): void { - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'test complex type @Provide decorated variables transformation', - [parsedTransform, structNoRecheck], - { - checked: [testParsedAndCheckedTransformer], - }, - { - stopAfter: 'checked', - } -); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/resource/resource-in-build.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/resource/resource-in-build.test.ts deleted file mode 100644 index ad9e6798b..000000000 --- a/arkui-plugins/test/ut/ui-plugins/decorators/resource/resource-in-build.test.ts +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; -import { parseDumpSrc } from '../../../../utils/parse-string'; -import { uiNoRecheck } from '../../../../utils/plugins'; -import { uiTransform } from '../../../../../ui-plugins'; -import { Plugins } from '../../../../../common/plugin-context'; - -const BUILDER_LAMBDA_DIR_PATH: string = 'decorators/resource'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [ - path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, BUILDER_LAMBDA_DIR_PATH, 'resource-in-build.ets'), -]; - -const pluginTester = new PluginTester('test resource transform in build method', buildConfig); - -const parsedTransform: Plugins = { - name: 'resource-in-build', - parsed: uiTransform().parsed -}; - -const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; -import { memo as memo } from "arkui.stateManagement.runtime"; -import { UIImageAnimatorAttribute as UIImageAnimatorAttribute } from "@ohos.arkui.component"; -import { UISelectAttribute as UISelectAttribute } from "@ohos.arkui.component"; -import { UITextInputAttribute as UITextInputAttribute } from "@ohos.arkui.component"; -import { UIImageAttribute as UIImageAttribute } from "@ohos.arkui.component"; -import { UITextAttribute as UITextAttribute } from "@ohos.arkui.component"; -import { UIColumnAttribute as UIColumnAttribute } from "@ohos.arkui.component"; -import { _rawfile as _rawfile } from "@ohos.arkui.component"; -import { _r as _r } from "@ohos.arkui.component"; -import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; -import { Component as Component, $r as $r, $rawfile as $rawfile, Column as Column, Text as Text, Image as Image, TextInput as TextInput, Select as Select, SelectOption as SelectOption, Margin as Margin, ImageAnimator as ImageAnimator } from "@ohos.arkui.component"; - -function main() {} - -@Component({freezeWhenInactive:false}) final class ResourceComponent extends CustomComponent { - public __initializeStruct(initializers: __Options_ResourceComponent | undefined, @memo() content: (()=> void) | undefined): void { - this.__backing_str1 = ((({let gensym___147578113 = initializers; - (((gensym___147578113) == (null)) ? undefined : gensym___147578113.str1)})) ?? ("app.media.ri")); - this.__backing_str2 = ((({let gensym___220149772 = initializers; - (((gensym___220149772) == (null)) ? undefined : gensym___220149772.str2)})) ?? ("app.photo2.png")); - } - public __updateStruct(initializers: __Options_ResourceComponent | undefined): void {} - private __backing_str1?: string; - public get str1(): string { - return (this.__backing_str1 as string); - } - public set str1(value: string) { - this.__backing_str1 = value; - } - private __backing_str2?: string; - public get str2(): string { - return (this.__backing_str2 as string); - } - public set str2(value: string) { - this.__backing_str2 = value; - } - - @memo() public _build(@memo() style: ((instance: ResourceComponent)=> ResourceComponent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_ResourceComponent | undefined): void { - Column(undefined, undefined, (() => { - Text(undefined, _r("", "", "app.string.app_name"), undefined, undefined); - Image(undefined, _rawfile("", "", "app.photo.png"), undefined, undefined); - TextInput(undefined, { - text: _r("", "", "app.string.input_content"), - }, undefined); - Text(undefined, _r("", "", this.str1), undefined, undefined); - Text(undefined, _r("", "", this.str2), undefined, undefined); - Select(undefined, new Array({ - value: "aaa", - icon: _r("", "", "app.media.selection"), - }, { - value: "bbb", - icon: _r("", "", "app.media.selection"), - }, { - value: "ccc", - icon: _r("", "", "app.media.selection"), - }, { - value: "ddd", - icon: _r("", "", "app.media.selection"), - }), undefined); - Image(@memo() ((instance: UIImageAttribute): void => { - instance.margin(({ - top: _r("", "", "app.float.elements_margin_horizontal_m"), - bottom: _r("", "", "app.float.elements_margin_horizontal_l"), - } as Margin)); - return; - }), _r("", "", "app.media.app_icon"), undefined, undefined); - ImageAnimator(@memo() ((instance: UIImageAnimatorAttribute): void => { - instance.images([{ - src: _r("", "", "app.media.aaa"), - }, { - src: _r("", "", "app.media.bbb"), - }]); - return; - }), undefined); - })); - } - public constructor() {} -} - -interface __Options_ResourceComponent { - set str1(str1: string | undefined) - get str1(): string | undefined - set str2(str2: string | undefined) - get str2(): string | undefined -} -`; - -function testParsedAndCheckedTransformer(this: PluginTestContext): void { - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'test resource transform in build method', - [parsedTransform, uiNoRecheck], - { - checked: [testParsedAndCheckedTransformer], - }, - { - stopAfter: 'checked', - } -); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/resource/resource-in-property.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/resource/resource-in-property.test.ts deleted file mode 100644 index 741751b9f..000000000 --- a/arkui-plugins/test/ut/ui-plugins/decorators/resource/resource-in-property.test.ts +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; -import { parseDumpSrc } from '../../../../utils/parse-string'; -import { uiNoRecheck } from '../../../../utils/plugins'; -import { uiTransform } from '../../../../../ui-plugins'; -import { Plugins } from '../../../../../common/plugin-context'; - -const BUILDER_LAMBDA_DIR_PATH: string = 'decorators/resource'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [ - path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, BUILDER_LAMBDA_DIR_PATH, 'resource-in-property.ets'), -]; - -const pluginTester = new PluginTester('test resource transform in property', buildConfig); - -const parsedTransform: Plugins = { - name: 'resource-in-property', - parsed: uiTransform().parsed -}; - -const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; -import { memo as memo } from "arkui.stateManagement.runtime"; -import { UIImageAttribute as UIImageAttribute } from "@ohos.arkui.component"; -import { UITextAttribute as UITextAttribute } from "@ohos.arkui.component"; -import { UIColumnAttribute as UIColumnAttribute } from "@ohos.arkui.component"; -import { _rawfile as _rawfile } from "@ohos.arkui.component"; -import { _r as _r } from "@ohos.arkui.component"; -import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; -import { Component as Component, $r as $r, $rawfile as $rawfile, Column as Column, Text as Text, Image as Image, Resource as Resource } from "@ohos.arkui.component"; - -let i: Resource; -function main() {} -i = _r("", "", "app.string.app_name"); - -@Component({freezeWhenInactive:false}) final class ResourceComponent extends CustomComponent { - public __initializeStruct(initializers: __Options_ResourceComponent | undefined, @memo() content: (()=> void) | undefined): void { - this.__backing_str = ((({let gensym___42103502 = initializers; - (((gensym___42103502) == (null)) ? undefined : gensym___42103502.str)})) ?? (_r("", "", "app.string.app_name"))); - this.__backing_icon = ((({let gensym___38135554 = initializers; - (((gensym___38135554) == (null)) ? undefined : gensym___38135554.icon)})) ?? (_rawfile("", "", "app.photo.png"))); - } - public __updateStruct(initializers: __Options_ResourceComponent | undefined): void {} - private __backing_str?: Resource; - public get str(): Resource { - return (this.__backing_str as Resource); - } - public set str(value: Resource) { - this.__backing_str = value; - } - private __backing_icon?: Resource; - public get icon(): Resource { - return (this.__backing_icon as Resource); - } - public set icon(value: Resource) { - this.__backing_icon = value; - } - @memo() public _build(@memo() style: ((instance: ResourceComponent)=> ResourceComponent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_ResourceComponent | undefined): void { - Column(undefined, undefined, (() => { - Text(undefined, this.str, undefined, undefined); - Text(undefined, i, undefined, undefined); - Image(undefined, this.icon, undefined, undefined); - })); - } - public constructor() {} -} - -interface __Options_ResourceComponent { - set str(str: Resource | undefined) - get str(): Resource | undefined - set icon(icon: Resource | undefined) - get icon(): Resource | undefined -} -`; - -function testParsedAndCheckedTransformer(this: PluginTestContext): void { - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'test resource transform in property', - [parsedTransform, uiNoRecheck], - { - checked: [testParsedAndCheckedTransformer], - }, - { - stopAfter: 'checked', - } -); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/reusable/reusable-basic.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/reusable/reusable-basic.test.ts deleted file mode 100644 index 0589b25ab..000000000 --- a/arkui-plugins/test/ut/ui-plugins/decorators/reusable/reusable-basic.test.ts +++ /dev/null @@ -1,159 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; -import { parseDumpSrc } from '../../../../utils/parse-string'; -import { uiNoRecheck } from '../../../../utils/plugins'; -import { uiTransform } from '../../../../../ui-plugins'; -import { Plugins } from '../../../../../common/plugin-context'; - -const REUSABLE_DIR_PATH: string = 'decorators/reusable'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [ - path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, REUSABLE_DIR_PATH, 'reusable-basic.ets'), -]; - -const reusableTransform: Plugins = { - name: 'reusable', - parsed: uiTransform().parsed, -} - -const pluginTester = new PluginTester('test basic reusable', buildConfig); - -const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; - -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; - -import { memo as memo } from "arkui.stateManagement.runtime"; - -import { DecoratedV1VariableBase as DecoratedV1VariableBase } from "@ohos.arkui.stateManagement"; - -import { LinkDecoratedVariable as LinkDecoratedVariable } from "@ohos.arkui.stateManagement"; - -import { StateDecoratedVariable as StateDecoratedVariable } from "@ohos.arkui.stateManagement"; - -import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; - -import { Component as Component, Reusable as Reusable } from "@ohos.arkui.component"; - -import { State as State, Link as Link } from "@ohos.arkui.stateManagement"; - -function main() {} - - - -@Component({freezeWhenInactive:false}) final class MyStateSample extends CustomComponent { - public __initializeStruct(initializers: __Options_MyStateSample | undefined, @memo() content: (()=> void) | undefined): void {} - - public __updateStruct(initializers: __Options_MyStateSample | undefined): void {} - - @memo() public _build(@memo() style: ((instance: MyStateSample)=> MyStateSample) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_MyStateSample | undefined): void { - Child._instantiateImpl(undefined, (() => { - return new Child(); - }), ({ - num: 5, - } as __Options_Child), undefined, "Child"); - } - - public constructor() {} - -} - -@Component({freezeWhenInactive:false}) @Reusable() final class Child extends CustomComponent { - public __initializeStruct(initializers: __Options_Child | undefined, @memo() content: (()=> void) | undefined): void { - if (({let gensym___98468840 = initializers; - (((gensym___98468840) == (null)) ? undefined : gensym___98468840.__backing_num)})) { - this.__backing_num = new LinkDecoratedVariable("num", initializers!.__backing_num!); - }; - this.__backing_num1 = new StateDecoratedVariable("num1", ((({let gensym___33833641 = initializers; - (((gensym___33833641) == (null)) ? undefined : gensym___33833641.num1)})) ?? (2))); - } - - public __updateStruct(initializers: __Options_Child | undefined): void {} - - public override __toRecord(params: Object): Record { - const paramsCasted = (params as __Options_Child); - return { - "num": ((paramsCasted.num) ?? (new Object())), - "num1": ((paramsCasted.num1) ?? (new Object())), - }; - } - - private __backing_num?: LinkDecoratedVariable; - - public get num(): number { - return this.__backing_num!.get(); - } - - public set num(value: number) { - this.__backing_num!.set(value); - } - - private __backing_num1?: StateDecoratedVariable; - - public get num1(): number { - return this.__backing_num1!.get(); - } - - public set num1(value: number) { - this.__backing_num1!.set(value); - } - - @memo() public _build(@memo() style: ((instance: Child)=> Child) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Child | undefined): void {} - - public constructor() {} - -} - -interface __Options_MyStateSample { - -} - -interface __Options_Child { - set num(num: number | undefined) - - get num(): number | undefined - set __backing_num(__backing_num: DecoratedV1VariableBase | undefined) - - get __backing_num(): DecoratedV1VariableBase | undefined - set num1(num1: number | undefined) - - get num1(): number | undefined - set __backing_num1(__backing_num1: StateDecoratedVariable | undefined) - - get __backing_num1(): StateDecoratedVariable | undefined - -} -`; - -function testReusableTransformer(this: PluginTestContext): void { - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'test basic reusable', - [reusableTransform, uiNoRecheck], - { - checked: [testReusableTransformer], - }, - { - stopAfter: 'checked', - } -); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/reusable/reusable-complex.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/reusable/reusable-complex.test.ts deleted file mode 100644 index 873738ced..000000000 --- a/arkui-plugins/test/ut/ui-plugins/decorators/reusable/reusable-complex.test.ts +++ /dev/null @@ -1,209 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; -import { parseDumpSrc } from '../../../../utils/parse-string'; -import { uiNoRecheck } from '../../../../utils/plugins'; -import { uiTransform } from '../../../../../ui-plugins'; -import { Plugins } from '../../../../../common/plugin-context'; - -const REUSABLE_DIR_PATH: string = 'decorators/reusable'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [ - path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, REUSABLE_DIR_PATH, 'reusable-complex.ets'), -]; - -const reusableTransform: Plugins = { - name: 'reusable', - parsed: uiTransform().parsed, -} - -const pluginTester = new PluginTester('test complex reusable', buildConfig); - -const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; - -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; - -import { memo as memo } from "arkui.stateManagement.runtime"; - -import { StateDecoratedVariable as StateDecoratedVariable } from "@ohos.arkui.stateManagement"; - -import { UIButtonAttribute as UIButtonAttribute } from "@ohos.arkui.component"; - -import { UITextAttribute as UITextAttribute } from "@ohos.arkui.component"; - -import { UIColumnAttribute as UIColumnAttribute } from "@ohos.arkui.component"; - -import { EntryPoint as EntryPoint } from "arkui.UserView"; - -import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; - -import { Component as Component, Entry as Entry, Reusable as Reusable, Column as Column, Text as Text, Button as Button, ClickEvent as ClickEvent, FontWeight as FontWeight } from "@ohos.arkui.component"; - -import { State as State } from "@ohos.arkui.stateManagement"; - -function main() {} - - - -class Message { - public value: string | undefined; - - public constructor(value: string) { - this.value = value; - } - -} - -@Entry({useSharedStorage:false,storage:"",routeName:""}) @Component({freezeWhenInactive:false}) final class Index extends CustomComponent { - public __initializeStruct(initializers: __Options_Index | undefined, @memo() content: (()=> void) | undefined): void { - this.__backing_display = new StateDecoratedVariable("display", ((({let gensym___83835842 = initializers; - (((gensym___83835842) == (null)) ? undefined : gensym___83835842.display)})) ?? (true))); - } - - public __updateStruct(initializers: __Options_Index | undefined): void {} - - private __backing_display?: StateDecoratedVariable; - - public get display(): boolean { - return this.__backing_display!.get(); - } - - public set display(value: boolean) { - this.__backing_display!.set(value); - } - - @memo() public _build(@memo() style: ((instance: Index)=> Index) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Index | undefined): void { - Column(@memo() ((instance: UIColumnAttribute): void => { - instance.height("100%").width("100%"); - return; - }), undefined, (() => { - Button(@memo() ((instance: UIButtonAttribute): void => { - instance.fontSize(30).fontWeight(FontWeight.Bold).onClick(((e: ClickEvent) => { - this.display = !(this.display); - })); - return; - }), "Hello", undefined, undefined); - if (this.display) { - Child._instantiateImpl(undefined, (() => { - return new Child(); - }), ({ - message: new Message("Child"), - } as __Options_Child), undefined, "Child"); - } - })); - } - - public constructor() {} - -} - -@Reusable() @Component({freezeWhenInactive:false}) final class Child extends CustomComponent { - public __initializeStruct(initializers: __Options_Child | undefined, @memo() content: (()=> void) | undefined): void { - this.__backing_message = new StateDecoratedVariable("message", ((({let gensym___91869411 = initializers; - (((gensym___91869411) == (null)) ? undefined : gensym___91869411.message)})) ?? (new Message("AboutToReuse")))); - } - - public __updateStruct(initializers: __Options_Child | undefined): void {} - - public override __toRecord(params: Object): Record { - const paramsCasted = (params as __Options_Child); - return { - "message": ((paramsCasted.message) ?? (new Object())), - }; - } - - private __backing_message?: StateDecoratedVariable; - - public get message(): Message { - return this.__backing_message!.get(); - } - - public set message(value: Message) { - this.__backing_message!.set(value); - } - - public aboutToReuse(params: Record) { - console.info("Recycle ====Child=="); - } - - @memo() public _build(@memo() style: ((instance: Child)=> Child) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Child | undefined): void { - Column(@memo() ((instance: UIColumnAttribute): void => { - instance.borderWidth(1).height(100); - return; - }), undefined, (() => { - Text(@memo() ((instance: UITextAttribute): void => { - instance.fontSize(30); - return; - }), this.message.value, undefined, undefined); - })); - } - - public constructor() {} - -} - -interface __Options_Index { - set display(display: boolean | undefined) - - get display(): boolean | undefined - set __backing_display(__backing_display: StateDecoratedVariable | undefined) - - get __backing_display(): StateDecoratedVariable | undefined - -} - -interface __Options_Child { - set message(message: Message | undefined) - - get message(): Message | undefined - set __backing_message(__backing_message: StateDecoratedVariable | undefined) - - get __backing_message(): StateDecoratedVariable | undefined - -} - -class __EntryWrapper extends EntryPoint { - @memo() public entry(): void { - Index._instantiateImpl(undefined, (() => { - return new Index(); - }), undefined, undefined, undefined); - } - - public constructor() {} - -} - -`; - -function testReusableTransformer(this: PluginTestContext): void { - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'test complex reusable', - [reusableTransform, uiNoRecheck], - { - checked: [testReusableTransformer], - }, - { - stopAfter: 'checked', - } -); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/state/state-basic-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/state/state-basic-type.test.ts deleted file mode 100644 index 96d03ea4b..000000000 --- a/arkui-plugins/test/ut/ui-plugins/decorators/state/state-basic-type.test.ts +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; -import { parseDumpSrc } from '../../../../utils/parse-string'; -import { structNoRecheck } from '../../../../utils/plugins'; -import { uiTransform } from '../../../../../ui-plugins'; -import { Plugins } from '../../../../../common/plugin-context'; - -const BUILDER_LAMBDA_DIR_PATH: string = 'decorators/state'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [ - path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, BUILDER_LAMBDA_DIR_PATH, 'state-basic-type.ets'), -]; - -const pluginTester = new PluginTester('test basic type @State decorated variables transformation', buildConfig); - -const parsedTransform: Plugins = { - name: 'state-basic-type', - parsed: uiTransform().parsed -}; - -const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; -import { memo as memo } from "arkui.stateManagement.runtime"; -import { StateDecoratedVariable as StateDecoratedVariable } from "@ohos.arkui.stateManagement"; -import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; -import { Component as Component } from "@ohos.arkui.component"; -import { State as State } from "@ohos.arkui.stateManagement"; - -function main() {} - -@Component({freezeWhenInactive:false}) final class Parent extends CustomComponent { - public __initializeStruct(initializers: __Options_Parent | undefined, @memo() content: (()=> void) | undefined): void { - this.__backing_stateVar1 = new StateDecoratedVariable("stateVar1", ((({let gensym___213853607 = initializers; - (((gensym___213853607) == (null)) ? undefined : gensym___213853607.stateVar1)})) ?? ("stateVar1"))); - this.__backing_stateVar2 = new StateDecoratedVariable("stateVar2", ((({let gensym___113574154 = initializers; - (((gensym___113574154) == (null)) ? undefined : gensym___113574154.stateVar2)})) ?? (50))); - this.__backing_stateVar3 = new StateDecoratedVariable("stateVar3", ((({let gensym___166994972 = initializers; - (((gensym___166994972) == (null)) ? undefined : gensym___166994972.stateVar3)})) ?? (true))); - this.__backing_stateVar4 = new StateDecoratedVariable("stateVar4", ((({let gensym___148024261 = initializers; - (((gensym___148024261) == (null)) ? undefined : gensym___148024261.stateVar4)})) ?? (undefined))); - this.__backing_stateVar5 = new StateDecoratedVariable("stateVar5", ((({let gensym___99384342 = initializers; - (((gensym___99384342) == (null)) ? undefined : gensym___99384342.stateVar5)})) ?? (null))); - } - public __updateStruct(initializers: __Options_Parent | undefined): void {} - private __backing_stateVar1?: StateDecoratedVariable; - public get stateVar1(): string { - return this.__backing_stateVar1!.get(); - } - public set stateVar1(value: string) { - this.__backing_stateVar1!.set(value); - } - private __backing_stateVar2?: StateDecoratedVariable; - public get stateVar2(): number { - return this.__backing_stateVar2!.get(); - } - public set stateVar2(value: number) { - this.__backing_stateVar2!.set(value); - } - private __backing_stateVar3?: StateDecoratedVariable; - public get stateVar3(): boolean { - return this.__backing_stateVar3!.get(); - } - public set stateVar3(value: boolean) { - this.__backing_stateVar3!.set(value); - } - private __backing_stateVar4?: StateDecoratedVariable; - public get stateVar4(): undefined { - return this.__backing_stateVar4!.get(); - } - public set stateVar4(value: undefined) { - this.__backing_stateVar4!.set(value); - } - private __backing_stateVar5?: StateDecoratedVariable; - public get stateVar5(): null { - return this.__backing_stateVar5!.get(); - } - public set stateVar5(value: null) { - this.__backing_stateVar5!.set(value); - } - @memo() public _build(@memo() style: ((instance: Parent)=> Parent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Parent | undefined): void {} - public constructor() {} -} - -interface __Options_Parent { - set stateVar1(stateVar1: string | undefined) - get stateVar1(): string | undefined - set __backing_stateVar1(__backing_stateVar1: StateDecoratedVariable | undefined) - get __backing_stateVar1(): StateDecoratedVariable | undefined - set stateVar2(stateVar2: number | undefined) - get stateVar2(): number | undefined - set __backing_stateVar2(__backing_stateVar2: StateDecoratedVariable | undefined) - get __backing_stateVar2(): StateDecoratedVariable | undefined - set stateVar3(stateVar3: boolean | undefined) - get stateVar3(): boolean | undefined - set __backing_stateVar3(__backing_stateVar3: StateDecoratedVariable | undefined) - get __backing_stateVar3(): StateDecoratedVariable | undefined - set stateVar4(stateVar4: undefined | undefined) - get stateVar4(): undefined | undefined - set __backing_stateVar4(__backing_stateVar4: StateDecoratedVariable | undefined) - get __backing_stateVar4(): StateDecoratedVariable | undefined - set stateVar5(stateVar5: null | undefined) - get stateVar5(): null | undefined - set __backing_stateVar5(__backing_stateVar5: StateDecoratedVariable | undefined) - get __backing_stateVar5(): StateDecoratedVariable | undefined -} -`; - -function testParsedAndCheckedTransformer(this: PluginTestContext): void { - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'test basic type @State decorated variables transformation', - [parsedTransform, structNoRecheck], - { - checked: [testParsedAndCheckedTransformer], - }, - { - stopAfter: 'checked', - } -); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/state/state-complex-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/state/state-complex-type.test.ts deleted file mode 100644 index e42e34006..000000000 --- a/arkui-plugins/test/ut/ui-plugins/decorators/state/state-complex-type.test.ts +++ /dev/null @@ -1,288 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; -import { parseDumpSrc } from '../../../../utils/parse-string'; -import { structNoRecheck } from '../../../../utils/plugins'; -import { uiTransform } from '../../../../../ui-plugins'; -import { Plugins } from '../../../../../common/plugin-context'; - -const BUILDER_LAMBDA_DIR_PATH: string = 'decorators/state'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [ - path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, BUILDER_LAMBDA_DIR_PATH, 'state-complex-type.ets'), -]; - -const pluginTester = new PluginTester('test complex type @State decorated variables transformation', buildConfig); - -const parsedTransform: Plugins = { - name: 'state-complex-type', - parsed: uiTransform().parsed -}; - -const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; -import { memo as memo } from "arkui.stateManagement.runtime"; -import { StateDecoratedVariable as StateDecoratedVariable } from "@ohos.arkui.stateManagement"; -import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; -import { Component as Component } from "@ohos.arkui.component"; -import { State as State } from "@ohos.arkui.stateManagement"; - -function main() {} - -class Per { - public num: number; - public constructor(num: number) { - this.num = num; - } -} - -final class StateType extends BaseEnum { - private readonly #ordinal: int; - private static () {} - public constructor(ordinal: int, value: int) { - super(value); - this.#ordinal = ordinal; - } - public static readonly TYPE1: StateType = new StateType(0, 0); - public static readonly TYPE2: StateType = new StateType(1, 1); - public static readonly TYPE3: StateType = new StateType(2, 3); - private static readonly #NamesArray: String[] = ["TYPE1", "TYPE2", "TYPE3"]; - private static readonly #ValuesArray: int[] = [0, 1, 3]; - private static readonly #StringValuesArray: String[] = ["0", "1", "3"]; - private static readonly #ItemsArray: StateType[] = [StateType.TYPE1, StateType.TYPE2, StateType.TYPE3]; - public getName(): String { - return StateType.#NamesArray[this.#ordinal]; - } - public static getValueOf(name: String): StateType { - for (let i = 0;((i) < (StateType.#NamesArray.length));(++i)) { - if (((name) == (StateType.#NamesArray[i]))) { - return StateType.#ItemsArray[i]; - } - } - throw new Error((("No enum constant StateType.") + (name))); - } - public static fromValue(value: int): StateType { - for (let i = 0;((i) < (StateType.#ValuesArray.length));(++i)) { - if (((value) == (StateType.#ValuesArray[i]))) { - return StateType.#ItemsArray[i]; - } - } - throw new Error((("No enum StateType with value ") + (value))); - } - public valueOf(): int { - return StateType.#ValuesArray[this.#ordinal]; - } - public toString(): String { - return StateType.#StringValuesArray[this.#ordinal]; - } - public static values(): StateType[] { - return StateType.#ItemsArray; - } - public getOrdinal(): int { - return this.#ordinal; - } - public static $_get(e: StateType): String { - return e.getName(); - } -} - -@Component({freezeWhenInactive:false}) final class Parent extends CustomComponent { - public __initializeStruct(initializers: __Options_Parent | undefined, @memo() content: (()=> void) | undefined): void { - this.__backing_stateVar1 = new StateDecoratedVariable("stateVar1", ((({let gensym___213853607 = initializers; - (((gensym___213853607) == (null)) ? undefined : gensym___213853607.stateVar1)})) ?? (new Per(6)))); - this.__backing_stateVar2 = new StateDecoratedVariable>("stateVar2", ((({let gensym___113574154 = initializers; - (((gensym___113574154) == (null)) ? undefined : gensym___113574154.stateVar2)})) ?? (new Array(3, 6, 8)))); - this.__backing_stateVar3 = new StateDecoratedVariable("stateVar3", ((({let gensym___166994972 = initializers; - (((gensym___166994972) == (null)) ? undefined : gensym___166994972.stateVar3)})) ?? (StateType.TYPE3))); - this.__backing_stateVar4 = new StateDecoratedVariable>("stateVar4", ((({let gensym___148024261 = initializers; - (((gensym___148024261) == (null)) ? undefined : gensym___148024261.stateVar4)})) ?? (new Set(new Array("aa", "bb"))))); - this.__backing_stateVar5 = new StateDecoratedVariable>("stateVar5", ((({let gensym___99384342 = initializers; - (((gensym___99384342) == (null)) ? undefined : gensym___99384342.stateVar5)})) ?? ([true, false]))); - this.__backing_stateVar6 = new StateDecoratedVariable>("stateVar6", ((({let gensym___133364871 = initializers; - (((gensym___133364871) == (null)) ? undefined : gensym___133364871.stateVar6)})) ?? (new Array(new Per(7), new Per(11))))); - this.__backing_stateVar7 = new StateDecoratedVariable>("stateVar7", ((({let gensym___69403028 = initializers; - (((gensym___69403028) == (null)) ? undefined : gensym___69403028.stateVar7)})) ?? ([new Per(7), new Per(11)]))); - this.__backing_stateVar8 = new StateDecoratedVariable<((sr: string)=> void)>("stateVar8", ((({let gensym___219403122 = initializers; - (((gensym___219403122) == (null)) ? undefined : gensym___219403122.stateVar8)})) ?? (((sr: string) => {})))); - this.__backing_stateVar9 = new StateDecoratedVariable("stateVar9", ((({let gensym___171171899 = initializers; - (((gensym___171171899) == (null)) ? undefined : gensym___171171899.stateVar9)})) ?? (new Date("2025-4-23")))); - this.__backing_stateVar10 = new StateDecoratedVariable>("stateVar10", ((({let gensym___91651348 = initializers; - (((gensym___91651348) == (null)) ? undefined : gensym___91651348.stateVar10)})) ?? (new Map([[0, new Per(7)], [1, new Per(10)]])))); - this.__backing_stateVar11 = new StateDecoratedVariable("stateVar11", ((({let gensym___56045278 = initializers; - (((gensym___56045278) == (null)) ? undefined : gensym___56045278.stateVar11)})) ?? (0.0))); - this.__backing_stateVar12 = new StateDecoratedVariable | Per>("stateVar12", ((({let gensym___164759887 = initializers; - (((gensym___164759887) == (null)) ? undefined : gensym___164759887.stateVar12)})) ?? (new Per(6)))); - } - public __updateStruct(initializers: __Options_Parent | undefined): void {} - private __backing_stateVar1?: StateDecoratedVariable; - public get stateVar1(): Per { - return this.__backing_stateVar1!.get(); - } - public set stateVar1(value: Per) { - this.__backing_stateVar1!.set(value); - } - private __backing_stateVar2?: StateDecoratedVariable>; - public get stateVar2(): Array { - return this.__backing_stateVar2!.get(); - } - public set stateVar2(value: Array) { - this.__backing_stateVar2!.set(value); - } - private __backing_stateVar3?: StateDecoratedVariable; - public get stateVar3(): StateType { - return this.__backing_stateVar3!.get(); - } - public set stateVar3(value: StateType) { - this.__backing_stateVar3!.set(value); - } - private __backing_stateVar4?: StateDecoratedVariable>; - public get stateVar4(): Set { - return this.__backing_stateVar4!.get(); - } - public set stateVar4(value: Set) { - this.__backing_stateVar4!.set(value); - } - private __backing_stateVar5?: StateDecoratedVariable>; - public get stateVar5(): Array { - return this.__backing_stateVar5!.get(); - } - public set stateVar5(value: Array) { - this.__backing_stateVar5!.set(value); - } - private __backing_stateVar6?: StateDecoratedVariable>; - public get stateVar6(): Array { - return this.__backing_stateVar6!.get(); - } - public set stateVar6(value: Array) { - this.__backing_stateVar6!.set(value); - } - private __backing_stateVar7?: StateDecoratedVariable>; - public get stateVar7(): Array { - return this.__backing_stateVar7!.get(); - } - public set stateVar7(value: Array) { - this.__backing_stateVar7!.set(value); - } - private __backing_stateVar8?: StateDecoratedVariable<((sr: string)=> void)>; - public get stateVar8(): ((sr: string)=> void) { - return this.__backing_stateVar8!.get(); - } - public set stateVar8(value: ((sr: string)=> void)) { - this.__backing_stateVar8!.set(value); - } - private __backing_stateVar9?: StateDecoratedVariable; - public get stateVar9(): Date { - return this.__backing_stateVar9!.get(); - } - public set stateVar9(value: Date) { - this.__backing_stateVar9!.set(value); - } - private __backing_stateVar10?: StateDecoratedVariable>; - public get stateVar10(): Map { - return this.__backing_stateVar10!.get(); - } - public set stateVar10(value: Map) { - this.__backing_stateVar10!.set(value); - } - private __backing_stateVar11?: StateDecoratedVariable; - public get stateVar11(): string | number { - return this.__backing_stateVar11!.get(); - } - public set stateVar11(value: string | number) { - this.__backing_stateVar11!.set(value); - } - private __backing_stateVar12?: StateDecoratedVariable | Per>; - public get stateVar12(): Set | Per { - return this.__backing_stateVar12!.get(); - } - public set stateVar12(value: Set | Per) { - this.__backing_stateVar12!.set(value); - } - @memo() public _build(@memo() style: ((instance: Parent)=> Parent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Parent | undefined): void {} - public constructor() {} -} - -interface __Options_Parent { - set stateVar1(stateVar1: Per | undefined) - get stateVar1(): Per | undefined - set __backing_stateVar1(__backing_stateVar1: StateDecoratedVariable | undefined) - get __backing_stateVar1(): StateDecoratedVariable | undefined - set stateVar2(stateVar2: Array | undefined) - get stateVar2(): Array | undefined - set __backing_stateVar2(__backing_stateVar2: StateDecoratedVariable> | undefined) - get __backing_stateVar2(): StateDecoratedVariable> | undefined - set stateVar3(stateVar3: StateType | undefined) - get stateVar3(): StateType | undefined - set __backing_stateVar3(__backing_stateVar3: StateDecoratedVariable | undefined) - get __backing_stateVar3(): StateDecoratedVariable | undefined - set stateVar4(stateVar4: Set | undefined) - get stateVar4(): Set | undefined - set __backing_stateVar4(__backing_stateVar4: StateDecoratedVariable> | undefined) - get __backing_stateVar4(): StateDecoratedVariable> | undefined - set stateVar5(stateVar5: Array | undefined) - get stateVar5(): Array | undefined - set __backing_stateVar5(__backing_stateVar5: StateDecoratedVariable> | undefined) - get __backing_stateVar5(): StateDecoratedVariable> | undefined - set stateVar6(stateVar6: Array | undefined) - get stateVar6(): Array | undefined - set __backing_stateVar6(__backing_stateVar6: StateDecoratedVariable> | undefined) - get __backing_stateVar6(): StateDecoratedVariable> | undefined - set stateVar7(stateVar7: Array | undefined) - get stateVar7(): Array | undefined - set __backing_stateVar7(__backing_stateVar7: StateDecoratedVariable> | undefined) - get __backing_stateVar7(): StateDecoratedVariable> | undefined - set stateVar8(stateVar8: ((sr: string)=> void) | undefined) - get stateVar8(): ((sr: string)=> void) | undefined - set __backing_stateVar8(__backing_stateVar8: StateDecoratedVariable<((sr: string)=> void)> | undefined) - get __backing_stateVar8(): StateDecoratedVariable<((sr: string)=> void)> | undefined - set stateVar9(stateVar9: Date | undefined) - get stateVar9(): Date | undefined - set __backing_stateVar9(__backing_stateVar9: StateDecoratedVariable | undefined) - get __backing_stateVar9(): StateDecoratedVariable | undefined - set stateVar10(stateVar10: Map | undefined) - get stateVar10(): Map | undefined - set __backing_stateVar10(__backing_stateVar10: StateDecoratedVariable> | undefined) - get __backing_stateVar10(): StateDecoratedVariable> | undefined - set stateVar11(stateVar11: string | number | undefined) - get stateVar11(): string | number | undefined - set __backing_stateVar11(__backing_stateVar11: StateDecoratedVariable | undefined) - get __backing_stateVar11(): StateDecoratedVariable | undefined - set stateVar12(stateVar12: Set | Per | undefined) - get stateVar12(): Set | Per | undefined - set __backing_stateVar12(__backing_stateVar12: StateDecoratedVariable | Per> | undefined) - get __backing_stateVar12(): StateDecoratedVariable | Per> | undefined -} -`; - -function testParsedAndCheckedTransformer(this: PluginTestContext): void { - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'test complex type @State decorated variables transformation', - [parsedTransform, structNoRecheck], - { - checked: [testParsedAndCheckedTransformer], - }, - { - stopAfter: 'checked', - } -); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/state/state-to-state.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/state/state-to-state.test.ts deleted file mode 100644 index 52a438991..000000000 --- a/arkui-plugins/test/ut/ui-plugins/decorators/state/state-to-state.test.ts +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; -import { parseDumpSrc } from '../../../../utils/parse-string'; -import { uiNoRecheck } from '../../../../utils/plugins'; -import { uiTransform } from '../../../../../ui-plugins'; -import { Plugins } from '../../../../../common/plugin-context'; - -const BUILDER_LAMBDA_DIR_PATH: string = 'decorators/state'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [ - path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, BUILDER_LAMBDA_DIR_PATH, 'state-to-state.ets'), -]; - -const pluginTester = new PluginTester('test @State decorated variables passing', buildConfig); - -const parsedTransform: Plugins = { - name: 'state-to-state', - parsed: uiTransform().parsed -}; - -const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; -import { memo as memo } from "arkui.stateManagement.runtime"; -import { StateDecoratedVariable as StateDecoratedVariable } from "@ohos.arkui.stateManagement"; -import { UITextAttribute as UITextAttribute } from "@ohos.arkui.component"; -import { UIColumnAttribute as UIColumnAttribute } from "@ohos.arkui.component"; -import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; -import { Component as Component, Column as Column, Text as Text } from "@ohos.arkui.component"; -import { State as State } from "@ohos.arkui.stateManagement"; - -function main() {} - -class Per { - public str: string; - public constructor(str: string) { - this.str = str; - } -} - -@Component({freezeWhenInactive:false}) final class Parent extends CustomComponent { - public __initializeStruct(initializers: __Options_Parent | undefined, @memo() content: (()=> void) | undefined): void { - this.__backing_parentVar1 = new StateDecoratedVariable("parentVar1", ((({let gensym___247315634 = initializers; - (((gensym___247315634) == (null)) ? undefined : gensym___247315634.parentVar1)})) ?? (new Per("hello")))); - } - public __updateStruct(initializers: __Options_Parent | undefined): void {} - private __backing_parentVar1?: StateDecoratedVariable; - public get parentVar1(): Per { - return this.__backing_parentVar1!.get(); - } - public set parentVar1(value: Per) { - this.__backing_parentVar1!.set(value); - } - @memo() public _build(@memo() style: ((instance: Parent)=> Parent) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Parent | undefined): void { - Column(undefined, undefined, (() => { - Child._instantiateImpl(undefined, (() => { - return new Child(); - }), ({ - childVar1: this.parentVar1, - } as __Options_Child), undefined, undefined); - })); - } - public constructor() {} -} - -@Component({freezeWhenInactive:false}) final class Child extends CustomComponent { - public __initializeStruct(initializers: __Options_Child | undefined, @memo() content: (()=> void) | undefined): void { - this.__backing_childVar1 = new StateDecoratedVariable("childVar1", ((({let gensym___218939886 = initializers; - (((gensym___218939886) == (null)) ? undefined : gensym___218939886.childVar1)})) ?? (new Per("ccc")))); - } - public __updateStruct(initializers: __Options_Child | undefined): void {} - private __backing_childVar1?: StateDecoratedVariable; - public get childVar1(): Per { - return this.__backing_childVar1!.get(); - } - public set childVar1(value: Per) { - this.__backing_childVar1!.set(value); - } - @memo() public _build(@memo() style: ((instance: Child)=> Child) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Child | undefined): void { - Text(undefined, this.childVar1.str, undefined, undefined); - } - public constructor() {} - -} - -interface __Options_Parent { - set parentVar1(parentVar1: Per | undefined) - get parentVar1(): Per | undefined - set __backing_parentVar1(__backing_parentVar1: StateDecoratedVariable | undefined) - get __backing_parentVar1(): StateDecoratedVariable | undefined -} - -interface __Options_Child { - set childVar1(childVar1: Per | undefined) - get childVar1(): Per | undefined - set __backing_childVar1(__backing_childVar1: StateDecoratedVariable | undefined) - get __backing_childVar1(): StateDecoratedVariable | undefined -} -`; - -function testParsedAndCheckedTransformer(this: PluginTestContext): void { - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'test @State decorated variables passing', - [parsedTransform, uiNoRecheck], - { - checked: [testParsedAndCheckedTransformer], - }, - { - stopAfter: 'checked', - } -); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-appstorage.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-appstorage.test.ts deleted file mode 100644 index 7f4460286..000000000 --- a/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-appstorage.test.ts +++ /dev/null @@ -1,164 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; -import { parseDumpSrc } from '../../../../utils/parse-string'; -import { uiNoRecheck } from '../../../../utils/plugins'; -import { uiTransform } from '../../../../../ui-plugins'; -import { Plugins } from '../../../../../common/plugin-context'; - -const STORAGELINK_DIR_PATH: string = 'decorators/storagelink'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [ - path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, STORAGELINK_DIR_PATH, 'storagelink-appstorage.ets'), -]; - -const storageLinkTransform: Plugins = { - name: 'storageLink', - parsed: uiTransform().parsed, -} - -const pluginTester = new PluginTester('test storagelink with appstorage', buildConfig); - -const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; - -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; - -import { memo as memo } from "arkui.stateManagement.runtime"; - -import { StorageLinkDecoratedVariable as StorageLinkDecoratedVariable } from "@ohos.arkui.stateManagement"; - -import { UITextAttribute as UITextAttribute } from "@ohos.arkui.component"; - -import { UIColumnAttribute as UIColumnAttribute } from "@ohos.arkui.component"; - -import { EntryPoint as EntryPoint } from "arkui.UserView"; - -import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; - -import { Component as Component, Entry as Entry, Column as Column, Text as Text, ClickEvent as ClickEvent } from "@ohos.arkui.component"; - -import { StorageLink as StorageLink, AppStorage as AppStorage } from "@ohos.arkui.stateManagement"; - -function main() {} - -AppStorage.setOrCreate("PropA", 47); -AppStorage.setOrCreate("PropB", new Data(50)); - -class Data { - public code: number; - - public constructor(code: number) { - this.code = code; - } - -} - -@Entry({useSharedStorage:false,storage:"",routeName:""}) @Component({freezeWhenInactive:false}) final class Index extends CustomComponent { - public __initializeStruct(initializers: __Options_Index | undefined, @memo() content: (()=> void) | undefined): void { - this.__backing_storageLink = new StorageLinkDecoratedVariable("PropA", "storageLink", 1) - this.__backing_storageLinkObject = new StorageLinkDecoratedVariable("PropB", "storageLinkObject", new Data(1)) - } - - public __updateStruct(initializers: __Options_Index | undefined): void {} - - private __backing_storageLink?: StorageLinkDecoratedVariable; - - public get storageLink(): number { - return this.__backing_storageLink!.get(); - } - - public set storageLink(value: number) { - this.__backing_storageLink!.set(value); - } - - private __backing_storageLinkObject?: StorageLinkDecoratedVariable; - - public get storageLinkObject(): Data { - return this.__backing_storageLinkObject!.get(); - } - - public set storageLinkObject(value: Data) { - this.__backing_storageLinkObject!.set(value); - } - - @memo() public _build(@memo() style: ((instance: Index)=> Index) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Index | undefined): void { - Column(undefined, undefined, (() => { - Text(@memo() ((instance: UITextAttribute): void => { - instance.onClick(((e: ClickEvent) => { - this.storageLink += 1; - })); - return; - }), \`From AppStorage \${this.storageLink}\`, undefined, undefined); - Text(@memo() ((instance: UITextAttribute): void => { - instance.onClick(((e: ClickEvent) => { - this.storageLinkObject.code += 1; - })); - return; - }), \`From AppStorage \${this.storageLinkObject.code}\`, undefined, undefined); - })); - } - - public constructor() {} - -} - -interface __Options_Index { - set storageLink(storageLink: number | undefined) - - get storageLink(): number | undefined - set __backing_storageLink(__backing_storageLink: StorageLinkDecoratedVariable | undefined) - - get __backing_storageLink(): StorageLinkDecoratedVariable | undefined - set storageLinkObject(storageLinkObject: Data | undefined) - - get storageLinkObject(): Data | undefined - set __backing_storageLinkObject(__backing_storageLinkObject: StorageLinkDecoratedVariable | undefined) - - get __backing_storageLinkObject(): StorageLinkDecoratedVariable | undefined - -} - -class __EntryWrapper extends EntryPoint { - @memo() public entry(): void { - Index._instantiateImpl(undefined, (() => { - return new Index(); - }), undefined, undefined, undefined); - } - - public constructor() {} - -} -`; - -function testStorageLinkTransformer(this: PluginTestContext): void { - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'test storagelink with appstorage', - [storageLinkTransform, uiNoRecheck], - { - checked: [testStorageLinkTransformer], - }, - { - stopAfter: 'checked', - } -); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-complex-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-complex-type.test.ts deleted file mode 100644 index dba913594..000000000 --- a/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-complex-type.test.ts +++ /dev/null @@ -1,313 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; -import { parseDumpSrc } from '../../../../utils/parse-string'; -import { uiNoRecheck } from '../../../../utils/plugins'; -import { uiTransform } from '../../../../../ui-plugins'; -import { Plugins } from '../../../../../common/plugin-context'; - -const STORAGELINK_DIR_PATH: string = 'decorators/storagelink'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [ - path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, STORAGELINK_DIR_PATH, 'storagelink-complex-type.ets'), -]; - -const storageLinkTransform: Plugins = { - name: 'storageLink', - parsed: uiTransform().parsed, -} - -const pluginTester = new PluginTester('test storagelink complex type transform', buildConfig); - -const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; - -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; - -import { memo as memo } from "arkui.stateManagement.runtime"; - -import { StorageLinkDecoratedVariable as StorageLinkDecoratedVariable } from "@ohos.arkui.stateManagement"; - -import { EntryPoint as EntryPoint } from "arkui.UserView"; - -import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; - -import { Component as Component, Entry as Entry } from "@ohos.arkui.component"; - -import { StorageLink as StorageLink } from "@ohos.arkui.stateManagement"; - -function main() {} - - - -class Person { - public name: string = ""; - - public constructor(name: string) {} - -} - -final class Status extends BaseEnum { - private readonly #ordinal: int; - - private static () {} - - public constructor(ordinal: int, value: int) { - super(value); - this.#ordinal = ordinal; - } - - public static readonly Success: Status = new Status(0, 200); - - public static readonly NotFound: Status = new Status(1, 404); - - public static readonly ServerError: Status = new Status(2, 500); - - private static readonly #NamesArray: String[] = ["Success", "NotFound", "ServerError"]; - - private static readonly #ValuesArray: int[] = [200, 404, 500]; - - private static readonly #StringValuesArray: String[] = ["200", "404", "500"]; - - private static readonly #ItemsArray: Status[] = [Status.Success, Status.NotFound, Status.ServerError]; - - public getName(): String { - return Status.#NamesArray[this.#ordinal]; - } - - public static getValueOf(name: String): Status { - for (let i = 0;((i) < (Status.#NamesArray.length));(++i)) { - if (((name) == (Status.#NamesArray[i]))) { - return Status.#ItemsArray[i]; - } - } - throw new Error((("No enum constant Status.") + (name))); - } - - public static fromValue(value: int): Status { - for (let i = 0;((i) < (Status.#ValuesArray.length));(++i)) { - if (((value) == (Status.#ValuesArray[i]))) { - return Status.#ItemsArray[i]; - } - } - throw new Error((("No enum Status with value ") + (value))); - } - - public valueOf(): int { - return Status.#ValuesArray[this.#ordinal]; - } - - public toString(): String { - return Status.#StringValuesArray[this.#ordinal]; - } - - public static values(): Status[] { - return Status.#ItemsArray; - } - - public getOrdinal(): int { - return this.#ordinal; - } - - public static $_get(e: Status): String { - return e.getName(); - } - -} - -@Entry({useSharedStorage:false,storage:"",routeName:""}) @Component({freezeWhenInactive:false}) final class MyStateSample extends CustomComponent { - public __initializeStruct(initializers: __Options_MyStateSample | undefined, @memo() content: (()=> void) | undefined): void { - this.__backing_arrayA = new StorageLinkDecoratedVariable>("Prop1", "arrayA", [1, 2, 3]) - this.__backing_objectA = new StorageLinkDecoratedVariable("Prop2", "objectA", {}) - this.__backing_dateA = new StorageLinkDecoratedVariable("Prop3", "dateA", new Date("2021-08-08")) - this.__backing_setA = new StorageLinkDecoratedVariable>("Prop4", "setA", new Set()) - this.__backing_mapA = new StorageLinkDecoratedVariable>("Prop5", "mapA", new Map()) - this.__backing_unionA = new StorageLinkDecoratedVariable("Prop6", "unionA", "") - this.__backing_classA = new StorageLinkDecoratedVariable("Prop7", "classA", new Person("John")) - this.__backing_enumA = new StorageLinkDecoratedVariable("Prop8", "enumA", Status.NotFound) - } - - public __updateStruct(initializers: __Options_MyStateSample | undefined): void {} - - private __backing_arrayA?: StorageLinkDecoratedVariable>; - - public get arrayA(): Array { - return this.__backing_arrayA!.get(); - } - - public set arrayA(value: Array) { - this.__backing_arrayA!.set(value); - } - - private __backing_objectA?: StorageLinkDecoratedVariable; - - public get objectA(): Object { - return this.__backing_objectA!.get(); - } - - public set objectA(value: Object) { - this.__backing_objectA!.set(value); - } - - private __backing_dateA?: StorageLinkDecoratedVariable; - - public get dateA(): Date { - return this.__backing_dateA!.get(); - } - - public set dateA(value: Date) { - this.__backing_dateA!.set(value); - } - - private __backing_setA?: StorageLinkDecoratedVariable>; - - public get setA(): Set { - return this.__backing_setA!.get(); - } - - public set setA(value: Set) { - this.__backing_setA!.set(value); - } - - private __backing_mapA?: StorageLinkDecoratedVariable>; - - public get mapA(): Map { - return this.__backing_mapA!.get(); - } - - public set mapA(value: Map) { - this.__backing_mapA!.set(value); - } - - private __backing_unionA?: StorageLinkDecoratedVariable; - - public get unionA(): string | undefined { - return this.__backing_unionA!.get(); - } - - public set unionA(value: string | undefined) { - this.__backing_unionA!.set(value); - } - - private __backing_classA?: StorageLinkDecoratedVariable; - - public get classA(): Person { - return this.__backing_classA!.get(); - } - - public set classA(value: Person) { - this.__backing_classA!.set(value); - } - - private __backing_enumA?: StorageLinkDecoratedVariable; - - public get enumA(): Status { - return this.__backing_enumA!.get(); - } - - public set enumA(value: Status) { - this.__backing_enumA!.set(value); - } - - @memo() public _build(@memo() style: ((instance: MyStateSample)=> MyStateSample) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_MyStateSample | undefined): void {} - - public constructor() {} - -} - -interface __Options_MyStateSample { - set arrayA(arrayA: Array | undefined) - - get arrayA(): Array | undefined - set __backing_arrayA(__backing_arrayA: StorageLinkDecoratedVariable> | undefined) - - get __backing_arrayA(): StorageLinkDecoratedVariable> | undefined - set objectA(objectA: Object | undefined) - - get objectA(): Object | undefined - set __backing_objectA(__backing_objectA: StorageLinkDecoratedVariable | undefined) - - get __backing_objectA(): StorageLinkDecoratedVariable | undefined - set dateA(dateA: Date | undefined) - - get dateA(): Date | undefined - set __backing_dateA(__backing_dateA: StorageLinkDecoratedVariable | undefined) - - get __backing_dateA(): StorageLinkDecoratedVariable | undefined - set setA(setA: Set | undefined) - - get setA(): Set | undefined - set __backing_setA(__backing_setA: StorageLinkDecoratedVariable> | undefined) - - get __backing_setA(): StorageLinkDecoratedVariable> | undefined - set mapA(mapA: Map | undefined) - - get mapA(): Map | undefined - set __backing_mapA(__backing_mapA: StorageLinkDecoratedVariable> | undefined) - - get __backing_mapA(): StorageLinkDecoratedVariable> | undefined - set unionA(unionA: string | undefined | undefined) - - get unionA(): string | undefined | undefined - set __backing_unionA(__backing_unionA: StorageLinkDecoratedVariable | undefined) - - get __backing_unionA(): StorageLinkDecoratedVariable | undefined - set classA(classA: Person | undefined) - - get classA(): Person | undefined - set __backing_classA(__backing_classA: StorageLinkDecoratedVariable | undefined) - - get __backing_classA(): StorageLinkDecoratedVariable | undefined - set enumA(enumA: Status | undefined) - - get enumA(): Status | undefined - set __backing_enumA(__backing_enumA: StorageLinkDecoratedVariable | undefined) - - get __backing_enumA(): StorageLinkDecoratedVariable | undefined - -} - -class __EntryWrapper extends EntryPoint { - @memo() public entry(): void { - MyStateSample._instantiateImpl(undefined, (() => { - return new MyStateSample(); - }), undefined, undefined, undefined); - } - - public constructor() {} - -} - -`; - -function testStorageLinkTransformer(this: PluginTestContext): void { - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'test storagelink complex type transform', - [storageLinkTransform, uiNoRecheck], - { - checked: [testStorageLinkTransformer], - }, - { - stopAfter: 'checked', - } -); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-primitive-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-primitive-type.test.ts deleted file mode 100644 index 27a78307e..000000000 --- a/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-primitive-type.test.ts +++ /dev/null @@ -1,153 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; -import { parseDumpSrc } from '../../../../utils/parse-string'; -import { uiNoRecheck } from '../../../../utils/plugins'; -import { uiTransform } from '../../../../../ui-plugins'; -import { Plugins } from '../../../../../common/plugin-context'; - -const STORAGELINK_DIR_PATH: string = 'decorators/storagelink'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [ - path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, STORAGELINK_DIR_PATH, 'storagelink-primitive-type.ets'), -]; - -const storageLinkTransform: Plugins = { - name: 'storageLink', - parsed: uiTransform().parsed, -} - -const pluginTester = new PluginTester('test storagelink primitive type transform', buildConfig); - -const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; - -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; - -import { memo as memo } from "arkui.stateManagement.runtime"; - -import { StorageLinkDecoratedVariable as StorageLinkDecoratedVariable } from "@ohos.arkui.stateManagement"; - -import { EntryPoint as EntryPoint } from "arkui.UserView"; - -import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; - -import { Component as Component, Entry as Entry } from "@ohos.arkui.component"; - -import { StorageLink as StorageLink } from "@ohos.arkui.stateManagement"; - -function main() {} - - - -@Entry({useSharedStorage:false,storage:"",routeName:""}) @Component({freezeWhenInactive:false}) final class MyStateSample extends CustomComponent { - public __initializeStruct(initializers: __Options_MyStateSample | undefined, @memo() content: (()=> void) | undefined): void { - this.__backing_numA = new StorageLinkDecoratedVariable("Prop1", "numA", 33) - this.__backing_stringA = new StorageLinkDecoratedVariable("Prop2", "stringA", "AA") - this.__backing_booleanA = new StorageLinkDecoratedVariable("Prop3", "booleanA", true) - } - - public __updateStruct(initializers: __Options_MyStateSample | undefined): void {} - - private __backing_numA?: StorageLinkDecoratedVariable; - - public get numA(): number { - return this.__backing_numA!.get(); - } - - public set numA(value: number) { - this.__backing_numA!.set(value); - } - - private __backing_stringA?: StorageLinkDecoratedVariable; - - public get stringA(): string { - return this.__backing_stringA!.get(); - } - - public set stringA(value: string) { - this.__backing_stringA!.set(value); - } - - private __backing_booleanA?: StorageLinkDecoratedVariable; - - public get booleanA(): boolean { - return this.__backing_booleanA!.get(); - } - - public set booleanA(value: boolean) { - this.__backing_booleanA!.set(value); - } - - @memo() public _build(@memo() style: ((instance: MyStateSample)=> MyStateSample) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_MyStateSample | undefined): void {} - - public constructor() {} - -} - -interface __Options_MyStateSample { - set numA(numA: number | undefined) - - get numA(): number | undefined - set __backing_numA(__backing_numA: StorageLinkDecoratedVariable | undefined) - - get __backing_numA(): StorageLinkDecoratedVariable | undefined - set stringA(stringA: string | undefined) - - get stringA(): string | undefined - set __backing_stringA(__backing_stringA: StorageLinkDecoratedVariable | undefined) - - get __backing_stringA(): StorageLinkDecoratedVariable | undefined - set booleanA(booleanA: boolean | undefined) - - get booleanA(): boolean | undefined - set __backing_booleanA(__backing_booleanA: StorageLinkDecoratedVariable | undefined) - - get __backing_booleanA(): StorageLinkDecoratedVariable | undefined - -} - -class __EntryWrapper extends EntryPoint { - @memo() public entry(): void { - MyStateSample._instantiateImpl(undefined, (() => { - return new MyStateSample(); - }), undefined, undefined, undefined); - } - - public constructor() {} - -} - -`; - -function testStorageLinkTransformer(this: PluginTestContext): void { - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'test storagelink primitive type transform', - [storageLinkTransform, uiNoRecheck], - { - checked: [testStorageLinkTransformer], - }, - { - stopAfter: 'checked', - } -); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-appstorage.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-appstorage.test.ts deleted file mode 100644 index e00d66d86..000000000 --- a/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-appstorage.test.ts +++ /dev/null @@ -1,165 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; -import { parseDumpSrc } from '../../../../utils/parse-string'; -import { uiNoRecheck } from '../../../../utils/plugins'; -import { uiTransform } from '../../../../../ui-plugins'; -import { Plugins } from '../../../../../common/plugin-context'; - -const STORAGEPROP_DIR_PATH: string = 'decorators/storageprop'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [ - path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, STORAGEPROP_DIR_PATH, 'storageprop-appstorage.ets'), -]; - -const storagePropTransform: Plugins = { - name: 'storageprop', - parsed: uiTransform().parsed, -} - -const pluginTester = new PluginTester('test storageprop with appstorage', buildConfig); - -const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; - -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; - -import { memo as memo } from "arkui.stateManagement.runtime"; - -import { StoragePropDecoratedVariable as StoragePropDecoratedVariable } from "@ohos.arkui.stateManagement"; - -import { UITextAttribute as UITextAttribute } from "@ohos.arkui.component"; - -import { UIColumnAttribute as UIColumnAttribute } from "@ohos.arkui.component"; - -import { EntryPoint as EntryPoint } from "arkui.UserView"; - -import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; - -import { Component as Component, Entry as Entry, Column as Column, Text as Text, ClickEvent as ClickEvent } from "@ohos.arkui.component"; - -import { StorageProp as StorageProp, AppStorage as AppStorage } from "@ohos.arkui.stateManagement"; - -function main() {} - -AppStorage.setOrCreate("PropA", 47); -AppStorage.setOrCreate("PropB", new Data(50)); - -class Data { - public code: number; - - public constructor(code: number) { - this.code = code; - } - -} - -@Entry({useSharedStorage:false,storage:"",routeName:""}) @Component({freezeWhenInactive:false}) final class Index extends CustomComponent { - public __initializeStruct(initializers: __Options_Index | undefined, @memo() content: (()=> void) | undefined): void { - this.__backing_storageProp = new StoragePropDecoratedVariable("PropA", "storageProp", 1) - this.__backing_storagePropObject = new StoragePropDecoratedVariable("PropB", "storagePropObject", new Data(1)) - } - - public __updateStruct(initializers: __Options_Index | undefined): void {} - - private __backing_storageProp?: StoragePropDecoratedVariable; - - public get storageProp(): number { - return this.__backing_storageProp!.get(); - } - - public set storageProp(value: number) { - this.__backing_storageProp!.set(value); - } - - private __backing_storagePropObject?: StoragePropDecoratedVariable; - - public get storagePropObject(): Data { - return this.__backing_storagePropObject!.get(); - } - - public set storagePropObject(value: Data) { - this.__backing_storagePropObject!.set(value); - } - - @memo() public _build(@memo() style: ((instance: Index)=> Index) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Index | undefined): void { - Column(undefined, undefined, (() => { - Text(@memo() ((instance: UITextAttribute): void => { - instance.onClick(((e: ClickEvent) => { - this.storageProp += 1; - })); - return; - }), \`From AppStorage \${this.storageProp}\`, undefined, undefined); - Text(@memo() ((instance: UITextAttribute): void => { - instance.onClick(((e: ClickEvent) => { - this.storagePropObject.code += 1; - })); - return; - }), \`From AppStorage \${this.storagePropObject.code}\`, undefined, undefined); - })); - } - - public constructor() {} - -} - -interface __Options_Index { - set storageProp(storageProp: number | undefined) - - get storageProp(): number | undefined - set __backing_storageProp(__backing_storageProp: StoragePropDecoratedVariable | undefined) - - get __backing_storageProp(): StoragePropDecoratedVariable | undefined - set storagePropObject(storagePropObject: Data | undefined) - - get storagePropObject(): Data | undefined - set __backing_storagePropObject(__backing_storagePropObject: StoragePropDecoratedVariable | undefined) - - get __backing_storagePropObject(): StoragePropDecoratedVariable | undefined - -} - -class __EntryWrapper extends EntryPoint { - @memo() public entry(): void { - Index._instantiateImpl(undefined, (() => { - return new Index(); - }), undefined, undefined, undefined); - } - - public constructor() {} - -} - -`; - -function testStoragePropTransformer(this: PluginTestContext): void { - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'test storageprop with appstorage', - [storagePropTransform, uiNoRecheck], - { - checked: [testStoragePropTransformer], - }, - { - stopAfter: 'checked', - } -); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-complex-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-complex-type.test.ts deleted file mode 100644 index ca212c7ca..000000000 --- a/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-complex-type.test.ts +++ /dev/null @@ -1,312 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; -import { parseDumpSrc } from '../../../../utils/parse-string'; -import { uiNoRecheck } from '../../../../utils/plugins'; -import { uiTransform } from '../../../../../ui-plugins'; -import { Plugins } from '../../../../../common/plugin-context'; - -const STORAGEPROP_DIR_PATH: string = 'decorators/storageprop'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [ - path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, STORAGEPROP_DIR_PATH, 'storageprop-complex-type.ets'), -]; - -const storagePropTransform: Plugins = { - name: 'storageprop', - parsed: uiTransform().parsed, -} - -const pluginTester = new PluginTester('test storageprop complex type transform', buildConfig); - -const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; - -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; - -import { memo as memo } from "arkui.stateManagement.runtime"; - -import { StoragePropDecoratedVariable as StoragePropDecoratedVariable } from "@ohos.arkui.stateManagement"; - -import { EntryPoint as EntryPoint } from "arkui.UserView"; - -import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; - -import { Component as Component, Entry as Entry } from "@ohos.arkui.component"; - -import { StorageProp as StorageProp } from "@ohos.arkui.stateManagement"; - -function main() {} - - - -class Person { - public name: string = ""; - - public constructor(name: string) {} - -} - -final class Status extends BaseEnum { - private readonly #ordinal: int; - - private static () {} - - public constructor(ordinal: int, value: int) { - super(value); - this.#ordinal = ordinal; - } - - public static readonly Success: Status = new Status(0, 200); - - public static readonly NotFound: Status = new Status(1, 404); - - public static readonly ServerError: Status = new Status(2, 500); - - private static readonly #NamesArray: String[] = ["Success", "NotFound", "ServerError"]; - - private static readonly #ValuesArray: int[] = [200, 404, 500]; - - private static readonly #StringValuesArray: String[] = ["200", "404", "500"]; - - private static readonly #ItemsArray: Status[] = [Status.Success, Status.NotFound, Status.ServerError]; - - public getName(): String { - return Status.#NamesArray[this.#ordinal]; - } - - public static getValueOf(name: String): Status { - for (let i = 0;((i) < (Status.#NamesArray.length));(++i)) { - if (((name) == (Status.#NamesArray[i]))) { - return Status.#ItemsArray[i]; - } - } - throw new Error((("No enum constant Status.") + (name))); - } - - public static fromValue(value: int): Status { - for (let i = 0;((i) < (Status.#ValuesArray.length));(++i)) { - if (((value) == (Status.#ValuesArray[i]))) { - return Status.#ItemsArray[i]; - } - } - throw new Error((("No enum Status with value ") + (value))); - } - - public valueOf(): int { - return Status.#ValuesArray[this.#ordinal]; - } - - public toString(): String { - return Status.#StringValuesArray[this.#ordinal]; - } - - public static values(): Status[] { - return Status.#ItemsArray; - } - - public getOrdinal(): int { - return this.#ordinal; - } - - public static $_get(e: Status): String { - return e.getName(); - } - -} - -@Entry({useSharedStorage:false,storage:"",routeName:""}) @Component({freezeWhenInactive:false}) final class MyStateSample extends CustomComponent { - public __initializeStruct(initializers: __Options_MyStateSample | undefined, @memo() content: (()=> void) | undefined): void { - this.__backing_arrayB = new StoragePropDecoratedVariable>("Prop1", "arrayB", [1, 2, 3]) - this.__backing_objectB = new StoragePropDecoratedVariable("Prop2", "objectB", {}) - this.__backing_dateB = new StoragePropDecoratedVariable("Prop3", "dateB", new Date("2021-09-09")) - this.__backing_setB = new StoragePropDecoratedVariable>("Prop4", "setB", new Set()) - this.__backing_mapB = new StoragePropDecoratedVariable>("Prop5", "mapB", new Map()) - this.__backing_unionB = new StoragePropDecoratedVariable("Prop6", "unionB", "") - this.__backing_classB = new StoragePropDecoratedVariable("Prop7", "classB", new Person("Kevin")) - this.__backing_enumB = new StoragePropDecoratedVariable("Prop8", "enumB", Status.NotFound) - } - - public __updateStruct(initializers: __Options_MyStateSample | undefined): void {} - - private __backing_arrayB?: StoragePropDecoratedVariable>; - - public get arrayB(): Array { - return this.__backing_arrayB!.get(); - } - - public set arrayB(value: Array) { - this.__backing_arrayB!.set(value); - } - - private __backing_objectB?: StoragePropDecoratedVariable; - - public get objectB(): Object { - return this.__backing_objectB!.get(); - } - - public set objectB(value: Object) { - this.__backing_objectB!.set(value); - } - - private __backing_dateB?: StoragePropDecoratedVariable; - - public get dateB(): Date { - return this.__backing_dateB!.get(); - } - - public set dateB(value: Date) { - this.__backing_dateB!.set(value); - } - - private __backing_setB?: StoragePropDecoratedVariable>; - - public get setB(): Set { - return this.__backing_setB!.get(); - } - - public set setB(value: Set) { - this.__backing_setB!.set(value); - } - - private __backing_mapB?: StoragePropDecoratedVariable>; - - public get mapB(): Map { - return this.__backing_mapB!.get(); - } - - public set mapB(value: Map) { - this.__backing_mapB!.set(value); - } - - private __backing_unionB?: StoragePropDecoratedVariable; - - public get unionB(): string | undefined { - return this.__backing_unionB!.get(); - } - - public set unionB(value: string | undefined) { - this.__backing_unionB!.set(value); - } - - private __backing_classB?: StoragePropDecoratedVariable; - - public get classB(): Person { - return this.__backing_classB!.get(); - } - - public set classB(value: Person) { - this.__backing_classB!.set(value); - } - - private __backing_enumB?: StoragePropDecoratedVariable; - - public get enumB(): Status { - return this.__backing_enumB!.get(); - } - - public set enumB(value: Status) { - this.__backing_enumB!.set(value); - } - - @memo() public _build(@memo() style: ((instance: MyStateSample)=> MyStateSample) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_MyStateSample | undefined): void {} - - public constructor() {} - -} - -interface __Options_MyStateSample { - set arrayB(arrayB: Array | undefined) - - get arrayB(): Array | undefined - set __backing_arrayB(__backing_arrayB: StoragePropDecoratedVariable> | undefined) - - get __backing_arrayB(): StoragePropDecoratedVariable> | undefined - set objectB(objectB: Object | undefined) - - get objectB(): Object | undefined - set __backing_objectB(__backing_objectB: StoragePropDecoratedVariable | undefined) - - get __backing_objectB(): StoragePropDecoratedVariable | undefined - set dateB(dateB: Date | undefined) - - get dateB(): Date | undefined - set __backing_dateB(__backing_dateB: StoragePropDecoratedVariable | undefined) - - get __backing_dateB(): StoragePropDecoratedVariable | undefined - set setB(setB: Set | undefined) - - get setB(): Set | undefined - set __backing_setB(__backing_setB: StoragePropDecoratedVariable> | undefined) - - get __backing_setB(): StoragePropDecoratedVariable> | undefined - set mapB(mapB: Map | undefined) - - get mapB(): Map | undefined - set __backing_mapB(__backing_mapB: StoragePropDecoratedVariable> | undefined) - - get __backing_mapB(): StoragePropDecoratedVariable> | undefined - set unionB(unionB: string | undefined | undefined) - - get unionB(): string | undefined | undefined - set __backing_unionB(__backing_unionB: StoragePropDecoratedVariable | undefined) - - get __backing_unionB(): StoragePropDecoratedVariable | undefined - set classB(classB: Person | undefined) - - get classB(): Person | undefined - set __backing_classB(__backing_classB: StoragePropDecoratedVariable | undefined) - - get __backing_classB(): StoragePropDecoratedVariable | undefined - set enumB(enumB: Status | undefined) - - get enumB(): Status | undefined - set __backing_enumB(__backing_enumB: StoragePropDecoratedVariable | undefined) - - get __backing_enumB(): StoragePropDecoratedVariable | undefined - -} - -class __EntryWrapper extends EntryPoint { - @memo() public entry(): void { - MyStateSample._instantiateImpl(undefined, (() => { - return new MyStateSample(); - }), undefined, undefined, undefined); - } - - public constructor() {} - -} -`; - -function testStoragePropTransformer(this: PluginTestContext): void { - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'test storageprop complex type transform', - [storagePropTransform, uiNoRecheck], - { - checked: [testStoragePropTransformer], - }, - { - stopAfter: 'checked', - } -); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-primitive-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-primitive-type.test.ts deleted file mode 100644 index d6247f205..000000000 --- a/arkui-plugins/test/ut/ui-plugins/decorators/storageprop/storageprop-primitive-type.test.ts +++ /dev/null @@ -1,152 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; -import { parseDumpSrc } from '../../../../utils/parse-string'; -import { uiNoRecheck } from '../../../../utils/plugins'; -import { uiTransform } from '../../../../../ui-plugins'; -import { Plugins } from '../../../../../common/plugin-context'; - -const STORAGEPROP_DIR_PATH: string = 'decorators/storageprop'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [ - path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, STORAGEPROP_DIR_PATH, 'storageprop-primitive-type.ets'), -]; - -const storagePropTransform: Plugins = { - name: 'storageprop', - parsed: uiTransform().parsed, -} - -const pluginTester = new PluginTester('test storageprop primitive type transform', buildConfig); - -const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; - -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; - -import { memo as memo } from "arkui.stateManagement.runtime"; - -import { StoragePropDecoratedVariable as StoragePropDecoratedVariable } from "@ohos.arkui.stateManagement"; - -import { EntryPoint as EntryPoint } from "arkui.UserView"; - -import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; - -import { Component as Component, Entry as Entry } from "@ohos.arkui.component"; - -import { StorageProp as StorageProp } from "@ohos.arkui.stateManagement"; - -function main() {} - - - -@Entry({useSharedStorage:false,storage:"",routeName:""}) @Component({freezeWhenInactive:false}) final class MyStateSample extends CustomComponent { - public __initializeStruct(initializers: __Options_MyStateSample | undefined, @memo() content: (()=> void) | undefined): void { - this.__backing_numB = new StoragePropDecoratedVariable("Prop1", "numB", 43) - this.__backing_stringB = new StoragePropDecoratedVariable("Prop2", "stringB", "BB") - this.__backing_booleanB = new StoragePropDecoratedVariable("Prop3", "booleanB", false) - } - - public __updateStruct(initializers: __Options_MyStateSample | undefined): void {} - - private __backing_numB?: StoragePropDecoratedVariable; - - public get numB(): number { - return this.__backing_numB!.get(); - } - - public set numB(value: number) { - this.__backing_numB!.set(value); - } - - private __backing_stringB?: StoragePropDecoratedVariable; - - public get stringB(): string { - return this.__backing_stringB!.get(); - } - - public set stringB(value: string) { - this.__backing_stringB!.set(value); - } - - private __backing_booleanB?: StoragePropDecoratedVariable; - - public get booleanB(): boolean { - return this.__backing_booleanB!.get(); - } - - public set booleanB(value: boolean) { - this.__backing_booleanB!.set(value); - } - - @memo() public _build(@memo() style: ((instance: MyStateSample)=> MyStateSample) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_MyStateSample | undefined): void {} - - public constructor() {} - -} - -interface __Options_MyStateSample { - set numB(numB: number | undefined) - - get numB(): number | undefined - set __backing_numB(__backing_numB: StoragePropDecoratedVariable | undefined) - - get __backing_numB(): StoragePropDecoratedVariable | undefined - set stringB(stringB: string | undefined) - - get stringB(): string | undefined - set __backing_stringB(__backing_stringB: StoragePropDecoratedVariable | undefined) - - get __backing_stringB(): StoragePropDecoratedVariable | undefined - set booleanB(booleanB: boolean | undefined) - - get booleanB(): boolean | undefined - set __backing_booleanB(__backing_booleanB: StoragePropDecoratedVariable | undefined) - - get __backing_booleanB(): StoragePropDecoratedVariable | undefined - -} - -class __EntryWrapper extends EntryPoint { - @memo() public entry(): void { - MyStateSample._instantiateImpl(undefined, (() => { - return new MyStateSample(); - }), undefined, undefined, undefined); - } - - public constructor() {} - -} -`; - -function testStoragePropTransformer(this: PluginTestContext): void { - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'test storageprop primitive type transform', - [storagePropTransform, uiNoRecheck], - { - checked: [testStoragePropTransformer], - }, - { - stopAfter: 'checked', - } -); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/watch/watch-basic.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/watch/watch-basic.test.ts deleted file mode 100644 index fbb612c70..000000000 --- a/arkui-plugins/test/ut/ui-plugins/decorators/watch/watch-basic.test.ts +++ /dev/null @@ -1,306 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../../utils/path-config'; -import { parseDumpSrc } from '../../../../utils/parse-string'; -import { uiNoRecheck } from '../../../../utils/plugins'; -import { uiTransform } from '../../../../../ui-plugins'; -import { Plugins } from '../../../../../common/plugin-context'; - -const WATCH_DIR_PATH: string = 'decorators/watch'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [ - path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, WATCH_DIR_PATH, 'watch-basic.ets'), -]; - -const watchTransform: Plugins = { - name: 'watch', - parsed: uiTransform().parsed, -}; - -const pluginTester = new PluginTester('test basic watch transform', buildConfig); - -const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; - -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; - -import { memo as memo } from "arkui.stateManagement.runtime"; - -import { ConsumeDecoratedVariable as ConsumeDecoratedVariable } from "@ohos.arkui.stateManagement"; - -import { ProvideDecoratedVariable as ProvideDecoratedVariable } from "@ohos.arkui.stateManagement"; - -import { SubscribedWatches as SubscribedWatches } from "@ohos.arkui.stateManagement"; - -import { WatchIdType as WatchIdType } from "@ohos.arkui.stateManagement"; - -import { int32 as int32 } from "@ohos.arkui.stateManagement"; - -import { IObservedObject as IObservedObject } from "@ohos.arkui.stateManagement"; - -import { setObservationDepth as setObservationDepth } from "@ohos.arkui.stateManagement"; - -import { BackingValue as BackingValue } from "@ohos.arkui.stateManagement"; - -import { MutableStateMeta as MutableStateMeta } from "@ohos.arkui.stateManagement"; - -import { ObjectLinkDecoratedVariable as ObjectLinkDecoratedVariable } from "@ohos.arkui.stateManagement"; - -import { DecoratedV1VariableBase as DecoratedV1VariableBase } from "@ohos.arkui.stateManagement"; - -import { LinkDecoratedVariable as LinkDecoratedVariable } from "@ohos.arkui.stateManagement"; - -import { StoragePropDecoratedVariable as StoragePropDecoratedVariable } from "@ohos.arkui.stateManagement"; - -import { StorageLinkDecoratedVariable as StorageLinkDecoratedVariable } from "@ohos.arkui.stateManagement"; - -import { PropDecoratedVariable as PropDecoratedVariable } from "@ohos.arkui.stateManagement"; - -import { StateDecoratedVariable as StateDecoratedVariable } from "@ohos.arkui.stateManagement"; - -import { EntryPoint as EntryPoint } from "arkui.UserView"; - -import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; - -import { Component as Component, Entry as Entry } from "@ohos.arkui.component"; - -import { State as State, Prop as Prop, StorageLink as StorageLink, StorageProp as StorageProp, Link as Link, Watch as Watch, ObjectLink as ObjectLink, Observed as Observed, Track as Track, Provide as Provide, Consume as Consume } from "@ohos.arkui.stateManagement"; - -function main() {} - - - -@Observed() class A implements IObservedObject { - private subscribedWatches: SubscribedWatches = new SubscribedWatches(); - - public addWatchSubscriber(watchId: WatchIdType): void { - this.subscribedWatches.addWatchSubscriber(watchId); - } - - public removeWatchSubscriber(watchId: WatchIdType): boolean { - return this.subscribedWatches.removeWatchSubscriber(watchId); - } - - public executeOnSubscribingWatches(propertyName: string): void { - this.subscribedWatches.executeOnSubscribingWatches(propertyName); - } - - public _permissibleAddRefDepth: int32 = 0; - - public propA: string = "hello"; - - private __backing_trackA: string = "world"; - - private __meta_trackA: MutableStateMeta = new MutableStateMeta("@Track"); - - public constructor() {} - - public get trackA(): string { - if (((this._permissibleAddRefDepth) > (0))) { - this.__meta_trackA.addRef(); - } - return this.__backing_trackA; - } - - public set trackA(newValue: string) { - if (((this.__backing_trackA) !== (newValue))) { - this.__backing_trackA = newValue; - this.__meta_trackA.fireChange(); - this.executeOnSubscribingWatches("trackA"); - } - } - -} - -@Entry({useSharedStorage:false,storage:"",routeName:""}) @Component({freezeWhenInactive:false}) final class MyStateSample extends CustomComponent { - public __initializeStruct(initializers: __Options_MyStateSample | undefined, @memo() content: (()=> void) | undefined): void { - this.__backing_statevar = new StateDecoratedVariable("statevar", ((({let gensym___76198660 = initializers; - (((gensym___76198660) == (null)) ? undefined : gensym___76198660.statevar)})) ?? ("Hello World")), ((_: string): void => { - this.stateOnChange(_); - })); - this.__backing_propvar = new PropDecoratedVariable("propvar", ((({let gensym___241486692 = initializers; - (((gensym___241486692) == (null)) ? undefined : gensym___241486692.propvar)})) ?? ("Hello World")), ((_: string): void => { - this.propOnChange(_); - })); - this.__backing_storagelinkvar = new StorageLinkDecoratedVariable("prop1", "storagelinkvar", "Hello World", ((_: string): void => { - this.storageLinkOnChange(_); - })) - this.__backing_storagepropvar = new StoragePropDecoratedVariable("prop2", "storagepropvar", "Hello World", ((_: string): void => { - this.storagePropOnChange(_); - })) - this.__backing_providevar = this.addProvidedVar("providevar", "providevar", ((({let gensym___194235814 = initializers; - (((gensym___194235814) == (null)) ? undefined : gensym___194235814.providevar)})) ?? ("Hello World")), false, ((_: string): void => { - this.ProvideOnChange(_); - })); - } - - public __updateStruct(initializers: __Options_MyStateSample | undefined): void { - if (((({let gensym___220608839 = initializers; - (((gensym___220608839) == (null)) ? undefined : gensym___220608839.propvar)})) !== (undefined))) { - this.__backing_propvar!.update((initializers!.propvar as string)); - } - } - - private __backing_statevar?: StateDecoratedVariable; - - public get statevar(): string { - return this.__backing_statevar!.get(); - } - - public set statevar(value: string) { - this.__backing_statevar!.set(value); - } - - private __backing_propvar?: PropDecoratedVariable; - - public get propvar(): string { - return this.__backing_propvar!.get(); - } - - public set propvar(value: string) { - this.__backing_propvar!.set(value); - } - - private __backing_storagelinkvar?: StorageLinkDecoratedVariable; - - public get storagelinkvar(): string { - return this.__backing_storagelinkvar!.get(); - } - - public set storagelinkvar(value: string) { - this.__backing_storagelinkvar!.set(value); - } - - private __backing_storagepropvar?: StoragePropDecoratedVariable; - - public get storagepropvar(): string { - return this.__backing_storagepropvar!.get(); - } - - public set storagepropvar(value: string) { - this.__backing_storagepropvar!.set(value); - } - - private __backing_providevar?: ProvideDecoratedVariable; - - public get providevar(): string { - return this.__backing_providevar!.get(); - } - - public set providevar(value: string) { - this.__backing_providevar!.set(value); - } - - public stateOnChange(propName: string) {} - - public propOnChange(propName: string) {} - - public storageLinkOnChange(propName: string) {} - - public storagePropOnChange(propName: string) {} - - public ProvideOnChange(propName: string) {} - - @memo() public _build(@memo() style: ((instance: MyStateSample)=> MyStateSample) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_MyStateSample | undefined): void { - Child._instantiateImpl(undefined, (() => { - return new Child(); - }), undefined, undefined, undefined); - } - - public constructor() {} - -} - -@Component({freezeWhenInactive:false}) final class Child extends CustomComponent { - public __initializeStruct(initializers: __Options_Child | undefined, @memo() content: (()=> void) | undefined): void {} - - public __updateStruct(initializers: __Options_Child | undefined): void {} - - @memo() public _build(@memo() style: ((instance: Child)=> Child) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Child | undefined): void {} - - public constructor() {} - -} - -interface __Options_MyStateSample { - set statevar(statevar: string | undefined) - - get statevar(): string | undefined - set __backing_statevar(__backing_statevar: StateDecoratedVariable | undefined) - - get __backing_statevar(): StateDecoratedVariable | undefined - set propvar(propvar: string | undefined) - - get propvar(): string | undefined - set __backing_propvar(__backing_propvar: PropDecoratedVariable | undefined) - - get __backing_propvar(): PropDecoratedVariable | undefined - set storagelinkvar(storagelinkvar: string | undefined) - - get storagelinkvar(): string | undefined - set __backing_storagelinkvar(__backing_storagelinkvar: StorageLinkDecoratedVariable | undefined) - - get __backing_storagelinkvar(): StorageLinkDecoratedVariable | undefined - set storagepropvar(storagepropvar: string | undefined) - - get storagepropvar(): string | undefined - set __backing_storagepropvar(__backing_storagepropvar: StoragePropDecoratedVariable | undefined) - - get __backing_storagepropvar(): StoragePropDecoratedVariable | undefined - set providevar(providevar: string | undefined) - - get providevar(): string | undefined - set __backing_providevar(__backing_providevar: ProvideDecoratedVariable | undefined) - - get __backing_providevar(): ProvideDecoratedVariable | undefined - -} - -interface __Options_Child { - -} - -class __EntryWrapper extends EntryPoint { - @memo() public entry(): void { - MyStateSample._instantiateImpl(undefined, (() => { - return new MyStateSample(); - }), undefined, undefined, undefined); - } - - public constructor() {} - -} - -`; - -function testWatchTransformer(this: PluginTestContext): void { - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'test basic watch transform', - [watchTransform, uiNoRecheck], - { - checked: [testWatchTransformer], - }, - { - stopAfter: 'checked', - } -); diff --git a/arkui-plugins/test/ut/ui-plugins/xcomponent/xcomponent-basic.test.ts b/arkui-plugins/test/ut/ui-plugins/xcomponent/xcomponent-basic.test.ts deleted file mode 100644 index fc5ee09c6..000000000 --- a/arkui-plugins/test/ut/ui-plugins/xcomponent/xcomponent-basic.test.ts +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as path from 'path'; -import { PluginTestContext, PluginTester } from '../../../utils/plugin-tester'; -import { BuildConfig, mockBuildConfig } from '../../../utils/artkts-config'; -import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; -import { parseDumpSrc } from '../../../utils/parse-string'; -import { uiNoRecheck } from '../../../utils/plugins'; -import { uiTransform } from '../../../../ui-plugins'; -import { Plugins } from '../../../../common/plugin-context'; - -const XCOMPONENT_DIR_PATH: string = 'xcomponent'; - -const buildConfig: BuildConfig = mockBuildConfig(); -buildConfig.compileFiles = [ - path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, XCOMPONENT_DIR_PATH, 'xcomponent-basic.ets'), -]; - -const xcomponentTransform: Plugins = { - name: 'xcomponent', - parsed: uiTransform().parsed, -} - -const pluginTester = new PluginTester('test basic XComponent transform', buildConfig); - -const expectedScript: string = ` -import { __memo_id_type as __memo_id_type } from "arkui.stateManagement.runtime"; - -import { __memo_context_type as __memo_context_type } from "arkui.stateManagement.runtime"; - -import { memo as memo } from "arkui.stateManagement.runtime"; - -import { UIXComponentAttribute as UIXComponentAttribute } from "@ohos.arkui.component"; - -import { UIFlexAttribute as UIFlexAttribute } from "@ohos.arkui.component"; - -import { EntryPoint as EntryPoint } from "arkui.UserView"; - -import { CustomComponent as CustomComponent } from "arkui.component.customComponent"; - -import { Component as Component, Flex as Flex, XComponent as XComponent, FlexDirection as FlexDirection, XComponentType as XComponentType, Entry as Entry, XComponentController as XComponentController, ItemAlign as ItemAlign, FlexAlign as FlexAlign, XComponentParameter as XComponentParameter } from "@ohos.arkui.component"; - -function main() {} - - - -@Entry({useSharedStorage:false,storage:"",routeName:""}) @Component({freezeWhenInactive:false}) final class Index extends CustomComponent { - public __initializeStruct(initializers: __Options_Index | undefined, @memo() content: (()=> void) | undefined): void { - this.__backing_myXComponentController = ((({let gensym___221905990 = initializers; - (((gensym___221905990) == (null)) ? undefined : gensym___221905990.myXComponentController)})) ?? (new XComponentController())); - } - - public __updateStruct(initializers: __Options_Index | undefined): void {} - - private __backing_myXComponentController?: XComponentController; - - public get myXComponentController(): XComponentController { - return (this.__backing_myXComponentController as XComponentController); - } - - public set myXComponentController(value: XComponentController) { - this.__backing_myXComponentController = value; - } - - @memo() public _build(@memo() style: ((instance: Index)=> Index) | undefined, @memo() content: (()=> void) | undefined, initializers: __Options_Index | undefined): void { - Flex(@memo() ((instance: UIFlexAttribute): void => { - instance.width("100%").height("100%"); - return; - }), { - direction: FlexDirection.Column, - alignItems: ItemAlign.Center, - justifyContent: FlexAlign.Start, - }, (() => { - XComponent(undefined, ({ - id: "xComponentId", - type: XComponentType.TEXTURE, - libraryname: "nativerender", - controller: this.myXComponentController, - } as XComponentParameter), "", undefined); - })); - } - - public constructor() {} - -} - -interface __Options_Index { - set myXComponentController(myXComponentController: XComponentController | undefined) - - get myXComponentController(): XComponentController | undefined - -} - -class __EntryWrapper extends EntryPoint { - @memo() public entry(): void { - Index._instantiateImpl(undefined, (() => { - return new Index(); - }), undefined, undefined, undefined); - } - - public constructor() {} - -} -`; - -function testXComponentTransformer(this: PluginTestContext): void { - expect(parseDumpSrc(this.scriptSnapshot ?? '')).toBe(parseDumpSrc(expectedScript)); -} - -pluginTester.run( - 'test basic XComponent transform', - [xcomponentTransform, uiNoRecheck], - { - checked: [testXComponentTransformer], - }, - { - stopAfter: 'checked', - } -); diff --git a/arkui-plugins/test/utils/artkts-config.ts b/arkui-plugins/test/utils/artkts-config.ts index 3474c59a2..db63f0e4b 100644 --- a/arkui-plugins/test/utils/artkts-config.ts +++ b/arkui-plugins/test/utils/artkts-config.ts @@ -21,6 +21,7 @@ import { changeFileExtension, ensurePathExists, getFileName, + getPandaSDKPath, getRootPath, MOCK_ENTRY_DIR_PATH, MOCK_ENTRY_FILE_NAME, @@ -173,40 +174,26 @@ function traverse(currentDir: string, pathSection: Record) { } } -function traverseSDK(currentDir: string, pathSection: Record, prefix?: string) { - const items = fs.readdirSync(currentDir); - - for (const item of items) { - const itemPath = path.join(currentDir, item); - const stat = fs.statSync(itemPath); - - if (stat.isFile() && !itemPath.endsWith('.d.ets')) { - continue; - } - - if (stat.isFile() && itemPath.endsWith('.d.ets')) { - const basename = path.basename(item, '.d.ets'); - const name = prefix && prefix !== 'arkui.runtime-api' ? `${prefix}.${basename}` : basename; - pathSection[name] = [changeFileExtension(itemPath, '', '.d.ets')]; - } else if (stat.isDirectory()) { - const basename = path.basename(itemPath); - const name = prefix && prefix !== 'arkui.runtime-api' ? `${prefix}.${basename}` : basename; - traverseSDK(itemPath, pathSection, name); - } - } -} - function mockBuildConfig(): BuildConfig { return { packageName: 'mock', compileFiles: [path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH, MOCK_ENTRY_FILE_NAME)], loaderOutPath: path.resolve(getRootPath(), MOCK_OUTPUT_DIR_PATH), cachePath: path.resolve(getRootPath(), MOCK_OUTPUT_CACHE_PATH), - pandaSdkPath: global.PANDA_SDK_PATH, - buildSdkPath: global.API_PATH, + pandaSdkPath: getPandaSDKPath(), + buildSdkPath: path.resolve(getRootPath(), MOCK_LOCAL_SDK_DIR_PATH), sourceRoots: [getRootPath()], moduleRootPath: path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH), - dependentModuleList: [], + dependentModuleList: [ + { + packageName: '@koalaui/runtime', + moduleName: '@koalaui/runtime', + moduleType: 'har', + modulePath: path.resolve(getRootPath(), RUNTIME_API_PATH), + sourceRoots: ['./'], + entryFile: 'index.sts', + }, + ], }; } @@ -307,7 +294,7 @@ class MockArktsConfigBuilder implements ArktsConfigBuilder { const pathSection: Record = {}; pathSection['std'] = [path.resolve(this.pandaSdkPath, PANDA_SDK_STDLIB_PATH, STDLIB_STD_PATH)]; pathSection['escompat'] = [path.resolve(this.pandaSdkPath, PANDA_SDK_STDLIB_PATH, STDLIB_ESCOMPAT_PATH)]; - traverseSDK(this.buildSdkPath, pathSection); + traverse(this.buildSdkPath, pathSection); this.moduleInfos.forEach((moduleInfo: ModuleInfo, moduleRootPath: string) => { pathSection[moduleInfo.packageName] = [path.resolve(moduleRootPath, moduleInfo.sourceRoots[0])]; diff --git a/arkui-plugins/test/utils/cache.ts b/arkui-plugins/test/utils/cache.ts deleted file mode 100644 index b24fcdf64..000000000 --- a/arkui-plugins/test/utils/cache.ts +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -class TesterCache { - private cacheInfo: Map; - private static instance: TesterCache; - - private constructor() { - this.cacheInfo = new Map(); - } - - static getInstance(): TesterCache { - if (!this.instance) { - this.instance = new TesterCache(); - } - return this.instance; - } - - public delete(key: string) { - if (this.cacheInfo.has(key)) { - this.cacheInfo.delete(key); - } - } - - public get(key: string) { - if (this.cacheInfo.has(key)) { - return this.cacheInfo.get(key); - } - return undefined; - } - - public has(key: string) { - return this.cacheInfo.has(key); - } - - public set(key: string, value: T) { - if (!this.cacheInfo.has(key)) { - this.cacheInfo.set(key, value); - } - } - - public clear() { - this.cacheInfo.clear(); - } -} - -export { TesterCache }; diff --git a/arkui-plugins/test/utils/compile.ts b/arkui-plugins/test/utils/compile.ts index f893dae3b..7694eac9f 100644 --- a/arkui-plugins/test/utils/compile.ts +++ b/arkui-plugins/test/utils/compile.ts @@ -13,10 +13,11 @@ * limitations under the License. */ +import * as arkts from '@koalaui/libarkts'; +import { arktsGlobal } from '@koalaui/libarkts/build/lib/es2panda'; import { PluginDriver } from './plugin-driver'; import { PluginContext, PluginExecutor } from '../../common/plugin-context'; import { EtsglobalRemover } from '../../common/etsglobal-remover'; -import * as arkts from '@koalaui/libarkts'; function restartCompilerUptoState(state: arkts.Es2pandaContextState, restart: boolean): boolean { try { @@ -27,8 +28,8 @@ function restartCompilerUptoState(state: arkts.Es2pandaContextState, restart: bo if (restart) { const srcText = new EtsglobalRemover().visitor(ast).dumpSrc(); - arkts.arktsGlobal.es2panda._DestroyContext(arkts.arktsGlobal.context); - arkts.arktsGlobal.compilerContext = arkts.Context.createFromString(srcText); + arktsGlobal.es2panda._DestroyContext(arktsGlobal.context); + arktsGlobal.compilerContext = arkts.Context.createFromString(srcText); } arkts.proceedToState(state); @@ -52,6 +53,8 @@ function insertPlugin( } if (plugin) { + pluginContext.setArkTSAst(ast); + pluginContext.setArkTSProgram(arktsGlobal.compilerContext.program); plugin.handler.apply(pluginContext); } return true; diff --git a/arkui-plugins/test/utils/global.ts b/arkui-plugins/test/utils/global.ts index cbccd4afa..4dc3d8511 100644 --- a/arkui-plugins/test/utils/global.ts +++ b/arkui-plugins/test/utils/global.ts @@ -14,14 +14,15 @@ */ import * as fs from 'fs'; -import { CompileFileInfo } from './artkts-config'; import * as arkts from '@koalaui/libarkts'; +import { arktsGlobal } from '@koalaui/libarkts/build/lib/es2panda'; +import { CompileFileInfo } from './artkts-config'; function initGlobal(fileInfo: CompileFileInfo, isDebug: boolean = true): void { const config = [ '_', '--extension', - 'ets', + 'sts', '--arktsconfig', fileInfo.arktsConfigFile, '--output', @@ -33,7 +34,7 @@ function initGlobal(fileInfo: CompileFileInfo, isDebug: boolean = true): void { } config.push(fileInfo.filePath); - arkts.arktsGlobal.filePath = fileInfo.filePath; + arktsGlobal.filePath = fileInfo.filePath; resetConfig(config); const source: string = fs.readFileSync(fileInfo.filePath).toString(); @@ -42,57 +43,48 @@ function initGlobal(fileInfo: CompileFileInfo, isDebug: boolean = true): void { function resetContext(source: string): void { try { - arkts.arktsGlobal.context; + arktsGlobal.context; } catch (e) { // Do nothing } finally { const context: arkts.Context = arkts.Context.createFromString(source); - arkts.arktsGlobal.compilerContext = context; + arktsGlobal.compilerContext = context; } } function resetConfig(cmd: string[]): void { try { - arkts.arktsGlobal.config; + arktsGlobal.config; destroyConfig(); } catch (e) { // Do nothing } finally { const arkTSConfig: arkts.Config = arkts.Config.create(cmd); - arkts.arktsGlobal.config = arkTSConfig.peer; + arktsGlobal.config = arkTSConfig.peer; } } function destroyContext(): void { - try { - arkts.arktsGlobal.clearContext(); - } catch (e) { - // Do nothing - } + arktsGlobal.es2panda._DestroyContext(arktsGlobal.context); } function destroyConfig(): void { - try { - arkts.destroyConfig(arkts.arktsGlobal.config); - } catch (e) { - // Do nothing - } + arkts.destroyConfig(arktsGlobal.config); } function canProceedToState(state: arkts.Es2pandaContextState): boolean { const stateToSkip: arkts.Es2pandaContextState[] = [ arkts.Es2pandaContextState.ES2PANDA_STATE_SCOPE_INITED, - arkts.Es2pandaContextState.ES2PANDA_STATE_BOUND, - arkts.Es2pandaContextState.ES2PANDA_STATE_LOWERED, arkts.Es2pandaContextState.ES2PANDA_STATE_ASM_GENERATED, arkts.Es2pandaContextState.ES2PANDA_STATE_ERROR, ]; + if (state in stateToSkip) { return false; } - const currState = arkts.arktsGlobal.es2panda._ContextState(arkts.arktsGlobal.context); + const currState = arktsGlobal.es2panda._ContextState(arktsGlobal.context); return currState < state; } -export { initGlobal, resetContext, resetConfig, destroyContext, destroyConfig, canProceedToState }; +export { initGlobal, resetContext, resetConfig, canProceedToState }; diff --git a/arkui-plugins/test/utils/parse-string.ts b/arkui-plugins/test/utils/parse-string.ts index 2db07c21f..58430ca1d 100644 --- a/arkui-plugins/test/utils/parse-string.ts +++ b/arkui-plugins/test/utils/parse-string.ts @@ -14,10 +14,9 @@ */ function parseDumpSrc(str: string): string { - let _str: string = str; + let _str: string = filterSource(str); _str = cleanCopyRight(_str); _str = removeSpaceAndReturn(_str); - _str = replaceWithRandomNumber(_str); return _str; } @@ -29,7 +28,7 @@ function filterSource(text: string): string { } function cleanCopyRight(str: string): string { - const copyrightBlockRegex = /(?:\/\*.*Copyright \([c|C]\) [- \d]+ [\w ]+\., Ltd\..*\*\/)/gs; + const copyrightBlockRegex = /(?:\/\*.*Copyright \(c\) [- \d]+ Huawei Device Co\., Ltd\..*\*\/)/gs; return str.replace(copyrightBlockRegex, ''); } @@ -37,13 +36,7 @@ function cleanCopyRight(str: string): string { function removeSpaceAndReturn(str: string): string { const spaceAndReturnRegex = /^[\s\r]+/gm; - return str.replace(spaceAndReturnRegex, '').trim(); + return str.replace(spaceAndReturnRegex, ''); } -function replaceWithRandomNumber(text: string): string { - return text - .replace(/(?<=__memo_id[\)+]?\s?\+\s?[\(+]?)\d+/g, () => '') - .replace(/(?<=gensym[_%]+)\d+/g, () => ''); -} - -export { parseDumpSrc, filterSource, cleanCopyRight, removeSpaceAndReturn, replaceWithRandomNumber }; +export { parseDumpSrc, filterSource, cleanCopyRight, removeSpaceAndReturn }; diff --git a/arkui-plugins/test/utils/path-config.ts b/arkui-plugins/test/utils/path-config.ts index 608df6dee..e322f28c8 100644 --- a/arkui-plugins/test/utils/path-config.ts +++ b/arkui-plugins/test/utils/path-config.ts @@ -36,6 +36,14 @@ function getRootPath(): string { return path.resolve(__dirname, '..'); } +function getPandaSDKPath(): string { + if (!process.env.ETS2PANDA_PATH) { + throw new Error('Environment Error: ets2panda path is not defined'); + } + + return path.resolve(process.env.ETS2PANDA_PATH); +} + function changeFileExtension(file: string, targetExt: string, originExt = ''): string { const currentExt: string = originExt.length === 0 ? path.extname(file) : originExt; const fileWithoutExt: string = file.substring(0, file.lastIndexOf(currentExt)); @@ -61,4 +69,4 @@ function ensurePathExists(filePath: string): void { } } -export { getRootPath, changeFileExtension, getFileName, ensurePathExists }; +export { getRootPath, getPandaSDKPath, changeFileExtension, getFileName, ensurePathExists }; diff --git a/arkui-plugins/test/utils/plugin-driver.ts b/arkui-plugins/test/utils/plugin-driver.ts index 46ce7f562..74e60a414 100644 --- a/arkui-plugins/test/utils/plugin-driver.ts +++ b/arkui-plugins/test/utils/plugin-driver.ts @@ -13,9 +13,9 @@ * limitations under the License. */ +import * as arkts from '@koalaui/libarkts'; import { isNumber } from './safe-types'; import { Plugins, PluginContext, PluginHandler, PluginState, PluginExecutor } from '../../common/plugin-context'; -import * as arkts from '@koalaui/libarkts'; export interface PluginDriver { initPlugins(plugins: Plugins[]): void; diff --git a/arkui-plugins/test/utils/plugin-tester.ts b/arkui-plugins/test/utils/plugin-tester.ts index 710456e21..c6b36d33d 100644 --- a/arkui-plugins/test/utils/plugin-tester.ts +++ b/arkui-plugins/test/utils/plugin-tester.ts @@ -13,22 +13,13 @@ * limitations under the License. */ +import * as arkts from '@koalaui/libarkts'; import { ArktsConfigBuilder, BuildConfig, CompileFileInfo, MockArktsConfigBuilder, ModuleInfo } from './artkts-config'; import { MockPluginDriver, PluginDriver, stateName } from './plugin-driver'; import { isNumber } from './safe-types'; -import { - canProceedToState, - destroyConfig, - destroyContext, - initGlobal, - resetConfig, - resetContext, -} from './global'; -import { insertPlugin } from './compile'; +import { canProceedToState, initGlobal } from './global'; +import { insertPlugin, restartCompilerUptoState } from './compile'; import { PluginExecutor, Plugins, PluginState } from '../../common/plugin-context'; -import { TesterCache } from './cache'; -import * as arkts from '@koalaui/libarkts'; -import * as fs from 'fs'; type TestParams = Parameters; @@ -40,12 +31,13 @@ type PluginTestHooks = { type TestHooks = { beforeAll?: Parameters; + afterAll?: Parameters; beforeEach?: Parameters; afterEach?: Parameters; }; export interface PluginTestContext { - scriptSnapshot?: string; + script?: arkts.AstNode; errors?: string[]; warnings?: string[]; } @@ -59,13 +51,12 @@ class PluginTester { private configBuilder: ArktsConfigBuilder; private pluginDriver: PluginDriver; private describe: string; - private cache: TesterCache; + private cache?: PluginTestContext; constructor(describe: string, buildConfig?: BuildConfig) { this.describe = describe; this.configBuilder = new MockArktsConfigBuilder(buildConfig); this.pluginDriver = new MockPluginDriver(); - this.cache = TesterCache.getInstance(); } private loadPluginDriver(plugins: Plugins[]): void { @@ -79,35 +70,27 @@ class PluginTester { pluginHooks: PluginTestHooks, plugin?: PluginExecutor ): void { - let cached: boolean = false; - const cacheKey: string = `${testName}-${key}`; + if (!this.cache) { + this.cache = {}; + } if (index > arkts.Es2pandaContextState.ES2PANDA_STATE_CHECKED) { return; } if (canProceedToState(index)) { + // TODO: this is a bug from compiler. + if (index > arkts.Es2pandaContextState.ES2PANDA_STATE_PARSED) { + restartCompilerUptoState(index, true); + } arkts.proceedToState(index); } if (plugin) { insertPlugin(this.pluginDriver, plugin, index); - this.captureContext(cacheKey); - cached = true; + // TODO: add error/warning handling after plugin + this.cache.script = arkts.EtsScript.fromContext(); } const hook: SkipFirstParam | undefined = pluginHooks[key]; if (!!hook) { - if (!cached) this.captureContext(cacheKey); - test(testName, hook[0]?.bind(this.cache.get(cacheKey)), hook[1]); - } - } - - private captureContext(cacheKey: string): void { - try { - // TODO: add error/warning handling after plugin - const context: PluginTestContext = this.cache.get(cacheKey) ?? {}; - const script: arkts.EtsScript = arkts.EtsScript.fromContext(); - context.scriptSnapshot = script.dumpSrc(); - this.cache.set(cacheKey, context); - } catch (e) { - // Do nothing + test(testName, hook[0]?.bind(this.cache), hook[1]); } } @@ -137,12 +120,12 @@ class PluginTester { ): void { let shouldStop: boolean = false; + initGlobal(fileInfo, this.configBuilder.isDebug); + Object.values(arkts.Es2pandaContextState) .filter(isNumber) .forEach((it) => { - if (shouldStop) { - return; - } + if (shouldStop) return; const state: PluginState = stateName(it); const plugins: PluginExecutor[] | undefined = this.pluginDriver.getSortedPlugins(it); this.proceedToState( @@ -157,16 +140,8 @@ class PluginTester { } private traverseFile(testName: string, pluginHooks: PluginTestHooks, stopAfter: PluginState): void { - let once: boolean = false; this.configBuilder.moduleInfos.forEach((moduleInfo) => { moduleInfo.compileFileInfos.forEach((fileInfo) => { - if (!once) { - initGlobal(fileInfo, this.configBuilder.isDebug); - once = true; - } else { - const source: string = fs.readFileSync(fileInfo.filePath).toString(); - resetContext(source); - } this.singleFileCompile(fileInfo, moduleInfo, testName, pluginHooks, stopAfter); }); }); @@ -183,25 +158,22 @@ class PluginTester { this.configBuilder = new MockArktsConfigBuilder(options.buildConfig); } - this.cache.clear(); this.loadPluginDriver(plugins); - const that = this; describe(this.describe, () => { if (testHooks?.beforeAll) { beforeAll(...testHooks.beforeAll); } + if (testHooks?.afterAll) { + afterAll(...testHooks.afterAll); + } if (testHooks?.beforeEach) { beforeEach(...testHooks.beforeEach); } if (testHooks?.afterEach) { afterEach(...testHooks.afterEach); } - afterAll(() => { - destroyContext(); - destroyConfig(); - }); - that.traverseFile(testName, pluginHooks, options.stopAfter); + this.traverseFile(testName, pluginHooks, options.stopAfter); }); } } diff --git a/arkui-plugins/test/utils/plugins/builder-lambda-no-recheck.ts b/arkui-plugins/test/utils/plugins/builder-lambda-no-recheck.ts deleted file mode 100644 index 69e2b23ad..000000000 --- a/arkui-plugins/test/utils/plugins/builder-lambda-no-recheck.ts +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as arkts from '@koalaui/libarkts'; -import { PluginContext, Plugins } from '../../../common/plugin-context'; -import { ProgramVisitor } from '../../../common/program-visitor'; -import { EXTERNAL_SOURCE_PREFIX_NAMES } from '../../../common/predefines'; -import { BuilderLambdaTransformer } from '../../../ui-plugins/builder-lambda-translators/builder-lambda-transformer'; - -/** - * AfterCheck builder-lambda transform with no recheck AST. - */ -export const builderLambdaNoRecheck: Plugins = { - name: 'builder-lambda-no-recheck', - checked(this: PluginContext): arkts.EtsScript | undefined { - let script: arkts.EtsScript | undefined; - const contextPtr = arkts.arktsGlobal.compilerContext?.peer ?? this.getContextPtr(); - if (!!contextPtr) { - let program = arkts.getOrUpdateGlobalContext(contextPtr).program; - script = program.astNode; - const builderLambdaTransformer = new BuilderLambdaTransformer(); - const programVisitor = new ProgramVisitor({ - pluginName: builderLambdaNoRecheck.name, - state: arkts.Es2pandaContextState.ES2PANDA_STATE_CHECKED, - visitors: [builderLambdaTransformer], - skipPrefixNames: EXTERNAL_SOURCE_PREFIX_NAMES, - pluginContext: this, - }); - program = programVisitor.programVisitor(program); - script = program.astNode; - arkts.GlobalInfo.getInfoInstance().reset(); - return script; - } - return script; - }, -}; diff --git a/arkui-plugins/test/utils/plugins/index.ts b/arkui-plugins/test/utils/plugins/index.ts deleted file mode 100644 index 4858b84b2..000000000 --- a/arkui-plugins/test/utils/plugins/index.ts +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// AfterParse -export * from './struct-to-component'; - -// AfterCheck -export * from './builder-lambda-no-recheck'; -export * from './memo-no-recheck'; -export * from './struct-no-recheck'; -export * from './ui-no-recheck'; -export * from './recheck'; diff --git a/arkui-plugins/test/utils/plugins/memo-no-recheck.ts b/arkui-plugins/test/utils/plugins/memo-no-recheck.ts deleted file mode 100644 index ff018cec5..000000000 --- a/arkui-plugins/test/utils/plugins/memo-no-recheck.ts +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as arkts from '@koalaui/libarkts'; -import { PluginContext, Plugins } from '../../../common/plugin-context'; -import { ProgramVisitor } from '../../../common/program-visitor'; -import { EXTERNAL_SOURCE_PREFIX_NAMES } from '../../../common/predefines'; -import { PositionalIdTracker } from '../../../memo-plugins/utils'; -import { ParameterTransformer } from '../../../memo-plugins/parameter-transformer'; -import { ReturnTransformer } from '../../../memo-plugins/return-transformer'; -import { SignatureTransformer } from '../../../memo-plugins/signature-transformer'; -import { FunctionTransformer } from '../../../memo-plugins/function-transformer'; - -/** - * AfterCheck unmemoizeTransform with no recheck AST. - */ -export const memoNoRecheck: Plugins = { - name: 'memo-no-recheck', - checked(this: PluginContext): arkts.EtsScript | undefined { - const contextPtr = arkts.arktsGlobal.compilerContext?.peer ?? this.getContextPtr(); - if (!!contextPtr) { - let program = arkts.getOrUpdateGlobalContext(contextPtr).program; - let script = program.astNode; - const positionalIdTracker = new PositionalIdTracker(arkts.getFileName(), false); - const parameterTransformer = new ParameterTransformer({ - positionalIdTracker, - }); - const returnTransformer = new ReturnTransformer(); - const signatureTransformer = new SignatureTransformer(); - const functionTransformer = new FunctionTransformer({ - positionalIdTracker, - parameterTransformer, - returnTransformer, - signatureTransformer, - }); - const programVisitor = new ProgramVisitor({ - pluginName: memoNoRecheck.name, - state: arkts.Es2pandaContextState.ES2PANDA_STATE_CHECKED, - visitors: [functionTransformer], - skipPrefixNames: EXTERNAL_SOURCE_PREFIX_NAMES, - pluginContext: this, - }); - program = programVisitor.programVisitor(program); - script = program.astNode; - return script; - } - }, -}; diff --git a/arkui-plugins/test/utils/plugins/recheck.ts b/arkui-plugins/test/utils/plugins/recheck.ts deleted file mode 100644 index 085d3731e..000000000 --- a/arkui-plugins/test/utils/plugins/recheck.ts +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as arkts from '@koalaui/libarkts'; -import { PluginContext, Plugins } from '../../../common/plugin-context'; - -/** - * Recheck the current AST. This plugin can ONLY be used at afterCheck. - */ -export const recheck: Plugins = { - name: 'recheck', - checked(this: PluginContext): arkts.EtsScript | undefined { - let script: arkts.EtsScript | undefined; - const contextPtr = arkts.arktsGlobal.compilerContext?.peer ?? this.getContextPtr(); - if (!!contextPtr) { - let program = arkts.getOrUpdateGlobalContext(contextPtr).program; - script = program.astNode; - arkts.recheckSubtree(script); - return script; - } - return script; - }, -}; diff --git a/arkui-plugins/test/utils/plugins/struct-no-recheck.ts b/arkui-plugins/test/utils/plugins/struct-no-recheck.ts deleted file mode 100644 index c564b71c7..000000000 --- a/arkui-plugins/test/utils/plugins/struct-no-recheck.ts +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as arkts from '@koalaui/libarkts'; -import { PluginContext, Plugins } from '../../../common/plugin-context'; -import { ProgramVisitor } from '../../../common/program-visitor'; -import { EXTERNAL_SOURCE_PREFIX_NAMES } from '../../../common/predefines'; -import { StructTransformer } from '../../../ui-plugins/struct-translators/struct-transformer'; - -/** - * AfterCheck struct transform with no recheck AST. - */ -export const structNoRecheck: Plugins = { - name: 'struct-no-recheck', - checked(this: PluginContext): arkts.EtsScript | undefined { - let script: arkts.EtsScript | undefined; - const contextPtr = arkts.arktsGlobal.compilerContext?.peer ?? this.getContextPtr(); - if (!!contextPtr) { - let program = arkts.getOrUpdateGlobalContext(contextPtr).program; - script = program.astNode; - const structTransformer = new StructTransformer(this.getProjectConfig()); - const programVisitor = new ProgramVisitor({ - pluginName: structNoRecheck.name, - state: arkts.Es2pandaContextState.ES2PANDA_STATE_CHECKED, - visitors: [structTransformer], - skipPrefixNames: EXTERNAL_SOURCE_PREFIX_NAMES, - pluginContext: this, - }); - program = programVisitor.programVisitor(program); - script = program.astNode; - arkts.GlobalInfo.getInfoInstance().reset(); - return script; - } - return script; - }, -}; diff --git a/arkui-plugins/test/utils/plugins/struct-to-component.ts b/arkui-plugins/test/utils/plugins/struct-to-component.ts deleted file mode 100644 index 14d494c05..000000000 --- a/arkui-plugins/test/utils/plugins/struct-to-component.ts +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as arkts from '@koalaui/libarkts'; -import { PluginContext, Plugins } from '../../../common/plugin-context'; -import { ProgramVisitor } from '../../../common/program-visitor'; -import { EXTERNAL_SOURCE_PREFIX_NAMES } from '../../../common/predefines'; -import { ComponentTransformer } from '../../../ui-plugins/component-transformer'; - -/** - * AfterParse transform struct to component. - */ -export const structToComponent: Plugins = { - name: 'struct-to-component', - parsed(this: PluginContext): arkts.EtsScript | undefined { - let script: arkts.EtsScript | undefined; - const contextPtr = arkts.arktsGlobal.compilerContext?.peer ?? this.getContextPtr(); - if (!!contextPtr) { - let program = arkts.getOrUpdateGlobalContext(contextPtr).program; - script = program.astNode; - const componentTransformer = new ComponentTransformer(); - const programVisitor = new ProgramVisitor({ - pluginName: structToComponent.name, - state: arkts.Es2pandaContextState.ES2PANDA_STATE_PARSED, - visitors: [componentTransformer], - skipPrefixNames: EXTERNAL_SOURCE_PREFIX_NAMES, - pluginContext: this, - }); - program = programVisitor.programVisitor(program); - script = program.astNode; - return script; - } - return script; - }, -}; diff --git a/arkui-plugins/test/utils/plugins/ui-no-recheck.ts b/arkui-plugins/test/utils/plugins/ui-no-recheck.ts deleted file mode 100644 index dec4b5296..000000000 --- a/arkui-plugins/test/utils/plugins/ui-no-recheck.ts +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as arkts from '@koalaui/libarkts'; -import { PluginContext, Plugins } from '../../../common/plugin-context'; -import { ProgramVisitor } from '../../../common/program-visitor'; -import { EXTERNAL_SOURCE_PREFIX_NAMES } from '../../../common/predefines'; -import { CheckedTransformer } from '../../../ui-plugins/checked-transformer'; - -/** - * AfterCheck uiTransform with no recheck AST. - */ -export const uiNoRecheck: Plugins = { - name: 'ui-no-recheck', - checked(this: PluginContext): arkts.EtsScript | undefined { - let script: arkts.EtsScript | undefined; - const contextPtr = arkts.arktsGlobal.compilerContext?.peer ?? this.getContextPtr(); - if (!!contextPtr) { - let program = arkts.getOrUpdateGlobalContext(contextPtr).program; - script = program.astNode; - const checkedTransformer = new CheckedTransformer(this.getProjectConfig()); - const programVisitor = new ProgramVisitor({ - pluginName: uiNoRecheck.name, - state: arkts.Es2pandaContextState.ES2PANDA_STATE_CHECKED, - visitors: [checkedTransformer], - skipPrefixNames: EXTERNAL_SOURCE_PREFIX_NAMES, - pluginContext: this, - }); - program = programVisitor.programVisitor(program); - script = program.astNode; - arkts.GlobalInfo.getInfoInstance().reset(); - return script; - } - return script; - }, -}; diff --git a/arkui-plugins/tsconfig.build.json b/arkui-plugins/tsconfig.build.json index 02074ad93..7efa8486d 100644 --- a/arkui-plugins/tsconfig.build.json +++ b/arkui-plugins/tsconfig.build.json @@ -20,7 +20,6 @@ "./common/**/*.ts", "./memo-plugins/**/*.ts", "./ui-plugins/**/*.ts", - "./ui-syntax-plugins/**/*.ts", "./interop-plugins/**/*.ts", ], "exclude": [ diff --git a/arkui-plugins/tsconfig.json b/arkui-plugins/tsconfig.json index 32677ce44..eab872848 100644 --- a/arkui-plugins/tsconfig.json +++ b/arkui-plugins/tsconfig.json @@ -15,14 +15,12 @@ "noEmitOnError": true, "strict": true, "skipLibCheck": true, - "removeComments": false, - "isolatedModules": true + "removeComments": false }, "include": [ "./common/**/*.ts", "./memo-plugins/**/*.ts", "./ui-plugins/**/*.ts", - "./ui-syntax-plugins/**/*.ts", "./interop-plugins/**/*.ts", "./path.ts", "./test/ut/**/*.ts", diff --git a/arkui-plugins/ui-plugins/builder-lambda-translators/builder-lambda-transformer.ts b/arkui-plugins/ui-plugins/builder-lambda-translators/builder-lambda-transformer.ts index 5e4dc8331..a0d1134c5 100644 --- a/arkui-plugins/ui-plugins/builder-lambda-translators/builder-lambda-transformer.ts +++ b/arkui-plugins/ui-plugins/builder-lambda-translators/builder-lambda-transformer.ts @@ -12,26 +12,263 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + import * as arkts from '@koalaui/libarkts'; import { AbstractVisitor } from '../../common/abstract-visitor'; -import { isBuilderLambda, isBuilderLambdaMethodDecl } from './utils'; +import { BuilderLambdaNames } from '../utils'; +import { filterDefined, removeAnnotationByName, backingField } from '../../common/arkts-utils'; +import { DecoratorNames } from '../property-translators/utils'; +import { + BuilderLambdaDeclInfo, + isBuilderLambda, + builderLambdaFunctionName, + findBuilderLambdaDeclInfo, + isBuilderLambdaMethodDecl, + replaceBuilderLambdaDeclMethodName, + isBuilderLambdaFunctionCall, + callIsGoodForBuilderLambda, + builderLambdaTypeName, + builderLambdaMethodDeclType, + builderLambdaType, +} from './utils'; import { factory } from './factory'; +// TODO: very time-consuming... +function updateIfElseContentBodyInBuilderLambda(statement: arkts.AstNode, isExternal?: boolean): arkts.AstNode { + if (arkts.isIfStatement(statement)) { + const alternate = !!statement.alternate + ? updateIfElseContentBodyInBuilderLambda(statement.alternate, isExternal) + : statement.alternate; + const consequence = updateIfElseContentBodyInBuilderLambda(statement.consequent, isExternal); + return arkts.factory.updateIfStatement(statement, statement.test, consequence!, alternate); + } + if (arkts.isBlockStatement(statement)) { + return arkts.factory.updateBlock( + statement, + statement.statements.map((st) => updateContentBodyInBuilderLambda(st, isExternal)) + ); + } + return statement; +} + +function updateContentBodyInBuilderLambda(statement: arkts.Statement, isExternal?: boolean): arkts.Statement { + if ( + arkts.isExpressionStatement(statement) && + arkts.isCallExpression(statement.expression) && + isBuilderLambda(statement.expression, isExternal) + ) { + return arkts.factory.updateExpressionStatement(statement, transformBuilderLambda(statement.expression)); + } + // TODO: very time-consuming... + if (arkts.isIfStatement(statement)) { + return updateIfElseContentBodyInBuilderLambda(statement, isExternal); + } + + return statement; +} + +function builderLambdaReplace(leaf: arkts.CallExpression): arkts.Identifier | arkts.MemberExpression | undefined { + if (!callIsGoodForBuilderLambda(leaf)) { + return undefined; + } + const node = leaf.expression; + const funcName = builderLambdaFunctionName(leaf); + if (!funcName) { + return undefined; + } + if (arkts.isIdentifier(node)) { + return arkts.factory.createIdentifier(funcName); + } + if (arkts.isMemberExpression(node)) { + return arkts.factory.createMemberExpression( + node.object, + arkts.factory.createIdentifier(funcName), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + node.computed, + node.optional + ); + } + return undefined; +} + +function createOrUpdateArgInBuilderLambda( + arg: arkts.Expression | undefined, + isExternal?: boolean, + typeName?: string, + fallback?: arkts.AstNode +): arkts.AstNode { + if (!arg) { + return fallback ?? arkts.factory.createUndefinedLiteral(); + } + if (arkts.isArrowFunctionExpression(arg)) { + return processArgArrowFunction(arg, isExternal); + } + if (arkts.isTSAsExpression(arg)) { + return processArgTSAsExpression(arg, typeName!); + } + return arg; +} + +function processArgArrowFunction( + arg: arkts.ArrowFunctionExpression, + isExternal?: boolean +): arkts.ArrowFunctionExpression { + const func: arkts.ScriptFunction = arg.scriptFunction; + const updateFunc = arkts.factory.updateScriptFunction( + func, + !!func.body && arkts.isBlockStatement(func.body) + ? arkts.factory.updateBlock( + func.body, + func.body.statements.map((st) => updateContentBodyInBuilderLambda(st, isExternal)) + ) + : undefined, + arkts.FunctionSignature.createFunctionSignature(func.typeParams, func.params, func.returnTypeAnnotation, false), + func.flags, + func.modifiers + ); + return arkts.factory.updateArrowFunction(arg, updateFunc); +} + +function updateParameterPassing( + prop: arkts.Property, + index: number, + currentStructInfo: arkts.StructInfo, + properties: arkts.Property[] +): void { + if ( + prop.key && + prop.value && + arkts.isIdentifier(prop.key) && + arkts.isMemberExpression(prop.value) && + arkts.isThisExpression(prop.value.object) && + arkts.isIdentifier(prop.value.property) + ) { + const structVariableMetadata = currentStructInfo.metadata[prop.key.name]; + if (structVariableMetadata.properties.includes(DecoratorNames.LINK)) { + properties[index] = arkts.Property.updateProperty( + prop, + arkts.factory.createIdentifier(backingField(prop.key.name)), + factory.updateBackingMember(prop.value, prop.value.property.name) + ); + } + } +} + +function processArgTSAsExpression(arg: arkts.TSAsExpression, typeName: string): arkts.TSAsExpression { + if (!arg.expr || !arkts.isObjectExpression(arg.expr)) { + return arg; + } + const currentStructInfo: arkts.StructInfo = arkts.GlobalInfo.getInfoInstance().getStructInfo(typeName!); + const properties = arg.expr.properties as arkts.Property[]; + properties.forEach((prop, index) => { + updateParameterPassing(prop, index, currentStructInfo, properties); + }); + const updatedExpr: arkts.ObjectExpression = arkts.ObjectExpression.updateObjectExpression( + arg.expr, + arkts.Es2pandaAstNodeType.AST_NODE_TYPE_OBJECT_EXPRESSION, + properties, + false + ); + return arkts.TSAsExpression.updateTSAsExpression(arg, updatedExpr, arg.typeAnnotation, arg.isConst); +} + +function generateArgsInBuilderLambda( + leaf: arkts.CallExpression, + lambdaBody: arkts.Identifier | arkts.CallExpression, + declInfo: BuilderLambdaDeclInfo, + isExternal?: boolean +): (arkts.AstNode | undefined)[] { + const { params } = declInfo; + const typeNode: arkts.TypeNode | undefined = builderLambdaType(leaf); + const typeName: string | undefined = builderLambdaTypeName(leaf); + const args: (arkts.AstNode | undefined)[] = [factory.createStyleArgInBuilderLambda(lambdaBody, typeNode)]; + let index = 0; + while (index < params.length) { + const isReusable: boolean = typeName + ? arkts.GlobalInfo.getInfoInstance().getStructInfo(typeName).isReusable + : false; + if (isReusable && index === params.length - 1) { + const reuseId = arkts.factory.createStringLiteral(typeName!); + args.push(createOrUpdateArgInBuilderLambda(leaf.arguments.at(index), isExternal, typeName, reuseId)); + } else { + args.push(createOrUpdateArgInBuilderLambda(leaf.arguments.at(index), isExternal, typeName)); + } + index++; + } + return args; +} + +function transformBuilderLambda(node: arkts.CallExpression, isExternal?: boolean): arkts.AstNode { + let instanceCalls: arkts.CallExpression[] = []; + let leaf: arkts.CallExpression = node; + + while ( + true && + arkts.isMemberExpression(leaf.expression) && + arkts.isIdentifier(leaf.expression.property) && + arkts.isCallExpression(leaf.expression.object) + ) { + instanceCalls.push(arkts.factory.createCallExpression(leaf.expression.property, undefined, leaf.arguments)); + leaf = leaf.expression.object; + } + + const replace: arkts.Identifier | arkts.MemberExpression | undefined = builderLambdaReplace(leaf); + const declInfo: BuilderLambdaDeclInfo | undefined = findBuilderLambdaDeclInfo(leaf); + if (!replace || !declInfo) { + return node; + } + let lambdaBody: arkts.Identifier | arkts.CallExpression | undefined; + if (instanceCalls.length > 0) { + instanceCalls = instanceCalls.reverse(); + lambdaBody = arkts.factory.createIdentifier(BuilderLambdaNames.STYLE_ARROW_PARAM_NAME); + instanceCalls.forEach((call) => { + if (!arkts.isIdentifier(call.expression)) { + throw new Error('call expression should be identifier'); + } + lambdaBody = factory.createStyleLambdaBody(lambdaBody!, call); + }); + } + const args: (arkts.AstNode | undefined)[] = generateArgsInBuilderLambda(leaf, lambdaBody!, declInfo, isExternal); + return arkts.factory.updateCallExpression(node, replace, undefined, filterDefined(args)); +} + +function transformBuilderLambdaMethodDecl(node: arkts.MethodDefinition): arkts.AstNode { + const func: arkts.ScriptFunction = node.scriptFunction; + const isFunctionCall: boolean = isBuilderLambdaFunctionCall(node); + const typeNode: arkts.TypeNode | undefined = builderLambdaMethodDeclType(node); + const styleArg: arkts.ETSParameterExpression = factory.createStyleArgInBuilderLambdaDecl(typeNode, isFunctionCall); + return factory.updateBuilderLambdaMethodDecl( + node, + styleArg, + removeAnnotationByName(func.annotations, BuilderLambdaNames.ANNOTATION_NAME), + replaceBuilderLambdaDeclMethodName(node.name.name) + ); +} + export class BuilderLambdaTransformer extends AbstractVisitor { - reset(): void { - super.reset(); + visitEachChild(node: arkts.AstNode): arkts.AstNode { + if (arkts.isCallExpression(node) && isBuilderLambda(node, this.isExternal)) { + return node; + } + if (arkts.isMethodDefinition(node) && isBuilderLambdaMethodDecl(node, this.isExternal)) { + return node; + } + + return super.visitEachChild(node); } visitor(beforeChildren: arkts.AstNode): arkts.AstNode { - if (arkts.isCallExpression(beforeChildren) && isBuilderLambda(beforeChildren)) { - const lambda = factory.transformBuilderLambda(beforeChildren); - return this.visitEachChild(lambda); + const node = this.visitEachChild(beforeChildren); + + if (arkts.isCallExpression(node) && isBuilderLambda(node, this.isExternal)) { + const lambda = transformBuilderLambda(node, this.isExternal); + return lambda; } - if (arkts.isMethodDefinition(beforeChildren) && isBuilderLambdaMethodDecl(beforeChildren)) { - const lambda = factory.transformBuilderLambdaMethodDecl(beforeChildren); - return this.visitEachChild(lambda); + if (arkts.isMethodDefinition(node) && isBuilderLambdaMethodDecl(node, this.isExternal)) { + const lambda = transformBuilderLambdaMethodDecl(node); + return lambda; } - const node = this.visitEachChild(beforeChildren); + return node; } } diff --git a/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts b/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts index 9c303f765..5cf2d1240 100644 --- a/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts +++ b/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts @@ -15,30 +15,7 @@ import * as arkts from '@koalaui/libarkts'; import { BuilderLambdaNames } from '../utils'; -import { annotation, backingField, filterDefined, removeAnnotationByName } from '../../common/arkts-utils'; -import { - BuilderLambdaDeclInfo, - builderLambdaFunctionName, - builderLambdaMethodDeclType, - builderLambdaTypeName, - callIsGoodForBuilderLambda, - findBuilderLambdaDecl, - findBuilderLambdaDeclInfo, - isBuilderLambda, - isBuilderLambdaFunctionCall, - isSafeType, - replaceBuilderLambdaDeclMethodName, - BindableDecl, - getDecalTypeFromValue, - hasBindableProperty, - isDoubleDollarCall, - InstanceCallInfo, - isStyleChainedCall, - isStyleWithReceiverCall, -} from './utils'; -import { DecoratorNames } from '../property-translators/utils'; -import { factory as PropertyFactory } from '../property-translators/factory'; -import { ProjectConfig } from '../../common/plugin-context'; +import { annotation, backingField } from '../../common/arkts-utils'; export class factory { /* @@ -49,7 +26,7 @@ export class factory { styleArg: arkts.ETSParameterExpression, newAnno: arkts.AnnotationUsage[], newName: string | undefined - ): arkts.MethodDefinition { + ): arkts.AstNode { const func: arkts.ScriptFunction = node.scriptFunction; const updateFunc = arkts.factory .updateScriptFunction( @@ -70,76 +47,27 @@ export class factory { node, node.kind, arkts.factory.updateIdentifier(node.name, newName ?? node.name.name), - updateFunc, + arkts.factory.createFunctionExpression(updateFunc), node.modifiers, false // TODO: how do I get it? ); } - /* - * transform arguments in style node. - */ - static getTransformedStyle(call: arkts.CallExpression): arkts.Expression[] { - const decl = arkts.getDecl(call.expression); - if (!decl || !arkts.isMethodDefinition(decl)) { - return [...call.arguments]; - } - const type: arkts.AstNode | undefined = arkts.isEtsParameterExpression(decl.scriptFunction.params[0]) - ? decl.scriptFunction.params[0].type - : undefined; - if ( - type && - arkts.isTypeNode(type) && - hasBindableProperty(type, BindableDecl.BINDABLE) && - isDoubleDollarCall(call.arguments[0]) - ) { - const bindableArg: arkts.Expression = (call.arguments[0] as arkts.CallExpression).arguments[0]; - return [factory.updateBindableStyleArguments(bindableArg), ...call.arguments.slice(1)]; - } - return [...call.arguments]; - } - - /* - * transform bundable arguments in style node, e.g. `Radio().checked($$(this.checked))` => `Radio().checked({value: xxx, onChange: xxx})`. - */ - static updateBindableStyleArguments(bindableArg: arkts.Expression): arkts.Expression { - const valueType: arkts.TypeNode = getDecalTypeFromValue(bindableArg); - const objExp: arkts.ObjectExpression = arkts.factory.createObjectExpression( - arkts.Es2pandaAstNodeType.AST_NODE_TYPE_OBJECT_EXPRESSION, - [factory.generateValueProperty(bindableArg), factory.generateOnChangeArrowFunc(bindableArg, valueType)], - false - ); - return arkts.factory.createTSAsExpression(objExp, factory.createBindableType(valueType), false); - } - /* * create style instance call, e.g. `instance.margin(10)`. */ - static createStyleLambdaBody(lambdaBody: arkts.AstNode, callInfo: InstanceCallInfo, projectConfig: ProjectConfig | undefined): arkts.CallExpression { - if (!callInfo.isReceiver) { - const newArgs: arkts.Expression[] = factory.getTransformedStyle(callInfo.call); - return arkts.factory.createCallExpression( - arkts.factory.createMemberExpression( - lambdaBody, - callInfo.call.expression, - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ), - undefined, - newArgs.map((arg) => { - if (arkts.isArrowFunctionExpression(arg)) { - return this.processArgArrowFunction(arg, projectConfig); - } - return arg; - }) - ); - } else { - return arkts.factory.createCallExpression(callInfo.call.expression, callInfo.call.typeArguments, [ + static createStyleLambdaBody(lambdaBody: arkts.AstNode, call: arkts.CallExpression): arkts.CallExpression { + return arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( lambdaBody, - ...callInfo.call.arguments.slice(1), - ]); - } + call.expression, + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + undefined, + call.arguments + ); } /* @@ -166,9 +94,9 @@ export class factory { if (!lambdaBody) { return arkts.factory.createUndefinedLiteral(); } - const safeType: arkts.TypeNode | undefined = isSafeType(typeNode) ? typeNode : undefined; + const styleLambdaParam: arkts.ETSParameterExpression = arkts.factory.createParameterDeclaration( - arkts.factory.createIdentifier(BuilderLambdaNames.STYLE_ARROW_PARAM_NAME, safeType), + arkts.factory.createIdentifier(BuilderLambdaNames.STYLE_ARROW_PARAM_NAME, typeNode), undefined ); @@ -231,418 +159,4 @@ export class factory { parameter.annotations = [annotation('memo')]; return parameter; } - - /** - * If a builder lambda's argument is an arrow function, - * then transform any builder lambda in the function body. - */ - static processArgArrowFunction(arg: arkts.ArrowFunctionExpression, projectConfig: ProjectConfig | undefined): arkts.ArrowFunctionExpression { - const func: arkts.ScriptFunction = arg.scriptFunction; - const updateFunc = arkts.factory.updateScriptFunction( - func, - !!func.body && arkts.isBlockStatement(func.body) - ? arkts.factory.updateBlock( - func.body, - func.body.statements.map((st) => this.updateContentBodyInBuilderLambda(st, projectConfig)) - ) - : undefined, - arkts.FunctionSignature.createFunctionSignature( - func.typeParams, - func.params, - func.returnTypeAnnotation, - false - ), - func.flags, - func.modifiers - ); - return arkts.factory.updateArrowFunction(arg, updateFunc); - } - - /** - * transform options argument in a builder lambda call. - */ - static processOptionsArg(arg: T, typeName: string): T { - let expr: arkts.ObjectExpression | undefined; - if (arkts.isTSAsExpression(arg) && !!arg.expr && arkts.isObjectExpression(arg.expr)) { - expr = arg.expr; - } else if (arkts.isObjectExpression(arg)) { - expr = arg; - } - - if (!expr) { - return arg; - } - - const currentStructInfo: arkts.StructInfo = arkts.GlobalInfo.getInfoInstance().getStructInfo(typeName!); - const properties = expr.properties as arkts.Property[]; - properties.forEach((prop, index) => { - this.updateParameterPassingInLinkedProperties(prop, index, currentStructInfo, properties); - }); - const updatedExpr: arkts.ObjectExpression = arkts.ObjectExpression.updateObjectExpression( - expr, - arkts.Es2pandaAstNodeType.AST_NODE_TYPE_OBJECT_EXPRESSION, - properties, - false - ); - if (arkts.isTSAsExpression(arg)) { - return arkts.TSAsExpression.updateTSAsExpression(arg, updatedExpr, arg.typeAnnotation, arg.isConst) as T; - } - return updatedExpr as T; - } - - /** - * update any `@Link` parameter passing to the custom-component child. - */ - static updateParameterPassingInLinkedProperties( - prop: arkts.Property, - index: number, - currentStructInfo: arkts.StructInfo, - properties: arkts.Property[] - ): void { - const decl = prop.key ? arkts.getDecl(prop.key) : undefined; - if (decl && arkts.isMethodDefinition(decl)) { - const type: arkts.TypeNode | undefined = decl.scriptFunction.returnTypeAnnotation; - if ( - type && - hasBindableProperty(type, BindableDecl.BINDABLE) && - arkts.isProperty(prop) && - prop.value && - isDoubleDollarCall(prop.value) - ) { - properties[index] = factory.updateBindableProperty(prop); - } - } - if ( - !!prop.key && - !!prop.value && - arkts.isIdentifier(prop.key) && - arkts.isMemberExpression(prop.value) && - arkts.isThisExpression(prop.value.object) && - arkts.isIdentifier(prop.value.property) - ) { - const structVariableMetadata = currentStructInfo.metadata[prop.key.name]; - if ( - structVariableMetadata && - structVariableMetadata.properties.length && - structVariableMetadata.properties.includes(DecoratorNames.LINK) - ) { - properties[index] = arkts.Property.updateProperty( - prop, - arkts.factory.createIdentifier(backingField(prop.key.name)), - this.updateBackingMember(prop.value, prop.value.property.name) - ); - } - } - } - - /** - * create or update arguments in a builder lambda call. - * If the corresponding argument is not provided, fill-in an `undefined` to it. - */ - static createOrUpdateArgInBuilderLambda( - arg: arkts.Expression | undefined, - projectConfig: ProjectConfig | undefined, - typeName?: string, - ): arkts.AstNode { - if (!arg) { - return arkts.factory.createUndefinedLiteral(); - } - if (arkts.isArrowFunctionExpression(arg)) { - return this.processArgArrowFunction(arg, projectConfig); - } - // this is too optimistic to check if this is an options argument... - if (arkts.isTSAsExpression(arg) || arkts.isObjectExpression(arg)) { - return this.processOptionsArg(arg, typeName!); - } - return arg; - } - - /** - * transform arguments in a builder lambda call. - */ - static generateArgsInBuilderLambda( - leaf: arkts.CallExpression, - lambdaBody: arkts.Identifier | arkts.CallExpression, - declInfo: BuilderLambdaDeclInfo, - projectConfig: ProjectConfig | undefined - ): (arkts.AstNode | undefined)[] { - const { params, returnType } = declInfo; - const typeName: string | undefined = builderLambdaTypeName(leaf); - const args: (arkts.AstNode | undefined)[] = [this.createStyleArgInBuilderLambda(lambdaBody, returnType)]; - let index = 0; - while (index < params.length) { - args.push(this.createOrUpdateArgInBuilderLambda(leaf.arguments.at(index), projectConfig, typeName)); - index++; - } - const isReusable: boolean = typeName - ? arkts.GlobalInfo.getInfoInstance().getStructInfo(typeName).isReusable : false; - if (isReusable) { - args.splice(-1, 1, arkts.factory.createStringLiteral(typeName!)); - } - else if (typeName === 'XComponent') { - let packageInfo: string = ''; - if (projectConfig?.bundleName && projectConfig?.moduleName) { - packageInfo = projectConfig?.bundleName + '/' + projectConfig?.moduleName; - } - args.splice(args.length - 1, 0, arkts.factory.createStringLiteral(packageInfo)); - } - return args; - } - - /** - * update if-else in trailing lambda contents in a builder lambda call. - */ - static updateIfElseContentBodyInBuilderLambda(statement: arkts.AstNode, projectConfig: ProjectConfig | undefined): arkts.AstNode { - if (arkts.isIfStatement(statement)) { - const alternate = !!statement.alternate - ? this.updateIfElseContentBodyInBuilderLambda(statement.alternate, projectConfig) - : statement.alternate; - const consequence = this.updateIfElseContentBodyInBuilderLambda(statement.consequent, projectConfig); - return arkts.factory.updateIfStatement(statement, statement.test, consequence!, alternate); - } - if (arkts.isBlockStatement(statement)) { - return arkts.factory.updateBlock( - statement, - statement.statements.map((st) => this.updateContentBodyInBuilderLambda(st, projectConfig)) - ); - } - return statement; - } - - /** - * update trailing lambda contents in a builder lambda call. - */ - static updateContentBodyInBuilderLambda(statement: arkts.Statement, projectConfig: ProjectConfig | undefined): arkts.Statement { - if ( - arkts.isExpressionStatement(statement) && - arkts.isCallExpression(statement.expression) && - isBuilderLambda(statement.expression) - ) { - return arkts.factory.updateExpressionStatement( - statement, - this.transformBuilderLambda(statement.expression, projectConfig) - ); - } - if (arkts.isIfStatement(statement)) { - return this.updateIfElseContentBodyInBuilderLambda(statement, projectConfig); - } - - return statement; - } - - /** - * replace function call's name to the corresponding transformed name. - */ - static builderLambdaReplace(leaf: arkts.CallExpression): arkts.Identifier | arkts.MemberExpression | undefined { - if (!callIsGoodForBuilderLambda(leaf)) { - return undefined; - } - const node = leaf.expression; - const funcName = builderLambdaFunctionName(leaf); - if (!funcName) { - return undefined; - } - if (arkts.isIdentifier(node)) { - return arkts.factory.createIdentifier(funcName); - } - if (arkts.isMemberExpression(node)) { - return arkts.factory.createMemberExpression( - node.object, - arkts.factory.createIdentifier(funcName), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - node.computed, - node.optional - ); - } - return undefined; - } - - /** - * transform `@ComponentBuilder` in declared methods. - */ - static transformBuilderLambdaMethodDecl(node: arkts.MethodDefinition): arkts.MethodDefinition { - const func: arkts.ScriptFunction = node.scriptFunction; - const isFunctionCall: boolean = isBuilderLambdaFunctionCall(node); - const typeNode: arkts.TypeNode | undefined = builderLambdaMethodDeclType(node); - const styleArg: arkts.ETSParameterExpression = this.createStyleArgInBuilderLambdaDecl(typeNode, isFunctionCall); - const newOverloads: arkts.MethodDefinition[] = node.overloads.map((method) => - factory.transformBuilderLambdaMethodDecl(method) - ); - - return this.updateBuilderLambdaMethodDecl( - node, - styleArg, - removeAnnotationByName(func.annotations, BuilderLambdaNames.ANNOTATION_NAME), - replaceBuilderLambdaDeclMethodName(node.name.name) - ).setOverloads(newOverloads); - } - - /** - * transform `.animation(...)` to `.animationStart(...) and .animationStop(...)` - */ - static updateAnimation(instanceCalls: InstanceCallInfo[]): void { - let lastAniIdx = 0; - let curIdx = 0; - - while (curIdx < instanceCalls.length) { - if (instanceCalls[curIdx].isReceiver) { - curIdx++; - continue; - } - const property: arkts.Identifier = instanceCalls[curIdx].call.expression as arkts.Identifier; - if (property.name === BuilderLambdaNames.ANIMATION_NAME) { - const aniStart: arkts.CallExpression = arkts.factory.createCallExpression( - arkts.factory.createIdentifier(BuilderLambdaNames.ANIMATION_START), - undefined, - instanceCalls[curIdx].call.arguments - ); - const aniStop: arkts.CallExpression = arkts.factory.createCallExpression( - arkts.factory.createIdentifier(BuilderLambdaNames.ANIMATION_STOP), - undefined, - instanceCalls[curIdx].call.arguments.map((arg) => arg.clone()) - ); - instanceCalls.splice(lastAniIdx, 0, { isReceiver: false, call: aniStart }); - instanceCalls[curIdx + 1] = { isReceiver: false, call: aniStop }; - curIdx += 2; - lastAniIdx = curIdx; - } else { - curIdx++; - } - } - } - - /** - * transform `@ComponentBuilder` in non-declared calls. - */ - static transformBuilderLambda(node: arkts.CallExpression, projectConfig: ProjectConfig | undefined): arkts.AstNode { - let instanceCalls: InstanceCallInfo[] = []; - let leaf: arkts.CallExpression = node; - - while (isStyleChainedCall(leaf) || isStyleWithReceiverCall(leaf)) { - if (isStyleChainedCall(leaf)) { - instanceCalls.push({ - isReceiver: false, - call: arkts.factory.createCallExpression( - (leaf.expression as arkts.MemberExpression).property, - leaf.typeArguments, - leaf.arguments - ), - }); - leaf = (leaf.expression as arkts.MemberExpression).object as arkts.CallExpression; - } - - if (isStyleWithReceiverCall(leaf)) { - instanceCalls.push({ - isReceiver: true, - call: arkts.factory.createCallExpression(leaf.expression, leaf.typeArguments, leaf.arguments), - }); - leaf = leaf.arguments[0] as arkts.CallExpression; - } - } - - const decl: arkts.AstNode | undefined = findBuilderLambdaDecl(leaf); - if (!decl) { - return node; - } - - const replace: arkts.Identifier | arkts.MemberExpression | undefined = this.builderLambdaReplace(leaf); - const declInfo: BuilderLambdaDeclInfo | undefined = findBuilderLambdaDeclInfo(decl); - if (!replace || !declInfo) { - return node; - } - - let lambdaBody: arkts.Identifier | arkts.CallExpression | undefined; - if (instanceCalls.length > 0) { - instanceCalls = instanceCalls.reverse(); - this.updateAnimation(instanceCalls); - lambdaBody = arkts.factory.createIdentifier(BuilderLambdaNames.STYLE_ARROW_PARAM_NAME); - instanceCalls.forEach((callInfo) => { - lambdaBody = this.createStyleLambdaBody(lambdaBody!, callInfo, projectConfig); - }); - } - - const args: (arkts.AstNode | undefined)[] = this.generateArgsInBuilderLambda(leaf, lambdaBody!, declInfo, projectConfig); - return arkts.factory.updateCallExpression(node, replace, leaf.typeArguments, filterDefined(args)); - } - - /* - * update bindableProperty, e.g. `text: $$(this.text)` => `text: { value: xxx , onChange: xxx }`. - */ - static updateBindableProperty(prop: arkts.Property, type?: arkts.TypeNode): arkts.Property { - let res: arkts.Property[] = []; - let valueType: arkts.TypeNode; - if ( - prop.value && - arkts.isCallExpression(prop.value) && - prop.value.arguments && - prop.value.arguments.length === 1 - ) { - let bindableArg = prop.value.arguments[0]; - valueType = getDecalTypeFromValue(bindableArg); - res.push( - factory.generateValueProperty(bindableArg), - factory.generateOnChangeArrowFunc(bindableArg, valueType) - ); - } else { - return prop; - } - const asObjProp: arkts.TSAsExpression = arkts.factory.createTSAsExpression( - arkts.ObjectExpression.createObjectExpression( - arkts.Es2pandaAstNodeType.AST_NODE_TYPE_OBJECT_EXPRESSION, - res, - false - ), - factory.createBindableType(valueType), - false - ); - return arkts.factory.updateProperty(prop, prop.key, asObjProp); - } - - /* - * generate `value: ` in object. - */ - static generateValueProperty(bindableArg: arkts.Expression): arkts.Property { - return arkts.factory.createProperty(arkts.factory.createIdentifier('value'), bindableArg.clone()); - } - - /* - * generate `onChange: (value) => = value` in object. - */ - static generateOnChangeArrowFunc(bindableArg: arkts.Expression, valueType: arkts.TypeNode): arkts.Property { - return arkts.factory.createProperty( - arkts.factory.createIdentifier('onChange'), - PropertyFactory.createArrowFunctionWithParamsAndBody( - undefined, - [ - arkts.factory.createParameterDeclaration( - arkts.factory.createIdentifier('value', valueType.clone()), - undefined - ), - ], - undefined, - false, - [ - arkts.factory.createExpressionStatement( - arkts.factory.createAssignmentExpression( - bindableArg.clone(), - arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - arkts.factory.createIdentifier('value') - ) - ), - ] - ) - ); - } - - /* - * generate `Bindable`. - */ - static createBindableType(valueType: arkts.TypeNode): arkts.ETSTypeReference { - return arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier(BindableDecl.BINDABLE), - arkts.factory.createTSTypeParameterInstantiation([valueType.clone()]) - ) - ); - } } diff --git a/arkui-plugins/ui-plugins/builder-lambda-translators/utils.ts b/arkui-plugins/ui-plugins/builder-lambda-translators/utils.ts index f7cd7c6de..b31f6e284 100644 --- a/arkui-plugins/ui-plugins/builder-lambda-translators/utils.ts +++ b/arkui-plugins/ui-plugins/builder-lambda-translators/utils.ts @@ -15,25 +15,15 @@ import * as arkts from '@koalaui/libarkts'; import { isAnnotation } from '../../common/arkts-utils'; -import { BuilderLambdaNames, Dollars } from '../utils'; +import { BuilderLambdaNames } from '../utils'; export type BuilderLambdaDeclInfo = { isFunctionCall: boolean; // isFunctionCall means it is from $_instantiate. params: readonly arkts.Expression[]; - returnType: arkts.TypeNode | undefined; }; -export enum BindableDecl { - BINDABLE = 'Bindable', -} - export type BuilderLambdaAstNode = arkts.ScriptFunction | arkts.ETSParameterExpression | arkts.FunctionDeclaration; -export type InstanceCallInfo = { - isReceiver: boolean; - call: arkts.CallExpression; -}; - /** * Used in finding "XXX" in BuilderLambda("XXX") * @deprecated @@ -61,64 +51,9 @@ export function builderLambdaArgumentName(annotation: arkts.AnnotationUsage): st */ export function isBuilderLambda(node: arkts.AstNode, isExternal?: boolean): boolean { const builderLambdaCall: arkts.AstNode | undefined = getDeclForBuilderLambda(node); - if (!builderLambdaCall) { - return arkts.isCallExpression(node) && node.arguments.length > 0 && isBuilderLambda(node.arguments[0]); - } return !!builderLambdaCall; } -/** - * Determine whether it is a function with receiver method definition. - * - * @param node method definition node - */ -export function isFunctionWithReceiver(node: arkts.MethodDefinition): boolean { - if (node.scriptFunction && arkts.isScriptFunction(node.scriptFunction)) { - return node.scriptFunction.hasReceiver; - } - return false; -} - -/** - * Determine whether it is a function with receiver call. - * - * @param node identifier node - */ -export function isFunctionWithReceiverCall(node: arkts.Identifier): boolean { - const decl: arkts.AstNode | undefined = arkts.getDecl(node); - if (decl && arkts.isMethodDefinition(decl)) { - return isFunctionWithReceiver(decl); - } - return false; -} - -/** - * Determine whether it is a style chained call. - * - * @param node call expression node - */ -export function isStyleChainedCall(node: arkts.CallExpression): boolean { - return ( - arkts.isMemberExpression(node.expression) && - arkts.isIdentifier(node.expression.property) && - arkts.isCallExpression(node.expression.object) - ); -} - -/** - * Determine whether it is a style function with receiver call. - * - * @param node call expression node - */ -export function isStyleWithReceiverCall(node: arkts.CallExpression): boolean { - return ( - arkts.isIdentifier(node.expression) && - isFunctionWithReceiverCall(node.expression) && - !!node.arguments.length && - arkts.isCallExpression(node.arguments[0]) - ); -} - /** * replace $_instantiate with _instantiateImpl. * @@ -194,13 +129,6 @@ export function isBuilderLambdaCall(node: arkts.CallExpression | arkts.Identifie } if (arkts.isMethodDefinition(decl)) { - if (isFunctionWithReceiver(decl)) { - return ( - arkts.isCallExpression(node) && - node.arguments.length > 0 && - !!getDeclForBuilderLambda(node.arguments[0]) - ); - } return isBuilderLambdaMethod(decl); } if (arkts.isFunctionExpression(decl)) { @@ -297,16 +225,15 @@ export function isParameterPassing(prop: arkts.Property): boolean | undefined { ); } -export function findBuilderLambdaDeclInfo(decl: arkts.AstNode | undefined): BuilderLambdaDeclInfo | undefined { +export function findBuilderLambdaDeclInfo(node: arkts.CallExpression): BuilderLambdaDeclInfo | undefined { + const decl = findBuilderLambdaDecl(node); if (!decl) { return undefined; } - if (arkts.isMethodDefinition(decl)) { const params = decl.scriptFunction.params.map((p) => p.clone()); - const returnType = decl.scriptFunction.returnTypeAnnotation?.clone(); const isFunctionCall = isBuilderLambdaFunctionCall(decl); - return { isFunctionCall, params, returnType }; + return { isFunctionCall, params }; } return undefined; @@ -330,15 +257,15 @@ export function callIsGoodForBuilderLambda(leaf: arkts.CallExpression): boolean return arkts.isIdentifier(node) || arkts.isMemberExpression(node); } -export function isSafeType(type: arkts.TypeNode | undefined): boolean { - if (!type) { - return false; - } - // type can be generic (not safe) if includes any type params in a type reference. - if (arkts.isETSTypeReference(type) && !!type.part && !!type.part.typeParams) { - return false; +export function builderLambdaType(leaf: arkts.CallExpression): arkts.TypeNode | undefined { + const name: string | undefined = builderLambdaTypeName(leaf); + if (!name) { + return undefined; } - return true; + // TODO: it should be the return type of the function annotated with the @BuilderLambda + return arkts.factory.createTypeReference( + arkts.factory.createTypeReferencePart(arkts.factory.createIdentifier(`${name}Attribute`)) + ); } export function builderLambdaMethodDeclType(method: arkts.MethodDefinition): arkts.TypeNode | undefined { @@ -380,98 +307,3 @@ export function builderLambdaFunctionName(node: arkts.CallExpression): string | } return undefined; } - -/** - * Determine whether the node `` is `` bindable property. - * - * @param type type node - * @param bindableDecl bindable decalaration name - */ -export function hasBindableProperty(type: arkts.AstNode, bindableDecl: BindableDecl): boolean { - let res: boolean = false; - if (arkts.isETSUnionType(type)) { - type.types.forEach((item: arkts.TypeNode) => { - res = res || hasBindableProperty(item, bindableDecl); - }); - } - if (arkts.isETSTypeReference(type)) { - res = - res || - (!!type.part && - !!type.part.name && - arkts.isIdentifier(type.part.name) && - type.part.name.name === bindableDecl); - } - - return res; -} - -/** - * Determine whether `` is `$$()` call expression node. - * - * @param value expression node - */ -export function isDoubleDollarCall(value: arkts.Expression): boolean { - if ( - arkts.isCallExpression(value) && - value.expression && - arkts.isIdentifier(value.expression) && - value.expression.name - ) { - return value.expression.name === Dollars.DOLLAR_DOLLAR; - } - return false; -} - -/** - * get declaration type from `{xxx: }` or `fun()`. - * - * @param value type node - */ -export function getDecalTypeFromValue(value: arkts.Expression): arkts.TypeNode { - const decl: arkts.AstNode | undefined = arkts.getDecl(value); - if (!decl || !arkts.isClassProperty(decl)) { - throw new Error('cannot get declaration'); - } - if (isArrayType(decl.typeAnnotation!)) { - return getElementTypeFromArray(decl.typeAnnotation!)!; - } - return decl.typeAnnotation!; -} - -/** - * Determine whether `` is array type, e.g. `xxx[]` or `Array`. - * - * @param type type node - */ -export function isArrayType(type: arkts.TypeNode): boolean { - return ( - arkts.isTSArrayType(type) || - (arkts.isETSTypeReference(type) && - !!type.part && - arkts.isETSTypeReferencePart(type.part) && - !!type.part.name && - arkts.isIdentifier(type.part.name) && - type.part.name.name === 'Array') - ); -} - -/** - * get element type from array type node ``. - * - * @param arrayType array type node - */ -export function getElementTypeFromArray(arrayType: arkts.TypeNode): arkts.TypeNode | undefined { - if (arkts.isTSArrayType(arrayType)) { - return arrayType.elementType?.clone(); - } else if ( - arkts.isETSTypeReference(arrayType) && - !!arrayType.part && - arkts.isETSTypeReferencePart(arrayType.part) && - !!arrayType.part.typeParams && - arrayType.part.typeParams.params.length - ) { - return arrayType.part.typeParams.params[0].clone(); - } - return undefined; -} diff --git a/arkui-plugins/ui-plugins/checked-transformer.ts b/arkui-plugins/ui-plugins/checked-transformer.ts index eddd49be3..e544623b2 100644 --- a/arkui-plugins/ui-plugins/checked-transformer.ts +++ b/arkui-plugins/ui-plugins/checked-transformer.ts @@ -20,83 +20,90 @@ import { factory as builderLambdaFactory } from './builder-lambda-translators/fa import { factory as uiFactory } from './ui-factory'; import { factory as entryFactory } from './entry-translators/factory'; import { AbstractVisitor } from '../common/abstract-visitor'; -import { annotation, collect, filterDefined } from '../common/arkts-utils'; +import { annotation, collect, filterDefined, removeAnnotationByName, backingField } from '../common/arkts-utils'; import { CustomComponentNames, getCustomComponentOptionsName, getTypeNameFromTypeParameter, getTypeParamsFromClassDecl, - getGettersFromClassDecl, - addMemoAnnotation, + BuilderLambdaNames, } from './utils'; import { hasDecorator, DecoratorNames } from './property-translators/utils'; import { + ScopeInfo, isCustomComponentClass, isKnownMethodDefinition, isEtsGlobalClass, isReourceNode, - ScopeInfoCollection, - CustomComponentScopeInfo, - isMemoCall, - findCanAddMemoFromArrowFunction, } from './struct-translators/utils'; -import { isBuilderLambda, isBuilderLambdaMethodDecl } from './builder-lambda-translators/utils'; +import { + isBuilderLambda, + isBuilderLambdaMethodDecl, + isBuilderLambdaFunctionCall, + builderLambdaMethodDeclType, + replaceBuilderLambdaDeclMethodName, + findBuilderLambdaDeclInfo, + callIsGoodForBuilderLambda, + builderLambdaFunctionName, + BuilderLambdaDeclInfo, + builderLambdaType, + builderLambdaTypeName, +} from './builder-lambda-translators/utils'; import { isEntryWrapperClass } from './entry-translators/utils'; -import { classifyObservedTrack, classifyProperty, PropertyTranslator } from './property-translators'; -import { ObservedTrackTranslator } from './property-translators/observedTrack'; -import { nodeByType } from '@koalaui/libarkts/build/src/reexport-for-generated'; -import { isArkUICompatible, updateArkUICompatible } from './interop'; +import { classifyProperty, PropertyTranslator } from './property-translators'; export class CheckedTransformer extends AbstractVisitor { - private scopeInfoCollection: ScopeInfoCollection; + private scopeInfos: ScopeInfo[] = []; projectConfig: ProjectConfig | undefined; constructor(projectConfig: ProjectConfig | undefined) { super(); this.projectConfig = projectConfig; - this.scopeInfoCollection = { customComponents: [] }; } reset(): void { super.reset(); - this.scopeInfoCollection = { customComponents: [] }; + this.scopeInfos = []; } enter(node: arkts.AstNode): void { if (arkts.isClassDeclaration(node) && isCustomComponentClass(node)) { - this.scopeInfoCollection.customComponents.push({ name: node.definition!.ident!.name }); + this.scopeInfos.push({ name: node.definition!.ident!.name }); } - if (arkts.isMethodDefinition(node) && this.scopeInfoCollection.customComponents.length > 0) { + if (arkts.isMethodDefinition(node) && this.scopeInfos.length > 0) { const name = node.name.name; - const scopeInfo = this.scopeInfoCollection.customComponents.pop()!; + const scopeInfo = this.scopeInfos.pop()!; scopeInfo.hasInitializeStruct ||= name === CustomComponentNames.COMPONENT_INITIALIZE_STRUCT; scopeInfo.hasUpdateStruct ||= name === CustomComponentNames.COMPONENT_UPDATE_STRUCT; scopeInfo.hasReusableRebind ||= name === CustomComponentNames.REUSABLE_COMPONENT_REBIND_STATE; - this.scopeInfoCollection.customComponents.push(scopeInfo); + this.scopeInfos.push(scopeInfo); } } exit(node: arkts.AstNode): void { if (arkts.isClassDeclaration(node) && isCustomComponentClass(node)) { - this.scopeInfoCollection.customComponents.pop(); + this.scopeInfos.pop(); + } + } + + visitEachChild(node: arkts.AstNode): arkts.AstNode { + if (arkts.isCallExpression(node) && isBuilderLambda(node, this.isExternal)) { + return node; + } + if (arkts.isMethodDefinition(node) && isBuilderLambdaMethodDecl(node, this.isExternal)) { + return node; } + + return super.visitEachChild(node); } visitor(beforeChildren: arkts.AstNode): arkts.AstNode { this.enter(beforeChildren); - if (arkts.isCallExpression(beforeChildren) && isBuilderLambda(beforeChildren)) { - const lambda = builderLambdaFactory.transformBuilderLambda(beforeChildren, this.projectConfig); - return this.visitEachChild(lambda); - } else if (arkts.isMethodDefinition(beforeChildren) && isBuilderLambdaMethodDecl(beforeChildren)) { - const lambda = builderLambdaFactory.transformBuilderLambdaMethodDecl(beforeChildren); - return this.visitEachChild(lambda); - } const node = this.visitEachChild(beforeChildren); if (arkts.isClassDeclaration(node) && isCustomComponentClass(node)) { - let scope: CustomComponentScopeInfo | undefined; - const scopeInfos: CustomComponentScopeInfo[] = this.scopeInfoCollection.customComponents; - if (scopeInfos.length > 0) { - scope = scopeInfos[scopeInfos.length - 1]; + let scope: ScopeInfo | undefined; + if (this.scopeInfos.length > 0) { + scope = this.scopeInfos[this.scopeInfos.length - 1]; } const newClass: arkts.ClassDeclaration = tranformClassMembers( node, @@ -112,236 +119,21 @@ export class CheckedTransformer extends AbstractVisitor { return transformEtsGlobalClassMembers(node); } else if (arkts.isCallExpression(node) && isReourceNode(node)) { return transformResource(node, this.projectConfig); - } else if (findCanAddMemoFromArrowFunction(node)) { - return addMemoAnnotation(node); - } else if (arkts.isClassDeclaration(node)) { - return transformObservedTracked(node); - } else if (isArkUICompatible(node)) { - return updateArkUICompatible(node as arkts.CallExpression); - } else if (this.externalSourceName) { - return structFactory.transformExternalSource(this.externalSourceName, node); + } else if (arkts.isCallExpression(node) && isBuilderLambda(node, this.isExternal)) { + const lambda = transformBuilderLambda(node, this.isExternal); + return lambda; + } else if (arkts.isMethodDefinition(node) && isBuilderLambdaMethodDecl(node, this.isExternal)) { + const lambda = transformBuilderLambdaMethodDecl(node); + return lambda; } return node; } } -export type ClassScopeInfo = { - isObserved: boolean; - classHasTrack: boolean; - getters: arkts.MethodDefinition[]; -}; - -function transformObservedTracked(node: arkts.ClassDeclaration): arkts.ClassDeclaration { - if (!node.definition) { - return node; - } - const isObserved: boolean = hasDecorator(node.definition, DecoratorNames.OBSERVED); - const classHasTrack: boolean = node.definition.body.some( - (member) => arkts.isClassProperty(member) && hasDecorator(member, DecoratorNames.TRACK) - ); - if (!isObserved && !classHasTrack) { - return node; - } - - const updateClassDef: arkts.ClassDefinition = arkts.factory.updateClassDefinition( - node.definition, - node.definition.ident, - node.definition.typeParams, - node.definition.superTypeParams, - [ - ...node.definition.implements, - arkts.TSClassImplements.createTSClassImplements( - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart(arkts.factory.createIdentifier('IObservedObject')) - ) - ), - ], - undefined, - node.definition.super, - observedTrackPropertyMembers(classHasTrack, node.definition, isObserved), - node.definition.modifiers, - arkts.classDefinitionFlags(node.definition) - ); - return arkts.factory.updateClassDeclaration(node, updateClassDef); -} - -function observedTrackPropertyMembers( - classHasTrack: boolean, - definition: arkts.ClassDefinition, - isObserved: boolean -): arkts.AstNode[] { - const watchMembers: arkts.AstNode[] = createWatchMembers(); - const permissibleAddRefDepth: arkts.ClassProperty = arkts.factory.createClassProperty( - arkts.factory.createIdentifier('_permissibleAddRefDepth'), - arkts.factory.createNumericLiteral(0), - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart(arkts.factory.createIdentifier('int32')) - ), - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, - false - ); - - const meta: arkts.ClassProperty = arkts.factory.createClassProperty( - arkts.factory.createIdentifier('__meta'), - arkts.factory.createETSNewClassInstanceExpression( - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart(arkts.factory.createIdentifier('MutableStateMeta')) - ), - [arkts.factory.createStringLiteral('@Observe properties (no @Track)')] - ), - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart(arkts.factory.createIdentifier('MutableStateMeta')) - ), - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE, - false - ); - - const getters: arkts.MethodDefinition[] = getGettersFromClassDecl(definition); - - const classScopeInfo: ClassScopeInfo = { - isObserved: isObserved, - classHasTrack: classHasTrack, - getters: getters, - }; - - const propertyTranslators: ObservedTrackTranslator[] = filterDefined( - definition.body.map((it) => classifyObservedTrack(it, classScopeInfo)) - ); - - const propertyMembers = propertyTranslators.map((translator) => translator.translateMember()); - - const nonClassPropertyOrGetter: arkts.AstNode[] = definition.body.filter( - (member) => - !arkts.isClassProperty(member) && - !( - arkts.isMethodDefinition(member) && - arkts.hasModifierFlag(member, arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_GETTER) - ) - ); - - return [ - ...watchMembers, - ...(classHasTrack ? [permissibleAddRefDepth] : [permissibleAddRefDepth, meta]), - ...collect(...propertyMembers), - ...nonClassPropertyOrGetter, - ...classScopeInfo.getters, - ]; -} - -function createWatchMethod( - methodName: string, - returnType: arkts.Es2pandaPrimitiveType, - paramName: string, - paramType: string, - isReturnStatement: boolean -): arkts.MethodDefinition { - return arkts.factory.createMethodDefinition( - arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_METHOD, - arkts.factory.createIdentifier(methodName), - arkts.factory.createScriptFunction( - arkts.factory.createBlock([ - isReturnStatement - ? arkts.factory.createReturnStatement( - arkts.factory.createCallExpression(thisSubscribedWatchesMember(methodName), undefined, [ - arkts.factory.createIdentifier(paramName), - ]) - ) - : arkts.factory.createExpressionStatement( - arkts.factory.createCallExpression(thisSubscribedWatchesMember(methodName), undefined, [ - arkts.factory.createIdentifier(paramName), - ]) - ), - ]), - arkts.factory.createFunctionSignature( - undefined, - [ - arkts.factory.createParameterDeclaration( - arkts.factory.createIdentifier( - paramName, - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart(arkts.factory.createIdentifier(paramType)) - ) - ), - undefined - ), - ], - arkts.factory.createPrimitiveType(returnType), - false - ), - arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD, - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC - ), - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, - false - ); -} - -function createWatchMembers(): arkts.AstNode[] { - const subscribedWatches: arkts.ClassProperty = arkts.factory.createClassProperty( - arkts.factory.createIdentifier('subscribedWatches'), - arkts.factory.createETSNewClassInstanceExpression( - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart(arkts.factory.createIdentifier('SubscribedWatches')) - ), - [] - ), - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart(arkts.factory.createIdentifier('SubscribedWatches')) - ), - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE, - false - ); - - const addWatchSubscriber = createWatchMethod( - 'addWatchSubscriber', - arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID, - 'watchId', - 'WatchIdType', - false - ); - - const removeWatchSubscriber = createWatchMethod( - 'removeWatchSubscriber', - arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_BOOLEAN, - 'watchId', - 'WatchIdType', - true - ); - - const executeOnSubscribingWatches = createWatchMethod( - 'executeOnSubscribingWatches', - arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID, - 'propertyName', - 'string', - false - ); - - return [subscribedWatches, addWatchSubscriber, removeWatchSubscriber, executeOnSubscribingWatches]; -} - -function thisSubscribedWatchesMember(member: string): arkts.MemberExpression { - return arkts.factory.createMemberExpression( - arkts.factory.createMemberExpression( - arkts.factory.createThisExpression(), - arkts.factory.createIdentifier('subscribedWatches'), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ), - arkts.factory.createIdentifier(member), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ); -} - -/** - * @deprecated - */ function tranformClassMembers( node: arkts.ClassDeclaration, isDecl?: boolean, - scope?: CustomComponentScopeInfo + scope?: ScopeInfo ): arkts.ClassDeclaration { if (!node.definition) { return node; @@ -383,9 +175,6 @@ function tranformClassMembers( return arkts.factory.updateClassDeclaration(node, updateClassDef); } -/** - * @deprecated - */ function transformOtherMembersInClass( member: arkts.AstNode, classTypeName: string | undefined, @@ -415,15 +204,12 @@ function transformOtherMembersInClass( return member; } -/** - * @deprecated - */ function tranformPropertyMembers( className: string, propertyTranslators: PropertyTranslator[], optionsTypeName: string, isDecl?: boolean, - scope?: CustomComponentScopeInfo + scope?: ScopeInfo ): arkts.AstNode[] { const propertyMembers = propertyTranslators.map((translator) => translator.translateMember()); const currentStructInfo: arkts.StructInfo = arkts.GlobalInfo.getInfoInstance().getStructInfo(className); @@ -440,9 +226,22 @@ function tranformPropertyMembers( return collect(...collections, ...propertyMembers); } -/** - * @deprecated - */ +function transformBuilderLambdaMethodDecl(node: arkts.MethodDefinition): arkts.AstNode { + const func: arkts.ScriptFunction = node.scriptFunction; + const isFunctionCall: boolean = isBuilderLambdaFunctionCall(node); + const typeNode: arkts.TypeNode | undefined = builderLambdaMethodDeclType(node); + const styleArg: arkts.ETSParameterExpression = builderLambdaFactory.createStyleArgInBuilderLambdaDecl( + typeNode, + isFunctionCall + ); + return builderLambdaFactory.updateBuilderLambdaMethodDecl( + node, + styleArg, + removeAnnotationByName(func.annotations, BuilderLambdaNames.ANNOTATION_NAME), + replaceBuilderLambdaDeclMethodName(node.name.name) + ); +} + function transformEtsGlobalClassMembers(node: arkts.ClassDeclaration): arkts.ClassDeclaration { if (!node.definition) { return node; @@ -456,9 +255,6 @@ function transformEtsGlobalClassMembers(node: arkts.ClassDeclaration): arkts.Cla return node; } -/** - * @deprecated - */ function transformResource( resourceNode: arkts.CallExpression, projectConfig: ProjectConfig | undefined @@ -470,3 +266,204 @@ function transformResource( ]; return structFactory.generateTransformedResource(resourceNode, newArgs); } + +function transformBuilderLambda(node: arkts.CallExpression, isExternal?: boolean): arkts.AstNode { + let instanceCalls: arkts.CallExpression[] = []; + let leaf: arkts.CallExpression = node; + + while ( + true && + arkts.isMemberExpression(leaf.expression) && + arkts.isIdentifier(leaf.expression.property) && + arkts.isCallExpression(leaf.expression.object) + ) { + instanceCalls.push(arkts.factory.createCallExpression(leaf.expression.property, undefined, leaf.arguments)); + leaf = leaf.expression.object; + } + + const replace: arkts.Identifier | arkts.MemberExpression | undefined = builderLambdaReplace(leaf); + const declInfo: BuilderLambdaDeclInfo | undefined = findBuilderLambdaDeclInfo(leaf); + if (!replace || !declInfo) { + return node; + } + let lambdaBody: arkts.Identifier | arkts.CallExpression | undefined; + if (instanceCalls.length > 0) { + instanceCalls = instanceCalls.reverse(); + lambdaBody = arkts.factory.createIdentifier(BuilderLambdaNames.STYLE_ARROW_PARAM_NAME); + instanceCalls.forEach((call) => { + if (!arkts.isIdentifier(call.expression)) { + throw new Error('call expression should be identifier'); + } + lambdaBody = builderLambdaFactory.createStyleLambdaBody(lambdaBody!, call); + }); + } + const args: (arkts.AstNode | undefined)[] = generateArgsInBuilderLambda(leaf, lambdaBody!, declInfo, isExternal); + return arkts.factory.updateCallExpression(node, replace, undefined, filterDefined(args)); +} + +function builderLambdaReplace(leaf: arkts.CallExpression): arkts.Identifier | arkts.MemberExpression | undefined { + if (!callIsGoodForBuilderLambda(leaf)) { + return undefined; + } + const node = leaf.expression; + const funcName = builderLambdaFunctionName(leaf); + if (!funcName) { + return undefined; + } + if (arkts.isIdentifier(node)) { + return arkts.factory.createIdentifier(funcName); + } + if (arkts.isMemberExpression(node)) { + return arkts.factory.createMemberExpression( + node.object, + arkts.factory.createIdentifier(funcName), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + node.computed, + node.optional + ); + } + return undefined; +} + +function generateArgsInBuilderLambda( + leaf: arkts.CallExpression, + lambdaBody: arkts.Identifier | arkts.CallExpression, + declInfo: BuilderLambdaDeclInfo, + isExternal?: boolean +): (arkts.AstNode | undefined)[] { + const { params } = declInfo; + const typeNode: arkts.TypeNode | undefined = builderLambdaType(leaf); + const typeName: string | undefined = builderLambdaTypeName(leaf); + const args: (arkts.AstNode | undefined)[] = [ + builderLambdaFactory.createStyleArgInBuilderLambda(lambdaBody, typeNode), + ]; + let index = 0; + while (index < params.length) { + const isReusable: boolean = typeName + ? arkts.GlobalInfo.getInfoInstance().getStructInfo(typeName).isReusable + : false; + if (isReusable && index === params.length - 1) { + const reuseId = arkts.factory.createStringLiteral(typeName!); + args.push(createOrUpdateArgInBuilderLambda(leaf.arguments.at(index), isExternal, typeName, reuseId)); + } else { + args.push(createOrUpdateArgInBuilderLambda(leaf.arguments.at(index), isExternal, typeName)); + } + index++; + } + return args; +} + +function createOrUpdateArgInBuilderLambda( + arg: arkts.Expression | undefined, + isExternal?: boolean, + typeName?: string, + fallback?: arkts.AstNode +): arkts.AstNode { + if (!arg) { + return fallback ?? arkts.factory.createUndefinedLiteral(); + } + if (arkts.isArrowFunctionExpression(arg)) { + return processArgArrowFunction(arg, isExternal); + } + if (arkts.isTSAsExpression(arg)) { + return processArgTSAsExpression(arg, typeName!); + } + return arg; +} + +function processArgArrowFunction( + arg: arkts.ArrowFunctionExpression, + isExternal?: boolean +): arkts.ArrowFunctionExpression { + const func: arkts.ScriptFunction = arg.scriptFunction; + const updateFunc = arkts.factory.updateScriptFunction( + func, + !!func.body && arkts.isBlockStatement(func.body) + ? arkts.factory.updateBlock( + func.body, + func.body.statements.map((st) => updateContentBodyInBuilderLambda(st, isExternal)) + ) + : undefined, + arkts.FunctionSignature.createFunctionSignature(func.typeParams, func.params, func.returnTypeAnnotation, false), + func.flags, + func.modifiers + ); + return arkts.factory.updateArrowFunction(arg, updateFunc); +} + +function processArgTSAsExpression(arg: arkts.TSAsExpression, typeName: string): arkts.TSAsExpression { + if (!arg.expr || !arkts.isObjectExpression(arg.expr)) { + return arg; + } + const currentStructInfo: arkts.StructInfo = arkts.GlobalInfo.getInfoInstance().getStructInfo(typeName!); + const properties = arg.expr.properties as arkts.Property[]; + properties.forEach((prop, index) => { + updateParameterPassing(prop, index, currentStructInfo, properties); + }); + const updatedExpr: arkts.ObjectExpression = arkts.ObjectExpression.updateObjectExpression( + arg.expr, + arkts.Es2pandaAstNodeType.AST_NODE_TYPE_OBJECT_EXPRESSION, + properties, + false + ); + return arkts.TSAsExpression.updateTSAsExpression(arg, updatedExpr, arg.typeAnnotation, arg.isConst); +} + +function updateContentBodyInBuilderLambda(statement: arkts.Statement, isExternal?: boolean): arkts.Statement { + if ( + arkts.isExpressionStatement(statement) && + arkts.isCallExpression(statement.expression) && + isBuilderLambda(statement.expression, isExternal) + ) { + return arkts.factory.updateExpressionStatement(statement, transformBuilderLambda(statement.expression)); + } + // TODO: very time-consuming... + if (arkts.isIfStatement(statement)) { + return updateIfElseContentBodyInBuilderLambda(statement, isExternal); + } + + return statement; +} + +function updateParameterPassing( + prop: arkts.Property, + index: number, + currentStructInfo: arkts.StructInfo, + properties: arkts.Property[] +): void { + if ( + prop.key && + prop.value && + arkts.isIdentifier(prop.key) && + arkts.isMemberExpression(prop.value) && + arkts.isThisExpression(prop.value.object) && + arkts.isIdentifier(prop.value.property) + ) { + const structVariableMetadata = currentStructInfo.metadata[prop.key.name]; + if (structVariableMetadata.properties.includes(DecoratorNames.LINK)) { + properties[index] = arkts.Property.updateProperty( + prop, + arkts.factory.createIdentifier(backingField(prop.key.name)), + builderLambdaFactory.updateBackingMember(prop.value, prop.value.property.name) + ); + } + } +} + +// TODO: very time-consuming... +function updateIfElseContentBodyInBuilderLambda(statement: arkts.AstNode, isExternal?: boolean): arkts.AstNode { + if (arkts.isIfStatement(statement)) { + const alternate = !!statement.alternate + ? updateIfElseContentBodyInBuilderLambda(statement.alternate, isExternal) + : statement.alternate; + const consequence = updateIfElseContentBodyInBuilderLambda(statement.consequent, isExternal); + return arkts.factory.updateIfStatement(statement, statement.test, consequence!, alternate); + } + if (arkts.isBlockStatement(statement)) { + return arkts.factory.updateBlock( + statement, + statement.statements.map((st) => updateContentBodyInBuilderLambda(st, isExternal)) + ); + } + return statement; +} diff --git a/arkui-plugins/ui-plugins/component-transformer.ts b/arkui-plugins/ui-plugins/component-transformer.ts index 46c7bfbf2..5208f9995 100644 --- a/arkui-plugins/ui-plugins/component-transformer.ts +++ b/arkui-plugins/ui-plugins/component-transformer.ts @@ -34,9 +34,6 @@ import { collectPropertyDecorators, } from './property-translators/utils'; import { factory } from './ui-factory'; -import { StructMap } from '../common/program-visitor'; -import { generateTempCallFunction } from './interop'; -import { stringify } from 'querystring'; export interface ComponentTransformerOptions extends VisitorOptions { arkui?: string; @@ -53,14 +50,6 @@ interface ComponentContext { structMembers: Map; } -export interface InteropContext { - className: string; - path: string; - line?: number; - col?: number; - arguments?: arkts.ObjectExpression; -} - export class ComponentTransformer extends AbstractVisitor { private scopeInfos: ScopeInfo[] = []; private componentInterfaceCollection: arkts.TSInterfaceDeclaration[] = []; @@ -70,9 +59,6 @@ export class ComponentTransformer extends AbstractVisitor { private context: ComponentContext = { structMembers: new Map() }; private isCustomComponentImported: boolean = false; private isEntryPointImported: boolean = false; - private hasLegacy = false; - private legacyStructMap: Map = new Map(); - private legacyCallMap: Map = new Map(); constructor(options?: ComponentTransformerOptions) { const _options: ComponentTransformerOptions = options ?? {}; @@ -89,9 +75,6 @@ export class ComponentTransformer extends AbstractVisitor { this.context = { structMembers: new Map() }; this.isCustomComponentImported = false; this.isEntryPointImported = false; - this.hasLegacy = false; - this.legacyStructMap = new Map(); - this.legacyCallMap = new Map(); } enter(node: arkts.AstNode) { @@ -203,7 +186,7 @@ export class ComponentTransformer extends AbstractVisitor { return arkts.factory.createMethodDefinition( arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_METHOD, arkts.factory.createIdentifier(CustomComponentNames.BUILDCOMPATIBLENODE), - script, + arkts.factory.createFunctionExpression(script), arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC | arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_STATIC, false ); @@ -264,14 +247,14 @@ export class ComponentTransformer extends AbstractVisitor { definition: arkts.ClassDefinition, newDefinitionBody: arkts.AstNode[] ): arkts.ClassDefinition { - const staticMethodBody: arkts.AstNode[] = []; + const staticMethonBody: arkts.AstNode[] = []; const hasExportFlag = (node.modifiers & arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_EXPORT) === arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_EXPORT; if (hasExportFlag) { const buildCompatibleNode: arkts.MethodDefinition = this.createStaticMethod(definition); if (!!buildCompatibleNode) { - staticMethodBody.push(buildCompatibleNode); + staticMethonBody.push(buildCompatibleNode); } } return arkts.factory.updateClassDefinition( @@ -298,11 +281,7 @@ export class ComponentTransformer extends AbstractVisitor { ]) ) ), - [ - ...newDefinitionBody, - ...definition.body.map((st: arkts.AstNode) => factory.PreprocessClassPropertyModifier(st)), - ...staticMethodBody, - ], + [...newDefinitionBody, ...definition.body, ...staticMethonBody], definition.modifiers, arkts.classDefinitionFlags(definition) | arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_FINAL ); @@ -328,9 +307,6 @@ export class ComponentTransformer extends AbstractVisitor { } node.definition.body.map((it) => { if (arkts.isClassProperty(it)) { - if (hasDecorator(it, DecoratorNames.PROVIDE)) { - factory.processNoAliasProvideVariable(it); - } this.context.structMembers.get(className)!.push(...this.createInterfaceInnerMember(it, structInfo)); } }); @@ -360,34 +336,12 @@ export class ComponentTransformer extends AbstractVisitor { ); return [originMember, newMember]; } - if (hasDecorator(member, DecoratorNames.BUILDER_PARAM) && !!originMember.typeAnnotation) { - originMember.typeAnnotation.setAnnotations([annotation('memo')]); + if (hasDecorator(member, DecoratorNames.BUILDER_PARAM)) { + originMember.setAnnotations([annotation('memo')]); } return [originMember]; } - registerMap(map: Map): void { - this.legacyStructMap = map; - this.hasLegacy = true; - } - - processImport(node: arkts.ETSImportDeclaration): void { - const source = node.source?.str!; - const specifiers = node.specifiers; - if (this.legacyStructMap.has(source)) { - const structMap = this.legacyStructMap.get(source); - if (!structMap) { - return; - } - for (const specifier of specifiers) { - const name = specifier.local.name; - if (structMap[name]) { - this.legacyCallMap.set(name, structMap[name]); - } - } - } - } - visitor(node: arkts.AstNode): arkts.AstNode { this.enter(node); const newNode = this.visitEachChild(node); @@ -399,32 +353,6 @@ export class ComponentTransformer extends AbstractVisitor { this.exit(newNode); return updateNode; } - if (!this.hasLegacy) { - return newNode; - } - if (arkts.isETSImportDeclaration(newNode)) { - this.processImport(newNode); - } - if (arkts.isCallExpression(newNode)) { - const ident = newNode.expression; - if (!(ident instanceof arkts.Identifier)) { - return newNode; - } - const className = ident.name; - if (this.legacyCallMap.has(className)) { - const path = this.legacyCallMap.get(className)!; - // const pathName = 'path/har1'; - const args = newNode.arguments; - const context: InteropContext = { - className: className, - path: path, - arguments: args && args.length === 1 && args[0] instanceof arkts.ObjectExpression - ? args[0] - : undefined - }; - return generateTempCallFunction(context); - } - } return newNode; } } diff --git a/arkui-plugins/ui-plugins/entry-translators/factory.ts b/arkui-plugins/ui-plugins/entry-translators/factory.ts index fca4fe867..e2d04b3d2 100644 --- a/arkui-plugins/ui-plugins/entry-translators/factory.ts +++ b/arkui-plugins/ui-plugins/entry-translators/factory.ts @@ -108,7 +108,7 @@ export class factory { const def = arkts.factory.createMethodDefinition( arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_METHOD, key, - entryScript, + arkts.factory.createFunctionExpression(entryScript), arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, false ); @@ -132,7 +132,7 @@ export class factory { const def = arkts.factory.createMethodDefinition( arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_CONSTRUCTOR, key, - entryScript, + arkts.factory.createFunctionExpression(entryScript), arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, false ); diff --git a/arkui-plugins/ui-plugins/entry-translators/utils.ts b/arkui-plugins/ui-plugins/entry-translators/utils.ts index 61a03783c..c3b1dfbef 100644 --- a/arkui-plugins/ui-plugins/entry-translators/utils.ts +++ b/arkui-plugins/ui-plugins/entry-translators/utils.ts @@ -23,7 +23,7 @@ export enum EntryWrapperNames { WRAPPER_CLASS_NAME = '__EntryWrapper', ENTRY_STORAGE_ANNOTATION_KEY = 'storage', ENTRY_STORAGE_LOCAL_STORAGE_PROPERTY_NAME = '_entry_local_storage_', - ENTRY_DEFAULT_IMPORT = 'arkui.UserView', + ENTRY_DEFAULT_IMPORT = '@ohos.arkui.component', ENTRY_POINT_CLASS_NAME = 'EntryPoint', } diff --git a/arkui-plugins/ui-plugins/index.ts b/arkui-plugins/ui-plugins/index.ts index 1397e89c2..76e2e6883 100644 --- a/arkui-plugins/ui-plugins/index.ts +++ b/arkui-plugins/ui-plugins/index.ts @@ -17,7 +17,7 @@ import * as arkts from '@koalaui/libarkts'; import { ComponentTransformer } from './component-transformer'; import { PreprocessorTransformer } from './preprocessor-transform'; import { CheckedTransformer } from './checked-transformer'; -import { Plugins, PluginContext, ProjectConfig } from '../common/plugin-context'; +import { Plugins, PluginContext } from '../common/plugin-context'; import { ProgramVisitor } from '../common/program-visitor'; import { EXTERNAL_SOURCE_PREFIX_NAMES } from '../common/predefines'; import { debugDump, debugLog, getDumpFileName } from '../common/debug'; @@ -50,7 +50,16 @@ function parsedTransform(this: PluginContext): arkts.EtsScript | undefined { program.programFileNameWithExtension ); arkts.Performance.getInstance().createEvent('ui-parsed'); - program = parsedProgramVisit(program, this); + const componentTransformer = new ComponentTransformer(); + const preprocessorTransformer = new PreprocessorTransformer(); + const programVisitor = new ProgramVisitor({ + pluginName: uiTransform.name, + state: arkts.Es2pandaContextState.ES2PANDA_STATE_PARSED, + visitors: [componentTransformer, preprocessorTransformer], + skipPrefixNames: EXTERNAL_SOURCE_PREFIX_NAMES, + pluginContext: this, + }); + program = programVisitor.programVisitor(program); script = program.astNode; arkts.Performance.getInstance().stopEvent('ui-parsed', true); debugLog('[AFTER PARSED SCRIPT] script: ', script.dumpSrc()); @@ -69,29 +78,6 @@ function parsedTransform(this: PluginContext): arkts.EtsScript | undefined { return script; } -function parsedProgramVisit( - program: arkts.Program, - context: PluginContext, - canSkipPhases: boolean = false -): arkts.Program { - if (canSkipPhases) { - debugLog('[SKIP PHASE] phase: ui-parsed, moduleName: ', program.moduleName); - } else { - debugLog('[CANT SKIP PHASE] phase: ui-parsed, moduleName: ', program.moduleName); - const componentTransformer = new ComponentTransformer(); - const preprocessorTransformer = new PreprocessorTransformer(); - const programVisitor = new ProgramVisitor({ - pluginName: uiTransform.name, - state: arkts.Es2pandaContextState.ES2PANDA_STATE_PARSED, - visitors: [componentTransformer, preprocessorTransformer], - skipPrefixNames: EXTERNAL_SOURCE_PREFIX_NAMES, - pluginContext: context, - }); - program = programVisitor.programVisitor(program); - } - return program; -} - function checkedTransform(this: PluginContext): arkts.EtsScript | undefined { let script: arkts.EtsScript | undefined; console.log('[UI PLUGIN] AFTER CHECKED ENTER'); @@ -109,7 +95,15 @@ function checkedTransform(this: PluginContext): arkts.EtsScript | undefined { program.programFileNameWithExtension ); arkts.Performance.getInstance().createEvent('ui-checked'); - program = checkedProgramVisit(program, this); + const checkedTransformer = new CheckedTransformer(this.getProjectConfig()); + const programVisitor = new ProgramVisitor({ + pluginName: uiTransform.name, + state: arkts.Es2pandaContextState.ES2PANDA_STATE_CHECKED, + visitors: [checkedTransformer], + skipPrefixNames: EXTERNAL_SOURCE_PREFIX_NAMES, + pluginContext: this, + }); + program = programVisitor.programVisitor(program); script = program.astNode; arkts.Performance.getInstance().stopEvent('ui-checked', true); debugLog('[AFTER STRUCT SCRIPT] script: ', script.dumpSrc()); @@ -132,26 +126,3 @@ function checkedTransform(this: PluginContext): arkts.EtsScript | undefined { console.log('[UI PLUGIN] AFTER CHECKED EXIT WITH NO TRANSFORM'); return script; } - -function checkedProgramVisit( - program: arkts.Program, - context: PluginContext, - canSkipPhases: boolean = false -): arkts.Program { - if (canSkipPhases) { - debugLog('[SKIP PHASE] phase: ui-checked, moduleName: ', program.moduleName); - } else { - debugLog('[CANT SKIP PHASE] phase: ui-checked, moduleName: ', program.moduleName); - const projectConfig: ProjectConfig | undefined = context.getProjectConfig(); - const checkedTransformer = new CheckedTransformer(projectConfig); - const programVisitor = new ProgramVisitor({ - pluginName: uiTransform.name, - state: arkts.Es2pandaContextState.ES2PANDA_STATE_CHECKED, - visitors: [checkedTransformer], - skipPrefixNames: EXTERNAL_SOURCE_PREFIX_NAMES, - pluginContext: context, - }); - program = programVisitor.programVisitor(program); - } - return program; -} \ No newline at end of file diff --git a/arkui-plugins/ui-plugins/initstatevar.ts b/arkui-plugins/ui-plugins/initstatevar.ts deleted file mode 100644 index 3264db1a2..000000000 --- a/arkui-plugins/ui-plugins/initstatevar.ts +++ /dev/null @@ -1,290 +0,0 @@ -/* - * Copyright (c) 2022-2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - - -import * as arkts from '@koalaui/libarkts'; -import { InteroperAbilityNames } from '../common/predefines'; -import { annotation, backingField, isAnnotation } from '../common/arkts-utils'; -import { getPropertyESValue, getWrapValue, setPropertyESValue } from './interop'; - - -export function processNormal(keyName: string, value: arkts.AstNode): arkts.Statement[] { - const result: arkts.Statement[] = []; - const setProperty = setPropertyESValue( - InteroperAbilityNames.PARAM, - keyName, - getWrapValue(value) - ); - result.push(setProperty); - return result; -} - -export function createVariableLet(varName: string, expression: arkts.AstNode): arkts.VariableDeclaration { - return arkts.factory.createVariableDeclaration( - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, - arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_LET, - [arkts.factory.createVariableDeclarator( - arkts.Es2pandaVariableDeclaratorFlag.VARIABLE_DECLARATOR_FLAG_LET, - arkts.factory.createIdentifier(varName), - expression - )] - ); -} -export function setValueCallback(name: string, type: arkts.TypeNode, block: arkts.BlockStatement): arkts.AstNode { - return createVariableLet(name, - arkts.factory.createArrowFunction( - arkts.factory.createScriptFunction( - block, - arkts.factory.createFunctionSignature( - undefined, - [ - arkts.factory.createParameterDeclaration( - arkts.factory.createIdentifier('value', type), - undefined, - ), - ], - undefined, - false - ), - arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, - ) - ) - ); -} - -function createProxyBlock(varName: string): arkts.BlockStatement { - return arkts.factory.createBlock( - [ - arkts.factory.createExpressionStatement( - arkts.factory.createAssignmentExpression( - arkts.factory.createMemberExpression( - arkts.factory.createThisExpression(), - arkts.factory.createIdentifier(varName), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ), - arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - arkts.factory.createIdentifier('value') - ) - ) - ] - ); -} - -export function setCallbackForProxy(varName: string, type: arkts.TypeNode): arkts.Statement[] { - const createCallback = setValueCallback(addStatePrefix(varName, 'SetSource'), type, createProxyBlock(varName)); - const createProxyState = createVariableLet(addStatePrefix(varName, 'ProxyState'), - arkts.factory.createCallExpression( - arkts.factory.createMemberExpression( - arkts.factory.createIdentifier('createState'), - arkts.factory.createIdentifier('invoke'), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ), - undefined, - [ - getWrapValue( - arkts.factory.createMemberExpression( - arkts.factory.createThisExpression(), - arkts.factory.createIdentifier(varName), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ) - ), - getWrapValue(arkts.factory.createIdentifier(addStatePrefix(varName, 'SetSource'))) - ] - ) - ); - const setProxy = arkts.factory.createExpressionStatement( - arkts.factory.createCallExpression( - arkts.factory.createMemberExpression( - arkts.factory.createTSNonNullExpression( - arkts.factory.createMemberExpression( - arkts.factory.createThisExpression(), - arkts.factory.createIdentifier(backingField(varName)), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ) - ), - arkts.factory.createIdentifier('setProxy'), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ), - undefined, - [arkts.factory.createIdentifier(addStatePrefix(varName, 'ProxyState'))], - ) - ); - return [createCallback, createProxyState, setProxy]; -} - -function createSourceBlock(varName: string): arkts.BlockStatement { - return arkts.factory.createBlock( - [ - arkts.factory.createExpressionStatement( - arkts.factory.createCallExpression( - arkts.factory.createMemberExpression( - arkts.factory.createIdentifier(addStatePrefix(varName, 'ProxyState')), - arkts.factory.createIdentifier('invokeMethod'), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ), - undefined, - [ - arkts.factory.createStringLiteral('set'), - getWrapValue( - arkts.factory.createIdentifier('value') - ) - ] - ) - ) - ] - ); -} - -function createNotifyBlock(varName: string): arkts.BlockStatement { - return arkts.factory.createBlock( - [ - arkts.factory.createExpressionStatement( - arkts.factory.createCallExpression( - arkts.factory.createMemberExpression( - arkts.factory.createIdentifier(addStatePrefix(varName, 'ProxyState')), - arkts.factory.createIdentifier('invokeMethod'), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ), - undefined, - [ - arkts.factory.createStringLiteral('notifyPropertyHasChangedPU') - ] - ) - ) - ] - ); -} - -function setNotifyForSource(varName: string): arkts.Statement[] { - const block = createNotifyBlock(varName); - const createCallback = createVariableLet(addStatePrefix(varName, 'NotifyCallback'), - arkts.factory.createArrowFunction( - arkts.factory.createScriptFunction( - block, - arkts.factory.createFunctionSignature( - undefined, - [ - arkts.factory.createParameterDeclaration( - arkts.factory.createIdentifier('propertyName', - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier('string') - ) - ) - ), - undefined, - ), - ], - undefined, - false - ), - arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, - ) - ) - ); - const setCallback = arkts.factory.createExpressionStatement( - arkts.factory.createCallExpression( - arkts.factory.createMemberExpression( - arkts.factory.createTSNonNullExpression( - arkts.factory.createMemberExpression( - arkts.factory.createThisExpression(), - arkts.factory.createIdentifier(backingField(varName)), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ) - ), - arkts.factory.createIdentifier('setNotifyCallback'), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ), - undefined, - [arkts.factory.createIdentifier(addStatePrefix(varName, 'NotifyCallback'))], - ) - ); - return [createCallback, setCallback]; -} - -export function setCallbackForSource(varName: string, type: arkts.TypeNode): arkts.Statement[] { - const createCallback = setValueCallback(addStatePrefix(varName, 'SetProxy'), type, createSourceBlock(varName)); - const setFunc = arkts.factory.createExpressionStatement( - arkts.factory.createAssignmentExpression( - arkts.factory.createMemberExpression( - arkts.factory.createTSNonNullExpression( - arkts.factory.createMemberExpression( - arkts.factory.createThisExpression(), - arkts.factory.createIdentifier(backingField(varName)), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ) - ), - arkts.factory.createIdentifier('setProxyValue'), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ), - arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - arkts.factory.createIdentifier(addStatePrefix(varName, 'SetProxy')) - ) - ); - const setNotify = setNotifyForSource(varName); - return [createCallback, setFunc, ...setNotify]; -} - -export function processLink(keyName: string, value: arkts.AstNode, type: arkts.TypeNode, proxySet: Set): arkts.Statement[] { - const varName = ((value as arkts.MemberExpression).property as arkts.Identifier).name; - const result: arkts.Statement[] = []; - if (!proxySet.has(varName)) { - proxySet.add(varName); - const setProxy = setCallbackForProxy(varName, type); - result.push(...setProxy); - const setSource = setCallbackForSource(varName, type); - result.push(...setSource); - } - const setParam = setPropertyESValue( - 'param', - keyName, - arkts.factory.createIdentifier(addStatePrefix(varName, 'ProxyState')) - ); - result.push(setParam); - return result; -} - -export function hasLink(decorators: string[]): boolean { - return decorators.some(decorator => decorator === 'Link'); -} - -function addStatePrefix(stateVarName: string, name: string): string { - return `${stateVarName}_${name}`; -} \ No newline at end of file diff --git a/arkui-plugins/ui-plugins/interop.ts b/arkui-plugins/ui-plugins/interop.ts deleted file mode 100644 index d6c43d1c7..000000000 --- a/arkui-plugins/ui-plugins/interop.ts +++ /dev/null @@ -1,595 +0,0 @@ -/* - * Copyright (c) 2022-2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - - -import * as arkts from '@koalaui/libarkts'; -import { InteroperAbilityNames } from '../common/predefines'; -import { getCustomComponentOptionsName } from './utils'; -import { InteropContext } from './component-transformer'; -import { annotation, backingField, isAnnotation } from '../common/arkts-utils'; -import { hasLink, processLink, processNormal } from './initstatevar'; - -interface propertyInfo { - decorators: string[], - type: arkts.TypeNode, -} - -export function createEmptyESValue(name: string): arkts.VariableDeclaration { - return arkts.factory.createVariableDeclaration( - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, - arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_LET, - [ - arkts.factory.createVariableDeclarator( - arkts.Es2pandaVariableDeclaratorFlag.VARIABLE_DECLARATOR_FLAG_LET, - arkts.factory.createIdentifier(name), - arkts.factory.createCallExpression( - arkts.factory.createMemberExpression( - arkts.factory.createIdentifier(InteroperAbilityNames.ESVALUE), - arkts.factory.createIdentifier(InteroperAbilityNames.INITEMPTYOBJECT), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ), - undefined, - undefined - ) - ) - ] - ); -} - -export function getWrapValue(value: arkts.AstNode): arkts.AstNode { - return arkts.factory.createCallExpression( - arkts.factory.createMemberExpression( - arkts.factory.createIdentifier(InteroperAbilityNames.ESVALUE), - arkts.factory.createIdentifier(InteroperAbilityNames.WRAP), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ), - undefined, - [value] - ); -} - -export function setPropertyESValue(name: string, key: string, wrapValue: arkts.AstNode): arkts.ExpressionStatement { - return arkts.factory.createExpressionStatement( - arkts.factory.createCallExpression( - arkts.factory.createMemberExpression( - arkts.factory.createIdentifier(name), - arkts.factory.createIdentifier(InteroperAbilityNames.SETPROPERTY), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ), - undefined, - [ - arkts.factory.createStringLiteral(key), - wrapValue - ] - ) - ); -} - -export function getPropertyESValue(result: string, object: string, key: string): arkts.VariableDeclaration { - return arkts.factory.createVariableDeclaration( - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, - arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_LET, - [ - arkts.factory.createVariableDeclarator( - arkts.Es2pandaVariableDeclaratorFlag.VARIABLE_DECLARATOR_FLAG_LET, - arkts.factory.createIdentifier(result), - arkts.factory.createCallExpression( - arkts.factory.createMemberExpression( - arkts.factory.createIdentifier(object), - arkts.factory.createIdentifier(InteroperAbilityNames.GETPROPERTY), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ), - undefined, - [arkts.factory.create1StringLiteral(key)] - ) - ) - ] - ); -} - -function initialArgs(args: arkts.ObjectExpression, varMap: Map): arkts.Statement[] { - const result: arkts.Statement[] = [ - createEmptyESValue(InteroperAbilityNames.PARAM), - getPropertyESValue('createState', 'global', 'createStateVariable') - ]; - - const proxySet = new Set(); - - for (const property of args.properties) { - if (!(property instanceof arkts.Property)) { - continue; - } - const key = property.key; - const value = property.value; - if (!(key instanceof arkts.Identifier)) { - throw Error('Error arguments in Legacy Component'); - } - const name = key.name; - const decorators = varMap.get(name)?.decorators; - const type = varMap.get(name)?.type!; - if (decorators !== undefined && hasLink(decorators)) { - const initParam = processLink(key.name, value!, type, proxySet); - result.push(...initParam); - } else { - const initParam = processNormal(key.name, value!); - result.push(...initParam); - } - } - return result; -} - -function instantiateComponent(params: arkts.AstNode[]): arkts.VariableDeclaration { - return arkts.factory.createVariableDeclaration( - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, - arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_LET, - [ - arkts.factory.createVariableDeclarator( - arkts.Es2pandaVariableDeclaratorFlag.VARIABLE_DECLARATOR_FLAG_LET, - arkts.factory.createIdentifier(InteroperAbilityNames.COMPONENT), - arkts.factory.createCallExpression( - arkts.factory.createMemberExpression( - arkts.factory.createIdentifier(InteroperAbilityNames.STRUCTOBJECT), - arkts.factory.createIdentifier(InteroperAbilityNames.INSTANTIATE), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ), - undefined, - params - ) - ) - ] - ); -} - -function paramsLambdaDeclaration(name: string, args?: arkts.ObjectExpression): arkts.Statement[] { - const result = []; - result.push( - arkts.factory.createVariableDeclaration( - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, - arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_LET, - [ - arkts.factory.createVariableDeclarator( - arkts.Es2pandaVariableDeclaratorFlag.VARIABLE_DECLARATOR_FLAG_LET, - arkts.factory.createIdentifier(InteroperAbilityNames.PARAMSLAMBDA), - arkts.factory.createArrowFunction( - arkts.factory.createScriptFunction( - arkts.factory.createBlock([arkts.factory.createReturnStatement( - args ? args : arkts.ObjectExpression.createObjectExpression( - arkts.Es2pandaAstNodeType.AST_NODE_TYPE_OBJECT_EXPRESSION, - [], - false - ), - )]), - arkts.factory.createFunctionSignature( - undefined, - [], - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier(getCustomComponentOptionsName(name)) - ) - ), - false - ), - arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, - ) - ) - ), - - ] - ) - ); - return result; -} - -function createInitReturn(componentName: string): arkts.ReturnStatement { - return arkts.factory.createReturnStatement( - arkts.ObjectExpression.createObjectExpression( - arkts.Es2pandaAstNodeType.AST_NODE_TYPE_OBJECT_EXPRESSION, - [ - arkts.Property.createProperty( - arkts.factory.createIdentifier(InteroperAbilityNames.COMPONENT), - arkts.factory.createIdentifier(InteroperAbilityNames.COMPONENT) - ), - arkts.Property.createProperty( - arkts.factory.createIdentifier('name'), - arkts.factory.createStringLiteral(componentName) - ) - ], - false - ), - ); -} - -function createExtraInfo(properties: string[], value: string[]): arkts.Statement[] { - const body: arkts.AstNode[] = []; - body.push(createEmptyESValue(InteroperAbilityNames.EXTRAINFO)); - properties.forEach((prop, index) => { - const val = value[index]; - body.push(setPropertyESValue( - InteroperAbilityNames.EXTRAINFO, - prop, - arkts.factory.createStringLiteral(val)) - ); - }); - return body; -} - -function createESParent(): arkts.Statement { - return arkts.factory.createVariableDeclaration( - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, - arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_LET, - [ - arkts.factory.createVariableDeclarator( - arkts.Es2pandaVariableDeclaratorFlag.VARIABLE_DECLARATOR_FLAG_LET, - arkts.factory.createIdentifier('esparent'), - getWrapValue(arkts.factory.createIdentifier(InteroperAbilityNames.PARENT)) - ) - ] - ); -} - -function createESUndefined(): arkts.Statement { - return arkts.factory.createVariableDeclaration( - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, - arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_LET, - [ - arkts.factory.createVariableDeclarator( - arkts.Es2pandaVariableDeclaratorFlag.VARIABLE_DECLARATOR_FLAG_LET, - arkts.factory.createIdentifier('esundefined'), - getWrapValue(arkts.factory.createUndefinedLiteral()) - ) - ] - ); -} - -function createESBlank(): arkts.Statement[] { - const body: arkts.Statement[] = []; - const blank = arkts.factory.createVariableDeclaration( - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, - arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_LET, - [ - arkts.factory.createVariableDeclarator( - arkts.Es2pandaVariableDeclaratorFlag.VARIABLE_DECLARATOR_FLAG_LET, - arkts.factory.createIdentifier('blank'), - arkts.factory.createArrowFunction( - arkts.factory.createScriptFunction( - arkts.factory.createBlock([]), - arkts.factory.createFunctionSignature( - undefined, - [], - undefined, - false - ), - arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, - ) - ) - ) - ] - ); - body.push(blank); - const asExpression = arkts.factory.createTSAsExpression( - arkts.factory.createIdentifier('blank'), - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier('object') - ) - ), - false - ); - const esblank = arkts.factory.createVariableDeclaration( - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, - arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_LET, - [ - arkts.factory.createVariableDeclarator( - arkts.Es2pandaVariableDeclaratorFlag.VARIABLE_DECLARATOR_FLAG_LET, - arkts.factory.createIdentifier('esblank'), - getWrapValue(asExpression) - ) - ] - ); - body.push(esblank); - return body; -} - -function createGlobal(): arkts.Statement { - return arkts.factory.createVariableDeclaration( - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, - arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_LET, - [arkts.factory.createVariableDeclarator( - arkts.Es2pandaVariableDeclaratorFlag.VARIABLE_DECLARATOR_FLAG_LET, - arkts.factory.createIdentifier('global'), - arkts.factory.createCallExpression( - arkts.factory.createMemberExpression( - arkts.factory.createIdentifier(InteroperAbilityNames.ESVALUE), - arkts.factory.createIdentifier('getGlobal'), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ), - undefined, - undefined - ) - )] - ); -} - -function createELMTID(): arkts.Statement[] { - const body: arkts.Statement[] = []; - const viewStackProcessor = getPropertyESValue('viewStackProcessor', 'global', 'ViewStackProcessor'); - body.push(viewStackProcessor); - const createId = getPropertyESValue('createId', 'viewStackProcessor', 'AllocateNewElmetIdForNextComponent'); - body.push(createId); - const elmtId = arkts.factory.createVariableDeclaration( - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, - arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_LET, - [arkts.factory.createVariableDeclarator( - arkts.Es2pandaVariableDeclaratorFlag.VARIABLE_DECLARATOR_FLAG_LET, - arkts.factory.createIdentifier(InteroperAbilityNames.ELMTID), - arkts.factory.createCallExpression( - arkts.factory.createMemberExpression( - arkts.factory.createIdentifier('createId'), - arkts.factory.createIdentifier('invoke'), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ), - undefined, - undefined - ) - )] - ); - body.push(elmtId); - return body; -} - -function createComponent(moduleName: string, className: string): arkts.Statement[] { - const body: arkts.Statement[] = []; - const module = arkts.factory.createVariableDeclaration( - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, - arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_LET, - [ - arkts.factory.createVariableDeclarator( - arkts.Es2pandaVariableDeclaratorFlag.VARIABLE_DECLARATOR_FLAG_LET, - arkts.factory.createIdentifier(moduleName), - arkts.factory.createCallExpression( - arkts.factory.createMemberExpression( - arkts.factory.createIdentifier(InteroperAbilityNames.ESVALUE), - arkts.factory.createIdentifier(InteroperAbilityNames.LOAD), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ), - undefined, - [arkts.factory.create1StringLiteral(InteroperAbilityNames.OHMURL)] - ) - ) - ] - ); - body.push(module); - const structObject = getPropertyESValue('structObject', moduleName, className); - body.push(structObject); - const component = instantiateComponent( - [ - arkts.factory.createIdentifier('esundefined'), - arkts.factory.createIdentifier(InteroperAbilityNames.PARAM), - arkts.factory.createIdentifier('esundefined'), - arkts.factory.createIdentifier(InteroperAbilityNames.ELMTID), - arkts.factory.createIdentifier('esblank'), - arkts.factory.createIdentifier(InteroperAbilityNames.EXTRAINFO) - ] - ); - body.push(component); - return body; -} - -function invokeViewPUCreate(): arkts.Statement[] { - const body: arkts.Statement[] = []; - const createMethod = getPropertyESValue('create', 'structObject', 'create'); - body.push(createMethod); - const viewPUCreate = arkts.factory.createExpressionStatement( - arkts.factory.createCallExpression( - arkts.factory.createMemberExpression( - arkts.factory.createIdentifier('create'), - arkts.factory.createIdentifier('invoke'), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ), - undefined, - [ - arkts.factory.createIdentifier('component') - ] - ) - ); - body.push(viewPUCreate); - return body; -} - -function createWrapperBlock(context: InteropContext, varMap: Map): arkts.BlockStatement { - const className = context.className; - const path = context.path; - const args = context.arguments; - const index = path.indexOf('/'); - if (index === -1) { - throw new Error('Error path of Legacy Component.'); - } - const moduleName = path.substring(0, index); - const initialArgsStatement = args ? initialArgs(args, varMap) : []; - return arkts.factory.createBlock( - [ - createGlobal(), - ...initialArgsStatement, - ...createExtraInfo(['page'], [path]), - createESUndefined(), - ...createESBlank(), - ...createELMTID(), - ...createComponent(moduleName, className), - ...invokeViewPUCreate(), - // ...paramsLambdaDeclaration(className, args), - // setPropertyESValue( - // 'component', - // 'paramsGenerator_', - // arkts.factory.createIdentifier(InteroperAbilityNames.PARAMSLAMBDA) - // ), - createInitReturn(className) - ] - ); -} - -function createInitializer(context: InteropContext, varMap: Map): arkts.ArrowFunctionExpression { - const block = createWrapperBlock(context, varMap); - return arkts.factory.createArrowFunction( - arkts.factory.createScriptFunction( - block, - arkts.factory.createFunctionSignature( - undefined, - [], - undefined, - false, - ), - arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, - ) - ); -} - -function createUpdater(esvalue: arkts.ETSTypeReference, varMap: Map): arkts.ArrowFunctionExpression { - return arkts.factory.createArrowFunction( - arkts.factory.createScriptFunction( - arkts.factory.createBlock( - [ - - ] - ), - arkts.factory.createFunctionSignature( - undefined, - [ - arkts.factory.createParameterDeclaration( - arkts.factory.createIdentifier(InteroperAbilityNames.INSTANCE, esvalue), - undefined, - ), - ], - undefined, - false, - ), - arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, - ) - ); -} - -function generateVarMap(node: arkts.Identifier): Map { - const decl = arkts.getDecl(node); - if (!(decl instanceof arkts.ClassDefinition)) { - throw Error("can't find legacy class declaration"); - } - const result = new Map(); - const definition = decl; - const body = definition.body; - body.forEach(node => { - if (node instanceof arkts.ClassProperty && node.key instanceof arkts.Identifier) { - const key = node.key.name; - const annotations = node.annotations; - const decorators: string[] = annotations.map(annotation => { - return (annotation.expr as arkts.Identifier).name; - }); - const type: arkts.TypeNode = node.typeAnnotation!; - result.set(key, {decorators: decorators, type: type}); - } - }); - return result; -} - -export function updateArkUICompatible(node: arkts.CallExpression): arkts.CallExpression { - const classInterop = (node.expression as arkts.MemberExpression).object as arkts.Identifier; - const className = classInterop.name; - const args = node.arguments; - const path = (args[0] as arkts.StringLiteral).str; - const line = args[1] instanceof arkts.UndefinedLiteral ? undefined : (args[1] as arkts.NumberLiteral).value; - const col = args[2] instanceof arkts.UndefinedLiteral ? undefined : (args[2] as arkts.NumberLiteral).value; - const options = args[3] instanceof arkts.UndefinedLiteral ? undefined : args[3] as arkts.ObjectExpression; - const context: InteropContext = { - className: className, - path: path, - line: line, - col: col, - arguments: options - }; - - const varMap: Map = generateVarMap(classInterop); - const esvalue = arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier(InteroperAbilityNames.ESVALUE) - ) - ); - const initializer = createInitializer(context, varMap); - const updater = createUpdater(esvalue, varMap); - return arkts.factory.updateCallExpression( - node, - arkts.factory.createIdentifier(InteroperAbilityNames.ARKUICOMPATIBLE), - undefined, - [ - initializer, - updater, - ] - ); -} - - -function generateStructInfo(context: InteropContext): arkts.AstNode[] { - const result: arkts.AstNode[] = [ - arkts.factory.createStringLiteral(context.path), - context.line ? arkts.factory.createIdentifier(context.line.toString()) : arkts.factory.createUndefinedLiteral(), - context.col ? arkts.factory.createIdentifier(context.col.toString()) : arkts.factory.createUndefinedLiteral(), - context.arguments ?? arkts.factory.createUndefinedLiteral() - ]; - return result; - -} - -export function generateTempCallFunction(context: InteropContext): arkts.CallExpression { - return arkts.factory.createCallExpression( - arkts.factory.createMemberExpression( - arkts.factory.createIdentifier(context.className), - arkts.factory.createIdentifier('instantiate_Interop'), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ), - undefined, - generateStructInfo(context) - ); -} - -export function isArkUICompatible(node: arkts.AstNode): boolean { - if (node instanceof arkts.CallExpression && node.expression instanceof arkts.MemberExpression && - node.expression.property instanceof arkts.Identifier && - node.expression.property.name === 'instantiate_Interop') { - return true; - } - return false; -} \ No newline at end of file diff --git a/arkui-plugins/ui-plugins/legacy-transformer.ts b/arkui-plugins/ui-plugins/legacy-transformer.ts deleted file mode 100644 index 10047677a..000000000 --- a/arkui-plugins/ui-plugins/legacy-transformer.ts +++ /dev/null @@ -1,254 +0,0 @@ -/* - * Copyright (c) 2022-2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as arkts from '@koalaui/libarkts'; -import { getInteropPath } from '../path'; -const interop = require(getInteropPath()); -const nullptr = interop.nullptr; -import { AbstractVisitor, VisitorOptions } from '../common/abstract-visitor'; -import { InteroperAbilityNames } from '../common/predefines'; -import { getCustomComponentOptionsName } from './utils'; - -interface LegacyTransformerOptions extends VisitorOptions { - structList?: string[] -} - -export class LegacyTransformer extends AbstractVisitor { - private structList: string[] = []; - private componentInterfaceCollection: arkts.TSInterfaceDeclaration[] = []; - - constructor(options?: LegacyTransformerOptions) { - const _options: LegacyTransformerOptions = options ?? {}; - super(_options); - this.structList = _options.structList ?? []; - } - - reset(): void { - super.reset(); - this.componentInterfaceCollection = []; - } - - getList(): string[] { - return this.structList; - } - - createParam(name: string, type: string): arkts.ETSParameterExpression { - return arkts.factory.createParameterDeclaration( - arkts.factory.createIdentifier( - name, - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier(type) - ) - ) - ), - undefined - ); - } - - createInteropMethod(name: string): arkts.MethodDefinition { - const path = this.createParam('path', 'string'); - const line = this.createParam('line', 'number'); - line.setOptional(true); - const col = this.createParam('col', 'number'); - col.setOptional(true); - const options = this.createParam('options', getCustomComponentOptionsName(name)); - options.setOptional(true); - - const script = arkts.factory.createScriptFunction( - arkts.factory.createBlock([]), - arkts.FunctionSignature.createFunctionSignature( - undefined, - [path, line, col, options], - arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), - false - ), - arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD, - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC | arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_STATIC - ); - - return arkts.factory.createMethodDefinition( - arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_METHOD, - arkts.factory.createIdentifier('instantiate_Interop'), - script, - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC | arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_STATIC, - false - ); - } - - generateMember(map: Map): arkts.ClassProperty[] { - const properties: arkts.ClassProperty[] = []; - - map.forEach((value, key) => { - const property = arkts.factory.createClassProperty( - arkts.factory.createIdentifier(key), - undefined, - value, - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC | - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_OPTIONAL, - false - ); - - properties.push(property); - }); - - return properties; - } - - generateComponentInterface(name: string, modifiers: number, map: Map): arkts.TSInterfaceDeclaration { - const interfaceNode = arkts.factory.createInterfaceDeclaration( - [], - arkts.factory.createIdentifier(getCustomComponentOptionsName(name)), - nullptr, // TODO: wtf - arkts.factory.createInterfaceBody([...(this.generateMember(map) || [])]), - false, - false - ); - interfaceNode.modifiers = modifiers; - return interfaceNode; - } - - processComponent(node: arkts.StructDeclaration): arkts.StructDeclaration | arkts.ClassDeclaration { - const definition: arkts.ClassDefinition = node.definition!; - const ident = definition.ident!; - const hasExportFlag = - (node.modifiers & arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_EXPORT) === - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_EXPORT; - if (hasExportFlag) { - this.structList.push(ident.name); - } - - const instantiate_Interop: arkts.MethodDefinition = this.createInteropMethod(ident.name); - - const newDefinition = arkts.factory.updateClassDefinition( - definition, - definition.ident, - definition.typeParams, - definition.superTypeParams, - definition.implements, - undefined, - definition.super, - [...definition.body, instantiate_Interop], - definition.modifiers, - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE - ); - - console.log('print legacyclass definition' + newDefinition.dumpSrc()); - - - //TODO: need check - if (arkts.isStructDeclaration(node)) { - const _node = arkts.factory.createClassDeclaration(newDefinition); - _node.modifiers = node.modifiers; - return _node; - } else { - return arkts.factory.updateClassDeclaration(node, newDefinition); - } - } - - processConstructor(node: arkts.MethodDefinition): arkts.MethodDefinition { - const esvalue = arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier(InteroperAbilityNames.ESVALUE) - ) - ); - const script = arkts.factory.createScriptFunction( - arkts.factory.createBlock([]), - arkts.factory.createFunctionSignature( - undefined, - [ - arkts.factory.createParameterDeclaration( - arkts.factory.createIdentifier(InteroperAbilityNames.PARENT, esvalue), - undefined, - ), - arkts.factory.createParameterDeclaration( - arkts.factory.createIdentifier(InteroperAbilityNames.PARAM, esvalue), - undefined, - ), - arkts.factory.createParameterDeclaration( - arkts.factory.createIdentifier('localStorage', esvalue), - undefined, - ), - arkts.factory.createParameterDeclaration( - arkts.factory.createIdentifier(InteroperAbilityNames.ELMTID, esvalue), - undefined, - ), - arkts.factory.createParameterDeclaration( - arkts.factory.createIdentifier(InteroperAbilityNames.PARAMSLAMBDA, esvalue), - undefined, - ), - arkts.factory.createParameterDeclaration( - arkts.factory.createIdentifier(InteroperAbilityNames.EXTRAINFO, esvalue), - undefined, - ) - ], undefined, false), - arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_CONSTRUCTOR, - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, - ); - return arkts.factory.updateMethodDefinition( - node, - node.kind, - node.name, - script, - node.modifiers, - false - ); - } - - collectComponentMembers(node: arkts.StructDeclaration, className: string): Map { - const result: Map = new Map(); - node.definition.body.map((it) => { - if (arkts.isClassProperty(it)) { - const name = (it.key as arkts.Identifier).name; - const type = it.typeAnnotation!; - result.set(name, type); - } - }); - return result; - } - - processEtsScript(node: arkts.EtsScript): arkts.EtsScript { - let updateStatements: arkts.AstNode[] = []; - if (this.componentInterfaceCollection.length > 0) { - updateStatements.push(...this.componentInterfaceCollection); - } - if (updateStatements.length > 0) { - return arkts.factory.updateEtsScript(node, [...node.statements, ...updateStatements]); - } - return node; - } - - visitor(node: arkts.AstNode): arkts.AstNode { - const newNode = this.visitEachChild(node); - if (arkts.isEtsScript(newNode)) { - return this.processEtsScript(newNode); - } - if (arkts.isStructDeclaration(newNode)) { - const className = node.definition?.ident?.name; - const memberMap = this.collectComponentMembers(node as arkts.StructDeclaration, className); - this.componentInterfaceCollection.push(this.generateComponentInterface(className, node.modifiers, memberMap)); - const updateNode = this.processComponent(newNode); - return updateNode; - } - if (arkts.isMethodDefinition(newNode)) { - const kind = newNode.kind; - if (kind === arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_CONSTRUCTOR) { - const updateNode = this.processConstructor(newNode); - return updateNode; - } - } - return newNode; - } -} \ No newline at end of file diff --git a/arkui-plugins/ui-plugins/preprocessor-transform.ts b/arkui-plugins/ui-plugins/preprocessor-transform.ts index 635a1e83a..394b2327b 100644 --- a/arkui-plugins/ui-plugins/preprocessor-transform.ts +++ b/arkui-plugins/ui-plugins/preprocessor-transform.ts @@ -17,13 +17,7 @@ import * as arkts from '@koalaui/libarkts'; import { AbstractVisitor, VisitorOptions } from '../common/abstract-visitor'; import { CustomComponentNames } from './utils'; import { factory } from './ui-factory'; -import { - ARKUI_COMPONENT_IMPORT_NAME, - IMPORT_SOURCE_MAP, - OUTPUT_DEPENDENCY_MAP, - ARKUI_STATEMANAGEMENT_IMPORT_NAME, - KIT_ARKUI_NAME, -} from '../common/predefines'; +import { ARKUI_COMPONENT_IMPORT_NAME, IMPORT_SOURCE_MAP, OUTPUT_DEPENDENCY_MAP } from '../common/predefines'; import { NameCollector } from './name-collector'; interface MemoImportCollection { @@ -55,8 +49,6 @@ export class PreprocessorTransformer extends AbstractVisitor { this.memoImportCollection = {}; this.localComponentNames = []; this.isMemoImportOnce = false; - IMPORT_SOURCE_MAP.clear(); - IMPORT_SOURCE_MAP.set('arkui.stateManagement.runtime', new Set(['memo', '__memo_context_type', '__memo_id_type'])); } isCustomConponentDecl(node: arkts.CallExpression): boolean { @@ -74,14 +66,8 @@ export class PreprocessorTransformer extends AbstractVisitor { } transformComponentCall(node: arkts.CallExpression): arkts.TSAsExpression | arkts.CallExpression { - if (node.arguments.length === 0 && node.trailingBlock) { - return arkts.factory.updateCallExpression(node, node.expression, node.typeArguments, [ - arkts.factory.createUndefinedLiteral(), - ]); - } else if (arkts.isObjectExpression(node.arguments[0])) { - const componentName: string = `${ - CustomComponentNames.COMPONENT_INTERFACE_PREFIX - }${node.expression.dumpSrc()}`; + if (arkts.isObjectExpression(node.arguments[0])) { + const componentName: string = `${CustomComponentNames.COMPONENT_INTERFACE_PREFIX}${node.expression.dumpSrc()}`; const newArg = arkts.factory.createTSAsExpression( node.arguments[0].clone(), arkts.factory.createTypeReference( @@ -89,10 +75,9 @@ export class PreprocessorTransformer extends AbstractVisitor { ), true ); - return arkts.factory.updateCallExpression(node, node.expression, node.typeArguments, [ - newArg, - ...node.arguments.slice(1), - ]); + return arkts.factory + .updateCallExpression(node, node.expression, node.typeArguments, [newArg, ...node.arguments.slice(1)]) + .setTralingBlock(node.trailingBlock); } else { return node; } @@ -121,7 +106,7 @@ export class PreprocessorTransformer extends AbstractVisitor { addDependencesImport(node: arkts.ETSImportDeclaration): void { if (!node.source) return; - const isFromCompImport: boolean = node.source.str === ARKUI_COMPONENT_IMPORT_NAME || node.source.str === KIT_ARKUI_NAME; + const isFromCompImport: boolean = node.source.str === ARKUI_COMPONENT_IMPORT_NAME; const structCollection: Set = arkts.GlobalInfo.getInfoInstance().getStructCollection(); node.specifiers.forEach((item: arkts.AstNode) => { if (!arkts.isImportSpecifier(item) || !item.imported?.name) return; @@ -134,14 +119,12 @@ export class PreprocessorTransformer extends AbstractVisitor { this.localComponentNames.push(item.local?.name ?? importName); } - if (structCollection.has(importName)) { + if (structCollection.has(importName) && this.isExternal === false) { const interfaceName: string = CustomComponentNames.COMPONENT_INTERFACE_PREFIX + importName; const newImport: arkts.ETSImportDeclaration = arkts.factory.createImportDeclaration( node.source?.clone(), [factory.createAdditionalImportSpecifier(interfaceName, interfaceName)], - arkts.Es2pandaImportKinds.IMPORT_KINDS_VALUE, - this.program!, - arkts.Es2pandaImportFlags.IMPORT_FLAGS_NONE + arkts.Es2pandaImportKinds.IMPORT_KINDS_VALUE ); this.structInterfaceImport.push(newImport); } else { @@ -196,21 +179,10 @@ export class PreprocessorTransformer extends AbstractVisitor { // Handling component imports const importName: string = node.imported.name; const sourceName: string = source.str; - if ( - this.nameCollector.getComponents().includes(importName) && - (sourceName === ARKUI_COMPONENT_IMPORT_NAME || sourceName === KIT_ARKUI_NAME) - ) { - const newDependencies = [`UI${importName}Attribute`]; + if (this.nameCollector.getComponents().includes(importName) && sourceName === ARKUI_COMPONENT_IMPORT_NAME) { + const newDependencies = [`${importName}Attribute`]; this.updateOutDependencyMap(importName, newDependencies); this.updateSourceDependencyMap(sourceName, newDependencies); - } else if ( - OUTPUT_DEPENDENCY_MAP.get(importName) && - (sourceName === ARKUI_COMPONENT_IMPORT_NAME || - sourceName === ARKUI_STATEMANAGEMENT_IMPORT_NAME || - sourceName === KIT_ARKUI_NAME) - ) { - const newDependencies: string[] = OUTPUT_DEPENDENCY_MAP.get(importName) ?? []; - this.updateSourceDependencyMap(sourceName, newDependencies); } } @@ -250,9 +222,7 @@ export class PreprocessorTransformer extends AbstractVisitor { const newImport: arkts.ETSImportDeclaration = arkts.factory.createImportDeclaration( arkts.factory.create1StringLiteral(source), [factory.createAdditionalImportSpecifier(item, item)], - arkts.Es2pandaImportKinds.IMPORT_KINDS_VALUE, - this.program!, - arkts.Es2pandaImportFlags.IMPORT_FLAGS_NONE + arkts.Es2pandaImportKinds.IMPORT_KINDS_VALUE ); arkts.importDeclarationInsert(newImport, this.program!); }); diff --git a/arkui-plugins/ui-plugins/property-translators/builderParam.ts b/arkui-plugins/ui-plugins/property-translators/builderParam.ts index fbf600f06..f6b08b836 100644 --- a/arkui-plugins/ui-plugins/property-translators/builderParam.ts +++ b/arkui-plugins/ui-plugins/property-translators/builderParam.ts @@ -41,13 +41,19 @@ export class BuilderParamTranslator extends PropertyTranslator implements Initia const currentStructInfo: arkts.StructInfo = arkts.GlobalInfo.getInfoInstance().getStructInfo(this.structName); const mutableThis: arkts.Expression = generateThisBacking(newName); const initializeStruct: arkts.AstNode = this.generateInitializeStruct(mutableThis, originalName); + // const updateStruct: arkts.AstNode = this.generateUpdateStruct(mutableThis, originalName); currentStructInfo.initializeBody.push(initializeStruct); + // currentStructInfo.updateBody.push(updateStruct); arkts.GlobalInfo.getInfoInstance().setStructInfo(this.structName, currentStructInfo); } translateWithoutInitializer(newName: string, originalName: string): arkts.AstNode[] { - const field: arkts.ClassProperty = createOptionalClassProperty(newName, this.property, '', - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE, true); + const field: arkts.ClassProperty = createOptionalClassProperty( + newName, + this.property, + '', + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE + ); const thisGetValue: arkts.Expression = generateThisBacking(newName, false, true); const thisSetValue: arkts.Expression = generateThisBacking(newName, false, false); const getter: arkts.MethodDefinition = this.translateGetter( @@ -69,7 +75,7 @@ export class BuilderParamTranslator extends PropertyTranslator implements Initia typeAnnotation: arkts.TypeNode | undefined, returnValue: arkts.Expression ): arkts.MethodDefinition { - return createGetter(originalName, typeAnnotation, returnValue, true); + return createGetter(originalName, typeAnnotation, returnValue); } translateSetter( @@ -85,18 +91,25 @@ export class BuilderParamTranslator extends PropertyTranslator implements Initia return arkts.factory.createAssignmentExpression( mutableThis, arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - arkts.factory.createBinaryExpression( - arkts.factory.createBinaryExpression( - factory.createBlockStatementForOptionalExpression( - arkts.factory.createIdentifier('initializers'), - originalName - ), - arkts.factory.createIdentifier('content'), - arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_NULLISH_COALESCING - ), - this.property.value ?? arkts.factory.createUndefinedLiteral(), - arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_NULLISH_COALESCING + factory.createBlockStatementForOptionalExpression( + arkts.factory.createIdentifier('initializers'), + originalName ) ); } + + generateUpdateStruct(mutableThis: arkts.Expression, originalName: string): arkts.AstNode { + const right: arkts.MemberExpression = arkts.factory.createMemberExpression( + arkts.factory.createIdentifier('initializers'), + arkts.factory.createIdentifier(originalName), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + true + ); + return arkts.factory.createAssignmentExpression( + mutableThis, + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, + right + ); + } } diff --git a/arkui-plugins/ui-plugins/property-translators/consume.ts b/arkui-plugins/ui-plugins/property-translators/consume.ts index bbb32deb1..ac7491b70 100644 --- a/arkui-plugins/ui-plugins/property-translators/consume.ts +++ b/arkui-plugins/ui-plugins/property-translators/consume.ts @@ -16,11 +16,10 @@ import * as arkts from '@koalaui/libarkts'; import { - generateToRecord, createGetter, - createSetter2, + createSetter, + generateThisBackingValue, generateThisBacking, - generateGetOrSetCall, getValueInAnnotation, DecoratorNames, } from './utils'; @@ -28,7 +27,6 @@ import { PropertyTranslator } from './base'; import { GetterSetter, InitializerConstructor } from './types'; import { backingField, expectName } from '../../common/arkts-utils'; import { createOptionalClassProperty } from '../utils'; -import { factory } from './factory'; export class ConsumeTranslator extends PropertyTranslator implements InitializerConstructor, GetterSetter { translateMember(): arkts.AstNode[] { @@ -40,12 +38,8 @@ export class ConsumeTranslator extends PropertyTranslator implements Initializer cacheTranslatedInitializer(newName: string, originalName: string): void { const currentStructInfo: arkts.StructInfo = arkts.GlobalInfo.getInfoInstance().getStructInfo(this.structName); - const initializeStruct: arkts.AstNode = this.generateInitializeStruct(originalName, newName); + const initializeStruct: arkts.AstNode = this.generateInitializeStruct(newName, originalName); currentStructInfo.initializeBody.push(initializeStruct); - if (currentStructInfo.isReusable) { - const toRecord = generateToRecord(newName, originalName); - currentStructInfo.toRecordBody.push(toRecord); - } arkts.GlobalInfo.getInfoInstance().setStructInfo(this.structName, currentStructInfo); } @@ -53,23 +47,19 @@ export class ConsumeTranslator extends PropertyTranslator implements Initializer const field: arkts.ClassProperty = createOptionalClassProperty( newName, this.property, - 'ConsumeDecoratedVariable', + 'MutableState', arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE ); - const thisValue: arkts.Expression = generateThisBacking(newName, false, true); - const thisGet: arkts.CallExpression = generateGetOrSetCall(thisValue, 'get'); - const thisSet: arkts.ExpressionStatement = arkts.factory.createExpressionStatement( - generateGetOrSetCall(thisValue, 'set') - ); + const thisValue: arkts.MemberExpression = generateThisBackingValue(newName, false, true); const getter: arkts.MethodDefinition = this.translateGetter( originalName, this.property.typeAnnotation, - thisGet + thisValue ); const setter: arkts.MethodDefinition = this.translateSetter( originalName, this.property.typeAnnotation, - thisSet + thisValue ); return [field, getter, setter]; @@ -78,7 +68,7 @@ export class ConsumeTranslator extends PropertyTranslator implements Initializer translateGetter( originalName: string, typeAnnotation: arkts.TypeNode | undefined, - returnValue: arkts.Expression + returnValue: arkts.MemberExpression ): arkts.MethodDefinition { return createGetter(originalName, typeAnnotation, returnValue); } @@ -86,18 +76,37 @@ export class ConsumeTranslator extends PropertyTranslator implements Initializer translateSetter( originalName: string, typeAnnotation: arkts.TypeNode | undefined, - statement: arkts.AstNode + left: arkts.MemberExpression ): arkts.MethodDefinition { - return createSetter2(originalName, typeAnnotation, statement); + const right: arkts.CallExpression = arkts.factory.createCallExpression( + arkts.factory.createIdentifier('observableProxy'), + undefined, + [arkts.factory.createIdentifier('value')] + ); + + return createSetter(originalName, typeAnnotation, left, right); } - generateInitializeStruct(originalName: string, newName: string): arkts.AstNode { - const alias = getValueInAnnotation(this.property, DecoratorNames.CONSUME); - const assign: arkts.AssignmentExpression = arkts.factory.createAssignmentExpression( - generateThisBacking(newName), + generateInitializeStruct(newName: string, originalName: string): arkts.AstNode { + let consumeValueStr: string | undefined = getValueInAnnotation(this.property, DecoratorNames.CONSUME); + if (!consumeValueStr) { + consumeValueStr = originalName; + } + const right: arkts.CallExpression = arkts.factory.createCallExpression( + arkts.factory.createIdentifier('contextLocal'), + this.property.typeAnnotation ? [this.property.typeAnnotation] : undefined, + [arkts.factory.create1StringLiteral(consumeValueStr)] + ); + return arkts.factory.createAssignmentExpression( + arkts.factory.createMemberExpression( + arkts.factory.createThisExpression(), + arkts.factory.createIdentifier(newName), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - factory.generateInitConsumeCall(originalName, this.property, alias ?? originalName) + right ); - return arkts.factory.createExpressionStatement(assign); } } diff --git a/arkui-plugins/ui-plugins/property-translators/factory.ts b/arkui-plugins/ui-plugins/property-translators/factory.ts index c1f610a4b..7125b11c7 100644 --- a/arkui-plugins/ui-plugins/property-translators/factory.ts +++ b/arkui-plugins/ui-plugins/property-translators/factory.ts @@ -14,9 +14,11 @@ */ import * as arkts from '@koalaui/libarkts'; +import { getInteropPath } from '../../path'; import { GenSymGenerator } from '../../common/gensym-generator'; import { factory as UIFactory } from '../ui-factory'; -import { judgeIfAddWatchFunc } from './utils'; +const interop = require(getInteropPath()); +const nullptr = interop.nullptr; export class factory { /** @@ -231,66 +233,4 @@ export class factory { args?.length ? args : [] ); } - - /* - * create `this.addProvidedVar(, , initializers?. ?? , , watchFunc)`. - */ - static generateAddProvideVarCall( - originalName: string, - property: arkts.ClassProperty, - alias: string, - allowOverride: boolean = false - ): arkts.CallExpression { - const args: arkts.Expression[] = [ - arkts.factory.create1StringLiteral(originalName), - arkts.factory.create1StringLiteral(alias), - arkts.factory.createBinaryExpression( - factory.createBlockStatementForOptionalExpression( - arkts.factory.createIdentifier('initializers'), - originalName - ), - property.value ?? arkts.factory.createUndefinedLiteral(), - arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_NULLISH_COALESCING - ), - arkts.factory.createBooleanLiteral(allowOverride), - ]; - judgeIfAddWatchFunc(args, property); - return arkts.factory.createCallExpression( - arkts.factory.createMemberExpression( - arkts.factory.createThisExpression(), - arkts.factory.createIdentifier('addProvidedVar'), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ), - property.typeAnnotation ? [property.typeAnnotation.clone()] : undefined, - args - ); - } - - /* - * create `this.initConsume(, , watchFunc)`. - */ - static generateInitConsumeCall( - originalName: string, - property: arkts.ClassProperty, - alias: string - ): arkts.CallExpression { - const args: arkts.Expression[] = [ - arkts.factory.create1StringLiteral(originalName), - arkts.factory.create1StringLiteral(alias), - ]; - judgeIfAddWatchFunc(args, property); - return arkts.factory.createCallExpression( - arkts.factory.createMemberExpression( - arkts.factory.createThisExpression(), - arkts.factory.createIdentifier('initConsume'), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ), - property.typeAnnotation ? [property.typeAnnotation.clone()] : undefined, - args - ); - } } diff --git a/arkui-plugins/ui-plugins/property-translators/index.ts b/arkui-plugins/ui-plugins/property-translators/index.ts index 013eaa286..c30ace4fc 100644 --- a/arkui-plugins/ui-plugins/property-translators/index.ts +++ b/arkui-plugins/ui-plugins/property-translators/index.ts @@ -31,8 +31,6 @@ import { StoragePropTranslator } from './storageProp'; import { ConsumeTranslator } from './consume'; import { ProvideTranslator } from './provide'; import { BuilderParamTranslator } from './builderParam'; -import { ObservedTrackTranslator } from './observedTrack'; -import { ClassScopeInfo } from 'ui-plugins/checked-transformer'; export { PropertyTranslator }; @@ -76,10 +74,3 @@ export function classifyProperty(member: arkts.AstNode, structName: string): Pro return new regularPropertyTranslator(member, structName); } - -export function classifyObservedTrack(member: arkts.AstNode, classScopeInfo: ClassScopeInfo): ObservedTrackTranslator | undefined { - if (!arkts.isClassProperty(member)) { - return undefined; - } - return new ObservedTrackTranslator(member, classScopeInfo); -} \ No newline at end of file diff --git a/arkui-plugins/ui-plugins/property-translators/objectlink.ts b/arkui-plugins/ui-plugins/property-translators/objectlink.ts index 8da1283a2..49b177d4f 100644 --- a/arkui-plugins/ui-plugins/property-translators/objectlink.ts +++ b/arkui-plugins/ui-plugins/property-translators/objectlink.ts @@ -15,28 +15,16 @@ import * as arkts from '@koalaui/libarkts'; -import { - createGetter, - DecoratorNames, - generateGetOrSetCall, - generateThisBacking, - generateToRecord, - hasDecorator, - judgeIfAddWatchFunc, -} from './utils'; +import { generateToRecord } from './utils'; import { PropertyTranslator } from './base'; import { GetterSetter, InitializerConstructor } from './types'; import { backingField, expectName } from '../../common/arkts-utils'; import { factory } from './factory'; -import { createOptionalClassProperty } from '../utils'; export class ObjectLinkTranslator extends PropertyTranslator implements InitializerConstructor, GetterSetter { translateMember(): arkts.AstNode[] { const originalName: string = expectName(this.property.key); const newName: string = backingField(originalName); - if (!this.ifObservedDecoratedClass()) { - throw new Error('@ObjectLink decorated property only accepts @Observed decorated class instance'); // TODO: replace this with proper error message. - } this.cacheTranslatedInitializer(newName, originalName); // TODO: need to release cache after some point... return this.translateWithoutInitializer(newName, originalName); @@ -58,96 +46,53 @@ export class ObjectLinkTranslator extends PropertyTranslator implements Initiali } generateInitializeStruct(newName: string, originalName: string): arkts.AstNode { - const initializers = arkts.factory.createTSNonNullExpression( - factory.createBlockStatementForOptionalExpression( - arkts.factory.createIdentifier('initializers'), - originalName - ) - ); - - const args: arkts.Expression[] = [arkts.factory.create1StringLiteral(originalName), initializers]; - judgeIfAddWatchFunc(args, this.property); - - const newClass = arkts.factory.createETSNewClassInstanceExpression( - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier('ObjectLinkDecoratedVariable'), - arkts.factory.createTSTypeParameterInstantiation( - this.property.typeAnnotation ? [this.property.typeAnnotation] : [] - ) - ) - ), - args + const call = arkts.factory.createCallExpression( + arkts.factory.createIdentifier('objectLinkState'), + this.property.typeAnnotation ? [this.property.typeAnnotation] : [], + [] ); - return arkts.factory.createAssignmentExpression( - generateThisBacking(newName), + arkts.factory.createMemberExpression( + arkts.factory.createThisExpression(), + arkts.factory.createIdentifier(newName), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - newClass + call ); } generateUpdateStruct(newName: string, originalName: string): arkts.AstNode { - const binaryItem = arkts.factory.createBinaryExpression( - factory.createBlockStatementForOptionalExpression( - arkts.factory.createIdentifier('initializers'), - originalName - ), - arkts.factory.createUndefinedLiteral(), - arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_NOT_STRICT_EQUAL - ); - const member: arkts.MemberExpression = arkts.factory.createMemberExpression( - generateThisBacking(newName, false, true), - arkts.factory.createIdentifier('update'), + const test = arkts.factory.createMemberExpression( + arkts.factory.createThisExpression(), + arkts.factory.createIdentifier(newName), arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, false, false ); - const nonNullItem = arkts.factory.createTSNonNullExpression( - factory.createNonNullOrOptionalMemberExpression('initializers', originalName, false, true) - ); - return arkts.factory.createIfStatement( - binaryItem, - arkts.factory.createBlock([ - arkts.factory.createExpressionStatement( - arkts.factory.createCallExpression(member, undefined, [nonNullItem]) - ), - ]) - ); - } - - translateWithoutInitializer(newName: string, originalName: string): arkts.AstNode[] { - const field: arkts.ClassProperty = createOptionalClassProperty( - newName, - this.property, - 'ObjectLinkDecoratedVariable', - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE - ); - const thisValue: arkts.Expression = generateThisBacking(newName, false, true); - const thisGet: arkts.CallExpression = generateGetOrSetCall(thisValue, 'get'); - const getter: arkts.MethodDefinition = this.translateGetter( - originalName, - this.property.typeAnnotation, - thisGet - ); - return [field, getter]; - } - translateGetter( - originalName: string, - typeAnnotation: arkts.TypeNode | undefined, - returnValue: arkts.Expression - ): arkts.MethodDefinition { - return createGetter(originalName, typeAnnotation, returnValue); - } - - ifObservedDecoratedClass(): boolean { - if (this.property.typeAnnotation && arkts.isETSTypeReference(this.property.typeAnnotation)) { - const decl = arkts.getDecl(this.property.typeAnnotation.part?.name!); - if (arkts.isClassDefinition(decl!) && hasDecorator(decl, DecoratorNames.OBSERVED)) { - return true; - } - } - return false; + const consequent = arkts.BlockStatement.createBlockStatement([ + arkts.factory.createExpressionStatement( + arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + arkts.factory.createTSNonNullExpression(test), + arkts.factory.createIdentifier('update'), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + undefined, + [ + factory.createBlockStatementForOptionalExpression( + arkts.factory.createIdentifier('initializers'), + originalName + ), + ] + ) + ), + ]); + return arkts.factory.createExpressionStatement(arkts.factory.createIfStatement(test, consequent)); } } diff --git a/arkui-plugins/ui-plugins/property-translators/observedTrack.ts b/arkui-plugins/ui-plugins/property-translators/observedTrack.ts deleted file mode 100644 index 036132553..000000000 --- a/arkui-plugins/ui-plugins/property-translators/observedTrack.ts +++ /dev/null @@ -1,348 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as arkts from '@koalaui/libarkts'; -import { backingField, expectName } from '../../common/arkts-utils'; -import { DecoratorNames, hasDecorator } from './utils'; -import { ClassScopeInfo } from 'ui-plugins/checked-transformer'; - -export class ObservedTrackTranslator { - constructor(protected property: arkts.ClassProperty, protected classScopeInfo: ClassScopeInfo) {} - - private hasImplement: boolean = expectName(this.property.key).startsWith(''); - private isTracked: boolean = hasDecorator(this.property, DecoratorNames.TRACK); - - translateMember(): arkts.AstNode[] { - if (!this.isTracked && (this.classScopeInfo.classHasTrack || !this.classScopeInfo.isObserved)) { - return [this.property]; - } - const originalName: string = this.hasImplement - ? this.removeImplementProperty(expectName(this.property.key)) - : expectName(this.property.key); - const newName: string = backingField(originalName); - let properyIsClass = false; - - if (this.property.typeAnnotation && arkts.isETSTypeReference(this.property.typeAnnotation)) { - const decl = arkts.getDecl(this.property.typeAnnotation.part?.name!); - if (arkts.isClassDefinition(decl!)) { - properyIsClass = true; - } - } - const field = this.createField(originalName, newName, properyIsClass); - - this.transformGetterSetter(originalName, newName, properyIsClass); - - return [...field]; - } - - createField(originalName: string, newName: string, properyIsClass: boolean): arkts.ClassProperty[] { - const backingField = properyIsClass - ? this.propertyIsClassField(newName) - : arkts.factory.createClassProperty( - arkts.factory.createIdentifier(newName), - this.property.value, - this.property.typeAnnotation, - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE, - false - ); - if (!this.isTracked) { - return [backingField]; - } - const metaField = this.metaField(originalName); - return [backingField, metaField]; - } - - createGetter(originalName: string, newName: string, properyIsClass: boolean): arkts.MethodDefinition { - const ifRefDepth: arkts.IfStatement = this.getterIfRefDepth(originalName); - const returnMember: arkts.ReturnStatement = this.getterReturnMember(properyIsClass, newName); - const setObservationDepth = this.getterSetObservationDepth(newName); - - const body = arkts.factory.createBlock([ - ifRefDepth, - ...(properyIsClass ? [setObservationDepth] : []), - returnMember, - ]); - - const scriptFunction = arkts.factory.createScriptFunction( - body, - arkts.FunctionSignature.createFunctionSignature(undefined, [], this.property.typeAnnotation, false), - arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_GETTER, - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC - ); - - return arkts.factory.createMethodDefinition( - arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_GET, - arkts.factory.createIdentifier(originalName), - scriptFunction, - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, - false - ); - } - - createSetter(originalName: string, newName: string, properyIsClass: boolean): arkts.MethodDefinition { - const ifEqualsNewValue: arkts.IfStatement = this.setterIfEqualsNewValue(properyIsClass, originalName, newName); - const body = arkts.factory.createBlock([ifEqualsNewValue]); - const param = arkts.factory.createParameterDeclaration( - arkts.factory.createIdentifier('newValue', this.property.typeAnnotation), - undefined - ); - - const scriptFunction = arkts.factory.createScriptFunction( - body, - arkts.FunctionSignature.createFunctionSignature(undefined, [param], undefined, false), - arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_SETTER, - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC - ); - - return arkts.factory.createMethodDefinition( - arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_SET, - arkts.factory.createIdentifier(originalName), - scriptFunction, - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, - false - ); - } - - genThisBacking(newName: string): arkts.MemberExpression { - return arkts.factory.createMemberExpression( - arkts.factory.createThisExpression(), - arkts.factory.createIdentifier(newName), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ); - } - - genThisBackingValue(newName: string): arkts.MemberExpression { - return arkts.factory.createMemberExpression( - this.genThisBacking(newName), - arkts.factory.createIdentifier('value'), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ); - } - - metaIdentifier(originalName: string): arkts.Identifier { - return this.isTracked - ? arkts.factory.createIdentifier(`__meta_${originalName}`) - : arkts.factory.createIdentifier('__meta'); - } - - removeImplementProperty(originalName: string): string { - const prefix = ''; - return originalName.substring(prefix.length); - } - - transformGetterSetter(originalName: string, newName: string, properyIsClass: boolean): void { - const newGetter = this.createGetter(originalName, newName, properyIsClass); - const newSetter = this.createSetter(originalName, newName, properyIsClass); - if (this.hasImplement) { - { - const idx: number = this.classScopeInfo.getters.findIndex( - (getter) => getter.name.name === originalName - ); - const originGetter: arkts.MethodDefinition = this.classScopeInfo.getters[idx]; - const originSetter: arkts.MethodDefinition = originGetter.overloads[0]; - const updateGetter: arkts.MethodDefinition = arkts.factory.updateMethodDefinition( - originGetter, - originGetter.kind, - newGetter.name, - newGetter.scriptFunction.addFlag(arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD), - originGetter.modifiers, - false - ); - arkts.factory.updateMethodDefinition( - originSetter, - originSetter.kind, - newSetter.name, - newSetter.scriptFunction - .addFlag(arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_OVERLOAD) - .addFlag(arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD), - originSetter.modifiers, - false - ); - this.classScopeInfo.getters[idx] = updateGetter; - } - } else { - this.classScopeInfo.getters.push(...[newGetter, newSetter]); - } - } - - propertyIsClassField(newName: string): arkts.ClassProperty { - return arkts.factory.createClassProperty( - arkts.factory.createIdentifier(newName), - this.property.value - ? arkts.factory.createETSNewClassInstanceExpression( - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier('BackingValue'), - arkts.factory.createTSTypeParameterInstantiation( - this.property.typeAnnotation ? [this.property.typeAnnotation] : [] - ) - ) - ), - [this.property.value] - ) - : undefined, - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier('BackingValue'), - arkts.factory.createTSTypeParameterInstantiation( - this.property.typeAnnotation ? [this.property.typeAnnotation] : [] - ) - ) - ), - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE, - false - ); - } - - metaField(originalName: string): arkts.ClassProperty { - return arkts.factory.createClassProperty( - arkts.factory.createIdentifier(`__meta_${originalName}`), - arkts.factory.createETSNewClassInstanceExpression( - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart(arkts.factory.createIdentifier('MutableStateMeta')) - ), - [arkts.factory.createStringLiteral('@Track')] - ), - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart(arkts.factory.createIdentifier('MutableStateMeta')) - ), - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE, - false - ); - } - - getterIfRefDepth(originalName: string): arkts.IfStatement { - return arkts.factory.createIfStatement( - arkts.factory.createBinaryExpression( - arkts.factory.createMemberExpression( - arkts.factory.createThisExpression(), - arkts.factory.createIdentifier('_permissibleAddRefDepth'), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ), - arkts.factory.createNumericLiteral(0), - arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_GREATER_THAN - ), - arkts.factory.createBlock([ - arkts.factory.createExpressionStatement( - arkts.factory.createCallExpression( - arkts.factory.createMemberExpression( - arkts.factory.createMemberExpression( - arkts.factory.createThisExpression(), - this.metaIdentifier(originalName), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ), - arkts.factory.createIdentifier('addRef'), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ), - undefined, - undefined, - false, - false - ) - ), - ]) - ); - } - - getterSetObservationDepth(newName: string): arkts.ExpressionStatement { - return arkts.factory.createExpressionStatement( - arkts.factory.createCallExpression(arkts.factory.createIdentifier('setObservationDepth'), undefined, [ - this.genThisBackingValue(newName), - arkts.factory.createBinaryExpression( - arkts.factory.createMemberExpression( - arkts.factory.createThisExpression(), - arkts.factory.createIdentifier('_permissibleAddRefDepth'), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ), - arkts.factory.createNumericLiteral(1), - arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_MINUS - ), - ]) - ); - } - - getterReturnMember(properyIsClass: boolean, newName: string): arkts.ReturnStatement { - return arkts.factory.createReturnStatement( - properyIsClass ? this.genThisBackingValue(newName) : this.genThisBacking(newName) - ); - } - - setterIfEqualsNewValue(properyIsClass: boolean, originalName: string, newName: string): arkts.IfStatement { - const backingValue = properyIsClass ? this.genThisBackingValue(newName) : this.genThisBacking(newName); - - const setNewValue = arkts.factory.createExpressionStatement( - arkts.factory.createAssignmentExpression( - backingValue, - arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - arkts.factory.createIdentifier('newValue') - ) - ); - - const fireChange = arkts.factory.createExpressionStatement( - arkts.factory.createCallExpression( - arkts.factory.createMemberExpression( - arkts.factory.createMemberExpression( - arkts.factory.createThisExpression(), - this.metaIdentifier(originalName), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ), - arkts.factory.createIdentifier('fireChange'), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ), - undefined, - undefined - ) - ); - - const subscribingWatches = arkts.factory.createExpressionStatement( - arkts.factory.createCallExpression( - arkts.factory.createMemberExpression( - arkts.factory.createThisExpression(), - arkts.factory.createIdentifier('executeOnSubscribingWatches'), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false - ), - undefined, - [arkts.factory.createStringLiteral(originalName)] - ) - ); - - return arkts.factory.createIfStatement( - arkts.factory.createBinaryExpression( - backingValue, - arkts.factory.createIdentifier('newValue'), - arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_NOT_STRICT_EQUAL - ), - arkts.factory.createBlock([setNewValue, fireChange, subscribingWatches]) - ); - } -} diff --git a/arkui-plugins/ui-plugins/property-translators/provide.ts b/arkui-plugins/ui-plugins/property-translators/provide.ts index 144d1239a..ced49cefa 100644 --- a/arkui-plugins/ui-plugins/property-translators/provide.ts +++ b/arkui-plugins/ui-plugins/property-translators/provide.ts @@ -15,15 +15,7 @@ import * as arkts from '@koalaui/libarkts'; -import { - generateToRecord, - createGetter, - createSetter2, - generateThisBacking, - generateGetOrSetCall, - getValueInProvideAnnotation, - ProvideOptions, -} from './utils'; +import { createGetter, createSetter, generateThisBackingValue, getValueInAnnotation, DecoratorNames } from './utils'; import { PropertyTranslator } from './base'; import { GetterSetter, InitializerConstructor } from './types'; import { backingField, expectName } from '../../common/arkts-utils'; @@ -40,12 +32,8 @@ export class ProvideTranslator extends PropertyTranslator implements Initializer cacheTranslatedInitializer(newName: string, originalName: string): void { const currentStructInfo: arkts.StructInfo = arkts.GlobalInfo.getInfoInstance().getStructInfo(this.structName); - const initializeStruct: arkts.AstNode = this.generateInitializeStruct(originalName, newName); + const initializeStruct: arkts.AstNode = this.generateInitializeStruct(newName, originalName); currentStructInfo.initializeBody.push(initializeStruct); - if (currentStructInfo.isReusable) { - const toRecord = generateToRecord(newName, originalName); - currentStructInfo.toRecordBody.push(toRecord); - } arkts.GlobalInfo.getInfoInstance().setStructInfo(this.structName, currentStructInfo); } @@ -53,23 +41,19 @@ export class ProvideTranslator extends PropertyTranslator implements Initializer const field: arkts.ClassProperty = createOptionalClassProperty( newName, this.property, - 'ProvideDecoratedVariable', + 'MutableState', arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE ); - const thisValue: arkts.Expression = generateThisBacking(newName, false, true); - const thisGet: arkts.CallExpression = generateGetOrSetCall(thisValue, 'get'); - const thisSet: arkts.ExpressionStatement = arkts.factory.createExpressionStatement( - generateGetOrSetCall(thisValue, 'set') - ); + const thisValue: arkts.MemberExpression = generateThisBackingValue(newName, false, true); const getter: arkts.MethodDefinition = this.translateGetter( originalName, this.property.typeAnnotation, - thisGet + thisValue ); const setter: arkts.MethodDefinition = this.translateSetter( originalName, this.property.typeAnnotation, - thisSet + thisValue ); return [field, getter, setter]; @@ -78,7 +62,7 @@ export class ProvideTranslator extends PropertyTranslator implements Initializer translateGetter( originalName: string, typeAnnotation: arkts.TypeNode | undefined, - returnValue: arkts.Expression + returnValue: arkts.MemberExpression ): arkts.MethodDefinition { return createGetter(originalName, typeAnnotation, returnValue); } @@ -86,20 +70,59 @@ export class ProvideTranslator extends PropertyTranslator implements Initializer translateSetter( originalName: string, typeAnnotation: arkts.TypeNode | undefined, - statement: arkts.AstNode + left: arkts.MemberExpression ): arkts.MethodDefinition { - return createSetter2(originalName, typeAnnotation, statement); + const right: arkts.CallExpression = arkts.factory.createCallExpression( + arkts.factory.createIdentifier('observableProxy'), + undefined, + [arkts.factory.createIdentifier('value')] + ); + + return createSetter(originalName, typeAnnotation, left, right); } - generateInitializeStruct(originalName: string, newName: string): arkts.AstNode { - const options: undefined | ProvideOptions = getValueInProvideAnnotation(this.property); - const alias: string = options?.alias ?? originalName; - const allowOverride: boolean = options?.allowOverride ?? false; - const assign: arkts.AssignmentExpression = arkts.factory.createAssignmentExpression( - generateThisBacking(newName), - arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - factory.generateAddProvideVarCall(originalName, this.property, alias, allowOverride) + generateInitializeStruct(newName: string, originName: string): arkts.AstNode { + let provideValueStr: string | undefined = getValueInAnnotation(this.property, DecoratorNames.PROVIDE); + if (!provideValueStr) { + provideValueStr = originName; + } + const memExp: arkts.Expression = factory.createDoubleBlockStatementForOptionalExpression( + arkts.factory.createIdentifier('initializers'), + newName, + 'value' + ); + const body: arkts.BlockStatement = arkts.factory.createBlock([ + arkts.factory.createReturnStatement( + arkts.factory.createBinaryExpression( + memExp, + this.property.value, + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_NULLISH_COALESCING + ) + ), + ]); + const script = arkts.factory.createScriptFunction( + body, + arkts.FunctionSignature.createFunctionSignature(undefined, [], this.property.typeAnnotation, false), + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC + ); + const right: arkts.CallExpression = arkts.factory.createCallExpression( + arkts.factory.createIdentifier('contextLocalStateOf'), + this.property.typeAnnotation ? [this.property.typeAnnotation] : undefined, + [arkts.factory.create1StringLiteral(provideValueStr), arkts.factory.createArrowFunction(script)] + ); + return arkts.factory.createExpressionStatement( + arkts.factory.createAssignmentExpression( + arkts.factory.createMemberExpression( + arkts.factory.createThisExpression(), + arkts.factory.createIdentifier(newName), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, + right + ) ); - return arkts.factory.createExpressionStatement(assign); } } diff --git a/arkui-plugins/ui-plugins/property-translators/regularProperty.ts b/arkui-plugins/ui-plugins/property-translators/regularProperty.ts index d89b471e7..0d87d638a 100644 --- a/arkui-plugins/ui-plugins/property-translators/regularProperty.ts +++ b/arkui-plugins/ui-plugins/property-translators/regularProperty.ts @@ -15,12 +15,10 @@ import * as arkts from '@koalaui/libarkts'; -import { createGetter, generateToRecord, generateThisBacking, createSetter2 } from './utils'; +import { createGetter, createSetter } from './utils'; import { PropertyTranslator } from './base'; import { GetterSetter, InitializerConstructor } from './types'; -import { createOptionalClassProperty } from '../utils'; import { backingField, expectName } from '../../common/arkts-utils'; -import { factory } from './factory'; export class regularPropertyTranslator extends PropertyTranslator implements InitializerConstructor, GetterSetter { translateMember(): arkts.AstNode[] { @@ -30,44 +28,10 @@ export class regularPropertyTranslator extends PropertyTranslator implements Ini return this.translateWithoutInitializer(newName, originalName); } - cacheTranslatedInitializer(newName: string, originalName: string): void { - const currentStructInfo: arkts.StructInfo = arkts.GlobalInfo.getInfoInstance().getStructInfo(this.structName); - const initializeStruct: arkts.AstNode = this.generateInitializeStruct(newName, originalName); - currentStructInfo.initializeBody.push(initializeStruct); - if (currentStructInfo.isReusable) { - const toRecord = generateToRecord(newName, originalName); - currentStructInfo.toRecordBody.push(toRecord); - } - arkts.GlobalInfo.getInfoInstance().setStructInfo(this.structName, currentStructInfo); - } + cacheTranslatedInitializer(newName: string, originalName: string): void {} translateWithoutInitializer(newName: string, originalName: string): arkts.AstNode[] { - const field: arkts.ClassProperty = createOptionalClassProperty( - newName, - this.property, - '', - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE - ); - const thisValue: arkts.Expression = generateThisBacking(newName, false, false); - const thisSet: arkts.ExpressionStatement = arkts.factory.createExpressionStatement( - arkts.factory.createAssignmentExpression( - thisValue, - arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - arkts.factory.createIdentifier('value'), - ) - ); - const getter: arkts.MethodDefinition = this.translateGetter( - originalName, - this.property.typeAnnotation, - arkts.factory.createTSAsExpression(thisValue, this.property.typeAnnotation, false) - ); - const setter: arkts.MethodDefinition = this.translateSetter( - originalName, - this.property.typeAnnotation, - thisSet - ); - - return [field, getter, setter]; + return [this.property]; } translateGetter( @@ -81,25 +45,23 @@ export class regularPropertyTranslator extends PropertyTranslator implements Ini translateSetter( originalName: string, typeAnnotation: arkts.TypeNode | undefined, - statement: arkts.AstNode + left: arkts.MemberExpression ): arkts.MethodDefinition { - return createSetter2(originalName, typeAnnotation, statement); + const right: arkts.Identifier = arkts.factory.createUndefinedLiteral(); + return createSetter(originalName, typeAnnotation, left, right); } generateInitializeStruct(newName: string, originalName: string): arkts.AstNode { - const binaryItem = arkts.factory.createBinaryExpression( - factory.createBlockStatementForOptionalExpression( - arkts.factory.createIdentifier('initializers'), - originalName + return arkts.factory.createAssignmentExpression( + arkts.factory.createMemberExpression( + arkts.factory.createIdentifier('this'), + arkts.factory.createIdentifier(originalName), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false ), - this.property.value ?? arkts.factory.createUndefinedLiteral(), - arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_NULLISH_COALESCING - ); - const assign: arkts.AssignmentExpression = arkts.factory.createAssignmentExpression( - generateThisBacking(newName), arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - binaryItem + this.property.value ?? arkts.factory.createUndefinedLiteral() ); - return arkts.factory.createExpressionStatement(assign); } } diff --git a/arkui-plugins/ui-plugins/property-translators/utils.ts b/arkui-plugins/ui-plugins/property-translators/utils.ts index 9feb4c4b2..95b8d8be0 100644 --- a/arkui-plugins/ui-plugins/property-translators/utils.ts +++ b/arkui-plugins/ui-plugins/property-translators/utils.ts @@ -34,7 +34,6 @@ export enum DecoratorNames { LOCAL_STORAGE_PROP = 'LocalStorageProp', LOCAL_STORAGE_LINK = 'LocalStorageLink', REUSABLE = 'Reusable', - TRACK = 'Track', } export function collectPropertyDecorators(property: arkts.ClassProperty): string[] { @@ -61,20 +60,6 @@ export function hasDecorator( return property.annotations.some((anno) => isDecoratorAnnotation(anno, decoratorName)); } -/** - * Determine whether the node `` is decorated by decorators that need initializing without assignment. - * - * @param st class property node - */ -export function needDefiniteOrOptionalModifier(st: arkts.ClassProperty): boolean { - return ( - hasDecorator(st, DecoratorNames.LINK) || - hasDecorator(st, DecoratorNames.CONSUME) || - hasDecorator(st, DecoratorNames.OBJECT_LINK) || - (hasDecorator(st, DecoratorNames.PROP) && !st.value) - ); -} - export function getStateManagementType(node: arkts.ClassProperty): string { if (hasDecorator(node, DecoratorNames.STATE)) { return 'StateDecoratedVariable'; @@ -86,13 +71,10 @@ export function getStateManagementType(node: arkts.ClassProperty): string { return 'StorageLinkDecoratedVariable'; } else if (hasDecorator(node, DecoratorNames.STORAGE_PROP)) { return 'StoragePropDecoratedVariable'; - } else if (hasDecorator(node, DecoratorNames.PROVIDE)) { - return 'ProvideDecoratedVariable'; - } else if (hasDecorator(node, DecoratorNames.CONSUME)) { - return 'ConsumeDecoratedVariable'; - } else if (hasDecorator(node, DecoratorNames.OBJECT_LINK)) { - return 'ObjectLinkDecoratedVariable'; - } else if (hasDecorator(node, DecoratorNames.LOCAL_STORAGE_PROP)) { + } else if ( + hasDecorator(node, DecoratorNames.LOCAL_STORAGE_PROP) || + hasDecorator(node, DecoratorNames.OBJECT_LINK) + ) { return 'SyncedProperty'; } return 'MutableState'; @@ -101,24 +83,20 @@ export function getStateManagementType(node: arkts.ClassProperty): string { export function createGetter( name: string, type: arkts.TypeNode | undefined, - returns: arkts.Expression, - needMemo: boolean = false, + returns: arkts.Expression ): arkts.MethodDefinition { - const returnType: arkts.TypeNode | undefined = type?.clone(); - if (needMemo) { - returnType?.setAnnotations([annotation('memo')]); - } const body = arkts.factory.createBlock([arkts.factory.createReturnStatement(returns)]); + const scriptFunction = arkts.factory.createScriptFunction( body, - arkts.FunctionSignature.createFunctionSignature(undefined, [], returnType, false), + arkts.FunctionSignature.createFunctionSignature(undefined, [], type?.clone(), false), arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_GETTER, arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC ); return arkts.factory.createMethodDefinition( arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_GET, arkts.factory.createIdentifier(name), - scriptFunction, + arkts.factory.createFunctionExpression(scriptFunction), arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, false ); @@ -157,7 +135,7 @@ export function createSetter( return arkts.factory.createMethodDefinition( arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_SET, arkts.factory.createIdentifier(name), - scriptFunction, + arkts.factory.createFunctionExpression(scriptFunction), arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, false ); @@ -183,7 +161,7 @@ export function createSetter2( return arkts.factory.createMethodDefinition( arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_SET, arkts.factory.createIdentifier(name), - scriptFunction, + arkts.factory.createFunctionExpression(scriptFunction), arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, false ); @@ -245,57 +223,40 @@ export function getValueInAnnotation(node: arkts.ClassProperty, decoratorName: D return undefined; } -export interface ProvideOptions { - alias: string; - allowOverride: boolean; +function getWatchValueStr(node: arkts.AstNode): string | undefined { + if (!arkts.isClassProperty(node) || !node.value) { + return undefined; + } + return arkts.isStringLiteral(node.value) ? node.value.str : undefined; +} + +function getWatchAnnotationValue(anno: arkts.AnnotationUsage): string | undefined { + const isWatchAnnotation: boolean = + !!anno.expr && arkts.isIdentifier(anno.expr) && anno.expr.name === DecoratorNames.WATCH; + + if (isWatchAnnotation && anno.properties.length === 1) { + return getWatchValueStr(anno.properties.at(0)!); + } + return undefined; } -export function getValueInProvideAnnotation(node: arkts.ClassProperty): ProvideOptions | undefined { +function getWatchValueInAnnotation(node: arkts.ClassProperty): string | undefined { const annotations: readonly arkts.AnnotationUsage[] = node.annotations; + for (let i = 0; i < annotations.length; i++) { const anno: arkts.AnnotationUsage = annotations[i]; - if (anno.expr && arkts.isIdentifier(anno.expr) && anno.expr.name === DecoratorNames.PROVIDE) { - const alias: string = getValueInObjectAnnotation(anno, DecoratorNames.PROVIDE, 'alias'); - const allowOverride: boolean = getValueInObjectAnnotation(anno, DecoratorNames.PROVIDE, 'allowOverride') - ? true - : false; - return { alias, allowOverride }; + const str: string | undefined = getWatchAnnotationValue(anno); + if (!!str) { + return str; } } - return undefined; -} -function getValueInObjectAnnotation(anno: arkts.AnnotationUsage, decoratorName: DecoratorNames, key: string): any { - const isSuitableAnnotation: boolean = - !!anno.expr && arkts.isIdentifier(anno.expr) && anno.expr.name === decoratorName; - if (!isSuitableAnnotation) { - return undefined; - } - const keyItem: arkts.AstNode | undefined = anno.properties.find( - (annoProp: arkts.AstNode) => - arkts.isClassProperty(annoProp) && - annoProp.key && - arkts.isIdentifier(annoProp.key) && - annoProp.key.name === key - ); - if (keyItem && arkts.isClassProperty(keyItem) && keyItem.value) { - return getDifferentAnnoTypeValue(keyItem.value); - } return undefined; } -function getDifferentAnnoTypeValue(value: arkts.Expression): string | boolean { - if (arkts.isBooleanLiteral(value)) { - return value.value; - } else if (arkts.isStringLiteral(value)) { - return value.str; - } - return value.dumpSrc(); -} - export function judgeIfAddWatchFunc(args: arkts.Expression[], property: arkts.ClassProperty): void { if (hasDecorator(property, DecoratorNames.WATCH)) { - const watchStr: string | undefined = getValueInAnnotation(property, DecoratorNames.WATCH); + const watchStr: string | undefined = getWatchValueInAnnotation(property); if (watchStr) { args.push(factory.createWatchCallback(watchStr)); } @@ -321,12 +282,12 @@ export function generateToRecord(newName: string, originalName: string): arkts.P return arkts.Property.createProperty( arkts.factory.createStringLiteral(originalName), arkts.factory.createBinaryExpression( - arkts.factory.createMemberExpression( - arkts.factory.createIdentifier('paramsCasted'), - arkts.factory.createIdentifier(originalName), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - false, - false + arkts.factory.createMemberExpression( + arkts.factory.createIdentifier('paramsCasted'), + arkts.factory.createIdentifier(originalName), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false ), arkts.ETSNewClassInstanceExpression.createETSNewClassInstanceExpression( arkts.factory.createTypeReference( diff --git a/arkui-plugins/ui-plugins/struct-translators/factory.ts b/arkui-plugins/ui-plugins/struct-translators/factory.ts index 77a9859ff..4b2d08594 100644 --- a/arkui-plugins/ui-plugins/struct-translators/factory.ts +++ b/arkui-plugins/ui-plugins/struct-translators/factory.ts @@ -14,7 +14,7 @@ */ import * as arkts from '@koalaui/libarkts'; -import { BuilderLambdaNames, CustomComponentNames, Dollars } from '../utils'; +import { CustomComponentNames, Dollars } from '../utils'; import { factory as uiFactory } from '../ui-factory'; import { annotation } from '../../common/arkts-utils'; @@ -26,14 +26,14 @@ export class factory { return arkts.factory.createMethodDefinition( arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_CONSTRUCTOR, member.name, - member.scriptFunction, + arkts.factory.createFunctionExpression(member.scriptFunction), arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_CONSTRUCTOR, false ); } /* - * create _build method. + * create _build menthod. */ static transformBuildMethodWithOriginBuild( method: arkts.MethodDefinition, @@ -68,7 +68,7 @@ export class factory { return arkts.factory.createMethodDefinition( arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_METHOD, updateKey, - updateScriptFunction, + arkts.factory.createFunctionExpression(updateScriptFunction), modifiers, false ); @@ -92,7 +92,7 @@ export class factory { } /* - * create __initializeStruct method. + * create __initializeStruct menthod. */ static createInitializeStruct( structInfo: arkts.StructInfo, @@ -126,14 +126,14 @@ export class factory { return arkts.factory.createMethodDefinition( arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_METHOD, updateKey, - scriptFunction, + arkts.factory.createFunctionExpression(scriptFunction), modifiers, false ); } /* - * create __updateStruct method. + * create __updateStruct menthod. */ static createUpdateStruct( structInfo: arkts.StructInfo, @@ -168,14 +168,14 @@ export class factory { return arkts.factory.createMethodDefinition( arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_METHOD, updateKey, - scriptFunction, + arkts.factory.createFunctionExpression(scriptFunction), modifiers, false ); } /* - * create __toRecord method when the component is decorated with @Reusable. + * create __toRecord menthod when the component is decorated with @Reusable. */ static toRecord(optionsTypeName: string, toRecordBody: arkts.Property[]): arkts.MethodDefinition { const paramsCasted = factory.generateParamsCasted(optionsTypeName); @@ -203,7 +203,7 @@ export class factory { return arkts.factory.createMethodDefinition( arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_CONSTRUCTOR, arkts.factory.createIdentifier('__toRecord'), - toRecordScriptFunction, + arkts.factory.createFunctionExpression(toRecordScriptFunction), arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_OVERRIDE, false ); @@ -274,112 +274,4 @@ export class factory { arkts.classDefinitionFlags(definition) ); } - - /* - * add headers for animation in UICommonMethod - */ - static modifyExternalComponentCommon(node: arkts.TSInterfaceDeclaration): arkts.AstNode { - const animationStart = factory.createAnimationMethod(BuilderLambdaNames.ANIMATION_START); - const animationStop = factory.createAnimationMethod(BuilderLambdaNames.ANIMATION_STOP); - const updatedBody = arkts.factory.updateInterfaceBody(node.body!, [ - animationStart, - animationStop, - ...node.body!.body, - ]); - return arkts.factory.updateInterfaceDeclaration( - node, - node.extends, - node.id, - node.typeParams, - updatedBody, - node.isStatic, - node.isFromExternal - ); - } - - /* - * generate animationStart(...) and animationStop(...) - */ - static createAnimationMethod(key: string): arkts.MethodDefinition { - const aniparams: arkts.Expression[] = [ - arkts.factory.createParameterDeclaration( - arkts.factory.createIdentifier( - 'value', - arkts.factory.createUnionType( - [ - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart(arkts.factory.createIdentifier('AnimateParam')) - ), - arkts.factory.createETSUndefinedType() - ] - ) - ), - undefined - ), - ]; - const aniFuncExpr = arkts.factory.createScriptFunction( - undefined, - arkts.factory.createFunctionSignature(undefined, aniparams, arkts.TSThisType.createTSThisType(), false), - arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD, - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC - ); - return arkts.factory.createMethodDefinition( - arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_METHOD, - arkts.factory.createIdentifier(key), - aniFuncExpr, - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, - false - ); - } - - /* - * generate XComponent(..., packageInfo: string, ...) - */ - static modifyXcomponent(node: arkts.ScriptFunction): arkts.ScriptFunction { - const info = arkts.factory.createParameterDeclaration( - arkts.factory.createIdentifier( - 'packageInfo', - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier('string') - ) - ) - ), - undefined - ); - return arkts.factory.updateScriptFunction( - node, - node.body, - arkts.factory.createFunctionSignature( - node.typeParams, - [...node.params.slice(0, 2), info, ...node.params.slice(2)], - node.returnTypeAnnotation, - false - ), - node.flags, - node.modifiers - ); - } - - /* - * transform ExternalSource headers - */ - static transformExternalSource(externalSourceName: string, node: arkts.AstNode): arkts.AstNode { - if ( - externalSourceName === 'arkui.component.common' && - arkts.isTSInterfaceDeclaration(node) && - !!node.id && - node.id.name === 'UICommonMethod' - ) { - return factory.modifyExternalComponentCommon(node); - } else if ( - externalSourceName === 'arkui.component.xcomponent' && - arkts.isScriptFunction(node) && - !!node.id && - node.id.name === 'XComponent' - ) { - return factory.modifyXcomponent(node); - } - return node; - } } diff --git a/arkui-plugins/ui-plugins/struct-translators/struct-transformer.ts b/arkui-plugins/ui-plugins/struct-translators/struct-transformer.ts index be9ebdb11..b280b0ad5 100644 --- a/arkui-plugins/ui-plugins/struct-translators/struct-transformer.ts +++ b/arkui-plugins/ui-plugins/struct-translators/struct-transformer.ts @@ -19,26 +19,25 @@ import { annotation, collect, filterDefined } from '../../common/arkts-utils'; import { ProjectConfig } from '../../common/plugin-context'; import { classifyProperty, PropertyTranslator } from '../property-translators'; import { - addMemoAnnotation, CustomComponentNames, getCustomComponentOptionsName, getTypeNameFromTypeParameter, getTypeParamsFromClassDecl, } from '../utils'; -import { isCustomComponentClass, isKnownMethodDefinition, isEtsGlobalClass, isReourceNode, CustomComponentScopeInfo, findCanAddMemoFromArrowFunction } from './utils'; +import { isCustomComponentClass, isKnownMethodDefinition, isEtsGlobalClass, isReourceNode } from './utils'; import { factory as uiFactory } from '../ui-factory'; import { factory } from './factory'; import { isEntryWrapperClass } from '../entry-translators/utils'; import { factory as entryFactory } from '../entry-translators/factory'; import { DecoratorNames, hasDecorator } from '../property-translators/utils'; -import { ScopeInfoCollection } from './utils'; +import { ScopeInfo } from './utils'; function tranformPropertyMembers( className: string, propertyTranslators: PropertyTranslator[], optionsTypeName: string, isDecl?: boolean, - scope?: CustomComponentScopeInfo + scope?: ScopeInfo ): arkts.AstNode[] { const propertyMembers = propertyTranslators.map((translator) => translator.translateMember()); const currentStructInfo: arkts.StructInfo = arkts.GlobalInfo.getInfoInstance().getStructInfo(className); @@ -100,7 +99,7 @@ function transformOtherMembersInClass( function tranformClassMembers( node: arkts.ClassDeclaration, isDecl?: boolean, - scope?: CustomComponentScopeInfo + scope?: ScopeInfo ): arkts.ClassDeclaration { if (!node.definition) { return node; @@ -155,37 +154,36 @@ function transformResource( } export class StructTransformer extends AbstractVisitor { - private scopeInfoCollection: ScopeInfoCollection; + private scopeInfos: ScopeInfo[] = []; projectConfig: ProjectConfig | undefined; constructor(projectConfig: ProjectConfig | undefined) { super(); this.projectConfig = projectConfig; - this.scopeInfoCollection = { customComponents: [] }; } reset(): void { super.reset(); - this.scopeInfoCollection = { customComponents: [] }; + this.scopeInfos = []; } enter(node: arkts.AstNode): void { if (arkts.isClassDeclaration(node) && isCustomComponentClass(node)) { - this.scopeInfoCollection.customComponents.push({ name: node.definition!.ident!.name }); + this.scopeInfos.push({ name: node.definition!.ident!.name }); } - if (arkts.isMethodDefinition(node) && this.scopeInfoCollection.customComponents.length > 0) { + if (arkts.isMethodDefinition(node) && this.scopeInfos.length > 0) { const name = node.name.name; - const scopeInfo = this.scopeInfoCollection.customComponents.pop()!; + const scopeInfo = this.scopeInfos.pop()!; scopeInfo.hasInitializeStruct ||= name === CustomComponentNames.COMPONENT_INITIALIZE_STRUCT; scopeInfo.hasUpdateStruct ||= name === CustomComponentNames.COMPONENT_UPDATE_STRUCT; scopeInfo.hasReusableRebind ||= name === CustomComponentNames.REUSABLE_COMPONENT_REBIND_STATE; - this.scopeInfoCollection.customComponents.push(scopeInfo); + this.scopeInfos.push(scopeInfo); } } exit(node: arkts.AstNode): void { if (arkts.isClassDeclaration(node) && isCustomComponentClass(node)) { - this.scopeInfoCollection.customComponents.pop(); + this.scopeInfos.pop(); } } @@ -193,10 +191,9 @@ export class StructTransformer extends AbstractVisitor { this.enter(beforeChildren); const node = this.visitEachChild(beforeChildren); if (arkts.isClassDeclaration(node) && isCustomComponentClass(node)) { - let scope: CustomComponentScopeInfo | undefined; - const scopeInfos: CustomComponentScopeInfo[] = this.scopeInfoCollection.customComponents; - if (scopeInfos.length > 0) { - scope = scopeInfos[scopeInfos.length - 1]; + let scope: ScopeInfo | undefined; + if (this.scopeInfos.length > 0) { + scope = this.scopeInfos[this.scopeInfos.length - 1]; } const newClass: arkts.ClassDeclaration = tranformClassMembers( node, @@ -212,8 +209,6 @@ export class StructTransformer extends AbstractVisitor { return transformEtsGlobalClassMembers(node); } else if (arkts.isCallExpression(node) && isReourceNode(node)) { return transformResource(node, this.projectConfig); - } else if (findCanAddMemoFromArrowFunction(node)) { - return addMemoAnnotation(node); } return node; } diff --git a/arkui-plugins/ui-plugins/struct-translators/utils.ts b/arkui-plugins/ui-plugins/struct-translators/utils.ts index 2af217626..502917ecf 100644 --- a/arkui-plugins/ui-plugins/struct-translators/utils.ts +++ b/arkui-plugins/ui-plugins/struct-translators/utils.ts @@ -14,15 +14,10 @@ */ import * as arkts from '@koalaui/libarkts'; -import { Dollars, isMemoAnnotation } from '../utils'; +import { Dollars } from '../utils'; import { CustomComponentNames } from '../utils'; -import { DecoratorNames, isDecoratorAnnotation } from '../property-translators/utils'; -export type ScopeInfoCollection = { - customComponents: CustomComponentScopeInfo[]; -}; - -export type CustomComponentScopeInfo = { +export type ScopeInfo = { name: string; hasInitializeStruct?: boolean; hasUpdateStruct?: boolean; @@ -82,35 +77,3 @@ export function isReourceNode(node: arkts.CallExpression): boolean { } return false; } - -export function isMemoCall(node: arkts.AstNode): node is arkts.CallExpression { - if (!arkts.isCallExpression(node)) { - return false; - } - const expr: arkts.AstNode = node.expression; - const decl: arkts.AstNode | undefined = arkts.getDecl(expr); - - if (!decl) { - return false; - } - - if (arkts.isMethodDefinition(decl)) { - return decl.scriptFunction.annotations.some( - (anno) => isDecoratorAnnotation(anno, DecoratorNames.BUILDER) || isMemoAnnotation(anno, 'memo') - ); - } - return false; -} - -export function findCanAddMemoFromArrowFunction(node: arkts.AstNode): node is arkts.ArrowFunctionExpression { - if (!arkts.isArrowFunctionExpression(node)) { - return false; - } - const hasMemo: boolean = node.annotations.some((anno) => isMemoAnnotation(anno, 'memo')); - if (!hasMemo && !!node.scriptFunction.body && arkts.isBlockStatement(node.scriptFunction.body)) { - return node.scriptFunction.body.statements.some( - (st) => arkts.isExpressionStatement(st) && isMemoCall(st.expression) - ); - } - return false; -} diff --git a/arkui-plugins/ui-plugins/ui-factory.ts b/arkui-plugins/ui-plugins/ui-factory.ts index 2b64ac64f..3c0c59e6b 100644 --- a/arkui-plugins/ui-plugins/ui-factory.ts +++ b/arkui-plugins/ui-plugins/ui-factory.ts @@ -14,9 +14,8 @@ */ import * as arkts from '@koalaui/libarkts'; -import { BuilderLambdaNames, CustomComponentNames, hasPropertyInAnnotation, hasNullOrUndefinedType } from './utils'; +import { BuilderLambdaNames, CustomComponentNames } from './utils'; import { annotation } from '../common/arkts-utils'; -import { DecoratorNames, needDefiniteOrOptionalModifier } from './property-translators/utils'; export class factory { /** @@ -157,9 +156,7 @@ export class factory { const importDecl: arkts.ETSImportDeclaration = arkts.factory.createImportDeclaration( source, [arkts.factory.createImportSpecifier(imported, local)], - importKind, - program, - arkts.Es2pandaImportFlags.IMPORT_FLAGS_NONE + importKind ); arkts.importDeclarationInsert(importDecl, program); return; @@ -182,7 +179,7 @@ export class factory { return arkts.factory.createMethodDefinition( arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_CONSTRUCTOR, member.name, - member.scriptFunction, + arkts.factory.createFunctionExpression(member.scriptFunction), arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_CONSTRUCTOR, false ); @@ -224,64 +221,9 @@ export class factory { return arkts.factory.createMethodDefinition( arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_METHOD, updateKey, - updateScriptFunction, + arkts.factory.createFunctionExpression(updateScriptFunction), modifiers, false ); } - - /* - * add alias: to @Provide annotation when no alias in @Provide({...}). - */ - static processNoAliasProvideVariable(property: arkts.ClassProperty): void { - let annotations: readonly arkts.AnnotationUsage[] = property.annotations; - if (annotations.length === 0) { - return; - } - const newAnnos: arkts.AnnotationUsage[] = annotations.map((anno: arkts.AnnotationUsage) => { - if ( - !!anno.expr && - arkts.isIdentifier(anno.expr) && - anno.expr.name === DecoratorNames.PROVIDE && - !hasPropertyInAnnotation(anno, 'alias') && - property.key && - arkts.isIdentifier(property.key) - ) { - return arkts.factory.update1AnnotationUsage(anno, anno.expr, [ - ...anno.properties, - factory.createAliasClassProperty(property.key), - ]); - } else { - return anno; - } - }); - property.setAnnotations(newAnnos); - } - - /* - * create class property : `alias: `. - */ - static createAliasClassProperty(value: arkts.Identifier): arkts.ClassProperty { - return arkts.factory.createClassProperty( - arkts.factory.createIdentifier('alias'), - arkts.factory.create1StringLiteral(value.name), - undefined, - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, - false - ); - } - - /* - * add optional or definite modifier for class property needs initializing without assignment. - */ - static PreprocessClassPropertyModifier(st: arkts.AstNode): arkts.AstNode { - if (arkts.isClassProperty(st) && needDefiniteOrOptionalModifier(st)) { - if (st.typeAnnotation && hasNullOrUndefinedType(st.typeAnnotation)) { - st.modifiers = arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_OPTIONAL; - } else { - st.modifiers = arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_DEFINITE; - } - } - return st; - } } diff --git a/arkui-plugins/ui-plugins/utils.ts b/arkui-plugins/ui-plugins/utils.ts index 847a830a5..c73d54b14 100644 --- a/arkui-plugins/ui-plugins/utils.ts +++ b/arkui-plugins/ui-plugins/utils.ts @@ -14,8 +14,6 @@ */ import * as arkts from '@koalaui/libarkts'; -import { annotation } from '../common/arkts-utils'; -import { DecoratorNames } from './property-translators/utils'; export enum CustomComponentNames { ENTRY_ANNOTATION_NAME = 'Entry', @@ -23,7 +21,7 @@ export enum CustomComponentNames { RESUABLE_ANNOTATION_NAME = 'Reusable', COMPONENT_BUILD_ORI = 'build', COMPONENT_CONSTRUCTOR_ORI = 'constructor', - COMPONENT_DEFAULT_IMPORT = 'arkui.component.customComponent', + COMPONENT_DEFAULT_IMPORT = '@ohos.arkui.component', COMPONENT_CLASS_NAME = 'CustomComponent', COMPONENT_INTERFACE_PREFIX = '__Options_', COMPONENT_INITIALIZE_STRUCT = '__initializeStruct', @@ -42,9 +40,6 @@ export enum BuilderLambdaNames { STYLE_PARAM_NAME = 'style', STYLE_ARROW_PARAM_NAME = 'instance', CONTENT_PARAM_NAME = 'content', - ANIMATION_NAME = 'animation', - ANIMATION_START = 'animationStart', - ANIMATION_STOP = 'animationStop', } export enum Dollars { @@ -95,17 +90,14 @@ export function createOptionalClassProperty( name: string, property: arkts.ClassProperty, stageManagementIdent: string, - modifiers: arkts.Es2pandaModifierFlags, - needMemo: boolean = false + modifiers: arkts.Es2pandaModifierFlags ): arkts.ClassProperty { - const newType: arkts.TypeNode | undefined = property.typeAnnotation?.clone(); - if (needMemo) { - newType?.setAnnotations([annotation('memo')]); - } const newProperty = arkts.factory.createClassProperty( arkts.factory.createIdentifier(name), undefined, - stageManagementIdent.length ? createStageManagementType(stageManagementIdent, property) : newType, + stageManagementIdent.length + ? createStageManagementType(stageManagementIdent, property) + : property.typeAnnotation?.clone(), modifiers, false ); @@ -125,75 +117,3 @@ export function createStageManagementType( ) ); } - -export function getGettersFromClassDecl(definition: arkts.ClassDefinition): arkts.MethodDefinition[] { - return definition.body.filter( - (member) => - arkts.isMethodDefinition(member) && - arkts.hasModifierFlag(member, arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_GETTER) - ) as arkts.MethodDefinition[]; -} - -export type MemoAstNode = - | arkts.ScriptFunction - | arkts.ETSParameterExpression - | arkts.ClassProperty - | arkts.TSTypeAliasDeclaration - | arkts.ETSFunctionType - | arkts.ArrowFunctionExpression - | arkts.ETSUnionType; - -export function isMemoAnnotation(node: arkts.AnnotationUsage, memoName: string): boolean { - if (!(node.expr !== undefined && arkts.isIdentifier(node.expr) && node.expr.name === memoName)) { - return false; - } - return true; -} - -export function addMemoAnnotation(node: T, memoName: string = 'memo'): T { - if (arkts.isETSUnionType(node)) { - const functionType = node.types.find((type) => arkts.isETSFunctionType(type)); - if (!functionType) { - return node; - } - addMemoAnnotation(functionType, memoName); - return node; - } - const newAnnotations: arkts.AnnotationUsage[] = [ - ...node.annotations.filter((it) => !isMemoAnnotation(it, memoName)), - annotation(memoName), - ]; - if (arkts.isEtsParameterExpression(node)) { - node.annotations = newAnnotations; - return node; - } - return node.setAnnotations(newAnnotations) as T; -} - -export function hasPropertyInAnnotation(annotation: arkts.AnnotationUsage, propertyName: string): boolean { - return !!annotation.properties.find( - (annoProp: arkts.AstNode) => - arkts.isClassProperty(annoProp) && - annoProp.key && - arkts.isIdentifier(annoProp.key) && - annoProp.key.name === propertyName - ); -} - -/** - * Determine whether the type node includes null or undefined type. - * - * @param type type node - */ -export function hasNullOrUndefinedType(type: arkts.TypeNode): boolean { - let res: boolean = false; - if (arkts.isETSUnionType(type)) { - type.types.forEach((item: arkts.TypeNode) => { - res = res || hasNullOrUndefinedType(item); - }); - } - if (arkts.isETSUndefinedType(type) || arkts.isETSNullType(type)) { - res = true; - } - return res; -} \ No newline at end of file diff --git a/arkui-plugins/ui-syntax-plugins/index.ts b/arkui-plugins/ui-syntax-plugins/index.ts deleted file mode 100644 index 53232081e..000000000 --- a/arkui-plugins/ui-syntax-plugins/index.ts +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as arkts from '@koalaui/libarkts'; -import { PluginContext, Plugins } from '../common/plugin-context'; -import { ParsedUISyntaxLinterTransformer } from './transformers/parsed-ui-syntax-linter-transformer'; -import { createUISyntaxRuleProcessor } from './processor'; -import rules from './rules'; - -export function uiSyntaxLinterTransform(): Plugins { - const processor = createUISyntaxRuleProcessor(rules); - return { - name: 'ui-syntax-plugin', - parsed(this: PluginContext): arkts.EtsScript | undefined { - const contextPtr = arkts.arktsGlobal.compilerContext?.peer ?? this.getContextPtr(); - if (!contextPtr) { - return undefined; - } - let program = arkts.getOrUpdateGlobalContext(contextPtr).program; - const node = program.astNode; - if (node) { - const script = new ParsedUISyntaxLinterTransformer(processor).visitor( - node, - ) as arkts.EtsScript; - arkts.setAllParents(script); - this.setArkTSAst(script); - return script; - } - return undefined; - } - }; -} diff --git a/arkui-plugins/ui-syntax-plugins/processor/index.ts b/arkui-plugins/ui-syntax-plugins/processor/index.ts deleted file mode 100644 index 0a447759e..000000000 --- a/arkui-plugins/ui-syntax-plugins/processor/index.ts +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as arkts from '@koalaui/libarkts'; -import { UISyntaxRule, UISyntaxRuleContext } from '../rules/ui-syntax-rule'; -import { getContainerComponents } from '../utils'; - -export type UISyntaxRuleProcessor = { - parsed(node: arkts.AstNode): void; -}; - -export function createUISyntaxRuleProcessor( - rules: UISyntaxRule[], -): UISyntaxRuleProcessor { - const containerComponents = getContainerComponents('../../components/'); - const context: UISyntaxRuleContext = { - report(options) { - const position = arkts.getStartPosition(options.node); - let message: string; - if (!options.data) { - message = options.message; - } else { - message = Object.entries(options.data).reduce( - (message, [placehoderName, placehoderValue]) => { - return message.replace(`{{${placehoderName}}}`, placehoderValue); - }, - options.message, - ); - } - // todo - if (options.fix) { - const suggestion = options.fix(options.node); - console.log(`error: ${message}`); - console.log(`range: (${suggestion.range[0].index()}, ${suggestion.range[0].line()}) - (${suggestion.range[1].index()}, ${suggestion.range[1].line()})`, - `code: ${suggestion.code}`); - } else { - console.log(`syntax-error: ${message} (${position.index()},${position.line()})`); - } - }, - containerComponents: containerComponents, - }; - - const instances = rules.map((rule) => rule.setup(context)); - - return { - parsed(node): void { - for (const instance of instances) { - instance.parsed?.(node); - } - }, - }; -} diff --git a/arkui-plugins/ui-syntax-plugins/rules/build-root-node.ts b/arkui-plugins/ui-syntax-plugins/rules/build-root-node.ts deleted file mode 100644 index c3678f1fe..000000000 --- a/arkui-plugins/ui-syntax-plugins/rules/build-root-node.ts +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as arkts from '@koalaui/libarkts'; -import { getIdentifierName, getAnnotationUsage, PresetDecorators } from '../utils'; -import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; - -const BUILD_NAME: string = 'build'; -const BUILD_ROOT_NUM: number = 1; -const STATEMENT_LENGTH: number = 1; - -function isBuildOneRoot(statements: readonly arkts.Statement[], buildNode: arkts.Identifier, - context: UISyntaxRuleContext): void { - if (statements.length > STATEMENT_LENGTH && buildNode) { - context.report({ - node: buildNode, - message: rule.messages.invalidBuildRootCount, - }); - } -} - -function checkBuildRootNode(node: arkts.AstNode, context: UISyntaxRuleContext): void { - const loadedContainerComponents = context.containerComponents; - if (!arkts.isStructDeclaration(node)) { - return; - } - const entryDecoratorUsage = getAnnotationUsage(node, PresetDecorators.ENTRY); - node.definition.body.forEach(member => { - // Determine the number of root node - if (!arkts.isMethodDefinition(member) || getIdentifierName(member.name) !== BUILD_NAME) { - return; - } - const blockStatement = member.scriptFunction.body; - if (!blockStatement || !arkts.isBlockStatement(blockStatement)) { - return; - } - const buildNode = member.scriptFunction.id; - const statements = blockStatement.statements; - // rule1: The 'build' method cannot have more than one root node. - if (buildNode) { - isBuildOneRoot(statements, buildNode, context); - } - if (statements.length !== BUILD_ROOT_NUM) { - return; - } - // Determine whether it is a container component - const expressionStatement = statements[0]; - if (!arkts.isExpressionStatement(expressionStatement)) { - return; - } - const callExpression = expressionStatement.expression; - if (!arkts.isCallExpression(callExpression)) { - return; - } - const componentName = callExpression.expression.dumpSrc(); - let isContainer: boolean = false; - loadedContainerComponents?.forEach(container => { - if (componentName.includes(container)) { - isContainer = true; - } - }); - // rule2: If the component is decorated by '@Entry', - // its 'build' function can have only one root node, which must be a container component. - if (entryDecoratorUsage && !isContainer && buildNode) { - context.report({ - node: buildNode, - message: rule.messages.invalidBuildRoot, - }); - } - }); -} - -const rule: UISyntaxRule = { - name: 'build-root-node', - messages: { - invalidBuildRootCount: `The 'build' method cannot have more than one root node.`, - invalidBuildRoot: `If the component is decorated by '@Entry', its 'build' function can have only one root node, which must be a container component.` - }, - setup(context) { - return { - parsed: (node): void => { - checkBuildRootNode(node, context); - }, - }; - }, -}; - -export default rule; diff --git a/arkui-plugins/ui-syntax-plugins/rules/check-construct-private-parameter.ts b/arkui-plugins/ui-syntax-plugins/rules/check-construct-private-parameter.ts deleted file mode 100644 index 7dfa570b0..000000000 --- a/arkui-plugins/ui-syntax-plugins/rules/check-construct-private-parameter.ts +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as arkts from '@koalaui/libarkts'; -import { getClassPropertyName, isPrivateClassProperty } from '../utils'; -import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; - -function addProperty(item: arkts.AstNode, structName: string, privateMap: Map): void { - if (!arkts.isClassProperty(item) || !isPrivateClassProperty(item)) { - return; - } - // Check if structName already exists in privateMap - if (privateMap.has(structName)) { - // If it exists, retrieve the current string[] and append the new content - privateMap.get(structName)?.push(getClassPropertyName(item)); - } else { - // If it doesn't exist, create a new string[] and add the content - privateMap.set(structName, [getClassPropertyName(item)]); - } -} - -function checkPrivateVariables( - node: arkts.AstNode, - context: UISyntaxRuleContext, - privateMap: Map -): void { - // Check if the current node is the root node - if (arkts.nodeType(node) === arkts.Es2pandaAstNodeType.AST_NODE_TYPE_ETS_MODULE) { - node.getChildren().forEach((member) => { - if (!arkts.isStructDeclaration(member)) { - return; - } - const structName: string = member.definition.ident?.name ?? ''; - member.definition?.body?.forEach((item) => { - addProperty(item, structName, privateMap); - }); - }); - } - if (!arkts.isCallExpression(node)) { - return; - } - const componentName = node.expression.dumpSrc(); - // If the initialization is for a component with private properties - if (!privateMap.has(componentName)) { - return; - } - node.arguments?.forEach((member) => { - member.getChildren().forEach((property) => { - if (!arkts.isProperty(property)) { - return; - } - const propertyName: string = property.key?.dumpSrc() ?? ''; - if (privateMap.get(componentName)!.includes(propertyName)) { - context.report({ - node: property, - message: rule.messages.cannotInitializePrivateVariables, - data: { - propertyName: propertyName, - }, - }); - } - }); - }); -} - -const rule: UISyntaxRule = { - name: 'check-construct-private-parameter', - messages: { - cannotInitializePrivateVariables: `Property '{{propertyName}}' is private and can not be initialized through the component constructor.`, - }, - setup(context) { - let privateMap: Map = new Map(); - return { - parsed: (node): void => { - checkPrivateVariables(node, context, privateMap); - }, - }; - }, -}; - -export default rule; \ No newline at end of file diff --git a/arkui-plugins/ui-syntax-plugins/rules/check-decorated-property-type.ts b/arkui-plugins/ui-syntax-plugins/rules/check-decorated-property-type.ts deleted file mode 100644 index 8448fa435..000000000 --- a/arkui-plugins/ui-syntax-plugins/rules/check-decorated-property-type.ts +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as arkts from '@koalaui/libarkts'; -import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; -import { - getAnnotationUsage, getClassPropertyAnnotationNames, getClassPropertyName, - getClassPropertyType, PresetDecorators -} from '../utils'; - -function checkDecoratedPropertyType( - member: arkts.AstNode, - context: UISyntaxRuleContext, - relationship: Record -): void { - if (!arkts.isClassProperty(member)) { - return; - } - const propertyName = getClassPropertyName(member); - const propertyType = getClassPropertyType(member); - const propertyAnnotationNames = getClassPropertyAnnotationNames(member); - Object.entries(relationship).forEach(([decoratorName, invalidPropertyTypes]) => { - if (propertyAnnotationNames.some(annotationName => annotationName === decoratorName) && - invalidPropertyTypes - .some(invalidPropertyType => invalidPropertyType === propertyType)) { - if (!arkts.isClassProperty || member.key === undefined) { - return; - } - const errorNode = member.key; - context.report({ - node: errorNode, - message: rule.messages.invalidDecoratedPropertyType, - data: { decoratorName, propertyName, propertyType }, - }); - } - }); -} - -const rule: UISyntaxRule = { - name: 'check-decorated-property-type', - messages: { - invalidDecoratedPropertyType: `The {{decoratorName}} property '{{propertyName}}' cannot be a '{{propertyType}}' object.`, - }, - setup(context) { - const relationship: Record = { - [PresetDecorators.STATE]: ['CustomDialogController'], - }; - return { - parsed: (node): void => { - if (!arkts.isStructDeclaration(node)) { - return; - } - const componentDecorator = getAnnotationUsage(node, PresetDecorators.COMPONENT_V1); - if (!componentDecorator) { - return; - } - node.definition.body.forEach(member => { - checkDecoratedPropertyType(member, context, relationship); - }); - }, - }; - }, -}; - -export default rule; \ No newline at end of file diff --git a/arkui-plugins/ui-syntax-plugins/rules/component-componentV2-mix-use-check.ts b/arkui-plugins/ui-syntax-plugins/rules/component-componentV2-mix-use-check.ts deleted file mode 100644 index ce7afdf8f..000000000 --- a/arkui-plugins/ui-syntax-plugins/rules/component-componentV2-mix-use-check.ts +++ /dev/null @@ -1,177 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as arkts from '@koalaui/libarkts'; -import { PresetDecorators } from '../utils'; -import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; - -// Report an Observed version violation error -function reportObservedConflict( - node: arkts.ClassProperty, - context: UISyntaxRuleContext, - message: string -): void { - node.annotations.forEach((anno) => { - if (anno.expr?.dumpSrc()) { - context.report({ - node: anno, - message: message, - data: { - annotation: anno.expr?.dumpSrc(), - } - }); - } - }); -} - -function processNode( - node: arkts.ClassProperty, - annotationName: string, - observedV1Name: Set, - observedV2Name: Set, - context: UISyntaxRuleContext -): void { - const queue: Array = [node]; - while (queue.length > 0) { - const currentNode: arkts.AstNode = queue.shift() as arkts.AstNode; - if (arkts.isIdentifier(currentNode)) { - if (observedV1Name.has(currentNode.dumpSrc()) && annotationName === PresetDecorators.COMPONENT_V2) { - reportObservedConflict(node, context, rule.messages.observedv1_v2); - break; - } - if (observedV2Name.has(currentNode.dumpSrc()) && annotationName === PresetDecorators.COMPONENT_V1) { - reportObservedConflict(node, context, rule.messages.observedv2_v1); - break; - } - } - const children = currentNode.getChildren(); - for (const child of children) { - queue.push(child); - } - } -} - -function traverseTree( - node: arkts.AstNode, - annotationName: string, - observedV1Name: Set, - observedV2Name: Set, - context: UISyntaxRuleContext -): void { - if (arkts.isClassProperty(node)) { - processNode(node, annotationName, observedV1Name, observedV2Name, context); - } - const children = node.getChildren(); - for (const child of children) { - traverseTree(child, annotationName, observedV1Name, observedV2Name, context); - } -} - -function findAllObserved(node: arkts.AstNode, observedV1Name: Set, observedV2Name: Set): void { - if (arkts.isClassDeclaration(node)) { - node.definition?.annotations.forEach((anno) => { - if (anno.expr?.dumpSrc() === PresetDecorators.OBSERVED_V1) { - const componentV1Name = node?.definition?.ident?.name; - componentV1Name ? observedV1Name.add(componentV1Name) : null; - } - if (anno.expr?.dumpSrc() === PresetDecorators.OBSERVED_V2) { - const componentV2Name = node?.definition?.ident?.name; - componentV2Name ? observedV2Name.add(componentV2Name) : null; - } - }); - } - const children = node.getChildren(); - for (const child of children) { - findAllObserved(child, observedV1Name, observedV2Name); - } -} - -function findAllTSTypeAliasDeclaration( - node: arkts.AstNode, - observedV1Name: Set, - observedV2Name: Set -): void { - if (arkts.nodeType(node) === arkts.Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_ALIAS_DECLARATION) { - node.getChildren().forEach((child) => { - if (arkts.isIdentifier(child)) { - const typeName = child.dumpSrc(); - findAllObservedType(node, typeName, observedV1Name, observedV2Name); - } - }); - } - const children = node.getChildren(); - for (const child of children) { - findAllTSTypeAliasDeclaration(child, observedV1Name, observedV2Name); - } -} - -function findAllObservedType( - node: arkts.AstNode, - typeName: string, - observedV1Name: Set, - observedV2Name: Set -): void { - if (arkts.isIdentifier(node) && observedV1Name.has(node.dumpSrc())) { - observedV1Name.add(typeName); - } - if (arkts.isIdentifier(node) && observedV2Name.has(node.dumpSrc())) { - observedV2Name.add(typeName); - } - const children = node.getChildren(); - for (const child of children) { - findAllObservedType(child, typeName, observedV1Name, observedV2Name); - } -} - -function processComponentAnnotations( - node: arkts.StructDeclaration, - observedV1Name: Set, - observedV2Name: Set, - context: UISyntaxRuleContext -): void { - node?.definition?.annotations.forEach((anno) => { - if (anno.expr?.dumpSrc() === PresetDecorators.COMPONENT_V2) { - traverseTree(node, PresetDecorators.COMPONENT_V2, observedV1Name, observedV2Name, context); - } - if (anno.expr?.dumpSrc() === PresetDecorators.COMPONENT_V1) { - traverseTree(node, PresetDecorators.COMPONENT_V1, observedV1Name, observedV2Name, context); - } - }); -} - -const rule: UISyntaxRule = { - name: 'component-componentV2-mix-use-check', - messages: { - observedv1_v2: `The type of the @{{annotation}} Decorator property can not be a class decorated with @Observed.`, - observedv2_v1: `The type of the @{{annotation}} Decorator property can not be a class decorated with @ObservedV2.` - }, - setup(context) { - let observedV1Name: Set = new Set(); - let observedV2Name: Set = new Set(); - return { - parsed: (node): void => { - if (arkts.nodeType(node) === arkts.Es2pandaAstNodeType.AST_NODE_TYPE_ETS_MODULE) { - findAllObserved(node, observedV1Name, observedV2Name); - findAllTSTypeAliasDeclaration(node, observedV1Name, observedV2Name); - } - if (arkts.isStructDeclaration(node)) { - processComponentAnnotations(node, observedV1Name, observedV2Name, context); - } - }, - }; - }, -}; - -export default rule; \ No newline at end of file diff --git a/arkui-plugins/ui-syntax-plugins/rules/componentV2-mix-check.ts b/arkui-plugins/ui-syntax-plugins/rules/componentV2-mix-check.ts deleted file mode 100644 index 082d768d1..000000000 --- a/arkui-plugins/ui-syntax-plugins/rules/componentV2-mix-check.ts +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as arkts from '@koalaui/libarkts'; -import { getAnnotationUsage, PresetDecorators } from '../utils'; -import { UISyntaxRule } from './ui-syntax-rule'; - -const rule: UISyntaxRule = { - name: 'componentV2-mix-check', - messages: { - conflictWithComponentV2: `The struct '{{structName}}' can not be decorated with '@ComponentV2' and '@Component', '@Reusable', '@CustomDialog' at the same time.`, - }, - setup(context) { - return { - parsed: (node): void => { - if (!arkts.isStructDeclaration(node)) { - return; - } - const structName = node.definition.ident?.name ?? ''; - const structNameNode = node.definition.ident; - if (!structNameNode) { - return; - } - // Check if the struct has the '@ComponentV2' annotation - const hasComponentV2 = getAnnotationUsage(node, PresetDecorators.COMPONENT_V2); - if (!hasComponentV2) { - return; - } - // Check for the presence of conflicting decorators: '@Component', '@Reusable', '@CustomDialog' - const hasComponent = getAnnotationUsage(node, PresetDecorators.COMPONENT_V1); - const hasReusable = getAnnotationUsage(node, PresetDecorators.REUSABLE_V1); - const hasCustomDialog = getAnnotationUsage(node, PresetDecorators.CUSTOM_DIALOG); - if (hasComponent || hasReusable || hasCustomDialog) { - context.report({ - node: structNameNode, - message: rule.messages.conflictWithComponentV2, - data: { structName }, - }); - } - }, - }; - }, -}; - -export default rule; diff --git a/arkui-plugins/ui-syntax-plugins/rules/componentV2-state-usage-validation.ts b/arkui-plugins/ui-syntax-plugins/rules/componentV2-state-usage-validation.ts deleted file mode 100644 index b60587aee..000000000 --- a/arkui-plugins/ui-syntax-plugins/rules/componentV2-state-usage-validation.ts +++ /dev/null @@ -1,168 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as arkts from '@koalaui/libarkts'; -import { getClassPropertyAnnotationNames, PresetDecorators, getAnnotationUsage } from '../utils'; -import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; - -// Helper functions for rules -const hasisComponentV2 = (node: arkts.StructDeclaration): boolean => !!getAnnotationUsage(node, - PresetDecorators.COMPONENT_V2); - -const hasComponent = (node: arkts.StructDeclaration): boolean => !!getAnnotationUsage(node, - PresetDecorators.COMPONENT_V1); -function checkMultipleBuiltInDecorators(context: UISyntaxRuleContext, member: arkts.ClassProperty, - propertyDecorators: string[]): void { - const builtInDecorators = [PresetDecorators.LOCAL, PresetDecorators.PARAM, PresetDecorators.EVENT]; - const appliedBuiltInDecorators = propertyDecorators.filter(d => builtInDecorators.includes(d)); - if (appliedBuiltInDecorators.length > 1) { - member.annotations?.forEach(annotation => { - const annotationsName = annotation.expr?.dumpSrc(); - reportMultipleBuiltInDecoratorsError(context, annotation, annotationsName, builtInDecorators); - }); - } -}; - -function reportMultipleBuiltInDecoratorsError(context: UISyntaxRuleContext, annotation: arkts.AstNode, - annotationsName: string | undefined, builtInDecorators: string[]): void { - if (annotationsName && builtInDecorators.includes(annotationsName)) { - context.report({ - node: annotation, - message: rule.messages.multipleBuiltInDecorators, - fix: (annotation) => { - const startPosition = arkts.getStartPosition(annotation); - const endPosition = arkts.getEndPosition(annotation); - return { - range: [startPosition, endPosition], - code: '', - }; - }, - }); - } -} - -function checkDecoratorOnlyInisComponentV2(context: UISyntaxRuleContext, member: arkts.ClassProperty, - node: arkts.StructDeclaration, hasisComponentV2: boolean, hasComponent: boolean): void { - const builtInDecorators = [PresetDecorators.LOCAL, PresetDecorators.PARAM, PresetDecorators.EVENT]; - member.annotations?.forEach(annotation => { - const annotationsName = annotation.expr?.dumpSrc(); - if (annotationsName && builtInDecorators.includes(annotationsName) && !hasisComponentV2 && !hasComponent) { - reportDecoratorOnlyInisComponentV2Error(context, annotation, annotationsName, node); - } - }); -}; - -function reportDecoratorOnlyInisComponentV2Error(context: UISyntaxRuleContext, annotation: arkts.AnnotationUsage, - annotationsName: string, node: arkts.StructDeclaration): void { - context.report({ - node: annotation, - message: rule.messages.decoratorOnlyInisComponentV2, - data: { annotationsName }, - fix: (annotation) => { - const startPosition = arkts.getStartPosition(node); - return { - range: [startPosition, startPosition], - code: `@${PresetDecorators.COMPONENT_V2}\n`, - }; - }, - }); -} - -function checkParamRequiresRequire(context: UISyntaxRuleContext, member: arkts.ClassProperty, - propertyDecorators: string[]): void { - if (propertyDecorators.includes(PresetDecorators.PARAM) && !member.value && - !propertyDecorators.includes(PresetDecorators.REQUIRE) && member.key) { - const memberKey = member.key; - context.report({ - node: memberKey, - message: rule.messages.paramRequiresRequire, - fix: (memberKey) => { - const startPosition = arkts.getStartPosition(memberKey); - return { - range: [startPosition, startPosition], - code: `@${PresetDecorators.REQUIRE} `, - }; - }, - }); - } -}; - -function checkRequireOnlyWithParam(context: UISyntaxRuleContext, member: arkts.ClassProperty, - propertyDecorators: string[]): void { - const requireDecorator = member.annotations?.find(annotation => - annotation.expr && annotation.expr.dumpSrc() === PresetDecorators.REQUIRE - ); - if (requireDecorator && !propertyDecorators.includes(PresetDecorators.PARAM)) { - context.report({ - node: requireDecorator, - message: rule.messages.requireOnlyWithParam, - fix: (requireDecorator) => { - const startPosition = arkts.getStartPosition(requireDecorator); - const endPosition = arkts.getEndPosition(requireDecorator); - return { - range: [startPosition, endPosition], - code: '', - }; - }, - }); - } -}; - -function validateClassPropertyDecorators(context: UISyntaxRuleContext, node: arkts.StructDeclaration): void { - const isComponentV2 = hasisComponentV2(node); - const isComponent = hasComponent(node); - node.definition.body.forEach(member => { - if (!arkts.isClassProperty(member)) { - return; - } - const propertyDecorators = getClassPropertyAnnotationNames(member); - - // Rule 1: Multiple built-in decorators - checkMultipleBuiltInDecorators(context, member, propertyDecorators); - - // Rule 2: Built-in decorators only allowed in @isComponentV2 - checkDecoratorOnlyInisComponentV2(context, member, node, isComponentV2, isComponent); - - // Rule 3: @Param without default value must be combined with @Require - checkParamRequiresRequire(context, member, propertyDecorators); - - // Rule 4: @Require must be used together with @Param - checkRequireOnlyWithParam(context, member, propertyDecorators); - }); -} - -const rule: UISyntaxRule = { - name: 'iscomponentV2-state-usage-validation', - messages: { - multipleBuiltInDecorators: `The member property or method cannot be decorated by multiple built-in decorators.`, - decoratorOnlyInisComponentV2: `The '@{{annotationsName}}' decorator can only be used in a 'struct' decorated with '@isComponentV2'.`, - paramRequiresRequire: `When a variable decorated with @Param is not assigned a default value, it must also be decorated with @Require.`, - requireOnlyWithParam: `In a struct decorated with @isComponentV2, @Require can only be used with @Param. ` - }, - - setup(context) { - return { - parsed: (node): void => { - - if (!arkts.isStructDeclaration(node)) { - return; - } - validateClassPropertyDecorators(context, node); - }, - }; - }, -}; - -export default rule; \ No newline at end of file diff --git a/arkui-plugins/ui-syntax-plugins/rules/construct-parameter-literal.ts b/arkui-plugins/ui-syntax-plugins/rules/construct-parameter-literal.ts deleted file mode 100644 index f893b01de..000000000 --- a/arkui-plugins/ui-syntax-plugins/rules/construct-parameter-literal.ts +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as arkts from '@koalaui/libarkts'; -import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; -import { PresetDecorators } from '../utils'; - -function recordStructWithLinkDecorators(item: arkts.AstNode, structName: string, linkMap: Map): void { - if (!arkts.isClassProperty(item)) { - return; - } - item.annotations?.forEach((annotation) => { - const annotationName: string = annotation.expr?.dumpSrc() ?? ''; - if (annotationName === '') { - return; - } - // If the node has properties decorated with Link or ObjectLink, record this structure node - if (annotationName === PresetDecorators.LINK || annotationName === PresetDecorators.OBJECT_LINK) { - linkMap.set(structName, annotationName); - } - }); -} - -function initMap(node: arkts.AstNode, linkMap: Map): void { - // Check if the current node is the root node - if (arkts.nodeType(node) !== arkts.Es2pandaAstNodeType.AST_NODE_TYPE_ETS_MODULE) { - return; - } - node.getChildren().forEach((member) => { - if (!arkts.isStructDeclaration(member)) { - return; - } - const structName: string = member.definition.ident?.name ?? ''; - if (structName === '') { - return; - } - member.definition?.body?.forEach((item) => { - recordStructWithLinkDecorators(item, structName, linkMap); - }); - }); -} - -function checkInitializeWithLiteral(node: arkts.AstNode, context: UISyntaxRuleContext, - linkMap: Map -): void { - if (!arkts.isCallExpression(node)) { - return; - } - const componentName = node.expression.dumpSrc(); - // Only assignments to properties decorated with Link or ObjectLink trigger rule checks - if (!linkMap.has(componentName)) { - return; - } - node.arguments.forEach((member) => { - member.getChildren().forEach((property) => { - if (!arkts.isProperty(property)) { - return; - } - if (property.value === undefined) { - return; - } - const propertyType: arkts.Es2pandaAstNodeType = arkts.nodeType(property.value); - const key: string = property.key?.dumpSrc() ?? ''; - if (key === '') { - return; - } - const value = property.value?.dumpSrc() ? property.value.dumpSrc() : ''; - // If the assignment statement is not of type MemberExpression, throw an error - if (propertyType !== arkts.Es2pandaAstNodeType.AST_NODE_TYPE_MEMBER_EXPRESSION) { - context.report({ - node: property, - message: rule.messages.cannotInitializeWithLiteral, - data: { - value: value, - annotationName: linkMap.get(componentName)!, - key: key, - }, - }); - } - }); - }); -} - -const rule: UISyntaxRule = { - name: 'construct-parameter-literal', - messages: { - cannotInitializeWithLiteral: `Assigning the attribute'{{value}}' to the '@{{annotationName}}' decorated attribute '{{key}}' is not allowed.`, - }, - setup(context) { - let linkMap: Map = new Map(); - return { - parsed: (node): void => { - initMap(node, linkMap); - checkInitializeWithLiteral(node, context, linkMap); - }, - }; - }, -}; - -export default rule; \ No newline at end of file diff --git a/arkui-plugins/ui-syntax-plugins/rules/consumer-provider-decorator-check.ts b/arkui-plugins/ui-syntax-plugins/rules/consumer-provider-decorator-check.ts deleted file mode 100644 index cb4f7fcd8..000000000 --- a/arkui-plugins/ui-syntax-plugins/rules/consumer-provider-decorator-check.ts +++ /dev/null @@ -1,271 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as arkts from '@koalaui/libarkts'; -import { getAnnotationUsage, MultiMap, PresetDecorators } from '../utils'; -import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; -// Traverse the member variables of the struct, recording the members of the @Consumer modifications -function processStructMembers( - node: arkts.StructDeclaration, - structName: string, - componentv2WithConsumer: MultiMap -): void { - node.definition.body.forEach((member) => { - // When a member variable is @consumer modified, it is stored to mark fields that cannot be initialized - if (arkts.isClassProperty(member)) { - const memberName = member?.key?.dumpSrc(); - structName && memberName ? componentv2WithConsumer.add(structName, memberName) : null; - } - }); -} -function rememberStructName(node: arkts.AstNode, componentv2WithConsumer: MultiMap): void { - // First it has to be of the struct type - if (arkts.isStructDeclaration(node)) { - node?.definition?.annotations.forEach((anno) => { - // Second, it must be decorated with a @component v2 decorator - if (anno.expr?.dumpSrc() === PresetDecorators.COMPONENT_V2) { - const structName = node.definition.ident?.name ?? ''; - processStructMembers(node, structName, componentv2WithConsumer); - } - }); - } -} -function findDecorator(member: arkts.ClassProperty, decorator: string): arkts.AnnotationUsage | undefined { - return member.annotations?.find(annotation => - annotation.expr && - annotation.expr.dumpSrc() === decorator - ); -} -// Verify that the @Consumer decorator is used on the method -function validateConsumerOnMethod(member: arkts.MethodDefinition, context: UISyntaxRuleContext): void { - const annotationNode = member.scriptFunction.annotations?.find(annotation => - annotation.expr && annotation.expr.dumpSrc() === PresetDecorators.CONSUMER - ); - if (annotationNode) { - context.report({ - node: annotationNode, - message: rule.messages.consumerOnlyOnMember, - fix: (annotationNode) => { - const startPosition = arkts.getStartPosition(annotationNode); - const endPosition = arkts.getEndPosition(annotationNode); - return { - range: [startPosition, endPosition], - code: '', - }; - } - }); - } -} -// @Consumer Bugs that conflict with other decorators -function reportMultipleBuiltInDecorators( - hasConsumeDecorator: arkts.AnnotationUsage, - otherDecorators: arkts.AnnotationUsage, - context: UISyntaxRuleContext, -): void { - context.report({ - node: hasConsumeDecorator, - message: rule.messages.multipleBuiltInDecorators, - fix: (hasConsumeDecorator) => { - const startPosition = arkts.getStartPosition(otherDecorators); - const endPosition = arkts.getEndPosition(otherDecorators); - return { - range: [startPosition, endPosition], - code: '', - }; - } - }); -} -// Report a bug where @Provider is missing @ComponentV2 -function reportProviderRequiresComponentV2( - hasProviderDecorator: arkts.AnnotationUsage, - hasComponent: arkts.AnnotationUsage | undefined, - node: arkts.AstNode, - context: UISyntaxRuleContext, -): void { - if (hasComponent) { - context.report({ - node: hasProviderDecorator, - message: rule.messages.providerRequiresComponentV2, - fix: (hasProviderDecorator) => { - const startPosition = arkts.getStartPosition(hasComponent); - const endPosition = arkts.getEndPosition(hasComponent); - return { - range: [startPosition, endPosition], - code: `@${PresetDecorators.COMPONENT_V2}`, - }; - } - }); - } else { - context.report({ - node: hasProviderDecorator, - message: rule.messages.providerRequiresComponentV2, - fix: (hasProviderDecorator) => { - const startPosition = arkts.getStartPosition(node); - const endPosition = startPosition; - return { - range: [startPosition, endPosition], - code: `@${PresetDecorators.COMPONENT_V2}\n`, - }; - } - }); - } -} -// Verify decorator conflicts on member variables -function validateMemberDecorators(member: arkts.ClassProperty, - hasComponentV2: arkts.AnnotationUsage | undefined, - hasComponent: arkts.AnnotationUsage | undefined, - node: arkts.AstNode, - context: UISyntaxRuleContext -): void { - const hasConsumeDecorator = findDecorator(member, PresetDecorators.CONSUMER); - const hasProviderDecorator = findDecorator(member, PresetDecorators.PROVIDER); - const otherDecorators = member.annotations?.find(annotation => - annotation.expr && - annotation.expr.dumpSrc() !== PresetDecorators.CONSUMER - ); - if (hasConsumeDecorator && otherDecorators) { - reportMultipleBuiltInDecorators(hasConsumeDecorator, otherDecorators, context); - } - if (hasProviderDecorator && !hasComponentV2) { - reportProviderRequiresComponentV2(hasProviderDecorator, hasComponent, node, context); - } -} -// Verify that @Provider is being used in the class -function validateProviderInClass(member: arkts.ClassProperty, context: UISyntaxRuleContext): void { - const hasProviderDecorator = findDecorator(member, PresetDecorators.PROVIDER); - if (hasProviderDecorator) { - context.report({ - node: hasProviderDecorator, - message: rule.messages.providerOnlyInStruct, - fix: (hasProviderDecorator) => { - const startPosition = arkts.getStartPosition(hasProviderDecorator); - const endPosition = arkts.getEndPosition(hasProviderDecorator); - return { - range: [startPosition, endPosition], - code: '', - }; - } - }); - } -} -// Verify that the current identifier is an illegally initialized @Consumer member variable -function reportValidateConsumer( - currentNode: arkts.Identifier, - callExpName: string, - componentv2WithConsumer: MultiMap, - context: UISyntaxRuleContext -): void { - if (componentv2WithConsumer.get(callExpName).includes(currentNode.dumpSrc())) { - context.report({ - node: currentNode.parent, - message: rule.messages.forbiddenInitialization, - data: { - value: currentNode.dumpSrc(), - structName: callExpName - }, - fix: () => { - const startPosition = arkts.getStartPosition(currentNode.parent); - const endPosition = arkts.getEndPosition(currentNode.parent); - return { - range: [startPosition, endPosition], - code: '', - }; - } - }); - } -} -// Verify that the @Consumer-decorated property is initialized -function validateConsumerInitialization(node: arkts.CallExpression, componentv2WithConsumer: MultiMap, - context: UISyntaxRuleContext): void { - const callExpName: string = node.expression.dumpSrc(); - if (componentv2WithConsumer.has(callExpName)) { - const queue: Array = [node]; - while (queue.length > 0) { - const currentNode: arkts.AstNode = queue.shift() as arkts.AstNode; - if (arkts.isIdentifier(currentNode)) { - reportValidateConsumer(currentNode, callExpName, componentv2WithConsumer, context); - } - const children = currentNode.getChildren(); - for (const child of children) { - queue.push(child); - } - } - } -} -function collectStructsWithConsumer(node: arkts.AstNode, componentv2WithConsumer: MultiMap): void { - // Used to document all V2 structs that use '@Consumer' - if (arkts.nodeType(node) === arkts.Es2pandaAstNodeType.AST_NODE_TYPE_ETS_MODULE) { - // Breadth traversal is done through while and queues - const queue: Array = [node]; - while (queue.length > 0) { - const currentNode: arkts.AstNode = queue.shift() as arkts.AstNode; - // Filter and record the nodes of the tree - rememberStructName(currentNode, componentv2WithConsumer); - const children = currentNode.getChildren(); - for (const child of children) { - queue.push(child); - } - } - } -} -function validateStructDecoratorsAndMembers(node: arkts.AstNode, context: UISyntaxRuleContext): void { - if (arkts.isStructDeclaration(node)) { - const hasComponentV2 = getAnnotationUsage(node, PresetDecorators.COMPONENT_V2); - const hasComponent = getAnnotationUsage(node, PresetDecorators.COMPONENT_V1); - node.definition.body.forEach(member => { - if (arkts.isMethodDefinition(member)) { - validateConsumerOnMethod(member, context); - } - if (arkts.isClassProperty(member)) { - validateMemberDecorators(member, hasComponentV2, hasComponent, node, context); - } - }); - } -} -function validateProviderInClasses(node: arkts.AstNode, context: UISyntaxRuleContext): void { - if (arkts.isClassDeclaration(node)) { - node.definition?.body.forEach(member => { - if (arkts.isClassProperty(member)) { - validateProviderInClass(member, context); - } - }); - } -} -const rule: UISyntaxRule = { - name: 'consumer-provider-decorator-check', - messages: { - consumerOnlyOnMember: `'@Consumer' can only decorate member property.`, - multipleBuiltInDecorators: `The struct member variable can not be decorated by multiple built-in decorators.`, - providerRequiresComponentV2: `The '@Provider' decorator can only be used in a 'struct' decorated with '@ComponentV2'.`, - providerOnlyInStruct: `The '@Provider' decorator can only be used with 'struct'.`, - forbiddenInitialization: `Property '{{value}}' in the custom component '{{structName}}' cannot be initialized here (forbidden to specify).`, - }, - setup(context) { - // Used to record the names of the corresponding structs and member variables that are @consumer modified - let componentv2WithConsumer: MultiMap = new MultiMap(); - return { - parsed: (node): void => { - collectStructsWithConsumer(node, componentv2WithConsumer); - validateStructDecoratorsAndMembers(node, context); - validateProviderInClasses(node, context); - if (arkts.isCallExpression(node)) { - validateConsumerInitialization(node, componentv2WithConsumer, context); - } - }, - }; - }, -}; - -export default rule; diff --git a/arkui-plugins/ui-syntax-plugins/rules/custom-dialog-missing-controller.ts b/arkui-plugins/ui-syntax-plugins/rules/custom-dialog-missing-controller.ts deleted file mode 100644 index f7721812c..000000000 --- a/arkui-plugins/ui-syntax-plugins/rules/custom-dialog-missing-controller.ts +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as arkts from '@koalaui/libarkts'; -import { getClassPropertyType, PresetDecorators, getAnnotationUsage } from '../utils'; -import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; - -const CUSTOM_DIALOG_CONTROLLER: string = 'CustomDialogController'; - -function missingController( - node: arkts.StructDeclaration, - context: UISyntaxRuleContext -): void { - // Check for the @CustomDialog decorator - const hasCustomDialogDecorator = getAnnotationUsage(node, PresetDecorators.CUSTOM_DIALOG); - const structName = node.definition.ident; - if (!structName) { - return; - } - // Check if there is an attribute of type CustomDialogController in the class - let hasControllerProperty = false; - node.definition.body.forEach((property) => { - if (arkts.isClassProperty(property)) { - const propertyType = getClassPropertyType(property); - if (propertyType === CUSTOM_DIALOG_CONTROLLER) { - hasControllerProperty = true; - } - } - }); - if (!hasControllerProperty && hasCustomDialogDecorator) { - context.report({ - node: structName, - message: rule.messages.missingController, - }); - } -} - -const rule: UISyntaxRule = { - name: 'custom-dialog-missing-controller', - messages: { - missingController: `The @CustomDialog decorated custom component must contain a property of the CustomDialogController type.`, - }, - setup(context) { - return { - parsed: (node): void => { - if (!arkts.isStructDeclaration(node)) { - return; - } - missingController(node, context); - }, - }; - }, -}; - -export default rule; - diff --git a/arkui-plugins/ui-syntax-plugins/rules/decorators-in-ui-component-only.ts b/arkui-plugins/ui-syntax-plugins/rules/decorators-in-ui-component-only.ts deleted file mode 100644 index b01e0d40a..000000000 --- a/arkui-plugins/ui-syntax-plugins/rules/decorators-in-ui-component-only.ts +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as arkts from '@koalaui/libarkts'; -import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; -import { PresetDecorators } from '../utils/index'; - -// Helper function to find the '@Component' decorator in a ClassDeclaration and report errors. -function findComponentDecorator(context: UISyntaxRuleContext, node: arkts.ClassDeclaration): void { - const componentDecorator = node.definition?.annotations?.find( - (annotation) => - annotation.expr && - arkts.isIdentifier(annotation.expr) && - annotation.expr.name === PresetDecorators.COMPONENT_V1 - ); - if (componentDecorator) { - reportDecoratorError(context, componentDecorator, rule.messages.invalidComponentDecorator); - } -} - -// Helper function to find the '@Prop' decorator in a MethodDefinition or ClassProperty. -const findPropDecorator = (node: arkts.MethodDefinition | arkts.ClassProperty): arkts.AnnotationUsage | undefined => { - const annotations = 'scriptFunction' in node ? node.scriptFunction.annotations : node.annotations; - return annotations?.find( - (annotation) => - annotation.expr && annotation.expr.dumpSrc() === PresetDecorators.PROP - ); -}; - -// Rule 2: Check for '@Prop' on MethodDefinition -function checkPropOnMethod(context: UISyntaxRuleContext, node: arkts.MethodDefinition): void { - const propDecorator = findPropDecorator(node); - if (propDecorator) { - reportDecoratorError(context, propDecorator, rule.messages.propOnMethod); - } -}; - -// Rule 3: Check for '@Prop' on ClassProperty within a ClassDeclaration -function checkPropOnClassProperty(context: UISyntaxRuleContext, node: arkts.ClassProperty, currentNode: arkts.AstNode) - : void { - const propDecorator = findPropDecorator(node); - while (arkts.nodeType(currentNode) !== arkts.Es2pandaAstNodeType.AST_NODE_TYPE_ETS_MODULE) { - currentNode = currentNode.parent; - if (propDecorator && arkts.isClassDeclaration(currentNode)) { - reportDecoratorError(context, propDecorator, rule.messages.propOnMethod); - } - } -}; - -function reportDecoratorError(context: UISyntaxRuleContext, Decorator: arkts.AnnotationUsage, message: string -): void { - context.report({ - node: Decorator, - message: message, - fix: () => { - const startPosition = arkts.getStartPosition(Decorator); - const endPosition = arkts.getEndPosition(Decorator); - return { - range: [startPosition, endPosition], - code: '', - }; - }, - }); -} - -const rule: UISyntaxRule = { - name: 'no-prop-on-method', - messages: { - invalidComponentDecorator: `'@Component' can decorate only custom components.`, - propOnMethod: `'@Prop' can decorate only member variables of custom components.`, - }, - setup(context) { - return { - parsed: (node: arkts.AstNode): void => { - if (arkts.isClassDeclaration(node)) { - findComponentDecorator(context, node); - } - if (arkts.isMethodDefinition(node)) { - checkPropOnMethod(context, node); - } - let currentNode = node; - if (arkts.isClassProperty(node)) { - checkPropOnClassProperty(context, node, currentNode); - } - }, - }; - }, -}; - -export default rule; \ No newline at end of file diff --git a/arkui-plugins/ui-syntax-plugins/rules/entry-localstorage-check.ts b/arkui-plugins/ui-syntax-plugins/rules/entry-localstorage-check.ts deleted file mode 100644 index aa82f3104..000000000 --- a/arkui-plugins/ui-syntax-plugins/rules/entry-localstorage-check.ts +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as arkts from '@koalaui/libarkts'; -import { getAnnotationUsage, getClassPropertyAnnotationNames, PresetDecorators } from '../utils'; -import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; - -function checkLocalStorageLink(node: arkts.StructDeclaration, context: UISyntaxRuleContext): void { - // Check if @Entry decorator exists with parameter - const entryDecorator = getAnnotationUsage(node, PresetDecorators.ENTRY); - const isStorageUsed = entryDecorator && node.definition?.annotations[0].properties[0]; - // Check if @LocalStorageLink exists - let localStorageLinkUsed = false; - node.definition.body.forEach(body => { - if (!arkts.isClassProperty(body)) { - return; - } - const propertyDecorators = getClassPropertyAnnotationNames(body); - localStorageLinkUsed = propertyDecorators.some( - decorator => decorator === PresetDecorators.LOCAL_STORAGE_LINK); - }); - - // If @LocalStorageLink is used but @Entry(storage) is missing, report error - if (entryDecorator && localStorageLinkUsed && !isStorageUsed) { - context.report({ - node: entryDecorator, - message: rule.messages.invalidUsage - }); - } -} - -const rule: UISyntaxRule = { - name: 'entry-localstorage-check', - messages: { - invalidUsage: `@LocalStorageLink requires @Entry(storage) on the struct.`, - }, - setup(context) { - return { - parsed: (node): void => { - if (!arkts.isStructDeclaration(node)) { - return; - } - checkLocalStorageLink(node, context); - }, - }; - }, -}; - -export default rule; diff --git a/arkui-plugins/ui-syntax-plugins/rules/entry-struct-no-export.ts b/arkui-plugins/ui-syntax-plugins/rules/entry-struct-no-export.ts deleted file mode 100644 index 7017ab54f..000000000 --- a/arkui-plugins/ui-syntax-plugins/rules/entry-struct-no-export.ts +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as arkts from '@koalaui/libarkts'; -import { getAnnotationUsage, PresetDecorators } from '../utils'; -import { UISyntaxRule } from './ui-syntax-rule'; - -const rule: UISyntaxRule = { - name: 'entry-struct-no-export', - messages: { - noExportWithEntry: `It's not a recommended way to export struct with @Entry decorator, which may cause ACE Engine error in component preview mode.`, - }, - setup(context) { - return { - parsed: (node): void => { - // Check if the current node is a schema declaration - if (!arkts.isStructDeclaration(node)) { - return; - } - // Get the usage of the @Entry decorator - const entryDecoratorUsage = getAnnotationUsage( - node, - PresetDecorators.ENTRY, - ); - - //Determines whether the struct is exported - const isExported = node.dumpSrc().includes('export struct'); - - // If a @Entry decorator is present and the struct is exported - if (entryDecoratorUsage && isExported) { - context.report({ - node: entryDecoratorUsage, - message: this.messages.noExportWithEntry, - }); - } - }, - }; - }, -}; - -export default rule; \ No newline at end of file diff --git a/arkui-plugins/ui-syntax-plugins/rules/index.ts b/arkui-plugins/ui-syntax-plugins/rules/index.ts deleted file mode 100644 index 13b008b62..000000000 --- a/arkui-plugins/ui-syntax-plugins/rules/index.ts +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { UISyntaxRule } from './ui-syntax-rule'; -import BuildRootNode from './build-root-node'; -import CheckConstructPrivateParameter from './check-construct-private-parameter'; -import CheckDecoratedPropertyType from './check-decorated-property-type'; -import ComponentComponentV2MixUseCheck from './component-componentV2-mix-use-check'; -import ComponentV2MixCheck from './componentV2-mix-check'; -import ConsumerProviderDecoratorCheck from './consumer-provider-decorator-check'; -import ComponentV2StateUsageValidation from './componentV2-state-usage-validation'; -import ConstructParameterLiteral from './construct-parameter-literal'; -import CustomDialogMissingController from './custom-dialog-missing-controller'; -import DecoratorsInUIComponentOnly from './decorators-in-ui-component-only'; -import EntryLoacalStorageCheck from './entry-localstorage-check'; -import EntryStructNoExport from './entry-struct-no-export'; -import LocalBuilderCheck from './local-builder-check'; -import MonitorDecoratorCheck from './monitor-decorator-check'; -import NestedRelationship from './nested-relationship'; -import NoChildInButton from './no-child-in-button'; -import NoDuplicateDecorators from './no-duplicate-decorators'; -import NoDuplicateEntry from './no-duplicate-entry'; -import NoDuplicatePreview from './no-duplicate-preview'; -import NoDuplicateStateManager from './no-duplicate-state-manager'; -import NoPropLinkObjectlinkInEntry from './no-prop-link-objectlink-in-entry'; -import NoSameAsBuiltInAttribute from './no-same-as-built-in-attribute'; -import ReuseAttributeCheck from './reuse-attribute-check'; -import StructMissingDecorator from './struct-missing-decorator'; -import StructPropertyDecorator from './struct-property-decorator'; -import StructVariableInitialization from './struct-variable-initialization'; -import TrackDecoratorCheck from './track-decorator-check'; -import TypeDecoratorCheck from './type-decorator-check'; -import ValidateBuildInStruct from './validate-build-in-struct'; -import VariableInitializationViaComponentCons from './variable-initialization-via-component-cons'; -import WatchDecoratorFunction from './watch-decorator-function'; -import WatchDecoratorRegular from './watch-decorator-regular'; -import WrapBuilderCheck from './wrap-builder-check'; -import ObservedHeritageCompatibleCheck from './observed-heritage-compatible-check'; -import ObservedObservedV2 from './observed-observedV2-check'; -import ObservedV2TraceUsageValidation from './observedV2-trace-usage-validation'; -import OnceDecoratorCheck from './once-decorator-check'; -import OneDecoratorOnFunctionMethod from './one-decorator-on-function-method'; -import OldNewDecoratorMixUseCheck from './old-new-decorator-mix-use-check'; - -const rules: UISyntaxRule[] = [ - BuildRootNode, - CheckConstructPrivateParameter, - CheckDecoratedPropertyType, - ComponentComponentV2MixUseCheck, - ComponentV2MixCheck, - ConsumerProviderDecoratorCheck, - ComponentV2StateUsageValidation, - ConstructParameterLiteral, - CustomDialogMissingController, - DecoratorsInUIComponentOnly, - EntryLoacalStorageCheck, - EntryStructNoExport, - LocalBuilderCheck, - MonitorDecoratorCheck, - NestedRelationship, - NoChildInButton, - NoDuplicateDecorators, - NoDuplicateEntry, - NoDuplicatePreview, - NoDuplicateStateManager, - NoPropLinkObjectlinkInEntry, - NoSameAsBuiltInAttribute, - ReuseAttributeCheck, - StructMissingDecorator, - StructPropertyDecorator, - StructVariableInitialization, - TrackDecoratorCheck, - TypeDecoratorCheck, - ValidateBuildInStruct, - VariableInitializationViaComponentCons, - WatchDecoratorFunction, - WatchDecoratorRegular, - WrapBuilderCheck, - ObservedHeritageCompatibleCheck, - ObservedObservedV2, - ObservedV2TraceUsageValidation, - OnceDecoratorCheck, - OneDecoratorOnFunctionMethod, - OldNewDecoratorMixUseCheck, -]; - -export default rules; diff --git a/arkui-plugins/ui-syntax-plugins/rules/local-builder-check.ts b/arkui-plugins/ui-syntax-plugins/rules/local-builder-check.ts deleted file mode 100644 index cbfeef0c3..000000000 --- a/arkui-plugins/ui-syntax-plugins/rules/local-builder-check.ts +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as arkts from '@koalaui/libarkts'; -import { PresetDecorators } from '../utils'; -import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; - -function checkLocalBuilder(node: arkts.ClassDeclaration, context: UISyntaxRuleContext): void { - node.definition?.body.forEach(body => { - if (!arkts.isMethodDefinition(body)) { - return; - } - const localBuilder = body.scriptFunction?.annotations?.find( - annotation => annotation.expr && - annotation.expr.dumpSrc() === PresetDecorators.LOCAL_BUILDER); - if (!localBuilder) { - return; - } - context.report({ - node: localBuilder, - message: rule.messages.invalidUsage, - fix: (localBuilder) => { - const startPosition = arkts.getStartPosition(localBuilder); - const endPosition = arkts.getEndPosition(localBuilder); - return { - range: [startPosition, endPosition], - code: '', - }; - }, - }); - }); -} - -const rule: UISyntaxRule = { - name: 'local-builder-check', - messages: { - invalidUsage: `The '@LocalBuilder' decorator can only be used in 'struct'.`, - }, - setup(context) { - return { - parsed: (node): void => { - if (!arkts.isClassDeclaration(node)) { - return; - } - checkLocalBuilder(node, context); - }, - }; - }, -}; - -export default rule; diff --git a/arkui-plugins/ui-syntax-plugins/rules/monitor-decorator-check.ts b/arkui-plugins/ui-syntax-plugins/rules/monitor-decorator-check.ts deleted file mode 100644 index e0696de48..000000000 --- a/arkui-plugins/ui-syntax-plugins/rules/monitor-decorator-check.ts +++ /dev/null @@ -1,174 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as arkts from '@koalaui/libarkts'; -import { PresetDecorators } from '../utils'; -import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; - -// Function declarations moved to the top with explicit return types -function getLocalMonitorUsed(body: arkts.MethodDefinition): arkts.AnnotationUsage | undefined { - const localMonitorUsed = body.scriptFunction.annotations?.find( - annotation => annotation.expr && - annotation.expr.dumpSrc() === PresetDecorators.MONITOR - ); - return localMonitorUsed; -} - -function checkConflictingDecorators(context: UISyntaxRuleContext, body: arkts.MethodDefinition, - localMonitorUsed: arkts.AnnotationUsage): boolean { - const conflictingDecorators = body.scriptFunction.annotations?.filter( - annotation => annotation.expr && - annotation.expr.dumpSrc() !== PresetDecorators.MONITOR - ); - if (conflictingDecorators?.length > 0) { - reportConflictingDecorators(context, localMonitorUsed, conflictingDecorators); - return true; - } - return false; -} - -function reportConflictingDecorators(context: UISyntaxRuleContext, localMonitorUsed: arkts.AstNode, - conflictingDecorators: arkts.AnnotationUsage[]): void { - context.report({ - node: localMonitorUsed, - message: rule.messages.invalidUsage1, - fix: () => { - const startPositions = conflictingDecorators.map(annotation => - arkts.getStartPosition(annotation)); - const endPositions = conflictingDecorators.map(annotation => arkts.getEndPosition(annotation)); - const startPosition = startPositions[0]; - const endPosition = endPositions[endPositions.length - 1]; - return { - range: [startPosition, endPosition], - code: '' - }; - } - }); -} - -function checkIfClassIsObservedV2(node: arkts.ClassDeclaration): boolean { - return node.definition?.annotations?.some( - observedV2 => observedV2.expr?.dumpSrc() === PresetDecorators.OBSERVED_V2 - ) ?? false; -} - -function checkIfStructIsComponentV2(node: arkts.StructDeclaration): boolean { - return node.definition?.annotations?.some( - componentV2 => componentV2.expr?.dumpSrc() === PresetDecorators.COMPONENT_V2 - ) ?? false; -} - -function reportInvalidUsage(context: UISyntaxRuleContext, node: arkts.AstNode, message: string, fixCode: string) - : void { - const startPosition = arkts.getStartPosition(node); - context.report({ - node, - message, - fix: () => ({ - range: [startPosition, startPosition], - code: fixCode, - }), - }); -} - -function checkMultipleDecorators( - node: arkts.ClassDeclaration | arkts.StructDeclaration, - context: UISyntaxRuleContext -): boolean { - // Traverse body of the class to check for @Monitor usage - let monitorUsed: boolean = false; - node.definition?.body.forEach(body => { - if (arkts.isMethodDefinition(body)) { - const localMonitorUsed = getLocalMonitorUsed(body); - if (localMonitorUsed) { - monitorUsed = true; - checkConflictingDecorators(context, body, localMonitorUsed); - return; // Stop further checks for this method - } - } - }); - return monitorUsed; -} - -function checkDecorateMethod( - node: arkts.ClassDeclaration | arkts.StructDeclaration, - context: UISyntaxRuleContext -): void { - // Check if @Monitor is used on a property (which is not allowed) - node.definition?.body.forEach(body => { - if (!arkts.isClassProperty(body)) { - return; - } - const monitorDecorator = body.annotations?.find( - annotation => annotation.expr?.dumpSrc() === PresetDecorators.MONITOR); - if (monitorDecorator === undefined) { - return; - } - context.report({ - node: monitorDecorator, - message: rule.messages.invalidUsage4, - fix: () => { - const startPosition = arkts.getStartPosition(monitorDecorator); - const endPosition = arkts.getEndPosition(monitorDecorator); - return { - range: [startPosition, endPosition], - code: '', - }; - }, - }); - }); -} - -// The rule object with its setup method -const rule: UISyntaxRule = { - name: 'monitor-decorator-check', - messages: { - invalidUsage1: - `The member property or method can not be decorated by multiple built-in decorators.`, - invalidUsage2: - `The '@Monitor' can decorate only member method within a 'class' decorated with @ObservedV2.`, - invalidUsage3: - `The '@Monitor' decorator can only be used in a 'struct' decorated with '@ComponentV2'.`, - invalidUsage4: - `@Monitor can only decorate method`, - }, - setup(context) { - return { - parsed: (node: arkts.AstNode): void => { - if (!arkts.isClassDeclaration(node) && !arkts.isStructDeclaration(node)) { - return; - } - let monitorUsed = false; - - const isObservedV2 = arkts.isClassDeclaration(node) && checkIfClassIsObservedV2(node); - const isComponentV2 = arkts.isStructDeclaration(node) && checkIfStructIsComponentV2(node); - - monitorUsed = checkMultipleDecorators(node, context); - - // Check for errors related to @Monitor usage - if (monitorUsed && !isObservedV2 && arkts.isClassDeclaration(node)) { - reportInvalidUsage(context, node, rule.messages.invalidUsage2, `@${PresetDecorators.OBSERVED_V2}\n`); - } - if (monitorUsed && !isComponentV2 && arkts.isStructDeclaration(node)) { - reportInvalidUsage(context, node, rule.messages.invalidUsage3, `@${PresetDecorators.COMPONENT_V2}\n`); - } - - checkDecorateMethod(node, context); - }, - }; - }, -}; - -export default rule; diff --git a/arkui-plugins/ui-syntax-plugins/rules/nested-relationship.ts b/arkui-plugins/ui-syntax-plugins/rules/nested-relationship.ts deleted file mode 100644 index fd18100e9..000000000 --- a/arkui-plugins/ui-syntax-plugins/rules/nested-relationship.ts +++ /dev/null @@ -1,191 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as arkts from '@koalaui/libarkts'; -import { getIdentifierName } from '../utils'; -import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; - -function checkInvalidChildInText(node: arkts.AstNode, context: UISyntaxRuleContext, textChild: string[]): void { - // Check if the current node is an identifier, and name is 'Text' - if (!arkts.isIdentifier(node)) { - return; - } - if (getIdentifierName(node) !== 'Text') { - return; - } - if (!node.parent) { - return; - } - const parentNode = node.parent; - if (!arkts.isCallExpression(parentNode)) { - return; - } - // If the BlockStatement contains a child component that should not exist under the text, an error will be reported - parentNode.getChildren().forEach(member => { - if (!arkts.isBlockStatement(member)) { - return; - } - member.getChildren().forEach(sibling => { - if (!arkts.isExpressionStatement(sibling) || !arkts.isCallExpression(sibling.expression)) { - return; - } - const childComponentName = sibling.expression.expression.dumpSrc(); - if (!textChild.includes(childComponentName)) { - context.report({ - node: node, - message: rule.messages.invalidChildInText - }); - return; - } - }); - }); -} -function checkOneChildInButton(node: arkts.AstNode, context: UISyntaxRuleContext): void { - // Check if the current node is an identifier, and name is 'Button' - if (!arkts.isIdentifier(node)) { - return; - } - if (getIdentifierName(node) !== 'Button') { - return; - } - if (!node.parent) { - return; - } - const parentNode = node.parent; - if (!arkts.isCallExpression(parentNode)) { - return; - } - // If there is more than one subcomponent in the BlockStatement, an error is reported - parentNode.getChildren().forEach(member => { - if (!arkts.isBlockStatement(member)) { - return; - } - if (member.statements.length > 1) { - context.report({ - node: node, - message: rule.messages.oneChildInButton - }); - } - }); -} - -function checkListItem(node: arkts.AstNode, context: UISyntaxRuleContext): void { - // Check if the current node is an identifier, and name is 'ListItem' - if (!arkts.isIdentifier(node)) { - return; - } - if (getIdentifierName(node) !== 'ListItem') { - return; - } - if (!node.parent || !node.parent.parent) { - return; - } - let curNode: arkts.AstNode = node.parent.parent; - do { - while (!arkts.isCallExpression(curNode)) { - if (!curNode.parent) { - return; - } - curNode = curNode.parent; - } - const parentName: string = curNode.expression.dumpSrc(); - if (parentName === 'List') { // If the parent component's name is 'List', exit directly - break; - } else if (parentName !== 'ForEach') { // If the parent component's name is not 'List' or 'ForEach', throw an error - context.report({ - node: node, - message: rule.messages.listItemCannotInOther, - data: { parentName: parentName } - }); - context.report({ - node: node, - message: rule.messages.listItemMustInList - }); - break; - } - // In the remaining case, the parent component is 'ForEach', continue traversing upwards for further checks - if (!curNode.parent) { - return; - } - curNode = curNode.parent; - } while (true); -} - -function checkSpan(node: arkts.AstNode, context: UISyntaxRuleContext): void { - // Check if the current node is an identifier, and name is 'Span' - if (!arkts.isIdentifier(node)) { - return; - } - if (getIdentifierName(node) !== 'Span') { - return; - } - let parentNode = node.parent; - if (!arkts.isCallExpression(parentNode)) { - return; - } - // If there are subcomponents in the BlockStatement, an error is reported - parentNode.getChildren().forEach(sibling => { - if (!arkts.isBlockStatement(sibling)) { - return; - } - if (sibling.statements.length > 0) { - context.report({ - node: node, - message: rule.messages.noChildInSpan - }); - } - }); - if (!node.parent || !node.parent.parent) { - return; - } - parentNode = parentNode.parent; - while (!arkts.isCallExpression(parentNode)) { - parentNode = parentNode.parent; - } - const parentName: string = parentNode.expression.dumpSrc(); - // If the name of the parent component is not 'Text', an error is reported - if (parentName !== 'Text' && parentName !== 'RichEditor' && parentName !== 'ContainerSpan') { - context.report({ - node: node, - message: rule.messages.spanMustInText - }); - } -} -// The 'Text' component can have only the Span, ImageSpan, ContainerSpan and SymbolSpan child component. - -const rule: UISyntaxRule = { - name: 'nested-relationship', - messages: { - invalidChildInText: `The 'Text' component can have only the Span, ImageSpan, ContainerSpan and SymbolSpan child component.`, - oneChildInButton: `The 'Button' component can have only one child component.`, - listItemMustInList: `The 'ListItem' component can only be nested in the List and ListItemGroup parent component.`, - listItemCannotInOther: `The 'ListItem' component cannot be a child component of the '{{parentName}}' component.`, - noChildInSpan: `No child component is allowed in the 'Span' component. `, - spanMustInText: `The 'Span' component can only be nested in the Text, RichEditor and ContainerSpan parent component. `, - }, - setup(context) { - const textChild: string[] = ['Span', 'ImageSpan', 'ContainerSpan', 'SymbolSpan']; - return { - parsed: (node): void => { - checkInvalidChildInText(node, context, textChild); - checkOneChildInButton(node, context); - checkListItem(node, context); - checkSpan(node, context); - }, - }; - }, -}; - -export default rule; \ No newline at end of file diff --git a/arkui-plugins/ui-syntax-plugins/rules/no-child-in-button.ts b/arkui-plugins/ui-syntax-plugins/rules/no-child-in-button.ts deleted file mode 100644 index 6cf999a27..000000000 --- a/arkui-plugins/ui-syntax-plugins/rules/no-child-in-button.ts +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as arkts from '@koalaui/libarkts'; -import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; -import { getIdentifierName } from '../utils'; - -function isInsideStructAndBuild(node: arkts.AstNode): boolean { - let parentNode = node.parent; - let isInStruct = false; - let isInBuild = false; - while (arkts.nodeType(parentNode) !== arkts.Es2pandaAstNodeType.AST_NODE_TYPE_ETS_MODULE) { - if (arkts.isStructDeclaration(parentNode)) { - isInStruct = true; - } - if (arkts.isScriptFunction(parentNode) && parentNode.id?.name === 'build') { - isInBuild = true; - } - parentNode = parentNode.parent; - } - return isInStruct && isInBuild; -} - -function reportNoChildInButtonError(parentNode: arkts.AstNode, context: UISyntaxRuleContext): void { - const siblings = parentNode.getChildren(); - if (!Array.isArray(siblings) || siblings.length < 3) { - return; - } - if (arkts.isStringLiteral(siblings[1]) && arkts.isBlockStatement(siblings[2])) { - context.report({ - node: parentNode, - message: rule.messages.noChildInButton, - fix: (parentNode) => { - const startPosition = arkts.getStartPosition(siblings[2]); - const endPosition = arkts.getEndPosition(siblings[2]); - return { - range: [startPosition, endPosition], - code: '', - }; - }, - }); - } -} - -const rule: UISyntaxRule = { - name: 'no-child-in-button', - messages: { - noChildInButton: `The Button component with a label parameter can not have any child.`, - }, - setup(context: UISyntaxRuleContext) { - return { - parsed: (node): void => { - // Check if the current node is an identifier - if (!arkts.isIdentifier(node)) { - return; - } - const componentName = getIdentifierName(node); - // If the current node is 'Button' - if (componentName !== 'Button') { - return; - } - if (!isInsideStructAndBuild(node)) { - return; - } - // Obtain the information of the parent node of the current node - let parentNode = node.parent; - if (!arkts.isCallExpression(parentNode)) { - return; - }; - // Gets and traverses all the children of the parent node - reportNoChildInButtonError(parentNode, context); - } - }; - }, -}; - -export default rule; \ No newline at end of file diff --git a/arkui-plugins/ui-syntax-plugins/rules/no-duplicate-decorators.ts b/arkui-plugins/ui-syntax-plugins/rules/no-duplicate-decorators.ts deleted file mode 100644 index ff42b2180..000000000 --- a/arkui-plugins/ui-syntax-plugins/rules/no-duplicate-decorators.ts +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as arkts from '@koalaui/libarkts'; -import { getAnnotationName, PresetDecorators } from '../utils'; -import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; - -// Decorators that cannot be repeated -const validDecorators = [ - PresetDecorators.ENTRY, - PresetDecorators.COMPONENT_V1, - PresetDecorators.COMPONENT_V2, - PresetDecorators.REUSABLE_V1, - PresetDecorators.PREVIEW, - PresetDecorators.REUSABLE_V2, - PresetDecorators.CUSTOM_DIALOG, -]; - -function checkForDuplicateDecorators(context: UISyntaxRuleContext, node: arkts.StructDeclaration): void { - // Initialize a map to record decorators and their occurrences - const decoratorCounts: Map = new Map(); - if (!node.definition || !node.definition.annotations) { - return; - } - // Record all decorators and their counts - node.definition.annotations.forEach((annotation) => { - const decoratorName = getAnnotationName(annotation); - if (!validDecorators.includes(decoratorName)) { - return; - } - - if (decoratorCounts.has(decoratorName)) { - const decoratorInfo = decoratorCounts.get(decoratorName)!; - decoratorInfo.count += 1; - decoratorInfo.annotations.push(annotation); - } else { - decoratorCounts.set(decoratorName, { count: 1, annotations: [annotation] }); - } - }); - - // Process decorators with more than one occurrence - decoratorCounts.forEach(({ count, annotations }, decoratorName) => { - if (count <= 1) { - return; - } - // Report errors for all occurrences except the last one - for (let i = 0; i < annotations.length - 1; i++) { - const prevAnnotation = annotations[i]; - reportDuplicateDecorator(context, prevAnnotation); - } - // For the last occurrence, report an error but do not provide a fix - const lastAnnotation = annotations[annotations.length - 1]; - context.report({ - node: lastAnnotation, - message: rule.messages.duplicateDecorator, - }); - }); -} - -function reportDuplicateDecorator(context: UISyntaxRuleContext, annotation: arkts.AnnotationUsage): void { - context.report({ - node: annotation, - message: rule.messages.duplicateDecorator, - fix: () => { - const startPosition = arkts.getStartPosition(annotation); - const endPosition = arkts.getEndPosition(annotation); - return { - range: [startPosition, endPosition], - code: '', - }; - }, - }); -} - -const rule: UISyntaxRule = { - name: 'no-duplicate-decorators', - messages: { - duplicateDecorator: `Duplicate decorators for struct are not allowed.`, - }, - setup(context) { - return { - parsed: (node): void => { - if (!arkts.isStructDeclaration(node)) { - return; - } - checkForDuplicateDecorators(context, node); - }, - }; - }, -}; - -export default rule; \ No newline at end of file diff --git a/arkui-plugins/ui-syntax-plugins/rules/no-duplicate-entry.ts b/arkui-plugins/ui-syntax-plugins/rules/no-duplicate-entry.ts deleted file mode 100644 index 60c810180..000000000 --- a/arkui-plugins/ui-syntax-plugins/rules/no-duplicate-entry.ts +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as arkts from '@koalaui/libarkts'; -import { getAnnotationUsage, PresetDecorators } from '../utils'; -import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; - -const MAX_ENTRY_DECORATOR_COUNT = 1; -function checkDuplicateEntry(node: arkts.AstNode, context: UISyntaxRuleContext): void { - if (arkts.nodeType(node) !== arkts.Es2pandaAstNodeType.AST_NODE_TYPE_ETS_MODULE) { - return; - } - let entryDecoratorUsages: arkts.AnnotationUsage[] = []; - node.getChildren().forEach((child) => { - if (!arkts.isStructDeclaration(child)) { - return; - } - const entryDecoratorUsage = getAnnotationUsage( - child, - PresetDecorators.ENTRY, - ); - if (entryDecoratorUsage) { - entryDecoratorUsages.push(entryDecoratorUsage); - } - }); - // If more than one entry decorator is recorded, an error is reported - if (entryDecoratorUsages.length <= MAX_ENTRY_DECORATOR_COUNT) { - return; - } - entryDecoratorUsages.forEach((entryDocoratorUsage) => { - context.report({ - node: entryDocoratorUsage, - message: rule.messages.duplicateEntry, - fix: (entryDocoratorUsage) => { - const startPosition = arkts.getStartPosition(entryDocoratorUsage); - const endPosition = arkts.getEndPosition(entryDocoratorUsage); - return { - range: [startPosition, endPosition], - code: '', - }; - } - }); - }); -} - -const rule: UISyntaxRule = { - name: 'no-duplicate-entry', - messages: { - duplicateEntry: `An ArkTS file can contain only one '@Entry' decorator.`, - }, - setup(context) { - return { - parsed: (node): void => { - checkDuplicateEntry(node, context); - }, - }; - }, -}; - -export default rule; \ No newline at end of file diff --git a/arkui-plugins/ui-syntax-plugins/rules/no-duplicate-preview.ts b/arkui-plugins/ui-syntax-plugins/rules/no-duplicate-preview.ts deleted file mode 100644 index fe57d8f11..000000000 --- a/arkui-plugins/ui-syntax-plugins/rules/no-duplicate-preview.ts +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as arkts from '@koalaui/libarkts'; -import { getAnnotationUsage, PresetDecorators } from '../utils'; -import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; - -const MAX_PREVIEW_DECORATOR_COUNT = 10; - -function checkDuplicatePreview(node: arkts.AstNode, context: UISyntaxRuleContext): void { - if (arkts.nodeType(node) !== arkts.Es2pandaAstNodeType.AST_NODE_TYPE_ETS_MODULE) { - return; - } - let previewDecoratorUsages: arkts.AnnotationUsage[] = []; - node.getChildren().forEach((child) => { - if (!arkts.isStructDeclaration(child)) { - return; - } - const previewDecoratorUsage = getAnnotationUsage( - child, - PresetDecorators.PREVIEW, - ); - if (previewDecoratorUsage) { - previewDecoratorUsages.push(previewDecoratorUsage); - } - }); - // If the number of preview decorators is greater than 10, an error is reported - if (previewDecoratorUsages.length <= MAX_PREVIEW_DECORATOR_COUNT) { - return; - } - previewDecoratorUsages.forEach((previewDecoratorUsage) => { - context.report({ - node: previewDecoratorUsage, - message: rule.messages.duplicateEntry, - fix: (previewDecoratorUsage) => { - const startPosition = arkts.getStartPosition(previewDecoratorUsage); - const endPosition = arkts.getEndPosition(previewDecoratorUsage); - return { - range: [startPosition, endPosition], - code: '', - }; - } - }); - }); -} - -const rule: UISyntaxRule = { - name: 'no-duplicate-preview', - messages: { - duplicateEntry: `An ArkTS file con contain at most 10 '@Preview' decorators.`, - }, - setup(context) { - return { - parsed: (node): void => { - checkDuplicatePreview(node, context); - }, - }; - }, -}; - -export default rule; \ No newline at end of file diff --git a/arkui-plugins/ui-syntax-plugins/rules/no-duplicate-state-manager.ts b/arkui-plugins/ui-syntax-plugins/rules/no-duplicate-state-manager.ts deleted file mode 100644 index df1468fd5..000000000 --- a/arkui-plugins/ui-syntax-plugins/rules/no-duplicate-state-manager.ts +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as arkts from '@koalaui/libarkts'; -import { getClassPropertyAnnotationNames } from '../utils'; -import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; - -export const stateManagementDecorator = { - STATE: 'State', - PROP: 'Prop', - LINK: 'Link', - PROVIDE: 'Provide', - CONSUME: 'Consume' -}; - -const CLASS_PROPERTY_ANNOTATION_ONE: number = 1; -function duplicateState( - node: arkts.StructDeclaration, - context: UISyntaxRuleContext -): void { - node.definition.body.forEach(body => { - if (arkts.isClassProperty(body)) { - // Get the list of decorators - const propertyDecorators = getClassPropertyAnnotationNames(body); - // Filter the decorators to get those related to state management - const stateDecorators = propertyDecorators.filter(decorator => - Object.values(stateManagementDecorator).includes(decorator) - ); - const propertyNameNode = body.key; - const attributeName = body.key?.dumpSrc(); - if (!propertyNameNode || !attributeName) { - return; - } - if (stateDecorators.length > CLASS_PROPERTY_ANNOTATION_ONE) { - context.report({ - node: propertyNameNode, - message: rule.messages.duplicateState, - data: { attributeName }, - }); - } - } - }); -} - -const rule: UISyntaxRule = { - name: 'no-duplicate-state-manager', - messages: { - duplicateState: `This attribute '{{attributeName}}' cannot have mutilate state management decorators. `, - }, - setup(context) { - return { - parsed: (node): void => { - if (!arkts.isStructDeclaration(node)) { - return; - } - duplicateState(node, context); - }, - }; - }, -}; - -export default rule; diff --git a/arkui-plugins/ui-syntax-plugins/rules/no-prop-link-objectlink-in-entry.ts b/arkui-plugins/ui-syntax-plugins/rules/no-prop-link-objectlink-in-entry.ts deleted file mode 100644 index 8815feff4..000000000 --- a/arkui-plugins/ui-syntax-plugins/rules/no-prop-link-objectlink-in-entry.ts +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as arkts from '@koalaui/libarkts'; -import { getAnnotationUsage, PresetDecorators } from '../utils'; -import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; - -function checkNoPropLinkOrObjectLinkInEntry(context: UISyntaxRuleContext, node: arkts.StructDeclaration): void { - // Check if the struct has the @Entry decorator - const isEntryComponent = !!getAnnotationUsage(node, PresetDecorators.ENTRY); - if (!isEntryComponent) { - return; - } - node.definition.body.forEach(body => { - if (!arkts.isClassProperty(body)) { - return; - } - const invalidDecorators = [PresetDecorators.PROP, PresetDecorators.LINK, PresetDecorators.OBJECT_LINK]; - // Check if any invalid decorators are applied to the class property - body.annotations?.forEach(annotation => { - reportInvalidDecorator(context, annotation, invalidDecorators); - }); - }); -} - -function reportInvalidDecorator(context: UISyntaxRuleContext, annotation: arkts.AnnotationUsage, - invalidDecorators: string[],): void { - if (annotation.expr && invalidDecorators.includes(annotation.expr.dumpSrc())) { - const decorator = annotation.expr.dumpSrc(); - context.report({ - node: annotation, - message: rule.messages.invalidUsage, - data: { decorator }, - fix: (annotation) => { - const startPosition = arkts.getStartPosition(annotation); - const endPosition = arkts.getEndPosition(annotation); - return { - range: [startPosition, endPosition], - code: '', - }; - }, - }); - } -} - -const rule: UISyntaxRule = { - name: 'no-prop-link-objectlink-in-entry', - messages: { - invalidUsage: `@{{decorator}} decorator cannot be used for '@Entry' decorated components.`, - }, - setup(context) { - return { - parsed: (node): void => { - if (!arkts.isStructDeclaration(node)) { - return; - } - checkNoPropLinkOrObjectLinkInEntry(context, node); - }, - }; - }, -}; - -export default rule; diff --git a/arkui-plugins/ui-syntax-plugins/rules/no-same-as-built-in-attribute.ts b/arkui-plugins/ui-syntax-plugins/rules/no-same-as-built-in-attribute.ts deleted file mode 100644 index e61af0b56..000000000 --- a/arkui-plugins/ui-syntax-plugins/rules/no-same-as-built-in-attribute.ts +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as arkts from '@koalaui/libarkts'; -import { UISyntaxRule } from './ui-syntax-rule'; - -const rule: UISyntaxRule = { - name: 'no-same-as-built-in-attribute', - messages: { - duplicateName: `The struct name '{{structName}}' should not have the same name as a built-in attribute.`, - }, - setup(context) { - const builtInAttributes = ['fontColor', 'width', 'height', 'size', 'border', 'backgroundColor', 'margin', - 'padding']; - return { - parsed: (node): void => { - if (!arkts.isStructDeclaration(node)) { - return; - } - const structName = node.definition.ident?.name ?? ' '; - const structIdent = node.definition.ident; - // If the struct name matches any built-in attribute, report an error - if (builtInAttributes.includes(structName) && structIdent) { - context.report({ - node: structIdent, - message: rule.messages.duplicateName, - data: { structName } - }); - } - }, - }; - }, -}; - -export default rule; diff --git a/arkui-plugins/ui-syntax-plugins/rules/observed-heritage-compatible-check.ts b/arkui-plugins/ui-syntax-plugins/rules/observed-heritage-compatible-check.ts deleted file mode 100644 index 95b605f2c..000000000 --- a/arkui-plugins/ui-syntax-plugins/rules/observed-heritage-compatible-check.ts +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as arkts from '@koalaui/libarkts'; -import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; -import { PresetDecorators } from '../utils/index'; - -function getObservedDecorator(node: arkts.AstNode, observedClasses: string[], observedV2Classes: string[]): void { - for (const child of node.getChildren()) { - // Check if it is of the ClassDeclaration type - if (arkts.isClassDeclaration(child)) { - // Get a list of annotations - const annotations = child.definition?.annotations ?? []; - // Check for @Observed decorators - const hasObservedDecorator = annotations.find((annotation: any) => - annotation.expr.name === PresetDecorators.OBSERVED_V1); - // Check if there is a @ObservedV2 decorator - const hasObservedV2Decorator = annotations.find((annotation: any) => - annotation.expr.name === PresetDecorators.OBSERVED_V2); - // If there is a @Observed decorator, record the class name - if (hasObservedDecorator) { - const className = child.definition?.ident?.name ?? ''; - observedClasses.push(className); - } - // If there is a @ObservedV2 decorator, record the class name - if (hasObservedV2Decorator) { - const className = child.definition?.ident?.name ?? ''; - observedV2Classes.push(className); - } - } - } -} - -function checkInheritanceCompatibility(context: UISyntaxRuleContext, node: arkts.ClassDeclaration, - observedClasses: string[], observedV2Classes: string[]): void { - const observedV1Decorator = node.definition?.annotations?.find(annotations => - annotations.expr && - arkts.isIdentifier(annotations.expr) && - annotations.expr.name === PresetDecorators.OBSERVED_V1 - ); - const observedV2Decorator = node.definition?.annotations?.find(annotations => - annotations.expr && - arkts.isIdentifier(annotations.expr) && - annotations.expr.name === PresetDecorators.OBSERVED_V2 - ); - - //Get the name of the superClass - const superClassName = node.definition?.super?.dumpSrc(); - if (!superClassName) { - return; - } - // Verify that the inheritance relationship is compatible - if (observedV1Decorator && observedV2Classes.includes(superClassName)) { - context.report({ - node: observedV1Decorator, - message: rule.messages.incompatibleHeritageObservedToObservedV2, - }); - } - if (observedV2Decorator && observedClasses.includes(superClassName)) { - context.report({ - node: observedV2Decorator, - message: rule.messages.incompatibleHeritageObservedV2ToObserved, - }); - } -} - -const rule: UISyntaxRule = { - name: 'observed-heritage-compatible-check', - messages: { - incompatibleHeritageObservedToObservedV2: `The current class is decorated by '@Observed', it cannot inherit a class decorated by '@ObservedV2'.`, - incompatibleHeritageObservedV2ToObserved: `The current class is decorated by '@ObservedV2', it cannot inherit a class decorated by '@Observed'.`, - }, - setup(context) { - // Record the class name decorated with @Observed and @ObservedV2 - const observedClasses: string[] = []; - const observedV2Classes: string[] = []; - return { - parsed: (node): void => { - // Check if it's of type "Program". - if (arkts.nodeType(node) === arkts.Es2pandaAstNodeType.AST_NODE_TYPE_ETS_MODULE) { - getObservedDecorator(node, observedClasses, observedV2Classes); - } - - // Check if the current node is a class declaration - if (!arkts.isClassDeclaration(node)) { - return; - } - checkInheritanceCompatibility(context, node, observedClasses, observedV2Classes); - }, - }; - }, -}; - -export default rule; \ No newline at end of file diff --git a/arkui-plugins/ui-syntax-plugins/rules/observed-observedV2-check.ts b/arkui-plugins/ui-syntax-plugins/rules/observed-observedV2-check.ts deleted file mode 100644 index e02304b3c..000000000 --- a/arkui-plugins/ui-syntax-plugins/rules/observed-observedV2-check.ts +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as arkts from '@koalaui/libarkts'; -import { PresetDecorators } from '../utils'; -import { UISyntaxRule } from './ui-syntax-rule'; - -const rule: UISyntaxRule = { - name: 'observed-observedV2-check', - messages: { - conflictingDecorators: `A class cannot be decorated by both '@Observed' and '@ObservedV2' at the same time.`, - }, - setup(context) { - return { - parsed: (node): void => { - if (!arkts.isClassDeclaration(node)) { - return; - } - const hasObservedDecorator = node.definition?.annotations?.find(annotations => annotations.expr && - annotations.expr.dumpSrc() === PresetDecorators.OBSERVED_V1); - const hasObservedV2Decorator = node.definition?.annotations?.find(annotations => annotations.expr && - annotations.expr.dumpSrc() === PresetDecorators.OBSERVED_V2); - // If the current class is decorated by @Observed and @ObservedV2, an error is reported - if (hasObservedDecorator && hasObservedV2Decorator) { - context.report({ - node: hasObservedDecorator, - message: rule.messages.conflictingDecorators, - }); - } - }, - }; - }, -}; - -export default rule; diff --git a/arkui-plugins/ui-syntax-plugins/rules/observedV2-trace-usage-validation.ts b/arkui-plugins/ui-syntax-plugins/rules/observedV2-trace-usage-validation.ts deleted file mode 100644 index d6285abd1..000000000 --- a/arkui-plugins/ui-syntax-plugins/rules/observedV2-trace-usage-validation.ts +++ /dev/null @@ -1,146 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as arkts from '@koalaui/libarkts'; -import { PresetDecorators, getAnnotationUsage } from '../utils'; -import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; - -const rule: UISyntaxRule = { - name: 'observedV2-trace-usage-validation', - messages: { - observedV2DecoratorError: `The '@ObservedV2' decorator can only be used in 'class'.`, - traceDecoratorError: `The '@Trace' decorator can only be used in 'class'.`, - traceInObservedV2Error: `The '@Trace' decorator can only be used in a 'class' decorated with '@ObservedV2'.`, - traceMemberVariableError: `The '@Trace' decorator can only decorate member variables within a 'class' decorated with '@ObservedV2'.`, - }, - setup(context) { - return { - parsed: (node): void => { - validateTraceDecoratorUsage(node, context); - }, - }; - }, -}; - -function reportObservedV2DecoratorError(context: UISyntaxRuleContext, hasObservedV2Decorator: arkts.AnnotationUsage) - : void { - context.report({ - node: hasObservedV2Decorator, - message: rule.messages.observedV2DecoratorError, - fix: (hasObservedV2Decorator) => { - const startPosition = arkts.getStartPosition(hasObservedV2Decorator); - const endPosition = arkts.getEndPosition(hasObservedV2Decorator); - return { - range: [startPosition, endPosition], - code: '', - }; - }, - }); -} - -function reportTraceMemberVariableError(context: UISyntaxRuleContext, hasTraceDecorator: arkts.AnnotationUsage) - : void { - context.report({ - node: hasTraceDecorator, - message: rule.messages.traceMemberVariableError, - fix: (hasTraceDecorator) => { - const startPosition = arkts.getStartPosition(hasTraceDecorator); - const endPosition = arkts.getEndPosition(hasTraceDecorator); - return { - range: [startPosition, endPosition], - code: '', - }; - }, - }); -} - -function tracePerportyRule( - context: UISyntaxRuleContext, - currentNode: arkts.AstNode, - hasTraceDecorator: arkts.AnnotationUsage): void { - if (arkts.isStructDeclaration(currentNode)) { - reportTraceDecoratorError(context, hasTraceDecorator); - } else if (arkts.isClassDeclaration(currentNode)) { - // The '@Trace' decorator can only be used in a 'class' decorated with '@ObservedV2' - if (!currentNode.definition?.annotations?.some((annotation: any) => annotation.expr.name === - PresetDecorators.OBSERVED_V2)) { - reportTraceInObservedV2Error(context, hasTraceDecorator, currentNode); - } - } -} - -function reportTraceDecoratorError(context: UISyntaxRuleContext, hasTraceDecorator: arkts.AnnotationUsage) - : void { - context.report({ - node: hasTraceDecorator, - message: rule.messages.traceDecoratorError, - fix: (hasTraceDecorator) => { - const startPosition = arkts.getStartPosition(hasTraceDecorator); - const endPosition = arkts.getEndPosition(hasTraceDecorator); - return { - range: [startPosition, endPosition], - code: '', - }; - }, - }); -} - -function reportTraceInObservedV2Error(context: UISyntaxRuleContext, hasTraceDecorator: arkts.AnnotationUsage, - currentNode: arkts.ClassDeclaration): void { - context.report({ - node: hasTraceDecorator, - message: rule.messages.traceInObservedV2Error, - fix: () => { - const startPosition = arkts.getStartPosition(currentNode); - return { - range: [startPosition, startPosition], - code: `@${PresetDecorators.OBSERVED_V2}\n`, - }; - }, - }); -} - -function validateTraceDecoratorUsage(node: arkts.AstNode, context: UISyntaxRuleContext): void { - let currentNode = node; - if (arkts.isStructDeclaration(node)) { - // Check whether the current custom component is decorated by the @ObservedV2 decorator - const hasObservedV2Decorator = getAnnotationUsage(node, PresetDecorators.OBSERVED_V2); - if (hasObservedV2Decorator) { - reportObservedV2DecoratorError(context, hasObservedV2Decorator); - } - } - if (arkts.isClassProperty(node)) { - const hasTraceDecorator = node.annotations?.find(annotation => - annotation.expr && annotation.expr.dumpSrc() === PresetDecorators.TRACE); - if (hasTraceDecorator) { - // Iterate up the parent node to check whether it is a class or a custom component - while (!arkts.isStructDeclaration(currentNode) && !arkts.isClassDeclaration(currentNode)) { - currentNode = currentNode.parent; - } - // The '@Trace' decorator can only be used in 'class' - tracePerportyRule(context, currentNode, hasTraceDecorator); - } - } - if (arkts.isMethodDefinition(node)) { - // Check that @Trace is in the correct location - const hasTraceDecorator = node.scriptFunction.annotations?.find(annotation => - annotation.expr && annotation.expr.dumpSrc() === PresetDecorators.TRACE); - if (hasTraceDecorator) { - reportTraceMemberVariableError(context, hasTraceDecorator); - } - } -} - -export default rule; diff --git a/arkui-plugins/ui-syntax-plugins/rules/old-new-decorator-mix-use-check.ts b/arkui-plugins/ui-syntax-plugins/rules/old-new-decorator-mix-use-check.ts deleted file mode 100644 index 356a28098..000000000 --- a/arkui-plugins/ui-syntax-plugins/rules/old-new-decorator-mix-use-check.ts +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as arkts from '@koalaui/libarkts'; -import { PresetDecorators, getAnnotationUsage } from '../utils'; -import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; - -function findPropertyDecorator( - node: arkts.ClassProperty, - decoratorName: string -): arkts.AnnotationUsage | undefined { - const annotation = node.annotations?.find(annotation => - annotation.expr && - annotation.expr.dumpSrc() === decoratorName - ); - return annotation; -} - -function paramDecoratorError( - context: UISyntaxRuleContext, - hasParamDecorator: arkts.AnnotationUsage, - hasComponentDecorator: arkts.AnnotationUsage -): void { - context.report({ - node: hasParamDecorator, - message: rule.messages.paramDecoratorError, - fix: () => { - const startPosition = arkts.getStartPosition(hasComponentDecorator); - const endPosition = arkts.getEndPosition(hasComponentDecorator); - return { - range: [startPosition, endPosition], - code: `@${PresetDecorators.COMPONENT_V2}`, - }; - }, - }); -} - -function stateDecoratorError( - context: UISyntaxRuleContext, - hasStateDecorator: arkts.AnnotationUsage, - hasComponentV2Decorator: arkts.AnnotationUsage -): void { - context.report({ - node: hasStateDecorator, - message: rule.messages.stateDecoratorError, - fix: () => { - const startPosition = arkts.getStartPosition(hasComponentV2Decorator); - const endPosition = arkts.getEndPosition(hasComponentV2Decorator); - return { - range: [startPosition, endPosition], - code: `@${PresetDecorators.COMPONENT_V1}`, - }; - }, - }); -} - -function findDecoratorError( - node: arkts.StructDeclaration, - context: UISyntaxRuleContext -): void { - const hasComponentV2Decorator = getAnnotationUsage(node, PresetDecorators.COMPONENT_V2); - const hasComponentDecorator = getAnnotationUsage(node, PresetDecorators.COMPONENT_V1); - // Check where @Param and @State are used - node.definition.body.forEach((property) => { - if (arkts.isClassProperty(property)) { - const hasParamDecorator = findPropertyDecorator(property, PresetDecorators.PARAM); - const hasStateDecorator = findPropertyDecorator(property, PresetDecorators.STATE); - // Check that @Param is in the correct location - if (hasParamDecorator && !hasComponentV2Decorator && hasComponentDecorator) { - paramDecoratorError(context, hasParamDecorator, hasComponentDecorator); - } - // Check that @State is in the correct location - if (hasStateDecorator && !hasComponentDecorator && hasComponentV2Decorator) { - stateDecoratorError(context, hasStateDecorator, hasComponentV2Decorator); - } - } - }); -} - - -const rule: UISyntaxRule = { - name: 'old-new-decorator-mix-use-check', - messages: { - paramDecoratorError: `The '@Param' decorator can only be used in a 'struct' decorated with '@ComponentV2'.`, - stateDecoratorError: `The '@State' decorator can only be used in a 'struct' decorated with '@Component'.`, - }, - setup(context) { - return { - parsed: (node): void => { - if (!arkts.isStructDeclaration(node)) { - return; - } - findDecoratorError(node, context); - }, - }; - }, -}; - -export default rule; diff --git a/arkui-plugins/ui-syntax-plugins/rules/once-decorator-check.ts b/arkui-plugins/ui-syntax-plugins/rules/once-decorator-check.ts deleted file mode 100644 index fabe04af0..000000000 --- a/arkui-plugins/ui-syntax-plugins/rules/once-decorator-check.ts +++ /dev/null @@ -1,187 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as arkts from '@koalaui/libarkts'; -import { getAnnotationUsage, getClassPropertyAnnotationNames, PresetDecorators } from '../utils'; -import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; - -function findDecorator(member: arkts.ClassProperty, decorator: string): arkts.AnnotationUsage | undefined { - return member.annotations?.find(annotation => - annotation.expr && - annotation.expr.dumpSrc() === decorator - ); -} - -// Check that the property decorator complies with the rules -function validatePropertyAnnotations( - body: arkts.ClassProperty, - context: UISyntaxRuleContext, - hasOnceDecorator: arkts.AnnotationUsage | undefined -): void { - const propertyAnnotations = getClassPropertyAnnotationNames(body); - hasOnceDecorator = findDecorator(body, PresetDecorators.ONCE); - if (hasOnceDecorator) { - const isParamUsed = propertyAnnotations.includes(PresetDecorators.PARAM); - // If @Once is found, check if @Param is also used - if (!isParamUsed) { - reportMissingParamWithOnce(hasOnceDecorator, context); - } else { - // If both @Once and @Param are used, check for other - // incompatible decorators - const otherDecorators = body.annotations?.find(annotation => - annotation.expr && - annotation.expr.dumpSrc() !== PresetDecorators.ONCE && - annotation.expr.dumpSrc() !== PresetDecorators.PARAM - ); - reportInvalidDecoratorsWithOnceAndParam(otherDecorators, context); - } - } -} - -function reportMissingParamWithOnce( - hasOnceDecorator: arkts.AnnotationUsage | undefined, - context: UISyntaxRuleContext -): void { - if (!hasOnceDecorator) { - return; - } - context.report({ - node: hasOnceDecorator, - message: rule.messages.invalidDecorator, - fix: (hasOnceDecorator) => { - const startPosition = arkts.getEndPosition(hasOnceDecorator); - const endPosition = arkts.getEndPosition(hasOnceDecorator); - return { - range: [startPosition, endPosition], - code: `@${PresetDecorators.PARAM}` - }; - } - }); -} - -function reportInvalidDecoratorsWithOnceAndParam( - otherDecorators: arkts.AnnotationUsage | undefined, - context: UISyntaxRuleContext -): void { - if (!otherDecorators) { - return; - } - context.report({ - node: otherDecorators, - message: rule.messages.invalidDecorator, - fix: (otherDecorators) => { - const startPosition = arkts.getStartPosition(otherDecorators); - const endPosition = arkts.getEndPosition(otherDecorators); - return { - range: [startPosition, endPosition], - code: '' - }; - } - }); -} - -// Check if the method is @Once decorated (not allowed) -function validateMethodAnnotations(body: arkts.MethodDefinition, context: UISyntaxRuleContext): void { - const methodAnnotations = body.scriptFunction.annotations?.find(annotation => - annotation.expr && - annotation.expr.dumpSrc() === PresetDecorators.ONCE - ); - if (methodAnnotations) { - context.report({ - node: methodAnnotations, - message: rule.messages.invalidMemberDecorate, - fix: (methodAnnotations) => { - const startPosition = arkts.getStartPosition(methodAnnotations); - const endPosition = arkts.getEndPosition(methodAnnotations); - return { - range: [startPosition, endPosition], - code: '' - }; - } - }); - } -} - -function invalidComponentUsage( - body: arkts.ClassProperty, - hasOnceDecorator: arkts.AnnotationUsage | undefined, - componentV2DocoratorUsage: arkts.AnnotationUsage | undefined, - componentDocoratorUsage: arkts.AnnotationUsage | undefined, - context: UISyntaxRuleContext -): void { - hasOnceDecorator = findDecorator(body, PresetDecorators.ONCE); - if (hasOnceDecorator && !componentV2DocoratorUsage && componentDocoratorUsage) { - context.report({ - node: hasOnceDecorator, - message: rule.messages.invalidUsage, - fix: (hasOnceDecorator) => { - const startPosition = arkts.getStartPosition(componentDocoratorUsage); - const endPosition = arkts.getEndPosition(componentDocoratorUsage); - return { - range: [startPosition, endPosition], - code: `@${PresetDecorators.COMPONENT_V2}` - }; - } - }); - } -} - -function validateDecorater( - node: arkts.StructDeclaration, - hasOnceDecorator: arkts.AnnotationUsage | undefined, - componentV2DocoratorUsage: arkts.AnnotationUsage | undefined, - componentDocoratorUsage: arkts.AnnotationUsage | undefined, - context: UISyntaxRuleContext, -): void { - node.definition?.body.forEach(body => { - // Check if @Once is used on a property and if @Param is used with - if (arkts.isClassProperty(body)) { - validatePropertyAnnotations(body, context, hasOnceDecorator); - // If @Once is used but not in a @ComponentV2 struct, report an error - invalidComponentUsage(body, hasOnceDecorator, componentV2DocoratorUsage, componentDocoratorUsage, context); - } - if (!arkts.isMethodDefinition(body)) { - return; - } - // Check if @Once is used on a method (which is not allowed) - validateMethodAnnotations(body, context); - }); -} - -const rule: UISyntaxRule = { - name: 'once-decorator-check', - messages: { - invalidUsage: `@Once can only decorate member properties in a @ComponentV2 struct.`, - invalidMemberDecorate: `@Once can only decorate member properties.`, - invalidDecorator: `@Once must be only used with @Param. ` - }, - setup(context) { - return { - parsed: (node): void => { - // Check if the node is a struct declaration - if (!arkts.isStructDeclaration(node)) { - return; - } - let hasOnceDecorator: arkts.AnnotationUsage | undefined; - // Check if the struct is decorated with @ComponentV2 - const componentV2DocoratorUsage = getAnnotationUsage(node, PresetDecorators.COMPONENT_V2); - const componentDocoratorUsage = getAnnotationUsage(node, PresetDecorators.COMPONENT_V1); - validateDecorater(node, hasOnceDecorator, componentV2DocoratorUsage, componentDocoratorUsage, context); - }, - }; - }, -}; - -export default rule; diff --git a/arkui-plugins/ui-syntax-plugins/rules/one-decorator-on-function-method.ts b/arkui-plugins/ui-syntax-plugins/rules/one-decorator-on-function-method.ts deleted file mode 100644 index 66dd9cdbd..000000000 --- a/arkui-plugins/ui-syntax-plugins/rules/one-decorator-on-function-method.ts +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as arkts from '@koalaui/libarkts'; -import { getAnnotationName } from '../utils'; -import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; - -const allowedDecorators = new Set(['Extend', 'Builder', 'Styles']); - -function validateFunctionDecorator(node: arkts.EtsScript, context: UISyntaxRuleContext): void { - node.statements.forEach((statement) => { - // If the node is not a function declaration, it is returned - if (!arkts.isFunctionDeclaration(statement)) { - return; - } - const annotations = statement.annotations; - // If there is no annotation, go straight back - if (!annotations) { - return; - } - // Check that each annotation is in the list of allowed decorators - annotations.forEach((annotation) => { - const decoratorName = getAnnotationName(annotation); - // rule1: misuse of decorator, only '@Extend', '@Builder' , '@Styles' decorators allowed on global functions - if (!allowedDecorators.has(decoratorName)) { - context.report({ - node: annotation, - message: rule.messages.invalidDecorator, - data: { - decoratorName, - }, - }); - } - }); - }); -} - -const rule: UISyntaxRule = { - name: 'one-decorator-on-function-method', - messages: { - invalidDecorator: `misuse of '@{{decoratorName}}' decorator, only '@Extend', '@Builder' and '@Styles' decorators allowed on global functions.`, - }, - setup(context) { - return { - parsed: (node: arkts.AstNode): void => { - // If the node is not an ETS script, it is returned directly - if (!arkts.isEtsScript(node)) { - return; - } - validateFunctionDecorator(node, context); - }, - }; - }, -}; - -export default rule; diff --git a/arkui-plugins/ui-syntax-plugins/rules/reuse-attribute-check.ts b/arkui-plugins/ui-syntax-plugins/rules/reuse-attribute-check.ts deleted file mode 100644 index 773b133ac..000000000 --- a/arkui-plugins/ui-syntax-plugins/rules/reuse-attribute-check.ts +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as arkts from '@koalaui/libarkts'; -import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; -import { PresetDecorators, getAnnotationUsage } from '../utils'; - -function findStructsWithReusableAndComponentV2(node: arkts.AstNode, reusableV2ComponentV2Struct: string[]): void { - //Go through all the children of Program - for (const childNode of node.getChildren()) { - // Check whether the type is struct - if (!arkts.isStructDeclaration(childNode)) { - continue; - } - // Check that the current component has @ComponentV2 and @ReusableV2 decorators - const hasReusableV2Decorator = getAnnotationUsage(childNode, PresetDecorators.REUSABLE_V2); - const hasComponentV2Decorator = getAnnotationUsage(childNode, PresetDecorators.COMPONENT_V2); - if (hasReusableV2Decorator && hasComponentV2Decorator) { - const struceName = childNode.definition?.ident?.name ?? ''; - reusableV2ComponentV2Struct.push(struceName); - } - } -} - -function validateReuseOrReuseIdUsage(context: UISyntaxRuleContext, node: arkts.MemberExpression, - reusableV2ComponentV2Struct: string[]): void { - const structNode = node.object; - // Gets the reuse or reuseId attribute - const decoratedNode = node.property; - if (arkts.isCallExpression(structNode)) { - const Node = structNode.expression; - if (decoratedNode.dumpSrc() === 'reuse' && !reusableV2ComponentV2Struct.includes(Node.dumpSrc())) { - reportInvalidReuseUsage(context, node, structNode, rule); - } - else if (decoratedNode.dumpSrc() === 'reuseId' && reusableV2ComponentV2Struct.includes(Node.dumpSrc())) { - reportInvalidReuseIdUsage(context, node, structNode, rule); - } - } -} - -function reportInvalidReuseUsage(context: UISyntaxRuleContext, node: arkts.AstNode, structNode: arkts.AstNode, - rule: any): void { - context.report({ - node: node, - message: rule.messages.invalidReuseUsage, - fix: (node) => { - const startPosition = arkts.getStartPosition(node); - const endPosition = arkts.getEndPosition(node); - return { - range: [startPosition, endPosition], - code: `${structNode.dumpSrc()}.reuseId`, - }; - }, - }); -} - -function reportInvalidReuseIdUsage(context: UISyntaxRuleContext, node: arkts.AstNode, structNode: arkts.AstNode, - rule: any): void { - context.report({ - node: node, - message: rule.messages.invalidReuseIdUsage, - fix: (node) => { - const startPosition = arkts.getStartPosition(node); - const endPosition = arkts.getEndPosition(node); - return { - range: [startPosition, endPosition], - code: `${structNode.dumpSrc()}.reuse`, - }; - }, - }); -} - -const rule: UISyntaxRule = { - name: 'reuse-attribute-check', - messages: { - invalidReuseUsage: `The reuse attribute is only applicable to custom components decorated with both @ComponentV2 and @ReusableV2.`, - invalidReuseIdUsage: `The reuseId attribute is not applicable to custom components decorated with both @ComponentV2 and @ReusableV2.`, - }, - setup(context) { - const reusableV2ComponentV2Struct: string[] = []; - return { - parsed: (node): void => { - // Check whether the type is "Program" - if (arkts.nodeType(node) === arkts.Es2pandaAstNodeType.AST_NODE_TYPE_ETS_MODULE) { - findStructsWithReusableAndComponentV2(node, reusableV2ComponentV2Struct); - } - if (arkts.isMemberExpression(node)) { - validateReuseOrReuseIdUsage(context, node, reusableV2ComponentV2Struct); - } - }, - }; - }, -}; - -export default rule; \ No newline at end of file diff --git a/arkui-plugins/ui-syntax-plugins/rules/struct-missing-decorator.ts b/arkui-plugins/ui-syntax-plugins/rules/struct-missing-decorator.ts deleted file mode 100644 index 7ca8e7b3a..000000000 --- a/arkui-plugins/ui-syntax-plugins/rules/struct-missing-decorator.ts +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as arkts from '@koalaui/libarkts'; -import { getAnnotationUsage, PresetDecorators } from '../utils'; -import { UISyntaxRule } from './ui-syntax-rule'; - -const rule: UISyntaxRule = { - name: 'struct-missing-decorator', - messages: { - missingComponentDecorator: `struct '{{structName}}' is missing '@Component' or '@CustomDialog' decorators`, - misusedPreview: `struct '{{structName}}' misused '@Preview' decorator. it should be decorated by '@Component' or '@CustomDialog'`, - misusedObserved: `struct '{{structName}}' misused '@Observed' decorator. it should be decorated by '@Component' or '@CustomDialog'`, - }, - setup(context) { - function hasDecorator(node: arkts.StructDeclaration, decorator: string): boolean { - return !!getAnnotationUsage(node, decorator); - } - - return { - parsed: (node): void => { - if (!arkts.isStructDeclaration(node)) { - return; - } - // Check for the presence of specific decorators on the struct - const structName = node.definition.ident?.name ?? ''; - const structNode = node.definition.ident; - const hasComponent = hasDecorator(node, PresetDecorators.COMPONENT_V1); - const hasComponentV2 = hasDecorator(node, PresetDecorators.COMPONENT_V2); - const hasCustomDialog = hasDecorator(node, PresetDecorators.CUSTOM_DIALOG); - const hasPreview = getAnnotationUsage(node, PresetDecorators.PREVIEW); - const hasObserved = getAnnotationUsage(node, PresetDecorators.OBSERVED_V1); - // If no valid component decorators (@Component or @CustomDialog) are found - if (!hasComponent && !hasComponentV2 && !hasCustomDialog && structNode) { - context.report({ - node: structNode, - message: rule.messages.missingComponentDecorator, - data: { structName }, - }); - } - // If the @Preview decorator is used but the struct is not decorated with @Component or @CustomDialog - if (hasPreview && !hasComponent && !hasComponentV2 && !hasCustomDialog && structNode) { - context.report({ - node: structNode, - message: rule.messages.misusedPreview, - data: { structName }, - }); - } - // If the @Observed decorator is used but the struct is not decorated with @Component or @CustomDialog - if (hasObserved && !hasComponent && !hasComponentV2 && !hasCustomDialog && structNode) { - context.report({ - node: structNode, - message: rule.messages.misusedObserved, - data: { structName }, - }); - } - }, - }; - }, -}; - -export default rule; diff --git a/arkui-plugins/ui-syntax-plugins/rules/struct-property-decorator.ts b/arkui-plugins/ui-syntax-plugins/rules/struct-property-decorator.ts deleted file mode 100644 index 9aaa53de0..000000000 --- a/arkui-plugins/ui-syntax-plugins/rules/struct-property-decorator.ts +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as arkts from '@koalaui/libarkts'; -import { getClassPropertyAnnotationNames } from '../utils'; -import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; - -function checkInvalidStaticPropertyDecorations(context: UISyntaxRuleContext, node: arkts.StructDeclaration): void { - node.definition.body.forEach((member) => { - // Errors are reported when the node type is ClassProperty, - if (arkts.isClassProperty(member)) { - const propertyNameNode = member.key; - if ((member.isStatic && getClassPropertyAnnotationNames(member).length > 0) && propertyNameNode) { - context.report({ - node: propertyNameNode, - message: rule.messages.invalidStaticUsage - }); - } - } - }); -} - -const rule: UISyntaxRule = { - name: 'struct-property-decorator', - messages: { - invalidStaticUsage: `Static variables in custom components cannot be decorated by built-in variable decorators.` - }, - setup(context) { - return { - parsed: (node): void => { - if (!arkts.isStructDeclaration(node)) { - return; - } - checkInvalidStaticPropertyDecorations(context, node); - }, - }; - }, -}; - -export default rule; \ No newline at end of file diff --git a/arkui-plugins/ui-syntax-plugins/rules/struct-variable-initialization.ts b/arkui-plugins/ui-syntax-plugins/rules/struct-variable-initialization.ts deleted file mode 100644 index 63c06587f..000000000 --- a/arkui-plugins/ui-syntax-plugins/rules/struct-variable-initialization.ts +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as arkts from '@koalaui/libarkts'; -import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; - -// A list of decorators that needs to be initialized locally -const mustInitializeDecorators = ['State', 'StorageLink', 'StorageProp', 'LocalStorageLink', 'LocalStorageProp', - 'Provide']; -// Disables a list of decorators that are initialized locally -const prohibitInitializeDecorators = ['Link', 'Consume', 'ObjectLink']; - -function reportVariablesInitializationError(context: UISyntaxRuleContext, node: arkts.ClassProperty): void { - // Check whether the value field exists and whether it has been initialized - const valueExists = !!node.value; - // Iterate through each decorator and verify the initialization rules - node.annotations.forEach(annotation => { - const decoratorName = annotation.expr?.dumpSrc() ?? ''; - if (mustInitializeDecorators.includes(decoratorName)) { - // If it is a decorator that needs to be initialized - if (!valueExists) { - // If there is no initialization expression and there is no @Require, an error is reported - context.report({ - node: annotation, - message: rule.messages.mustBeInitializedLocally, - }); - } - } else if (prohibitInitializeDecorators.includes(decoratorName)) { - // If it is a decorator that prohibits initialization - if (valueExists) { - // If an initialization expression exists, an error is reported - context.report({ - node: annotation, - message: rule.messages.prohibitLocalInitialization, - }); - } - } - }); -} - -const rule: UISyntaxRule = { - name: 'struct-variable-initialization', - messages: { - mustBeInitializedLocally: `Variables decorated by '@State', '@StorageLink', '@StorageProp', '@LocalStorageLink', '@LocalStorageProp' and '@Provide' must be initialized locally.`, - prohibitLocalInitialization: `Variables decorated by '@Link', '@Consume', and '@ObjectLink' cannot be initialized locally.` - }, - setup(context) { - return { - parsed: (node): void => { - // Check if the current node is a class attribute - if (!arkts.isClassProperty(node)) { - return; - } - reportVariablesInitializationError(context, node); - } - }; - } -}; - -export default rule; \ No newline at end of file diff --git a/arkui-plugins/ui-syntax-plugins/rules/track-decorator-check.ts b/arkui-plugins/ui-syntax-plugins/rules/track-decorator-check.ts deleted file mode 100644 index db909687b..000000000 --- a/arkui-plugins/ui-syntax-plugins/rules/track-decorator-check.ts +++ /dev/null @@ -1,146 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as arkts from '@koalaui/libarkts'; -import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; -import { PresetDecorators } from '../utils/index'; - -const rule: UISyntaxRule = { - name: 'track-decorator-check', - messages: { - invalidTarget: `The '@Track' decorator can only be used on class member variables.`, - invalidClass: `The '@Track' decorator can only be used within a 'class' decorated with '@Observed'.` - }, - setup(context) { - return { - parsed: (node): void => { - if (arkts.isStructDeclaration(node)) { - checkInvalidTrackAnnotations(context, node); - } - // Check if the current node is a class declaration - if (arkts.isClassDeclaration(node)) { - checkTrackOnlyUsedWithObserved(context, node); - } - } - }; - } -}; - -function checkInvalidTrackAnnotations(context: UISyntaxRuleContext, node: arkts.StructDeclaration): void { - // Traverse all members of the struct body - node.definition.body.forEach((member) => { - // Check whether it is a member variable - if (arkts.isClassProperty(member)) { - const hasTrackDecorator = findClassPropertyAnnotation(member, PresetDecorators.TRACK); - // If a member variable is decorated with @Track, an error is reported immediately - if (hasTrackDecorator) { - reportInvalidTarget(context, hasTrackDecorator); - } - } - // Check whether this is the method - if (arkts.isMethodDefinition(member)) { - const hasTrackDecorator = getMethodAnnotation(member, PresetDecorators.TRACK); - // If the method is decorated with @Track, an error is reported immediately - if (hasTrackDecorator) { - reportInvalidTarget(context, hasTrackDecorator); - } - } - },); -} - -function checkTrackOnlyUsedWithObserved(context: UISyntaxRuleContext, node: arkts.ClassDeclaration): void { - // Check if the class is decorated with @Observed - const hasObservedDecorator = node.definition?.annotations?.find( - annotations => - annotations.expr && - arkts.isIdentifier(annotations.expr) && - annotations.expr.name === PresetDecorators.OBSERVED_V1 - ); - // Traverse all members of the body class - node.definition?.body.forEach((member) => { - // Check whether it is a class attribute - if (arkts.isClassProperty(member)) { - const hasTrackDecorator = findClassPropertyAnnotation(member, PresetDecorators.TRACK); - // If the class is not decorated with @Observed and has decorators, an error is reported - if (!hasObservedDecorator && hasTrackDecorator) { - reportInvalidClass(context, hasTrackDecorator); - } - } - // Check whether this is the method - if (arkts.isMethodDefinition(member)) { - const hasTrackDecorator = getMethodAnnotation(member, PresetDecorators.TRACK); - // If the method is decorated with @Track, an error is reported immediately - if (hasTrackDecorator) { - reportInvalidTarget(context, hasTrackDecorator); - } - } - }); -} - -function reportInvalidClass(context: UISyntaxRuleContext, hasTrackDecorator: arkts.AnnotationUsage): void { - context.report({ - node: hasTrackDecorator, - message: rule.messages.invalidClass, - fix: (hasTrackDecorator) => { - const startPosition = arkts.getStartPosition(hasTrackDecorator); - const endPosition = arkts.getEndPosition(hasTrackDecorator); - return { - range: [startPosition, endPosition], - code: '', - }; - }, - }); -} - -function getMethodAnnotation( - node: arkts.MethodDefinition, - annotationName: string) - : arkts.AnnotationUsage | undefined { - return node.scriptFunction.annotations?.find( - annotation => - annotation.expr && - annotation.expr.dumpSrc() === annotationName - ); -} - -function findClassPropertyAnnotation( - node: arkts.ClassProperty, - annotationName: string) - : arkts.AnnotationUsage | undefined { - return node.annotations?.find(annotation => - annotation.expr && - annotation.expr.dumpSrc() === annotationName - ); -} - -function reportInvalidTarget( - context: UISyntaxRuleContext, - node: arkts.AnnotationUsage) - : void { - context.report({ - node: node, - message: rule.messages.invalidTarget, - fix: (node) => { - const startPosition = arkts.getStartPosition(node); - const endPosition = arkts.getEndPosition(node); - return { - range: [startPosition, endPosition], - code: '', - }; - }, - }); -} - -export default rule; \ No newline at end of file diff --git a/arkui-plugins/ui-syntax-plugins/rules/type-decorator-check.ts b/arkui-plugins/ui-syntax-plugins/rules/type-decorator-check.ts deleted file mode 100644 index 79c60be2e..000000000 --- a/arkui-plugins/ui-syntax-plugins/rules/type-decorator-check.ts +++ /dev/null @@ -1,167 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as arkts from '@koalaui/libarkts'; -import { getAnnotationName, PresetDecorators } from '../utils'; -import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; - -function findTypeDecorator( - annotations: readonly arkts.AnnotationUsage[] -): arkts.AnnotationUsage | undefined { - let hasTypeDecorator = annotations?.find(annotation => - annotation.expr && - annotation.expr.dumpSrc() === PresetDecorators.TYPE - ); - return hasTypeDecorator; -} - -function hasDecoratorType( - node: arkts.ClassDeclaration, -): arkts.AnnotationUsage | undefined { - let hasTypeDecorator: arkts.AnnotationUsage | undefined; - node.definition?.body.forEach(member => { - if (arkts.isClassProperty(member) && member.annotations) { - hasTypeDecorator = findTypeDecorator(member.annotations); - } - }); - return hasTypeDecorator; -} - -// rule1: @Type can only be used for class -function checkTypeInStruct( - node: arkts.StructDeclaration, - context: UISyntaxRuleContext, -): void { - let hasTypeDecorator: arkts.AnnotationUsage | undefined; - node.definition?.body.forEach(member => { - if (arkts.isClassProperty(member) && member.annotations) { - hasTypeDecorator = findTypeDecorator(member.annotations); - reportInvalidTypeUsageInStruct(hasTypeDecorator, context); - } - }); -} - -function reportInvalidTypeUsageInStruct( - hasTypeDecorator: arkts.AnnotationUsage | undefined, - context: UISyntaxRuleContext -): void { - if (!hasTypeDecorator) { - return; - } - context.report({ - node: hasTypeDecorator, - message: rule.messages.invalidType, - fix: (hasTypeDecorator) => { - const startPosition = arkts.getStartPosition(hasTypeDecorator); - const endPosition = arkts.getEndPosition(hasTypeDecorator); - return { - range: [startPosition, endPosition], - code: '' - }; - } - }); -} - -// rule2: Conflict between @Type and @Observed -function checkObservedAndTypeConflict( - node: arkts.ClassDeclaration, - context: UISyntaxRuleContext -): void { - let hasTypeDecorator: arkts.AnnotationUsage | undefined; - node.definition?.annotations.forEach(member => { - const annotation = getAnnotationName(member); - hasTypeDecorator = hasDecoratorType(node); - if (annotation === PresetDecorators.OBSERVED_V1) { - reportObservedAndTypeDecoratorConflict(hasTypeDecorator, context); - } - }); -} - -function reportObservedAndTypeDecoratorConflict( - hasTypeDecorator: arkts.AnnotationUsage | undefined, - context: UISyntaxRuleContext -): void { - if (!hasTypeDecorator) { - return; - } - context.report({ - node: hasTypeDecorator, - message: rule.messages.invalidDecoratorWith, - fix: () => { - const startPosition = arkts.getStartPosition(hasTypeDecorator); - const endPosition = arkts.getEndPosition(hasTypeDecorator); - return { - range: [startPosition, endPosition], - code: '' - }; - } - }); -} - -// rule3: @TypeCannot be used for function members -function validateScriptFunctionForTypeDecorator( - node: arkts.ScriptFunction, - context: UISyntaxRuleContext -): void { - const hasTypeDecorator = findTypeDecorator(node.annotations); - reportInvalidTypeDecorator(hasTypeDecorator, context); -} - -function reportInvalidTypeDecorator( - hasTypeDecorator: arkts.AnnotationUsage | undefined, - context: UISyntaxRuleContext -): void { - if (!hasTypeDecorator) { - return; - } - context.report({ - node: hasTypeDecorator, - message: rule.messages.invalidTypeMember, - fix: (hasTypeDecorator) => { - const startPosition = arkts.getStartPosition(hasTypeDecorator); - const endPosition = arkts.getEndPosition(hasTypeDecorator); - return { - range: [startPosition, endPosition], - code: '' - }; - } - }); -} - -const rule: UISyntaxRule = { - name: 'type-decorator-check', - messages: { - invalidType: `The @Type decorator can only be used in 'class'.`, - invalidDecoratorWith: `The @Type decorator can not be used within a 'class' decorated with @Observed.`, - invalidTypeMember: `The @Type can decorate only member variables in a 'class'.` - }, - setup(context) { - return { - parsed: (node): void => { - // Check the decorator on the class - if (arkts.isClassDeclaration(node)) { - checkObservedAndTypeConflict(node, context); - } - if (arkts.isStructDeclaration(node)) { - checkTypeInStruct(node, context); - } - if (arkts.isScriptFunction(node) && node.annotations) { - validateScriptFunctionForTypeDecorator(node, context); - } - }, - }; - }, -}; -export default rule; diff --git a/arkui-plugins/ui-syntax-plugins/rules/ui-syntax-rule.ts b/arkui-plugins/ui-syntax-plugins/rules/ui-syntax-rule.ts deleted file mode 100644 index c71a7c298..000000000 --- a/arkui-plugins/ui-syntax-plugins/rules/ui-syntax-rule.ts +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as arkts from '@koalaui/libarkts'; - -export type FixSuggestion = { - range: [start: arkts.SourcePosition, end: arkts.SourcePosition]; - code: string; -}; - -export type ReportOptions = { - node: arkts.AstNode; - message: string; - data?: Record; - fix?: (node: arkts.AstNode) => FixSuggestion; -}; - -export type UISyntaxRuleContext = { - report(options: ReportOptions): void; - containerComponents?: Set | undefined; -}; - -export type UISyntaxRuleHandler = (node: arkts.AstNode) => void; - -export type UISyntaxRule = { - name: string; - messages: Record; - setup(context: UISyntaxRuleContext): { - parsed?: UISyntaxRuleHandler; - }; -}; diff --git a/arkui-plugins/ui-syntax-plugins/rules/validate-build-in-struct.ts b/arkui-plugins/ui-syntax-plugins/rules/validate-build-in-struct.ts deleted file mode 100644 index 938c3a210..000000000 --- a/arkui-plugins/ui-syntax-plugins/rules/validate-build-in-struct.ts +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as arkts from '@koalaui/libarkts'; -import { getIdentifierName } from '../utils'; -import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; - -const NOT_PARAM_LENGTH: number = 0; -const BUILD_NAME: string = 'build'; -const BUILD_FUNCTION_COUNT_INI: number = 0; -const BUILD_FUNCTION_COUNT: number = 1; -const NOT_STATEMENT_LENGTH: number = 0; - -// rule1: Check if the build function contains arguments and report an error -function validateBuildFunctionParameters(buildFunction: arkts.MethodDefinition, context: UISyntaxRuleContext): void { - const paramsNodes = buildFunction.scriptFunction.params; - if (paramsNodes.length > NOT_PARAM_LENGTH) { - paramsNodes.forEach((param) => { - if (arkts.isEtsParameterExpression(param)) { - reportBuildParamNotAllowed(param, context); - } - }); - } -} - -// Report an error with an unallowed parameter in the build function -function reportBuildParamNotAllowed( - param: arkts.ETSParameterExpression, - context: UISyntaxRuleContext -): void { - context.report({ - node: param, - message: rule.messages.invalidComponet, - fix: (param) => { - const startPosition = arkts.getStartPosition(param); - const endPosition = arkts.getEndPosition(param); - return { - range: [startPosition, endPosition], - code: '' - }; - } - }); -} - -function validateConstructorForBuildFunction( - node: arkts.StructDeclaration, - member: arkts.MethodDefinition, - buildFunctionCount: number, - context: UISyntaxRuleContext -): void { - const blockStatement = member.scriptFunction.body; - if (!blockStatement || !arkts.isBlockStatement(blockStatement)) { - return; - } - const statements = blockStatement.statements; - const structName = node.definition.ident; - if (buildFunctionCount !== BUILD_FUNCTION_COUNT && - statements.length === NOT_STATEMENT_LENGTH) { - reportMissingBuildInStruct(structName, blockStatement, context); - } -} - -function reportMissingBuildInStruct( - structName: arkts.Identifier | undefined, - blockStatement: arkts.BlockStatement, - context: UISyntaxRuleContext -): void { - if (!structName) { - return; - } - context.report({ - node: structName, - message: rule.messages.invalidBuild, - fix: (structName) => { - const startPosition = arkts.getStartPosition(blockStatement); - const endPosition = startPosition; - return { - range: [startPosition, endPosition], - code: '{\nbuild {\n}' - }; - } - }); -} - -function validateBuild( - node: arkts.StructDeclaration, - buildFunctionCount: number, - context: UISyntaxRuleContext, -): void { - node.definition.body.forEach((member) => { - // Check if the member is defined for the method and the method name is 'build' - if (arkts.isMethodDefinition(member) && getIdentifierName(member.name) === BUILD_NAME) { - buildFunctionCount++; - validateBuildFunctionParameters(member, context); - } - // rule2: This rule validates the use of the 'build' function - if (arkts.isMethodDefinition(member) && - arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_CONSTRUCTOR === member.kind) { - validateConstructorForBuildFunction(node, member, buildFunctionCount, context); - } - }); -} - -const rule: UISyntaxRule = { - name: 'validate-build-in-struct', - messages: { - invalidComponet: `A custom component can have only one 'build' function, which does not require parameters.`, - invalidBuild: `This rule validates the use of the 'build' function`, - }, - setup(context) { - return { - parsed: (node: arkts.AstNode): void => { - if (!arkts.isStructDeclaration(node)) { - return; - } - let buildFunctionCount: number = BUILD_FUNCTION_COUNT_INI; - validateBuild(node, buildFunctionCount, context); - }, - }; - }, -}; - -export default rule; \ No newline at end of file diff --git a/arkui-plugins/ui-syntax-plugins/rules/variable-initialization-via-component-cons.ts b/arkui-plugins/ui-syntax-plugins/rules/variable-initialization-via-component-cons.ts deleted file mode 100644 index 7660e6624..000000000 --- a/arkui-plugins/ui-syntax-plugins/rules/variable-initialization-via-component-cons.ts +++ /dev/null @@ -1,210 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as arkts from '@koalaui/libarkts'; -import { getIdentifierName, getClassPropertyAnnotationNames, PresetDecorators } from '../utils'; -import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; - -// Define a function to add property data to the property map -function addProperty(propertyMap: Map>, structName: string, - propertyName: string, annotationName: string): void { - if (!propertyMap.has(structName)) { - propertyMap.set(structName, new Map()); - } - const structProperties = propertyMap.get(structName); - if (structProperties) { - structProperties.set(propertyName, annotationName); - } -} -// categorizePropertyBasedOnAnnotations -function checkPropertyByAnnotations( - item: arkts.AstNode, - structName: string, - mustInitMap: Map>, - cannotInitMap: Map> = new Map(), - mustInitArray: string[][], - cannotInitArray: string[][] -): void { - if (!arkts.isClassProperty(item)) { - return; - } - const propertyName: string = item.key?.dumpSrc() ?? ''; - if (item.annotations.length === 0 || propertyName === '') { - return; - } - const annotationArray: string[] = getClassPropertyAnnotationNames(item); - // If the member variable is decorated, it is added to the corresponding map - mustInitArray.forEach(arr => { - if (arr.every(annotation => annotationArray.includes(annotation))) { - const annotationName: string = arr[0]; - addProperty(mustInitMap, structName, propertyName, annotationName); - } - }); - cannotInitArray.forEach(arr => { - if (arr.every(annotation => annotationArray.includes(annotation))) { - const annotationName: string = arr[0]; - addProperty(cannotInitMap, structName, propertyName, annotationName); - } - }); -} - -function initMap( - node: arkts.AstNode, - mustInitMap: Map>, - cannotInitMap: Map> = new Map(), - mustInitArray: string[][], - cannotInitArray: string[][] -): void { - if (arkts.nodeType(node) !== arkts.Es2pandaAstNodeType.AST_NODE_TYPE_ETS_MODULE) { - return; - } - node.getChildren().forEach((member) => { - if (!arkts.isStructDeclaration(member)) { - return; - } - const structName: string = member.definition.ident?.name ?? ''; - if (structName === '') { - return; - } - member.definition?.body.forEach((item) => { - checkPropertyByAnnotations(item, structName, mustInitMap, cannotInitMap, mustInitArray, cannotInitArray); - }); - }); -} - -function getChildKeyNameArray(member: arkts.AstNode): string[] { - const childkeyNameArray: string[] = []; - member.getChildren().forEach((property) => { - if (arkts.isProperty(property)) { - const childkeyName = property.key?.dumpSrc() ?? ''; - if (childkeyName !== '') { - childkeyNameArray.push(childkeyName); - } - } - }); - return childkeyNameArray; -} - -function checkMustInitialize( - node: arkts.AstNode, - context: UISyntaxRuleContext, - mustInitMap: Map> -): void { - if (!arkts.isIdentifier(node)) { - return; - } - const structName: string = getIdentifierName(node); - if (!mustInitMap.has(structName)) { - return; - } - const parentNode: arkts.AstNode = node.parent; - if (!arkts.isCallExpression(parentNode)) { - return; - } - // Get all the properties of a record via StructName - const mustInitName: Map = mustInitMap.get(structName)!; - parentNode.arguments?.forEach((member) => { - const childkeyNameArray: string[] = getChildKeyNameArray(member); - mustInitName.forEach((value, key) => { - // If an attribute that must be initialized is not initialized, an error is reported - if (!childkeyNameArray.includes(key)) { - context.report({ - node: parentNode, - message: rule.messages.mustInitializeRule, - data: { - annotationName: value, - propertyName: key, - }, - }); - } - }); - }); -} - -function checkCannotInitialize( - node: arkts.AstNode, - context: UISyntaxRuleContext, - cannotInitMap: Map> -): void { - if (!arkts.isIdentifier(node)) { - return; - } - const structName: string = getIdentifierName(node); - if (!cannotInitMap.has(structName)) { - return; - } - const parentNode: arkts.AstNode = node.parent; - if (!arkts.isCallExpression(parentNode)) { - return; - } - // Get all the properties of a record via StructName - const cannotInitName: Map = cannotInitMap.get(structName)!; - parentNode.arguments.forEach((member) => { - member.getChildren().forEach((property) => { - if (!arkts.isProperty(property)) { - return; - } - if (!property.key) { - return; - } - const propertyName = property.key.dumpSrc(); - // If a property that cannot be initialized is initialized, an error is reported - if (cannotInitName.has(propertyName)) { - context.report({ - node: property.key, - message: rule.messages.cannotInitializeRule, - data: { - annotationName: cannotInitName.get(propertyName)!, - propertyName: propertyName, - }, - }); - } - }); - }); -} - -const rule: UISyntaxRule = { - name: 'variable-initialization-via-component-cons', - messages: { - mustInitializeRule: `'@{{annotationName}}' decorated '{{propertyName}}' must be initialized through the component constructor.`, - cannotInitializeRule: `'@{{annotationName}}' decorated '{{propertyName}}' cannot be initialized through the component constructor.`, - }, - setup(context) { - let mustInitMap: Map> = new Map(); - let cannotInitMap: Map> = new Map(); - const mustInitArray: string[][] = [ - [PresetDecorators.REQUIRE, PresetDecorators.PROP], - [PresetDecorators.REQUIRE, PresetDecorators.BUILDER_PARAM], - [PresetDecorators.LINK], - [PresetDecorators.OBJECT_LINK] - ]; - const cannotInitArray: string[][] = [ - [PresetDecorators.STORAGE_LINK], - [PresetDecorators.STORAGE_PROP], - [PresetDecorators.CONSUME], - [PresetDecorators.LOCAL_STORAGE_LINK], - [PresetDecorators.LOCAL_STORAGE_PROP] - ]; - return { - parsed: (node): void => { - initMap(node, mustInitMap, cannotInitMap, mustInitArray, cannotInitArray); - checkMustInitialize(node, context, mustInitMap); - checkCannotInitialize(node, context, cannotInitMap); - }, - }; - }, -}; - -export default rule; \ No newline at end of file diff --git a/arkui-plugins/ui-syntax-plugins/rules/watch-decorator-function.ts b/arkui-plugins/ui-syntax-plugins/rules/watch-decorator-function.ts deleted file mode 100644 index dae346a79..000000000 --- a/arkui-plugins/ui-syntax-plugins/rules/watch-decorator-function.ts +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as arkts from '@koalaui/libarkts'; -import { getIdentifierName, PresetDecorators } from '../utils'; -import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; - -// Gets the names of all methods in the struct -function getMethodNames(node: arkts.StructDeclaration): string[] { - const methodNames: string[] = []; - node.definition.body.forEach((member) => { - if (arkts.isMethodDefinition(member)) { - const methodName = getIdentifierName(member.name); - if (methodName) { - methodNames.push(methodName); - } - } - }); - return methodNames; -} - -// Invalid @Watch decorator bugs are reported -function reportInvalidWatch( - member: arkts.ClassProperty, - methodName: string, - hasWatchDecorator: arkts.AnnotationUsage, - context: UISyntaxRuleContext -): void { - context.report({ - node: hasWatchDecorator, - message: rule.messages.invalidWatch, - data: { methodName }, - fix: () => { - const startPosition = arkts.getEndPosition(member); - const endPosition = arkts.getEndPosition(member); - return { - range: [startPosition, endPosition], - code: `\n${methodName}(){\n}`, - }; - }, - }); -} - -function validateWatchDecorator( - member: arkts.ClassProperty, - methodNames: string[], - hasWatchDecorator: arkts.AnnotationUsage | undefined, - context: UISyntaxRuleContext -): void { - member.annotations.forEach((annotation) => { - validateWatchProperty(annotation, member, methodNames, hasWatchDecorator, context); - }); -} - -function validateWatchProperty( - annotation: arkts.AnnotationUsage, - member: arkts.ClassProperty, - methodNames: string[], - hasWatchDecorator: arkts.AnnotationUsage | undefined, - context: UISyntaxRuleContext -): void { - if ( - annotation.expr && - annotation.expr.dumpSrc() === PresetDecorators.WATCH - ) { - annotation.properties.forEach((element) => { - if (!arkts.isClassProperty(element)) { - return; - } - const methodName = element.value?.dumpSrc().slice(1, -1); - if (hasWatchDecorator && methodName && !methodNames.includes(methodName)) { - reportInvalidWatch(member, methodName, hasWatchDecorator, context); - } - }); - } - -} - -function validateWatch( - node: arkts.StructDeclaration, - methodNames: string[], - context: UISyntaxRuleContext -): void { - node.definition.body.forEach(member => { - if (!arkts.isClassProperty(member)) { - return; - } - const hasWatchDecorator = member.annotations?.find(annotation => - annotation.expr && - annotation.expr.dumpSrc() === PresetDecorators.WATCH - ); - // Determine whether it contains @watch decorators - validateWatchDecorator(member, methodNames, hasWatchDecorator, context); - }); -} - -const rule: UISyntaxRule = { - name: 'watch-decorator-function', - messages: { - invalidWatch: `The '@Watch' decorated parameter must be a callback '{{methodName}}' of a function in a custom component.`, - }, - setup(context) { - return { - parsed: (node): void => { - if (!arkts.isStructDeclaration(node)) { - return; - } - // Get all method names - const methodNames = getMethodNames(node); - validateWatch(node, methodNames, context); - }, - }; - }, -}; - -export default rule; \ No newline at end of file diff --git a/arkui-plugins/ui-syntax-plugins/rules/watch-decorator-regular.ts b/arkui-plugins/ui-syntax-plugins/rules/watch-decorator-regular.ts deleted file mode 100644 index 22eb47c74..000000000 --- a/arkui-plugins/ui-syntax-plugins/rules/watch-decorator-regular.ts +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as arkts from '@koalaui/libarkts'; -import { getClassPropertyAnnotationNames, PresetDecorators } from '../utils'; -import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; - -const PROPERTY_ANNOTATION_NUM: number = 2; - -function validateWatchDecorator(node: arkts.StructDeclaration, context: UISyntaxRuleContext): void { - node.definition.body.forEach(member => { - if (!arkts.isClassProperty(member)) { - return; - } - const hasWatchDecorator = member.annotations?.find(annotation => - annotation.expr && - annotation.expr.dumpSrc() === PresetDecorators.WATCH - ); - const propertyAnnotationNames = getClassPropertyAnnotationNames(member); - // Determine if there are any decorations other than @watch decorations - // rule1: The @Watch decorator must be used with other decorators - if (hasWatchDecorator && propertyAnnotationNames.length < PROPERTY_ANNOTATION_NUM) { - context.report({ - node: hasWatchDecorator, - message: rule.messages.invalidWatch, - }); - } - }); -} - -const rule: UISyntaxRule = { - name: 'watch-decorator-regular', - messages: { - invalidWatch: `The @Watch decorator must be used with other decorators.`, - }, - setup(context) { - return { - parsed: (node): void => { - if (!arkts.isStructDeclaration(node)) { - return; - } - validateWatchDecorator(node, context); - }, - }; - }, -}; - -export default rule; diff --git a/arkui-plugins/ui-syntax-plugins/rules/wrap-builder-check.ts b/arkui-plugins/ui-syntax-plugins/rules/wrap-builder-check.ts deleted file mode 100644 index 5f87ef3fc..000000000 --- a/arkui-plugins/ui-syntax-plugins/rules/wrap-builder-check.ts +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as arkts from '@koalaui/libarkts'; -import { getIdentifierName, getAnnotationName, PresetDecorators } from '../utils'; -import { UISyntaxRule, UISyntaxRuleContext } from './ui-syntax-rule'; - -const WRAPBUILDER_NAME: string = 'wrapBuilder'; -// Collect all the function names that are decorated with @Builder -function collectBuilderFunctions(node: arkts.EtsScript, builderFunctionNames: string[]): void { - node.statements.forEach((statement) => { - if (!arkts.isFunctionDeclaration(statement)) { - return; - } - const annotations = statement.annotations; - if (!annotations) { - return; - } - annotations.forEach((annotation) => { - const decoratorName = getAnnotationName(annotation); - // Find all the functions that are decorated with @Builder and note their names - if (!decoratorName.includes(PresetDecorators.BUILDER)) { - return; - } - const functionName = statement.scriptFunction.id?.name; - if (!functionName || builderFunctionNames.includes(functionName)) { - return; - } - builderFunctionNames.push(functionName); - }); - }); -} - -// Verify that the wrapBuilder's arguments are decorated with @Builder -function validateWrapBuilderArguments( - member: arkts.ClassProperty, - context: UISyntaxRuleContext, - builderFunctionNames: string[] -): void { - member.getChildren().forEach((child) => { - if (!arkts.isCallExpression(child) || child.expression.dumpSrc() !== WRAPBUILDER_NAME) { - return; - } - let functionName: string | undefined; - child.arguments.forEach(firstArgument => { - if (arkts.isMemberExpression(firstArgument)) { - functionName = getIdentifierName(firstArgument.property); - } else if (arkts.isIdentifier(firstArgument)) { - functionName = firstArgument.name; - } - // Verify that wrapBuilder's arguments are decorated with @Builder - // rule1: The wrapBuilder accepts only a function decorated by '@Builder' - if (functionName && !builderFunctionNames.includes(functionName)) { - context.report({ - node: firstArgument, - message: rule.messages.invalidBuilderCheck, - }); - } - }); - }); -} - -function validateWrapBuilder( - node: arkts.StructDeclaration, - builderFunctionNames: string[], - context: UISyntaxRuleContext -): void { - node.definition.body.forEach(member => { - if (!arkts.isClassProperty(member)) { - return; - } - validateWrapBuilderArguments(member, context, builderFunctionNames); - }); -} - -const rule: UISyntaxRule = { - name: 'wrap-builder-check', - messages: { - invalidBuilderCheck: 'The wrapBuilder accepts only a function decorated by @Builder.', - }, - setup(context) { - let builderFunctionNames: string[] = []; - return { - parsed: (node): void => { - if (arkts.isEtsScript(node)) { - collectBuilderFunctions(node, builderFunctionNames); - } - if (!arkts.isStructDeclaration(node)) { - return; - } - validateWrapBuilder(node, builderFunctionNames, context); - }, - }; - }, -}; - -export default rule; diff --git a/arkui-plugins/ui-syntax-plugins/transformers/parsed-ui-syntax-linter-transformer.ts b/arkui-plugins/ui-syntax-plugins/transformers/parsed-ui-syntax-linter-transformer.ts deleted file mode 100644 index d8c642ed2..000000000 --- a/arkui-plugins/ui-syntax-plugins/transformers/parsed-ui-syntax-linter-transformer.ts +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as arkts from '@koalaui/libarkts'; -import { UISyntaxLinterVisitor } from './ui-syntax-linter-visitor'; - -export class ParsedUISyntaxLinterTransformer extends UISyntaxLinterVisitor { - visitor(node: arkts.AstNode): arkts.AstNode { - this.processor.parsed(node); - node = this.visitEachChild(node); - return node; - } -} diff --git a/arkui-plugins/ui-syntax-plugins/transformers/ui-syntax-linter-visitor.ts b/arkui-plugins/ui-syntax-plugins/transformers/ui-syntax-linter-visitor.ts deleted file mode 100644 index 356304f88..000000000 --- a/arkui-plugins/ui-syntax-plugins/transformers/ui-syntax-linter-visitor.ts +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { AbstractVisitor } from '../../common/abstract-visitor'; -import { UISyntaxRuleProcessor } from '../processor'; - -export abstract class UISyntaxLinterVisitor extends AbstractVisitor { - constructor(protected processor: UISyntaxRuleProcessor) { - super(); - } -} diff --git a/arkui-plugins/ui-syntax-plugins/utils/index.ts b/arkui-plugins/ui-syntax-plugins/utils/index.ts deleted file mode 100644 index 87ba336a7..000000000 --- a/arkui-plugins/ui-syntax-plugins/utils/index.ts +++ /dev/null @@ -1,200 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as arkts from '@koalaui/libarkts'; -import * as fs from 'fs'; -import * as path from 'path'; - -export const PresetDecorators = { - BUILDER_PARAM: 'BuilderParam', - COMPONENT_V1: 'Component', - COMPONENT_V2: 'ComponentV2', - COMPUTED: 'Computed', - CONSUME: 'Consume', - CONSUMER: 'Consumer', - CUSTOM_DIALOG: 'CustomDialog', - ENTRY: 'Entry', - EVENT: 'Event', - PREVIEW: 'Preview', - STATE: 'State', - PARAM: 'Param', - PROP: 'Prop', - PROVIDE: 'Provide', - PROVIDER: 'Provider', - LINK: 'Link', - LOCAL: 'Local', - OBJECT_LINK: 'ObjectLink', - STORAGE_PROP: 'StorageProp', - STORAGE_LINK: 'StorageLink', - LOCAL_STORAGE_PROP: 'LocalStorageProp', - LOCAL_STORAGE_LINK: 'LocalStorageLink', - REQUIRE: 'Require', - REUSABLE_V1: 'Reusable', - REUSABLE_V2: 'ReusableV2', - OBSERVED_V1: 'Observed', - OBSERVED_V2: 'ObservedV2', - TYPE: 'Type', - WATCH: 'Watch', - BUILDER: 'Builder', - TRACK: 'Track', - TRACE: 'Trace', - ONCE: 'Once', - MONITOR: 'Monitor', - LOCAL_BUILDER: 'LocalBuilder', -}; - -const PUBLIC_PROPERTY_MODIFIERS: Number = 4; -const PROTECTED_PROPERTY_MODIFIERS: Number = 8; -const PRIVATE_PROPERTY_MODIFIERS: Number = 16; -export function getIdentifierName(node: arkts.AstNode): string { - if (!arkts.isIdentifier(node)) { - throw new Error(`Except a Identifier type!`); - } - return node.name; -} - -export function getAnnotationName(annotation: arkts.AnnotationUsage): string { - if (!annotation.expr) { - throw new Error(`The expr property does not exist!`); - } - return getIdentifierName(annotation.expr); -} - -export function getAnnotationUsage( - declaration: arkts.StructDeclaration, - annotationName: string, -): arkts.AnnotationUsage | undefined { - return declaration.definition.annotations.find( - (annotation) => - annotation.expr && - arkts.isIdentifier(annotation.expr) && - annotation.expr.name === annotationName, - ); -} - -export function getClassAnnotationUsage( - declaration: arkts.ClassDeclaration, - annotationName: string, -): arkts.AnnotationUsage | undefined { - if (!declaration.definition || !declaration.definition.annotations) { - return undefined; - } - return declaration.definition.annotations.find( - (annotation) => - annotation.expr && - ((arkts.isIdentifier(annotation.expr) && annotation.expr.name === annotationName) || - (arkts.isCallExpression(annotation.expr) && - arkts.isIdentifier(annotation.expr) && - annotation.expr.name === annotationName)) - ); -} - - - -export function getClassPropertyName(property: arkts.ClassProperty): string { - return getIdentifierName(property.key); -} - -export function getClassPropertyType(property: arkts.ClassProperty): string { - return property.typeAnnotation.dumpSrc(); -} - -export function getClassPropertyAnnotationNames( - property: arkts.ClassProperty, -): string[] { - return property.annotations.map((annotation) => - getAnnotationName(annotation), - ); -} - -export function isPublicClassProperty(property: arkts.ClassProperty): boolean { - // todo 使用接口实现 - return property.modifiers === PUBLIC_PROPERTY_MODIFIERS; -} - -export function isPrivateClassProperty(property: arkts.ClassProperty): boolean { - // todo 使用接口实现 - return property.modifiers === PRIVATE_PROPERTY_MODIFIERS; -} - -export function isProtectedlassProperty(property: arkts.ClassProperty): boolean { - // todo 使用接口实现 - return property.modifiers === PROTECTED_PROPERTY_MODIFIERS; -} - -export class MultiMap { - private readonly map: Map; - constructor() { - this.map = new Map(); - } - /** - * Add key-value pairs to MultiMap - * @param key key - * @param value value - */ - add(key: K, value: V): void { - if (!this.map.has(key)) { - this.map.set(key, []); - } - this.map.get(key)!.push(value); - } - - /** - * Gets all the values of the specified key - * @param key key - * @returns An array of values, which returns an empty array if the key does not exist - */ - get(key: K): V[] { - return this.map.get(key) || []; - } - - /** - * Check if the specified key exists in the MultiMap - * @param key key - * @returns Whether it exists - */ - has(key: K): boolean { - return this.map.has(key); - } -} - -interface ComponentJson { - name: string; - atomic?: boolean; - attrs: string[]; -} - -export function getContainerComponents(dirPath: string): Set { - const resultSet = new Set(); - const absolutePath = path.resolve(__dirname, dirPath); - - if (!fs.existsSync(absolutePath)) { - throw new Error(`Directory does not exist: ${absolutePath}`); - } - // Read all files in the directory - const files = fs.readdirSync(absolutePath); - - files.forEach(file => { - if (path.extname(file) === '.json') { - const filePath = path.join(absolutePath, file); - const fileContent = fs.readFileSync(filePath, 'utf-8'); - const componentJson: ComponentJson = JSON.parse(fileContent); - if ((!componentJson.atomic || componentJson.atomic !== true) && (componentJson.name)) { - resultSet.add(componentJson.name); - } - } - }); - return resultSet; -} \ No newline at end of file diff --git a/koala-wrapper/BUILD.gn b/koala-wrapper/BUILD.gn index 58807818d..d9ad69899 100644 --- a/koala-wrapper/BUILD.gn +++ b/koala-wrapper/BUILD.gn @@ -12,7 +12,6 @@ # limitations under the License. import("//build/ohos.gni") -import("//build/config/components/ets_frontend/ets2abc_config.gni") npm_path = "//prebuilts/build-tools/common/nodejs/current/bin/npm" @@ -44,11 +43,3 @@ ohos_copy("ets2panda_koala_wrapper") { subsystem_name = "developtools" part_name = "ace_ets2bundle" } - -ohos_copy("ohos_ets_koala_wrapper") { - deps = [ ":gen_sdk_ts_wrapper" ] - sources = [ rebase_path("$target_gen_dir") ] - outputs = [ ohos_ets_koala_wrapper_path ] - subsystem_name = "developtools" - part_name = "ace_ets2bundle" -} \ No newline at end of file diff --git a/koala-wrapper/native/src/bridges.cc b/koala-wrapper/native/src/bridges.cc index 2b0549ac7..5c177990e 100644 --- a/koala-wrapper/native/src/bridges.cc +++ b/koala-wrapper/native/src/bridges.cc @@ -31,22 +31,6 @@ void impl_ClassDefinitionSetFromStructModifier(KNativePointer contextPtr, KNativ } KOALA_INTEROP_V2(ClassDefinitionSetFromStructModifier, KNativePointer, KNativePointer); -KBoolean impl_ImportSpecifierIsRemovableConst(KNativePointer contextPtr, KNativePointer instancePtr) -{ - auto context = reinterpret_cast(contextPtr); - auto node = reinterpret_cast(instancePtr); - return GetImpl()->ImportSpecifierIsRemovableConst(context, node); -} -KOALA_INTEROP_2(ImportSpecifierIsRemovableConst, KBoolean, KNativePointer, KNativePointer); - -void impl_ImportSpecifierSetRemovable(KNativePointer contextPtr, KNativePointer instancePtr) -{ - auto context = reinterpret_cast(contextPtr); - auto node = reinterpret_cast(instancePtr); - return GetImpl()->ImportSpecifierSetRemovable(context, node, true); -} -KOALA_INTEROP_V2(ImportSpecifierSetRemovable, KNativePointer, KNativePointer); - KNativePointer impl_AstNodeRecheck(KNativePointer contextPtr, KNativePointer nodePtr) { auto context = reinterpret_cast(contextPtr); @@ -221,14 +205,6 @@ KNativePointer impl_ContextErrorMessage(KNativePointer contextPtr) } KOALA_INTEROP_1(ContextErrorMessage, KNativePointer, KNativePointer) -KNativePointer impl_GetAllErrorMessages(KNativePointer contextPtr) -{ - auto context = reinterpret_cast(contextPtr); - - return new string(GetImpl()->GetAllErrorMessages(context)); -} -KOALA_INTEROP_1(GetAllErrorMessages, KNativePointer, KNativePointer) - KNativePointer impl_CallExpressionSignature(KNativePointer context, KNativePointer classInstance) { const auto _context = reinterpret_cast(context); @@ -283,29 +259,6 @@ static KNativePointer impl_ExternalSourcePrograms(KNativePointer instance) } KOALA_INTEROP_1(ExternalSourcePrograms, KNativePointer, KNativePointer); -KNativePointer impl_CreateContextGenerateAbcForExternalSourceFiles( - KNativePointer configPtr, KInt fileNamesCount, KStringArray fileNames) -{ - auto config = reinterpret_cast(configPtr); - const std::size_t headerLen = 4; - const char **argv = - new const char *[static_cast(fileNamesCount)]; - std::size_t position = headerLen; - std::size_t strLen; - for (std::size_t i = 0; i < static_cast(fileNamesCount); ++i) { - strLen = unpackUInt(fileNames + position); - position += headerLen; - argv[i] = strdup(std::string(reinterpret_cast(fileNames + position), - strLen).c_str()); - position += strLen; - } - auto context = GetImpl()->CreateContextGenerateAbcForExternalSourceFiles( - config, fileNamesCount, argv); - delete[] argv; - return context; -} -KOALA_INTEROP_3(CreateContextGenerateAbcForExternalSourceFiles, KNativePointer, KNativePointer, KInt, KStringArray) - KBoolean impl_IsClassProperty(KNativePointer nodePtr) { auto node = reinterpret_cast(nodePtr); @@ -417,120 +370,4 @@ KNativePointer impl_ETSParserGetGlobalProgramAbsName(KNativePointer contextPtr) auto result = GetImpl()->ETSParserGetGlobalProgramAbsName(context); return new std::string(result); } -KOALA_INTEROP_1(ETSParserGetGlobalProgramAbsName, KNativePointer, KNativePointer) - -KNativePointer impl_ClassVariableDeclaration(KNativePointer context, KNativePointer classInstance) -{ - const auto _context = reinterpret_cast(context); - const auto _classInstance = reinterpret_cast(classInstance); - auto _typedTsType = GetImpl()->TypedTsType(_context, _classInstance); - if (_typedTsType == nullptr) { - return nullptr; - } - const auto _instanceType = reinterpret_cast(_typedTsType); - auto _typeVar = GetImpl()->TypeVariable(_context, _instanceType); - if (_typeVar == nullptr) { - return nullptr; - } - const auto result = reinterpret_cast(GetImpl()->VariableDeclaration(_context, _typeVar)); - const auto declNode = GetImpl()->DeclNode(_context, result); - return declNode; -} -KOALA_INTEROP_2(ClassVariableDeclaration, KNativePointer, KNativePointer, KNativePointer) - -KBoolean impl_IsMethodDefinition(KNativePointer nodePtr) -{ - auto node = reinterpret_cast(nodePtr); - return GetImpl()->IsMethodDefinition(node); -} -KOALA_INTEROP_1(IsMethodDefinition, KBoolean, KNativePointer) - -KNativePointer impl_CreateETSImportDeclaration(KNativePointer context, KNativePointer source, - KNativePointerArray specifiers, KUInt specifiersSequenceLength, - KInt importKind, KNativePointer programPtr, KInt flags) -{ - const auto _context = reinterpret_cast(context); - const auto _source = reinterpret_cast(source); - const auto _specifiers = reinterpret_cast(specifiers); - const auto _specifiersSequenceLength = static_cast(specifiersSequenceLength); - const auto _importKind = static_cast(importKind); - const auto _program = reinterpret_cast(programPtr); - const auto _flags = static_cast(flags); - auto result = GetImpl()->ETSParserBuildImportDeclaration(_context, _importKind, _specifiers, - _specifiersSequenceLength, _source, _program, _flags); - return result; -} -KOALA_INTEROP_7(CreateETSImportDeclaration, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, - KUInt, KInt, KNativePointer, KInt) - -KNativePointer impl_AstNodeRangeConst(KNativePointer context, KNativePointer node) -{ - const auto _context = reinterpret_cast(context); - const auto _node = reinterpret_cast(node); - auto result = GetImpl()->AstNodeRangeConst(_context, _node); - return (void*)result; -} -KOALA_INTEROP_2(AstNodeRangeConst, KNativePointer, KNativePointer, KNativePointer) - -KNativePointer impl_SourceRangeStart(KNativePointer context, KNativePointer range) -{ - const auto _context = reinterpret_cast(context); - const auto _range = reinterpret_cast(range); - auto result = GetImpl()->SourceRangeStart(_context, _range); - return result; -} -KOALA_INTEROP_2(SourceRangeStart, KNativePointer, KNativePointer, KNativePointer) - -KNativePointer impl_SourceRangeEnd(KNativePointer context, KNativePointer range) -{ - const auto _context = reinterpret_cast(context); - const auto _range = reinterpret_cast(range); - auto result = GetImpl()->SourceRangeEnd(_context, _range); - return result; -} -KOALA_INTEROP_2(SourceRangeEnd, KNativePointer, KNativePointer, KNativePointer) -bool impl_ClassPropertyIsDefaultAccessModifierConst(KNativePointer context, KNativePointer receiver) -{ - const auto _context = reinterpret_cast(context); - const auto _receiver = reinterpret_cast(receiver); - return GetImpl()->ClassPropertyIsDefaultAccessModifierConst(_context, _receiver); -} -KOALA_INTEROP_2(ClassPropertyIsDefaultAccessModifierConst, KBoolean, KNativePointer, KNativePointer); - -KNativePointer impl_AstNodeStartConst(KNativePointer context, KNativePointer receiver) -{ - const auto _context = reinterpret_cast(context); - const auto _receiver = reinterpret_cast(receiver); - return const_cast(GetImpl()->AstNodeStartConst(_context, _receiver)); -} -KOALA_INTEROP_2(AstNodeStartConst, KNativePointer, KNativePointer, KNativePointer); - -KNativePointer impl_AstNodeEndConst(KNativePointer context, KNativePointer receiver) -{ - const auto _context = reinterpret_cast(context); - const auto _receiver = reinterpret_cast(receiver); - return const_cast(GetImpl()->AstNodeEndConst(_context, _receiver)); -} -KOALA_INTEROP_2(AstNodeEndConst, KNativePointer, KNativePointer, KNativePointer); - -KBoolean impl_IsArrayExpression(KNativePointer nodePtr) -{ - auto node = reinterpret_cast(nodePtr); - return GetImpl()->IsArrayExpression(node); -} -KOALA_INTEROP_1(IsArrayExpression, KBoolean, KNativePointer) - -inline KUInt unpackUInt(const KByte* bytes) -{ - const KUInt BYTE_0 = 0; - const KUInt BYTE_1 = 1; - const KUInt BYTE_2 = 2; - const KUInt BYTE_3 = 3; - - const KUInt BYTE_1_SHIFT = 8; - const KUInt BYTE_2_SHIFT = 16; - const KUInt BYTE_3_SHIFT = 24; - return (bytes[BYTE_0] | (bytes[BYTE_1] << BYTE_1_SHIFT) - | (bytes[BYTE_2] << BYTE_2_SHIFT) | (bytes[BYTE_3] << BYTE_3_SHIFT) - ); -} +KOALA_INTEROP_1(ETSParserGetGlobalProgramAbsName, KNativePointer, KNativePointer) \ No newline at end of file diff --git a/koala-wrapper/native/src/common.cc b/koala-wrapper/native/src/common.cc index 084c86ea5..eb7a6acb5 100644 --- a/koala-wrapper/native/src/common.cc +++ b/koala-wrapper/native/src/common.cc @@ -41,45 +41,15 @@ static es2panda_Impl *impl = nullptr; const char* LIB_ES2PANDA_PUBLIC = LIB_PREFIX "es2panda_public" LIB_SUFFIX; -#ifdef KOALA_WINDOWS - const char *SEPARATOR = "\\"; -#else - const char *SEPARATOR = "/"; -#endif -const char *LIB_DIR = "lib"; - -static std::string ES2PANDA_LIB_PATH; - -std::string joinPath(vector &paths) -{ - std::string res; - for (int i = 0; i < paths.size(); ++i) { - if (i == 0) { - res = paths[i]; - } else { - res += SEPARATOR + paths[i]; - } - } - return res; -} - -void impl_SetUpSoPath(KStringPtr &soPath) -{ - ES2PANDA_LIB_PATH = std::string(soPath.c_str()); -} -KOALA_INTEROP_V1(SetUpSoPath, KStringPtr); - void* FindLibrary() { - std::vector pathArray; + std::string libraryName; char* envValue = getenv("PANDA_SDK_PATH"); if (envValue) { - pathArray = {envValue, PLUGIN_DIR, LIB_DIR, LIB_ES2PANDA_PUBLIC}; - } else if (!ES2PANDA_LIB_PATH.empty()) { - pathArray = {ES2PANDA_LIB_PATH, LIB_DIR, LIB_ES2PANDA_PUBLIC}; + libraryName = std::string(envValue) + ("/" PLUGIN_DIR "/lib/") + LIB_ES2PANDA_PUBLIC; } else { - pathArray = {LIB_ES2PANDA_PUBLIC}; + libraryName = LIB_ES2PANDA_PUBLIC; } - return loadLibrary(joinPath(pathArray)); + return loadLibrary(libraryName); } es2panda_Impl *GetImpl() { diff --git a/koala-wrapper/native/src/generated/bridges.cc b/koala-wrapper/native/src/generated/bridges.cc index 5bcf9071c..f1ca609eb 100644 --- a/koala-wrapper/native/src/generated/bridges.cc +++ b/koala-wrapper/native/src/generated/bridges.cc @@ -1713,6 +1713,15 @@ void impl_NamedTypeSetTypeParams(KNativePointer context, KNativePointer receiver } KOALA_INTEROP_V3(NamedTypeSetTypeParams, KNativePointer, KNativePointer, KNativePointer); +KNativePointer impl_NumberLiteralStrConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->NumberLiteralStrConst(_context, _receiver); + return new std::string(result); +} +KOALA_INTEROP_2(NumberLiteralStrConst, KNativePointer, KNativePointer, KNativePointer); + KNativePointer impl_CreateTSFunctionType(KNativePointer context, KNativePointer signature) { const auto _context = reinterpret_cast(context); @@ -4681,58 +4690,6 @@ void impl_ETSTupleSetTypeAnnotationsList(KNativePointer context, KNativePointer } KOALA_INTEROP_V4(ETSTupleSetTypeAnnotationsList, KNativePointer, KNativePointer, KNativePointerArray, KUInt); -KNativePointer impl_CreateTryStatement(KNativePointer context, KNativePointer block, KNativePointerArray catchClauses, KUInt catchClausesSequenceLength, KNativePointer finalizer, KNativePointerArray finalizerInsertionsLabelPair, KUInt finalizerInsertionsLabelPairSequenceLength, KNativePointerArray finalizerInsertionsStatement, KUInt finalizerInsertionsStatementSequenceLength) -{ - const auto _context = reinterpret_cast(context); - const auto _block = reinterpret_cast(block); - const auto _catchClauses = reinterpret_cast(catchClauses); - const auto _catchClausesSequenceLength = static_cast(catchClausesSequenceLength); - const auto _finalizer = reinterpret_cast(finalizer); - const auto _finalizerInsertionsLabelPair = reinterpret_cast(finalizerInsertionsLabelPair); - const auto _finalizerInsertionsLabelPairSequenceLength = static_cast(finalizerInsertionsLabelPairSequenceLength); - const auto _finalizerInsertionsStatement = reinterpret_cast(finalizerInsertionsStatement); - const auto _finalizerInsertionsStatementSequenceLength = static_cast(finalizerInsertionsStatementSequenceLength); - auto result = GetImpl()->CreateTryStatement(_context, _block, _catchClauses, _catchClausesSequenceLength, _finalizer, _finalizerInsertionsLabelPair, _finalizerInsertionsLabelPairSequenceLength, _finalizerInsertionsStatement, _finalizerInsertionsStatementSequenceLength); - return result; -} -KOALA_INTEROP_9(CreateTryStatement, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KUInt, KNativePointer, KNativePointerArray, KUInt, KNativePointerArray, KUInt); - -KNativePointer impl_UpdateTryStatement(KNativePointer context, KNativePointer original, KNativePointer block, KNativePointerArray catchClauses, KUInt catchClausesSequenceLength, KNativePointer finalizer, KNativePointerArray finalizerInsertionsLabelPair, KUInt finalizerInsertionsLabelPairSequenceLength, KNativePointerArray finalizerInsertionsStatement, KUInt finalizerInsertionsStatementSequenceLength) -{ - const auto _context = reinterpret_cast(context); - const auto _original = reinterpret_cast(original); - const auto _block = reinterpret_cast(block); - const auto _catchClauses = reinterpret_cast(catchClauses); - const auto _catchClausesSequenceLength = static_cast(catchClausesSequenceLength); - const auto _finalizer = reinterpret_cast(finalizer); - const auto _finalizerInsertionsLabelPair = reinterpret_cast(finalizerInsertionsLabelPair); - const auto _finalizerInsertionsLabelPairSequenceLength = static_cast(finalizerInsertionsLabelPairSequenceLength); - const auto _finalizerInsertionsStatement = reinterpret_cast(finalizerInsertionsStatement); - const auto _finalizerInsertionsStatementSequenceLength = static_cast(finalizerInsertionsStatementSequenceLength); - auto result = GetImpl()->UpdateTryStatement(_context, _original, _block, _catchClauses, _catchClausesSequenceLength, _finalizer, _finalizerInsertionsLabelPair, _finalizerInsertionsLabelPairSequenceLength, _finalizerInsertionsStatement, _finalizerInsertionsStatementSequenceLength); - return result; -} -KOALA_INTEROP_10(UpdateTryStatement, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KUInt, KNativePointer, KNativePointerArray, KUInt, KNativePointerArray, KUInt); - -KNativePointer impl_CreateTryStatement1(KNativePointer context, KNativePointer other) -{ - const auto _context = reinterpret_cast(context); - const auto _other = reinterpret_cast(other); - auto result = GetImpl()->CreateTryStatement1(_context, _other); - return result; -} -KOALA_INTEROP_2(CreateTryStatement1, KNativePointer, KNativePointer, KNativePointer); - -KNativePointer impl_UpdateTryStatement1(KNativePointer context, KNativePointer original, KNativePointer other) -{ - const auto _context = reinterpret_cast(context); - const auto _original = reinterpret_cast(original); - const auto _other = reinterpret_cast(other); - auto result = GetImpl()->UpdateTryStatement1(_context, _original, _other); - return result; -} -KOALA_INTEROP_3(UpdateTryStatement1, KNativePointer, KNativePointer, KNativePointer, KNativePointer); - KNativePointer impl_TryStatementFinallyBlockConst(KNativePointer context, KNativePointer receiver) { const auto _context = reinterpret_cast(context); @@ -6774,6 +6731,18 @@ KNativePointer impl_UpdateETSPackageDeclaration(KNativePointer context, KNativeP } KOALA_INTEROP_3(UpdateETSPackageDeclaration, KNativePointer, KNativePointer, KNativePointer, KNativePointer); +KNativePointer impl_CreateETSImportDeclaration(KNativePointer context, KNativePointer source , KNativePointerArray specifiers, KUInt specifiersSequenceLength, KInt importKind) +{ + const auto _context = reinterpret_cast(context); + const auto _source = reinterpret_cast(source); + const auto _specifiers = reinterpret_cast(specifiers); + const auto _specifiersSequenceLength = static_cast(specifiersSequenceLength); + const auto _importKind = static_cast(importKind); + auto result = GetImpl()->ETSParserBuildImportDeclaration(_context, _importKind, _specifiers, _specifiersSequenceLength, _source); + return result; +} +KOALA_INTEROP_5(CreateETSImportDeclaration, KNativePointer, KNativePointer, KNativePointer, KNativePointerArray, KUInt, KInt); + KNativePointer impl_UpdateETSImportDeclaration(KNativePointer context, KNativePointer original, KNativePointer source, KNativePointerArray specifiers, KUInt specifiersSequenceLength, KInt importKind) { const auto _context = reinterpret_cast(context); @@ -7273,6 +7242,43 @@ KNativePointer impl_UpdateEmptyStatement(KNativePointer context, KNativePointer } KOALA_INTEROP_2(UpdateEmptyStatement, KNativePointer, KNativePointer, KNativePointer); +KNativePointer impl_CreateETSLaunchExpression(KNativePointer context, KNativePointer expr) +{ + const auto _context = reinterpret_cast(context); + const auto _expr = reinterpret_cast(expr); + auto result = GetImpl()->CreateETSLaunchExpression(_context, _expr); + return result; +} +KOALA_INTEROP_2(CreateETSLaunchExpression, KNativePointer, KNativePointer, KNativePointer); + +KNativePointer impl_UpdateETSLaunchExpression(KNativePointer context, KNativePointer original, KNativePointer expr) +{ + const auto _context = reinterpret_cast(context); + const auto _original = reinterpret_cast(original); + const auto _expr = reinterpret_cast(expr); + auto result = GetImpl()->UpdateETSLaunchExpression(_context, _original, _expr); + return result; +} +KOALA_INTEROP_3(UpdateETSLaunchExpression, KNativePointer, KNativePointer, KNativePointer, KNativePointer); + +KBoolean impl_ETSLaunchExpressionIsStaticCallConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ETSLaunchExpressionIsStaticCallConst(_context, _receiver); + return result; +} +KOALA_INTEROP_2(ETSLaunchExpressionIsStaticCallConst, KBoolean, KNativePointer, KNativePointer); + +KNativePointer impl_ETSLaunchExpressionCallConst(KNativePointer context, KNativePointer receiver) +{ + const auto _context = reinterpret_cast(context); + const auto _receiver = reinterpret_cast(receiver); + auto result = GetImpl()->ETSLaunchExpressionCallConst(_context, _receiver); + return (void*)result; +} +KOALA_INTEROP_2(ETSLaunchExpressionCallConst, KNativePointer, KNativePointer, KNativePointer); + KNativePointer impl_CreateWhileStatement(KNativePointer context, KNativePointer test, KNativePointer body) { const auto _context = reinterpret_cast(context); @@ -11321,19 +11327,6 @@ KNativePointer impl_CreateForUpdateStatement(KNativePointer context, KNativePoin } KOALA_INTEROP_5(CreateForUpdateStatement, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer); -KNativePointer impl_UpdateForUpdateStatement(KNativePointer context, KNativePointer original, KNativePointer init, KNativePointer test, KNativePointer update, KNativePointer body) -{ - const auto _context = reinterpret_cast(context); - const auto _original = reinterpret_cast(original); - const auto _init = reinterpret_cast(init); - const auto _test = reinterpret_cast(test); - const auto _update = reinterpret_cast(update); - const auto _body = reinterpret_cast(body); - auto result = GetImpl()->UpdateForUpdateStatement(_context, _original, _init, _test, _update, _body); - return result; -} -KOALA_INTEROP_6(UpdateForUpdateStatement, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer, KNativePointer); - KNativePointer impl_ForUpdateStatementInit(KNativePointer context, KNativePointer receiver) { const auto _context = reinterpret_cast(context); @@ -11768,3 +11761,4 @@ KNativePointer impl_CreateFunctionDecl(KNativePointer context, KStringPtr& name, return result; } KOALA_INTEROP_3(CreateFunctionDecl, KNativePointer, KNativePointer, KStringPtr, KNativePointer); + diff --git a/koala-wrapper/src/Es2pandaEnums.ts b/koala-wrapper/src/Es2pandaEnums.ts index bf2ce0783..bf820a759 100644 --- a/koala-wrapper/src/Es2pandaEnums.ts +++ b/koala-wrapper/src/Es2pandaEnums.ts @@ -78,7 +78,6 @@ export enum Es2pandaAstNodeType { AST_NODE_TYPE_SCRIPT_FUNCTION, AST_NODE_TYPE_SEQUENCE_EXPRESSION, AST_NODE_TYPE_STRING_LITERAL, - AST_NODE_TYPE_ETS_NON_NULLISH_TYPE, AST_NODE_TYPE_ETS_NULL_TYPE, AST_NODE_TYPE_ETS_UNDEFINED_TYPE, AST_NODE_TYPE_ETS_NEVER_TYPE, @@ -92,6 +91,7 @@ export enum Es2pandaAstNodeType { AST_NODE_TYPE_ETS_TYPE_REFERENCE_PART, AST_NODE_TYPE_ETS_UNION_TYPE, AST_NODE_TYPE_ETS_KEYOF_TYPE, + AST_NODE_TYPE_ETS_LAUNCH_EXPRESSION, AST_NODE_TYPE_ETS_NEW_ARRAY_INSTANCE_EXPRESSION, AST_NODE_TYPE_ETS_NEW_MULTI_DIM_ARRAY_INSTANCE_EXPRESSION, AST_NODE_TYPE_ETS_NEW_CLASS_INSTANCE_EXPRESSION, @@ -182,9 +182,3 @@ export enum Es2pandaAstNodeType { AST_NODE_TYPE_SPREAD_ELEMENT, AST_NODE_TYPE_REST_ELEMENT, } - -export enum Es2pandaImportFlags { - IMPORT_FLAGS_NONE, - IMPORT_FLAGS_DEFAULT_IMPORT, - IMPORT_FLAGS_IMPLICIT_PACKAGE_IMPORT, -} diff --git a/koala-wrapper/src/Es2pandaNativeModule.ts b/koala-wrapper/src/Es2pandaNativeModule.ts index 4a220dcc1..3f271657a 100644 --- a/koala-wrapper/src/Es2pandaNativeModule.ts +++ b/koala-wrapper/src/Es2pandaNativeModule.ts @@ -78,9 +78,6 @@ export class Es2pandaNativeModule { _ContextErrorMessage(context: KPtr): KPtr { throw new Error('Not implemented'); } - _GetAllErrorMessages(context: KPtr): KPtr { - throw new Error('Not implemented'); - } _AstNodeChildren(context: KPtr, node: KPtr): KPtr { throw new Error('Not implemented'); } @@ -106,10 +103,6 @@ export class Es2pandaNativeModule { _CreateContextFromString(config: KPtr, source: String, filename: String): KPtr { throw new Error('Not implemented'); } - _CreateContextGenerateAbcForExternalSourceFiles(config: KPtr, fileCount: KInt, filenames: - string[]): KPtr { - throw new Error('Not implemented'); - } _CreateContextFromFile(config: KPtr, filename: String): KPtr { throw new Error('Not implemented'); } @@ -295,13 +288,11 @@ export class Es2pandaNativeModule { throw new Error('Not implemented'); } _CreateETSImportDeclaration( - context: KNativePointer, - importPath: KNativePointer, - specifiers: BigUint64Array, - specifiersSequenceLength: KInt, - importKind: KInt, - programPtr: KNativePointer, - flags: KInt + context: KPtr, + source: KPtr, + specifiers: KPtrArray, + specifiersLen: KInt, + importKind: KInt ): KNativePointer { throw new Error('Not implemented'); } @@ -803,58 +794,6 @@ export class Es2pandaNativeModule { _ETSParserGetGlobalProgramAbsName(context: KNativePointer): KNativePointer { throw new Error('Not implemented'); } - - _ImportSpecifierIsRemovableConst(context: KNativePointer, instance: KNativePointer): KBoolean { - throw new Error('Not implemented'); - } - - _ImportSpecifierSetRemovable(context: KNativePointer, instance: KNativePointer): void { - throw new Error('Not implemented'); - } - - _ClassPropertyIsDefaultAccessModifierConst(context: KNativePointer, receiver: KNativePointer): boolean { - throw new Error('Not implemented'); - } - - _AstNodeStartConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { - throw new Error('Not implemented'); - } - - _AstNodeEndConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { - throw new Error('Not implemented'); - } - - _ClassVariableDeclaration(context: KNativePointer, classInstance: KNativePointer): KNativePointer { - throw new Error('Not implemented'); - } - - _IsMethodDefinition(node: KPtr): KBoolean { - throw new Error('Not implemented'); - } - - _AstNodeRangeConst(context: KNativePointer, node: KNativePointer): KNativePointer { - throw new Error('CreateFunctionDecl was not overloaded by native module initialization'); - } - - _SourceRangeStart(context: KNativePointer, range: KNativePointer): KNativePointer { - throw new Error('CreateFunctionDecl was not overloaded by native module initialization'); - } - - _SourceRangeEnd(context: KNativePointer, range: KNativePointer): KNativePointer { - throw new Error('CreateFunctionDecl was not overloaded by native module initialization'); - } - - _CreateSourceRange(context: KNativePointer, start: KNativePointer, end: KNativePointer): KNativePointer { - throw new Error('CreateFunctionDecl was not overloaded by native module initialization'); - } - - _IsArrayExpression(node: KPtr): KBoolean { - throw new Error('Not implemented'); - } - - _SetUpSoPath(soPath: string): void { - throw new Error('Not implemented'); - } } export function initEs2panda(): Es2pandaNativeModule { diff --git a/koala-wrapper/src/arkts-api/factory/nodeFactory.ts b/koala-wrapper/src/arkts-api/factory/nodeFactory.ts index 1f66f9148..5283543ac 100644 --- a/koala-wrapper/src/arkts-api/factory/nodeFactory.ts +++ b/koala-wrapper/src/arkts-api/factory/nodeFactory.ts @@ -69,16 +69,7 @@ import { TSTypeAliasDeclaration, ChainExpression, BlockExpression, - ETSNewClassInstanceExpression, - BooleanLiteral, - ObjectExpression, - Property, - TemplateLiteral, - ArrayExpression, - TryStatement, - ForUpdateStatement, - ForInStatement, - ForOfStatement, + ETSNewClassInstanceExpression } from "../../generated" import { Es2pandaModifierFlags @@ -123,7 +114,7 @@ import { updateTSTypeParameterInstantiation } from "../node-utilities/TSTypePara import { updateTSInterfaceDeclaration } from "../node-utilities/TSInterfaceDeclaration" import { updateTSInterfaceBody } from "../node-utilities/TSInterfaceBody" import { updateUndefinedLiteral } from "../node-utilities/UndefinedLiteral" -import { updateAnnotationUsage, update1AnnotationUsage } from "../node-utilities/AnnotationUsage" +import { updateAnnotationUsage } from "../node-utilities/AnnotationUsage" import { updateAssignmentExpression } from "../node-utilities/AssignmentExpression" import { updateETSUndefinedType } from "../node-utilities/ETSUndefinedType" import { updateConditionalExpression } from "../node-utilities/ConditionalExpression" @@ -135,14 +126,6 @@ import { updateChainExpression } from "../node-utilities/ChainExpression" import { updateBlockExpression } from "../node-utilities/BlockExpression" import { updateNullLiteral } from "../node-utilities/NullLiteral" import { updateETSNewClassInstanceExpression } from "../node-utilities/ETSNewClassInstanceExpression" -import { updateObjectExpression } from "../node-utilities/ObjectExpression" -import { updateProperty } from "../node-utilities/Property" -import { updateTemplateLiteral } from "../node-utilities/TemplateLiteral" -import { updateArrayExpression } from "../node-utilities/ArrayExpression"; -import { updateTryStatement } from '../node-utilities/TryStatement'; -import { updateForUpdateStatement } from '../node-utilities/ForUpdateStatement'; -import { updateForInStatement } from '../node-utilities/ForInStatement'; -import { updateForOfStatement } from '../node-utilities/ForOfStatement'; export const factory = { get createIdentifier() { @@ -379,12 +362,6 @@ export const factory = { get updateAnnotationUsage() { return updateAnnotationUsage }, - get create1AnnotationUsage(): (...args: Parameters) => AnnotationUsage { - return AnnotationUsage.create1AnnotationUsage; - }, - get update1AnnotationUsage(): (...args: Parameters) => AnnotationUsage { - return update1AnnotationUsage; - }, get createAssignmentExpression() { return AssignmentExpression.create }, @@ -454,62 +431,9 @@ export const factory = { get updateETSNewClassInstanceExpression() { return updateETSNewClassInstanceExpression }, - get createETSStringLiteralType() { + get createETSStringLiteralType(){ return ETSStringLiteralType.create; }, - get createBooleanLiteral(): (...args: Parameters) => BooleanLiteral { - return BooleanLiteral.createBooleanLiteral; - }, - get createObjectExpression(): (...args: Parameters) => ObjectExpression { - return ObjectExpression.createObjectExpression; - }, - get updateObjectExpression(): (...args: Parameters) => ObjectExpression { - return updateObjectExpression; - }, - get createProperty(): (...args: Parameters) => Property { - return Property.createProperty; - }, - get updateProperty(): (...args: Parameters) => Property { - return updateProperty; - }, - get createTemplateLiteral(): (...args: Parameters) => TemplateLiteral { - return TemplateLiteral.createTemplateLiteral; - }, - get updateTemplateLiteral(): (...args: Parameters) => TemplateLiteral { - return updateTemplateLiteral; - }, - get createArrayExpression(): (...args: Parameters) => ArrayExpression { - return ArrayExpression.createArrayExpression; - }, - get updateArrayExpression(): (...args: Parameters) => ArrayExpression { - return updateArrayExpression; - }, - get createTryStatement(): (...args: Parameters) => TryStatement { - return TryStatement.createTryStatement; - }, - get updateTryStatement(): (...args: Parameters) => TryStatement { - return updateTryStatement; - }, - get createForUpdateStatement(): ( - ...args: Parameters - ) => ForUpdateStatement { - return ForUpdateStatement.createForUpdateStatement; - }, - get updateForUpdateStatement(): (...args: Parameters) => ForUpdateStatement { - return updateForUpdateStatement; - }, - get createForInStatement(): (...args: Parameters) => ForInStatement { - return ForInStatement.createForInStatement; - }, - get updateForInStatement(): (...args: Parameters) => ForInStatement { - return updateForInStatement; - }, - get createForOfStatement(): (...args: Parameters) => ForOfStatement { - return ForOfStatement.createForOfStatement; - }, - get updateForOfStatement(): (...args: Parameters) => ForOfStatement { - return updateForOfStatement; - }, /** @deprecated */ createTypeParameter1_(name: Identifier, constraint?: TypeNode, defaultType?: TypeNode) { return TSTypeParameter.createTSTypeParameter(Identifier.create1Identifier(name.name), constraint, defaultType) diff --git a/koala-wrapper/src/arkts-api/factory/nodeTests.ts b/koala-wrapper/src/arkts-api/factory/nodeTests.ts index 62c02275a..b40a1a353 100644 --- a/koala-wrapper/src/arkts-api/factory/nodeTests.ts +++ b/koala-wrapper/src/arkts-api/factory/nodeTests.ts @@ -28,8 +28,6 @@ import { StructDeclaration, VariableDeclaration, VariableDeclarator, - AssignmentExpression, - NumberLiteral } from "../types" import { MemberExpression } from "../to-be-generated/MemberExpression" import { AstNode } from "../peers/AstNode" @@ -47,7 +45,7 @@ export function isFunctionDeclaration(node: AstNode): node is FunctionDeclaratio } export function isMethodDefinition(node: AstNode): node is MethodDefinition { - return global.es2panda._IsMethodDefinition(node.peer); + return node instanceof MethodDefinition } export function isEtsScript(node: AstNode): node is EtsScript { @@ -89,11 +87,3 @@ export function isIfStatement(node: AstNode): node is IfStatement { export function isVariableDeclarator(node: AstNode): node is VariableDeclarator { return node instanceof VariableDeclarator } - -export function isAssignmentExpression(node: AstNode): node is AssignmentExpression { - return node instanceof AssignmentExpression; -} - -export function isNumberLiteral(node: AstNode): node is NumberLiteral { - return node instanceof NumberLiteral; -} \ No newline at end of file diff --git a/koala-wrapper/src/arkts-api/index.ts b/koala-wrapper/src/arkts-api/index.ts index 936a9b0f8..463ae2730 100644 --- a/koala-wrapper/src/arkts-api/index.ts +++ b/koala-wrapper/src/arkts-api/index.ts @@ -56,11 +56,6 @@ export * from "../generated/peers/ETSNewClassInstanceExpression" export * from "../generated/peers/ObjectExpression" export * from "../generated/peers/Property" export * from "../generated/peers/BlockExpression" -export * from "../generated/peers/TSClassImplements" -export * from "../generated/peers/BooleanLiteral" -export * from "../generated/peers/TSArrayType" -export * from "../generated/peers/ArrayExpression"; -export * from "../generated/peers/ETSNullType"; export * from "./types" export * from "./utilities/private" @@ -77,7 +72,6 @@ export * from "./peers/Context" export * from "./peers/Program" export * from "./peers/ImportPathManager" export * from "./peers/SourcePosition" -export * from "./peers/SourceRange" export * from "./to-be-generated/MemberExpression" export * from "./static/globalUtils" export { global as arktsGlobal } from "./static/global"; diff --git a/koala-wrapper/src/arkts-api/node-utilities/AnnotationUsage.ts b/koala-wrapper/src/arkts-api/node-utilities/AnnotationUsage.ts index 82b28fec3..e79cc04c3 100644 --- a/koala-wrapper/src/arkts-api/node-utilities/AnnotationUsage.ts +++ b/koala-wrapper/src/arkts-api/node-utilities/AnnotationUsage.ts @@ -16,7 +16,6 @@ import { AnnotationUsage, Expression } from '../../generated'; import { isSameNativeObject } from '../peers/ArktsObject'; import { attachModifiers, updateThenAttach } from '../utilities/private'; -import { AstNode } from '../peers/AstNode'; export function updateAnnotationUsage(original: AnnotationUsage, expr?: Expression): AnnotationUsage { if (isSameNativeObject(expr, original.expr)) { @@ -26,12 +25,3 @@ export function updateAnnotationUsage(original: AnnotationUsage, expr?: Expressi const update = updateThenAttach(AnnotationUsage.updateAnnotationUsage, attachModifiers); return update(original, expr); } - -export function update1AnnotationUsage(original: AnnotationUsage, expr: Expression | undefined, properties: readonly AstNode[]): AnnotationUsage { - if (isSameNativeObject(expr, original.expr) && isSameNativeObject(properties, original.properties)) { - return original; - } - - const update = updateThenAttach(AnnotationUsage.update1AnnotationUsage, attachModifiers); - return update(original, expr, properties); -} diff --git a/koala-wrapper/src/arkts-api/node-utilities/ArrayExpression.ts b/koala-wrapper/src/arkts-api/node-utilities/ArrayExpression.ts deleted file mode 100644 index 320b0d678..000000000 --- a/koala-wrapper/src/arkts-api/node-utilities/ArrayExpression.ts +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (c) 2024 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { ArrayExpression, Expression } from '../../generated'; -import { isSameNativeObject } from '../peers/ArktsObject'; -import { attachModifiers, updateThenAttach } from '../utilities/private'; - -export function updateArrayExpression(original: ArrayExpression, elements: readonly Expression[]): ArrayExpression { - if (isSameNativeObject(elements, original.elements)) { - return original; - } - const update = updateThenAttach( - ArrayExpression.updateArrayExpression, - attachModifiers, - attachOptionalAndDeclaration - ); - return update(original, elements); -} - -function attachOptionalAndDeclaration(node: ArrayExpression, original: ArrayExpression): ArrayExpression { - if (node.isDeclaration) { - node.setDeclaration(); - } - node.setOptional(original.isOptional); - return node; -} diff --git a/koala-wrapper/src/arkts-api/node-utilities/ForInStatement.ts b/koala-wrapper/src/arkts-api/node-utilities/ForInStatement.ts deleted file mode 100644 index 40f78ab06..000000000 --- a/koala-wrapper/src/arkts-api/node-utilities/ForInStatement.ts +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { ForInStatement, Statement, Expression } from '../../generated'; -import { isSameNativeObject } from '../peers/ArktsObject'; -import { AstNode } from '../peers/AstNode'; -import { attachModifiers, updateThenAttach } from '../utilities/private'; - -export function updateForInStatement( - original: ForInStatement, - left?: AstNode, - right?: Expression, - body?: Statement -): ForInStatement { - if ( - isSameNativeObject(left, original.left) && - isSameNativeObject(right, original.right) && - isSameNativeObject(body, original.body) - ) { - return original; - } - - const updateNode = updateThenAttach(ForInStatement.updateForInStatement, attachModifiers); - return updateNode(original, left, right, body); -} diff --git a/koala-wrapper/src/arkts-api/node-utilities/ForOfStatement.ts b/koala-wrapper/src/arkts-api/node-utilities/ForOfStatement.ts deleted file mode 100644 index 9c8d99a1d..000000000 --- a/koala-wrapper/src/arkts-api/node-utilities/ForOfStatement.ts +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { ForOfStatement, Statement, Expression } from '../../generated'; -import { isSameNativeObject } from '../peers/ArktsObject'; -import { AstNode } from '../peers/AstNode'; -import { attachModifiers, updateThenAttach } from '../utilities/private'; - -export function updateForOfStatement( - original: ForOfStatement, - left: AstNode | undefined, - right: Expression | undefined, - body: Statement | undefined, - isAwait: boolean -): ForOfStatement { - if ( - isSameNativeObject(left, original.left) && - isSameNativeObject(right, original.right) && - isSameNativeObject(body, original.body) - ) { - return original; - } - - const updateNode = updateThenAttach(ForOfStatement.updateForOfStatement, attachModifiers); - return updateNode(original, left, right, body, isAwait); -} diff --git a/koala-wrapper/src/arkts-api/node-utilities/ForUpdateStatement.ts b/koala-wrapper/src/arkts-api/node-utilities/ForUpdateStatement.ts deleted file mode 100644 index 0fa41007b..000000000 --- a/koala-wrapper/src/arkts-api/node-utilities/ForUpdateStatement.ts +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { ForUpdateStatement, Statement, Expression } from '../../generated'; -import { isSameNativeObject } from '../peers/ArktsObject'; -import { AstNode } from '../peers/AstNode'; -import { attachModifiers, updateThenAttach } from '../utilities/private'; - -export function updateForUpdateStatement( - original: ForUpdateStatement, - init?: AstNode, - test?: Expression, - update?: Expression, - body?: Statement -): ForUpdateStatement { - if ( - isSameNativeObject(init, original.init) && - isSameNativeObject(test, original.test) && - isSameNativeObject(update, original.update) && - isSameNativeObject(body, original.body) - ) { - return original; - } - - const updateNode = updateThenAttach(ForUpdateStatement.updateForUpdateStatement, attachModifiers); - return updateNode(original, init, test, update, body); -} diff --git a/koala-wrapper/src/arkts-api/node-utilities/MethodDefinition.ts b/koala-wrapper/src/arkts-api/node-utilities/MethodDefinition.ts index 42006a300..44afa1dbc 100644 --- a/koala-wrapper/src/arkts-api/node-utilities/MethodDefinition.ts +++ b/koala-wrapper/src/arkts-api/node-utilities/MethodDefinition.ts @@ -19,13 +19,12 @@ import { AstNode } from '../peers/AstNode'; import { MethodDefinition } from '../types'; import { updateThenAttach } from '../utilities/private'; import { Es2pandaMethodDefinitionKind } from '../../generated/Es2pandaEnums'; -import { ScriptFunction } from '../../generated'; export function updateMethodDefinition( original: MethodDefinition, kind: Es2pandaMethodDefinitionKind, key: AstNode, - value: ScriptFunction, + value: AstNode, modifiers: KInt, isComputed: boolean ): MethodDefinition { diff --git a/koala-wrapper/src/arkts-api/node-utilities/ObjectExpression.ts b/koala-wrapper/src/arkts-api/node-utilities/ObjectExpression.ts deleted file mode 100644 index ac7a9d6b6..000000000 --- a/koala-wrapper/src/arkts-api/node-utilities/ObjectExpression.ts +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { ObjectExpression, Property } from '../../generated'; -import { isSameNativeObject } from '../peers/ArktsObject'; -import { attachModifiers, updateThenAttach } from '../utilities/private'; -import { Es2pandaAstNodeType } from '../../Es2pandaEnums'; - -export function updateObjectExpression( - original: ObjectExpression, - nodeType: Es2pandaAstNodeType, - properties: Property[], - trailingComma: boolean -): ObjectExpression { - if ( - isSameNativeObject(properties, original.properties) - /* TODO: no getter for nodeType */ - /* TODO: no getter for trailingComma */ - ) { - return original; - } - - const update = updateThenAttach(ObjectExpression.updateObjectExpression, attachModifiers); - return update(original, nodeType, properties, trailingComma); -} diff --git a/koala-wrapper/src/arkts-api/node-utilities/Property.ts b/koala-wrapper/src/arkts-api/node-utilities/Property.ts deleted file mode 100644 index 4b0a33c5b..000000000 --- a/koala-wrapper/src/arkts-api/node-utilities/Property.ts +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { Expression, Property } from '../../generated'; -import { isSameNativeObject } from '../peers/ArktsObject'; -import { attachModifiers, updateThenAttach } from '../utilities/private'; - -export function updateProperty(original: Property, key?: Expression, value?: Expression): Property { - if (isSameNativeObject(key, original.key) && isSameNativeObject(value, original.value)) { - return original; - } - - const update = updateThenAttach(Property.updateProperty, attachModifiers); - return update(original, key, value); -} diff --git a/koala-wrapper/src/arkts-api/node-utilities/TemplateLiteral.ts b/koala-wrapper/src/arkts-api/node-utilities/TemplateLiteral.ts deleted file mode 100644 index 840c0d120..000000000 --- a/koala-wrapper/src/arkts-api/node-utilities/TemplateLiteral.ts +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (c) 2024 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { TemplateLiteral, TemplateElement, Expression } from '../../generated'; -import { isSameNativeObject } from '../peers/ArktsObject'; -import { attachModifiers, updateThenAttach } from '../utilities/private'; - -export function updateTemplateLiteral( - original: TemplateLiteral, - quasis: readonly TemplateElement[], - expressions: readonly Expression[], - multilineString: string -): TemplateLiteral { - if ( - isSameNativeObject(quasis, original.quasis) && - isSameNativeObject(expressions, original.expressions) - ) { - return original; - } - - const update = updateThenAttach(TemplateLiteral.updateTemplateLiteral, attachModifiers); - return update(original, quasis, expressions, multilineString); -} diff --git a/koala-wrapper/src/arkts-api/node-utilities/TryStatement.ts b/koala-wrapper/src/arkts-api/node-utilities/TryStatement.ts deleted file mode 100644 index 32512066c..000000000 --- a/koala-wrapper/src/arkts-api/node-utilities/TryStatement.ts +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (c) 2024 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { LabelPair } from '../../generated/peers/LabelPair'; -import { BlockStatement, CatchClause, Statement, TryStatement } from '../../generated'; -import { isSameNativeObject } from '../peers/ArktsObject'; -import { attachModifiers, updateThenAttach } from '../utilities/private'; - -export function updateTryStatement( - original: TryStatement, - block: BlockStatement | undefined, - catchClauses: readonly CatchClause[], - finalizer: BlockStatement | undefined, - finalizerInsertionsLabelPair: readonly LabelPair[], - finalizerInsertionsStatement: readonly Statement[] -): TryStatement { - if ( - isSameNativeObject(block, original.block) && - isSameNativeObject(catchClauses, original.catchClauses) && - isSameNativeObject(finalizer, original.finallyBlock) - /* TODO: no getter for finalizerInsertionsLabelPair */ - /* TODO: no getter for finalizerInsertionsStatement */ - ) { - return original; - } - - const update = updateThenAttach(TryStatement.updateTryStatement, attachModifiers); - return update(original, block, catchClauses, finalizer, finalizerInsertionsLabelPair, finalizerInsertionsStatement); -} diff --git a/koala-wrapper/src/arkts-api/node-utilities/VariableDeclaration.ts b/koala-wrapper/src/arkts-api/node-utilities/VariableDeclaration.ts index 0bd18e52d..24432ec6d 100644 --- a/koala-wrapper/src/arkts-api/node-utilities/VariableDeclaration.ts +++ b/koala-wrapper/src/arkts-api/node-utilities/VariableDeclaration.ts @@ -33,10 +33,6 @@ export function updateVariableDeclaration( return original; } - const update = updateThenAttach( - VariableDeclaration.update, - attachModifiers, - (node: VariableDeclaration, original: VariableDeclaration) => node.setAnnotations(original.annotations) - ); + const update = updateThenAttach(VariableDeclaration.update, attachModifiers); return update(original, modifiers, kind, declarators); } diff --git a/koala-wrapper/src/arkts-api/peers/AstNode.ts b/koala-wrapper/src/arkts-api/peers/AstNode.ts index 62a0b78d2..634da8e17 100644 --- a/koala-wrapper/src/arkts-api/peers/AstNode.ts +++ b/koala-wrapper/src/arkts-api/peers/AstNode.ts @@ -31,12 +31,7 @@ export abstract class AstNode extends ArktsObject { } public get originalPeer(): KNativePointer { - const result = global.generatedEs2panda._AstNodeOriginalNodeConst(global.context, this.peer) - if (result === nullptr) { - this.originalPeer = this.peer - return this.peer - } - return result + return global.generatedEs2panda._AstNodeOriginalNodeConst(global.context, this.peer) } public set originalPeer(peer: KNativePointer) { diff --git a/koala-wrapper/src/arkts-api/peers/Context.ts b/koala-wrapper/src/arkts-api/peers/Context.ts index 48f86043a..81a1ec31f 100644 --- a/koala-wrapper/src/arkts-api/peers/Context.ts +++ b/koala-wrapper/src/arkts-api/peers/Context.ts @@ -13,46 +13,44 @@ * limitations under the License. */ -import { ArktsObject } from './ArktsObject'; -import { global } from '../static/global'; -import { throwError, filterSource } from '../../utils'; -import { passString, passStringArray } from '../utilities/private'; -import { KBoolean, KInt, KNativePointer } from '@koalaui/interop'; -import { AstNode } from './AstNode'; -import { Program } from './Program'; +import { ArktsObject } from "./ArktsObject" +import { global } from "../static/global" +import { throwError, filterSource } from "../../utils" +import { passString } from "../utilities/private" +import { KNativePointer } from "@koalaui/interop" +import { AstNode } from "./AstNode" +import { Program } from "./Program" export class Context extends ArktsObject { constructor(peer: KNativePointer) { - super(peer); + super(peer) } - static createFromString(source: string): Context { + static createFromString( + source: string + ): Context { if (!global.configIsInitialized()) { - throwError(`Config not initialized`); + throwError(`Config not initialized`) } return new Context( - global.es2panda._CreateContextFromString(global.config, passString(source), passString(global.filePath)) - ); + global.es2panda._CreateContextFromString( + global.config, + passString(source), + passString(global.filePath) + ) + ) } - static destroyAndRecreate(ast: AstNode): Context { - console.log('[TS WRAPPER] DESTROY AND RECREATE'); - const source = filterSource(ast.dumpSrc()); - global.es2panda._DestroyContext(global.context); - global.compilerContext = Context.createFromString(source); + static destroyAndRecreate( + ast: AstNode + ): Context { + console.log("[TS WRAPPER] DESTROY AND RECREATE"); + const source = filterSource(ast.dumpSrc()) + global.es2panda._DestroyContext(global.context) + global.compilerContext = Context.createFromString(source) return new Context(global.context); } - static createContextGenerateAbcForExternalSourceFiles( - filenames: string[]): Context { - if (!global.configIsInitialized()) { - throwError(`Config not initialized`); - } - return new Context( - global.es2panda._CreateContextGenerateAbcForExternalSourceFiles(global.config, filenames.length, passStringArray(filenames)) - ); - } - get program(): Program { return new Program(global.es2panda._ContextProgram(this.peer)); } -} +} \ No newline at end of file diff --git a/koala-wrapper/src/arkts-api/peers/SourceRange.ts b/koala-wrapper/src/arkts-api/peers/SourceRange.ts deleted file mode 100644 index 5ecee4ccb..000000000 --- a/koala-wrapper/src/arkts-api/peers/SourceRange.ts +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import { SourcePosition } from './SourcePosition'; -import { ArktsObject } from './ArktsObject'; -import { global } from '../static/global'; -import { KNativePointer } from '@koalaui/interop'; - -export class SourceRange extends ArktsObject { - constructor(peer: KNativePointer) { - super(peer); - } - - static create(start: SourcePosition, end: SourcePosition): SourceRange { - return new SourceRange( - global.es2panda._CreateSourceRange(global.context, start.peer, end.peer) - ); - } - - start(): SourcePosition { - return new SourcePosition(global.es2panda._SourceRangeStart(global.context, this.peer)); - } - - end(): SourcePosition { - return new SourcePosition(global.es2panda._SourceRangeEnd(global.context, this.peer)); - } -} \ No newline at end of file diff --git a/koala-wrapper/src/arkts-api/types.ts b/koala-wrapper/src/arkts-api/types.ts index b58793902..3faf2f690 100644 --- a/koala-wrapper/src/arkts-api/types.ts +++ b/koala-wrapper/src/arkts-api/types.ts @@ -48,7 +48,6 @@ import { nodeByType } from './class-by-peer'; import { MemberExpression } from './to-be-generated/MemberExpression'; import { AnnotationUsage, - ArrayExpression, BlockStatement, ClassDefinition, ETSTypeReference, @@ -666,8 +665,9 @@ export class MethodDefinition extends AstNode { assertValidPeer(peer, Es2pandaAstNodeType.AST_NODE_TYPE_METHOD_DEFINITION); super(peer); this.kind = global.generatedEs2panda._MethodDefinitionKindConst(global.context, this.peer); - this.funcExpr = unpackNonNullableNode(global.generatedEs2panda._ClassElementValue(global.context, this.peer)); - this.scriptFunction = this.funcExpr.scriptFunction; + this.scriptFunction = unpackNonNullableNode( + global.generatedEs2panda._MethodDefinitionFunction(global.context, this.peer) + ); assertValidPeer(this.scriptFunction.peer, Es2pandaAstNodeType.AST_NODE_TYPE_SCRIPT_FUNCTION); // Somehow the scriptFunction cannot attach method's key to its ident after checker @@ -686,7 +686,7 @@ export class MethodDefinition extends AstNode { static create( kind: Es2pandaMethodDefinitionKind, key: AstNode, - value: ScriptFunction, + value: AstNode, modifiers: KInt, isComputed: boolean ): MethodDefinition { @@ -695,7 +695,7 @@ export class MethodDefinition extends AstNode { global.context, kind, passNode(key), - passNode(FunctionExpression.create(value)), + passNode(value), modifiers, isComputed ), @@ -707,7 +707,7 @@ export class MethodDefinition extends AstNode { node: MethodDefinition, kind: Es2pandaMethodDefinitionKind, key: AstNode, - value: ScriptFunction, + value: AstNode, modifiers: KInt, isComputed: boolean ): MethodDefinition { @@ -717,7 +717,7 @@ export class MethodDefinition extends AstNode { node.peer, kind, passNode(key), - passNode(FunctionExpression.update(node.funcExpr, value)), + passNode(value), modifiers, isComputed ), @@ -747,7 +747,6 @@ export class MethodDefinition extends AstNode { readonly kind: Es2pandaMethodDefinitionKind; readonly scriptFunction: ScriptFunction; readonly name: Identifier; - readonly funcExpr: FunctionExpression; } export class VariableDeclaration extends AstNode { @@ -794,22 +793,6 @@ export class VariableDeclaration extends AstNode { return new VariableDeclaration(peer); } - get annotations(): readonly AnnotationUsage[] { - return unpackNodeArray( - global.generatedEs2panda._VariableDeclarationAnnotationsConst(global.context, this.peer) - ); - } - /** @deprecated */ - setAnnotations(annotations: readonly AnnotationUsage[]): this { - global.generatedEs2panda._VariableDeclarationSetAnnotations( - global.context, - this.peer, - passNodeArray(annotations), - annotations.length - ); - return this; - } - readonly declarationKind: Es2pandaVariableDeclarationKind; readonly declarators: readonly VariableDeclarator[]; } @@ -916,6 +899,5 @@ const pairs: [Es2pandaAstNodeType, { new (peer: KNativePointer): AstNode }][] = [Es2pandaAstNodeType.AST_NODE_TYPE_ETS_TYPE_REFERENCE, ETSTypeReference], [Es2pandaAstNodeType.AST_NODE_TYPE_ETS_TYPE_REFERENCE_PART, ETSTypeReferencePart], [Es2pandaAstNodeType.AST_NODE_TYPE_OBJECT_EXPRESSION, ObjectExpression], - [Es2pandaAstNodeType.AST_NODE_TYPE_ARRAY_EXPRESSION, ArrayExpression], ]; pairs.forEach(([nodeType, astNode]) => nodeByType.set(nodeType, astNode)); diff --git a/koala-wrapper/src/arkts-api/utilities/public.ts b/koala-wrapper/src/arkts-api/utilities/public.ts index e381e594e..45888cd18 100644 --- a/koala-wrapper/src/arkts-api/utilities/public.ts +++ b/koala-wrapper/src/arkts-api/utilities/public.ts @@ -13,176 +13,88 @@ * limitations under the License. */ -import { global } from '../static/global'; -import { isNumber, throwError, getEnumName } from '../../utils'; -import { KNativePointer, KInt, nullptr, withStringResult } from '@koalaui/interop'; -import { passNode, passString, unpackNodeArray, unpackNonNullableNode } from './private'; -import { isFunctionDeclaration, isMemberExpression, isMethodDefinition, isNumberLiteral } from '../factory/nodeTests'; -import { - Es2pandaContextState, - Es2pandaMethodDefinitionKind, - Es2pandaModifierFlags, -} from '../../generated/Es2pandaEnums'; -import type { AstNode } from '../peers/AstNode'; -import { - ClassDefinition, - ClassProperty, - ETSImportDeclaration, - ImportSpecifier, - isClassDefinition, - isIdentifier, - isObjectExpression, - isProperty, - isScriptFunction, - isTSInterfaceDeclaration, - Property, - type AnnotationUsage, -} from '../../generated'; -import { Program } from '../peers/Program'; -import { clearNodeCache } from '../class-by-peer'; -import { SourcePosition } from '../peers/SourcePosition'; -import { MemberExpression } from '../to-be-generated/MemberExpression'; +import { global } from "../static/global" +import { isNumber, throwError, getEnumName } from "../../utils" +import { KNativePointer, KInt, nullptr, withStringResult } from "@koalaui/interop" +import { passNode, passString, unpackNodeArray, unpackNonNullableNode } from "./private" +import { isFunctionDeclaration, isMemberExpression } from "../factory/nodeTests" +import { Es2pandaContextState, Es2pandaModifierFlags } from "../../generated/Es2pandaEnums" +import type { AstNode } from "../peers/AstNode" +import { ClassDefinition, ClassProperty, ETSImportDeclaration, isClassDefinition, isScriptFunction, type AnnotationUsage } from "../../generated" +import { Program } from "../peers/Program" +import { clearNodeCache } from "../class-by-peer" export function proceedToState(state: Es2pandaContextState, forceDtsEmit = false): void { - console.log('[TS WRAPPER] PROCEED TO STATE: ', getEnumName(Es2pandaContextState, state)); - if (global.es2panda._ContextState(global.context) === Es2pandaContextState.ES2PANDA_STATE_ERROR) { - processErrorState(state, forceDtsEmit); - } + console.log("[TS WRAPPER] PROCEED TO STATE: ", getEnumName(Es2pandaContextState, state)); if (state <= global.es2panda._ContextState(global.context)) { - console.log('[TS WRAPPER] PROCEED TO STATE: SKIPPING'); - return; + console.log("[TS WRAPPER] PROCEED TO STATE: SKIPPING"); + return } - clearNodeCache(); - global.es2panda._ProceedToState(global.context, state); - processErrorState(state, forceDtsEmit); -} - -function processErrorState(state: Es2pandaContextState, forceDtsEmit = false): void { + clearNodeCache() try { - if ( - global.es2panda._ContextState(global.context) === Es2pandaContextState.ES2PANDA_STATE_ERROR && - !forceDtsEmit - ) { - const errorMessage = withStringResult(global.es2panda._ContextErrorMessage(global.context)); + global.es2panda._ProceedToState(global.context, state) + if (global.es2panda._ContextState(global.context) === Es2pandaContextState.ES2PANDA_STATE_ERROR && !forceDtsEmit) { + const errorMessage = withStringResult(global.es2panda._ContextErrorMessage(global.context)) if (errorMessage === undefined) { - throwError(`Could not get ContextErrorMessage`); + throwError(`Could not get ContextErrorMessage`) } - const allErrorMessages = withStringResult(global.es2panda._GetAllErrorMessages(global.context)); - if (allErrorMessages === undefined) { - throwError(`Could not get AllErrorMessages`); - } - throwError([`Failed to proceed to ${Es2pandaContextState[state]}`, errorMessage, allErrorMessages].join(`\n`)); + throwError( + [ + `Failed to proceed to ${Es2pandaContextState[state]}`, + errorMessage + ] + .join(`\n`) + ) } } catch (e) { - global.es2panda._DestroyContext(global.context); - throw e; + global.es2panda._DestroyContext(global.context) + throw e } } export function startChecker(): boolean { - return global.es2panda._CheckerStartChecker(global.context); + return global.es2panda._CheckerStartChecker(global.context) } export function recheckSubtree(node: AstNode): void { - global.es2panda._AstNodeRecheck(global.context, node.peer); + global.es2panda._AstNodeRecheck(global.context, node.peer) } export function rebindSubtree(node: AstNode): void { - global.es2panda._AstNodeRebind(global.context, node.peer); + global.es2panda._AstNodeRebind(global.context, node.peer) } export function getDecl(node: AstNode): AstNode | undefined { if (isMemberExpression(node)) { - return getDeclFromArrayOrObjectMember(node); - } - if (isObjectExpression(node)) { - return getPeerObjectDecl(passNode(node)); - } - const decl = getPeerDecl(passNode(node)); - if (!!decl) { - return decl; - } - if (isProperty(node.parent)) { - return getDeclFromProperty(node.parent); - } - return undefined; -} - -function getDeclFromProperty(node: Property): AstNode | undefined { - if (!node.key) { - return undefined; - } - if (!isObjectExpression(node.parent)) { - return getPeerDecl(passNode(node.key)); - } - return getDeclFromObjectExpressionProperty(node); -} - -function getDeclFromObjectExpressionProperty(node: Property): AstNode | undefined { - const declNode = getPeerObjectDecl(passNode(node.parent)); - if (!declNode || !node.key || !isIdentifier(node.key)) { - return undefined; - } - let body: readonly AstNode[] = []; - if (isClassDefinition(declNode)) { - body = declNode.body; - } else if (isTSInterfaceDeclaration(declNode)) { - body = declNode.body?.body ?? []; - } - return body.find( - (statement) => - isMethodDefinition(statement) && - statement.kind === Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_GET && - !!statement.name && - !!node.key && - isIdentifier(node.key) && - statement.name.name === node.key.name - ); -} - -function getDeclFromArrayOrObjectMember(node: MemberExpression): AstNode | undefined { - if (isNumberLiteral(node.property)) { - return getDecl(node.object); + return getDecl(node.property) } - return getDecl(node.property); -} - -export function getPeerDecl(peer: KNativePointer): AstNode | undefined { - const decl = global.es2panda._DeclarationFromIdentifier(global.context, peer); + const decl = global.es2panda._DeclarationFromIdentifier(global.context, passNode(node)) if (decl === nullptr) { - return undefined; + return undefined } - return unpackNonNullableNode(decl); -} - -export function getPeerObjectDecl(peer: KNativePointer): AstNode | undefined { - const decl = global.es2panda._ClassVariableDeclaration(global.context, peer); - if (decl === nullptr) { - return undefined; - } - return unpackNonNullableNode(decl); + return unpackNonNullableNode(decl) } export function getAnnotations(node: AstNode): readonly AnnotationUsage[] { if (!isFunctionDeclaration(node) && !isScriptFunction(node) && !isClassDefinition(node)) { - throwError('for now annotations allowed only for: functionDeclaration, scriptFunction, classDefinition'); + throwError('for now annotations allowed only for: functionDeclaration, scriptFunction, classDefinition') } - return unpackNodeArray(global.es2panda._AnnotationAllowedAnnotations(global.context, node.peer, nullptr)); + return unpackNodeArray(global.es2panda._AnnotationAllowedAnnotations(global.context, node.peer, nullptr)) } export function getOriginalNode(node: AstNode): AstNode { if (node === undefined) { // TODO: fix this - throwError('there is no arkts pair of ts node (unable to getOriginalNode)'); + throwError('there is no arkts pair of ts node (unable to getOriginalNode)') } if (node.originalPeer === nullptr) { - return node; + return node } - return unpackNonNullableNode(node.originalPeer); + return unpackNonNullableNode(node.originalPeer) } export function getFileName(): string { - return global.filePath; + return global.filePath } export function classDefinitionSetFromStructModifier(node: ClassDefinition): void { @@ -193,25 +105,17 @@ export function classDefinitionIsFromStructConst(node: ClassDefinition): boolean return global.es2panda._ClassDefinitionIsFromStructConst(global.context, node.peer); } -export function ImportSpecifierSetRemovable(node: ImportSpecifier): void { - global.es2panda._ImportSpecifierSetRemovable(global.context, node.peer); -} - -export function ImportSpecifierIsRemovableConst(node: ImportSpecifier): boolean { - return global.es2panda._ImportSpecifierIsRemovableConst(global.context, node.peer); -} - // TODO: It seems like Definition overrides AstNode modifiers // with it's own modifiers which is completely unrelated set of flags. // Use this function if you need // the language level modifiers: public, declare, export, etc. export function classDefinitionFlags(node: ClassDefinition): Es2pandaModifierFlags { - return global.generatedEs2panda._AstNodeModifiers(global.context, node.peer); + return global.generatedEs2panda._AstNodeModifiers(global.context, node.peer) } // TODO: Import statements should be inserted to the statements export function importDeclarationInsert(node: ETSImportDeclaration, program: Program): void { - global.es2panda._InsertETSImportDeclarationAndParse(global.context, program.peer, node.peer); + global.es2panda._InsertETSImportDeclarationAndParse(global.context, program.peer, node.peer) } export function hasModifierFlag(node: AstNode, flag: Es2pandaModifierFlags): boolean { @@ -221,7 +125,7 @@ export function hasModifierFlag(node: AstNode, flag: Es2pandaModifierFlags): boo if (isClassDefinition(node)) { modifiers = classDefinitionFlags(node); } else { - modifiers = node.modifiers; + modifiers = node.modifiers } return (modifiers & flag) === flag; } @@ -239,11 +143,10 @@ export function classPropertySetOptional(node: ClassProperty, value: boolean): C export function modifiersToString(modifiers: Es2pandaModifierFlags): string { return Object.values(Es2pandaModifierFlags) .filter(isNumber) - .map((it) => { - console.log(it.valueOf(), Es2pandaModifierFlags[it], modifiers.valueOf() & it); - return (modifiers.valueOf() & it) === it ? Es2pandaModifierFlags[it] : ''; - }) - .join(' '); + .map(it => { + console.log(it.valueOf(), Es2pandaModifierFlags[it], modifiers.valueOf() & it) + return ((modifiers.valueOf() & it) === it) ? Es2pandaModifierFlags[it] : "" + }).join(" ") } export function destroyConfig(config: KNativePointer): void { global.es2panda._DestroyConfig(config); @@ -251,26 +154,9 @@ export function destroyConfig(config: KNativePointer): void { } export function setAllParents(ast: AstNode) { - global.es2panda._AstNodeUpdateAll(global.context, ast.peer); + global.es2panda._AstNodeUpdateAll(global.context, ast.peer) } export function generateTsDeclarationsFromContext(outputDeclEts: string, outputEts: string, exportAll: boolean): KInt { - return global.es2panda._GenerateTsDeclarationsFromContext( - global.context, - passString(outputDeclEts), - passString(outputEts), - exportAll - ); -} - -export function isDefaultAccessModifierClassProperty(property: ClassProperty): boolean { - return global.es2panda._ClassPropertyIsDefaultAccessModifierConst(global.context, property.peer); -} - -export function getStartPosition(node: AstNode): SourcePosition { - return new SourcePosition(global.es2panda._AstNodeStartConst(global.context, node.peer)); -} - -export function getEndPosition(node: AstNode): SourcePosition { - return new SourcePosition(global.es2panda._AstNodeEndConst(global.context, node.peer)); -} + return global.es2panda._GenerateTsDeclarationsFromContext(global.context, passString(outputDeclEts), passString(outputEts), exportAll) +} \ No newline at end of file diff --git a/koala-wrapper/src/arkts-api/visitor.ts b/koala-wrapper/src/arkts-api/visitor.ts index e6ebd25db..2d62b5a42 100644 --- a/koala-wrapper/src/arkts-api/visitor.ts +++ b/koala-wrapper/src/arkts-api/visitor.ts @@ -13,21 +13,21 @@ * limitations under the License. */ -import { global } from './static/global'; -import { factory } from './factory/nodeFactory'; +import { global } from "./static/global" +import { factory } from "./factory/nodeFactory" import { Es2pandaClassDefinitionModifiers, Es2pandaImportKinds, Es2pandaModifierFlags, - Es2pandaVariableDeclaratorFlag, -} from '../generated/Es2pandaEnums'; -import { AstNode } from './peers/AstNode'; -import { - isBlockStatement, - isConditionalExpression, - isTSInterfaceBody, - isTSInterfaceDeclaration, - isClassDeclaration, + Es2pandaVariableDeclaratorFlag +} from "../generated/Es2pandaEnums" +import { AstNode } from "./peers/AstNode" +import { + isBlockStatement, + isConditionalExpression, + isTSInterfaceBody, + isTSInterfaceDeclaration, + isClassDeclaration, isClassDefinition, isTSAsExpression, isETSImportDeclaration, @@ -36,24 +36,8 @@ import { FunctionSignature, Property, isClassProperty, - isImportDeclaration, - isObjectExpression, - ObjectExpression, - isProperty, - Expression, - isETSNewClassInstanceExpression, - isTemplateLiteral, - isBlockExpression, - isReturnStatement, - isArrayExpression, - isTryStatement, - isBinaryExpression, - isForInStatement, - isForUpdateStatement, - isForOfStatement, - isTSTypeAliasDeclaration, - isETSFunctionType, -} from '../generated'; + isImportDeclaration +} from "../generated" import { isEtsScript, isCallExpression, @@ -66,20 +50,21 @@ import { isIfStatement, isVariableDeclaration, isVariableDeclarator, - isArrowFunctionExpression, - isAssignmentExpression, - isEtsParameterExpression, -} from './factory/nodeTests'; -import { classDefinitionFlags } from './utilities/public'; -import { Es2pandaAstNodeType } from '../Es2pandaEnums'; + isArrowFunctionExpression +} from "./factory/nodeTests" +import { + classDefinitionFlags, + hasModifierFlag, + classPropertySetOptional + } from "./utilities/public" -type Visitor = (node: AstNode) => AstNode; +type Visitor = (node: AstNode) => AstNode export interface StructVariableMetadata { - name: string; - properties: string[]; - modifiers: Es2pandaModifierFlags; - hasStateManagementType?: boolean; + name: string, + properties: string[], + modifiers: Es2pandaModifierFlags, + hasStateManagementType?: boolean } export class StructInfo { @@ -136,49 +121,41 @@ export class GlobalInfo { // TODO: rethink (remove as) function nodeVisitor(node: T, visitor: Visitor): T { if (node === undefined) { - return node; + return node } - return visitor(node) as T; + return visitor(node) as T } // TODO: rethink (remove as) -function nodesVisitor( - nodes: TIn, - visitor: Visitor -): T[] | TIn { +function nodesVisitor(nodes: TIn, visitor: Visitor): T[] | TIn { if (nodes === undefined) { - return nodes; + return nodes } - return nodes.map((node) => visitor(node) as T); + return nodes.map(node => visitor(node) as T) } -let updated: boolean = false; - -export function visitEachChild(node: AstNode, visitor: Visitor): AstNode { - updated = false; - let script: AstNode = node; - script = visitETSModule(script, visitor); - script = visitDeclaration(script, visitor); - script = visitDefinition(script, visitor); - script = visitDefinitionBody(script, visitor); - script = visitStatement(script, visitor); - script = visitForLoopStatement(script, visitor); - script = visitOuterExpression(script, visitor); - script = visitInnerExpression(script, visitor); - script = visitTrivialExpression(script, visitor); - script = visitLiteral(script, visitor); - // TODO - return visitWithoutUpdate(script, visitor); +// TODO: apply this to all nodes that does not require updating +function visitWithoutUpdate( + node: T, + visitor: Visitor +): T { + if (isImportDeclaration(node)) { + nodesVisitor(node.specifiers, visitor); + } + return node; } -function visitOuterExpression(node: AstNode, visitor: Visitor): AstNode { - if (updated) { - return node; - } else if (isBlockExpression(node)) { - updated = true; - return factory.updateBlockExpression(node, nodesVisitor(node.statements, visitor)); - } else if (isCallExpression(node)) { - updated = true; +export function visitEachChild( + node: AstNode, + visitor: Visitor +): AstNode { + if (isEtsScript(node)) { + return factory.updateEtsScript( + node, + nodesVisitor(node.statements, visitor) + ); + } + if (isCallExpression(node)) { const call = factory.updateCallExpression( node, nodeVisitor(node.expression, visitor), @@ -189,155 +166,41 @@ function visitOuterExpression(node: AstNode, visitor: Visitor): AstNode { call.setTralingBlock(nodeVisitor(node.trailingBlock, visitor)); } return call; - } else if (isArrowFunctionExpression(node)) { - updated = true; - return factory.updateArrowFunction(node, nodeVisitor(node.scriptFunction, visitor)); - } else if (isAssignmentExpression(node)) { - updated = true; - return factory.updateAssignmentExpression( - node, - nodeVisitor(node.left as Expression, visitor), - node.operatorType, - nodeVisitor(node.right as Expression, visitor) - ); - } else if (isETSNewClassInstanceExpression(node)) { - updated = true; - return factory.updateETSNewClassInstanceExpression( - node, - node.getTypeRef, - nodesVisitor(node.getArguments, visitor) - ); - } - if (isArrayExpression(node)) { - updated = true; - return factory.updateArrayExpression(node, nodesVisitor(node.elements, visitor)); - } - return node; -} - -function visitInnerExpression(node: AstNode, visitor: Visitor): AstNode { - if (updated) { - return node; - } - if (isMemberExpression(node)) { - updated = true; - return factory.updateMemberExpression( - node, - nodeVisitor(node.object, visitor), - nodeVisitor(node.property, visitor), - node.kind, - node.computed, - node.optional - ); } - if (isConditionalExpression(node)) { - updated = true; - return factory.updateConditionalExpression( + if (isFunctionDeclaration(node)) { + return factory.updateFunctionDeclaration( node, - nodeVisitor(node.test, visitor), - nodeVisitor(node.consequent, visitor), - nodeVisitor(node.alternate, visitor) + nodeVisitor(node.scriptFunction, visitor), + node.isAnon, + node.annotations, ); } - if (isTSAsExpression(node)) { - updated = true; - return factory.updateTSAsExpression( + if (isBlockStatement(node)) { + return factory.updateBlock( node, - nodeVisitor(node.expr, visitor), - nodeVisitor(node.typeAnnotation, visitor), - node.isConst + nodesVisitor(node.statements, visitor), ); } - if (isObjectExpression(node)) { - updated = true; - return factory.updateObjectExpression( + if (isExpressionStatement(node)) { + return factory.updateExpressionStatement( node, - Es2pandaAstNodeType.AST_NODE_TYPE_OBJECT_EXPRESSION, - nodesVisitor(node.properties as Property[], visitor), - false + nodeVisitor(node.expression, visitor) ); } - if (isProperty(node)) { - updated = true; - return factory.updateProperty(node, node.key, nodeVisitor(node.value, visitor)); - } - // TODO - return node; -} - -function visitTrivialExpression(node: AstNode, visitor: Visitor): AstNode { - if (updated) { - return node; - } - if (isBinaryExpression(node)) { - updated = true; - return factory.updateBinaryExpression( + if (isClassDeclaration(node)) { + return factory.updateClassDeclaration( node, - nodeVisitor(node.left, visitor), - nodeVisitor(node.right, visitor), - node.operatorType + nodeVisitor(node.definition, visitor) ); } - // TODO - return node; -} - -function visitDeclaration(node: AstNode, visitor: Visitor): AstNode { - if (updated) { - return node; - } else if (isFunctionDeclaration(node)) { - updated = true; - return factory.updateFunctionDeclaration( - node, - nodeVisitor(node.scriptFunction, visitor), - node.isAnon, - node.annotations - ); - } else if (isClassDeclaration(node)) { - updated = true; - return factory.updateClassDeclaration(node, nodeVisitor(node.definition, visitor)); - } else if (isStructDeclaration(node)) { - updated = true; - return factory.updateStructDeclaration(node, nodeVisitor(node.definition, visitor)); - } else if (isTSInterfaceDeclaration(node)) { - updated = true; - return factory.updateInterfaceDeclaration( - node, - nodesVisitor(node.extends, visitor), - nodeVisitor(node.id, visitor), - nodeVisitor(node.typeParams, visitor), - nodeVisitor(node.body, visitor), - node.isStatic, - // TODO: how do I get it? - true - ); - } else if (isVariableDeclaration(node)) { - updated = true; - return factory.updateVariableDeclaration( + if (isStructDeclaration(node)) { + return factory.updateStructDeclaration( node, - 0, - node.declarationKind, - nodesVisitor(node.declarators, visitor) - ); - } else if (isTSTypeAliasDeclaration(node)) { - updated = true; - return factory.updateTSTypeAliasDeclaration( - node, - node.id, - nodeVisitor(node.typeParams, visitor), - nodeVisitor(node.typeAnnotation, visitor) + nodeVisitor(node.definition, visitor) ); } - // TODO - return node; -} - -function visitDefinition(node: AstNode, visitor: Visitor): AstNode { - if (updated) { - return node; - } if (isClassDefinition(node)) { - updated = true; + // TODO: fix return factory.updateClassDefinition( node, node.ident, @@ -352,140 +215,108 @@ function visitDefinition(node: AstNode, visitor: Visitor): AstNode { ); } if (isMethodDefinition(node)) { - updated = true; + // TODO: fix return factory.updateMethodDefinition( node, node.kind, node.name, - nodeVisitor(node.scriptFunction, visitor), + factory.createFunctionExpression( + // TODO: maybe fix + nodeVisitor(node.scriptFunction, visitor) + ), node.modifiers, false ); } - if (isTSInterfaceBody(node)) { - updated = true; - return factory.updateInterfaceBody(node, nodesVisitor(node.body, visitor)); - } - if (isVariableDeclarator(node)) { - updated = true; - return factory.updateVariableDeclarator( + if (isScriptFunction(node)) { + return factory.updateScriptFunction( node, - global.generatedEs2panda._VariableDeclaratorFlag(global.context, node.peer), - nodeVisitor(node.name, visitor), - nodeVisitor(node.initializer, visitor) + nodeVisitor(node.body, visitor), + FunctionSignature.createFunctionSignature( + nodeVisitor(node.typeParams, visitor), + nodesVisitor(node.params, visitor), + nodeVisitor(node.returnTypeAnnotation, visitor), + node.hasReceiver + ), + node.flags, + node.modifiers ); } - return node; -} - -function visitStatement(node: AstNode, visitor: Visitor): AstNode { - if (updated) { - return node; + if (isMemberExpression(node)) { + return factory.updateMemberExpression( + node, + nodeVisitor(node.object, visitor), + nodeVisitor(node.property, visitor), + node.kind, + node.computed, + node.optional + ); } - if (isBlockStatement(node)) { - updated = true; - return factory.updateBlock(node, nodesVisitor(node.statements, visitor)); + if (isTSInterfaceDeclaration(node)) { + return factory.updateInterfaceDeclaration( + node, + nodesVisitor(node.extends, visitor), + nodeVisitor(node.id, visitor), + nodeVisitor(node.typeParams, visitor), + nodeVisitor(node.body, visitor), + node.isStatic, + // TODO: how do I get it? + true + ); } - if (isExpressionStatement(node)) { - updated = true; - return factory.updateExpressionStatement(node, nodeVisitor(node.expression, visitor)); + if (isTSInterfaceBody(node)) { + return factory.updateInterfaceBody( + node, + nodesVisitor(node.body, visitor) + ); } if (isIfStatement(node)) { - updated = true; return factory.updateIfStatement( node, nodeVisitor(node.test, visitor), nodeVisitor(node.consequent, visitor), - nodeVisitor(node.alternate, visitor) + nodeVisitor(node.alternate, visitor), ); } - if (isReturnStatement(node)) { - updated = true; - return factory.updateReturnStatement(node, nodeVisitor(node.argument, visitor)); - } - if (isTryStatement(node)) { - updated = true; - return factory.updateTryStatement( + if (isConditionalExpression(node)) { + return factory.updateConditionalExpression( node, - nodeVisitor(node.block, visitor), - nodesVisitor(node.catchClauses, visitor), - nodeVisitor(node.finallyBlock, visitor), - [], - [] + nodeVisitor(node.test, visitor), + nodeVisitor(node.consequent, visitor), + nodeVisitor(node.alternate, visitor), ); } - // TODO - return node; -} - -function visitForLoopStatement(node: AstNode, visitor: Visitor): AstNode { - if (updated) { - return node; - } - if (isForUpdateStatement(node)) { - updated = true; - return factory.updateForUpdateStatement( + if (isVariableDeclaration(node)) { + return factory.updateVariableDeclaration( node, - nodeVisitor(node.init, visitor), - nodeVisitor(node.test, visitor), - nodeVisitor(node.update, visitor), - nodeVisitor(node.body, visitor) + 0, + node.declarationKind, + nodesVisitor(node.declarators, visitor), ); } - if (isForInStatement(node)) { - updated = true; - return factory.updateForInStatement( + if (isVariableDeclarator(node)) { + return factory.updateVariableDeclarator( node, - nodeVisitor(node.left, visitor), - nodeVisitor(node.right, visitor), - nodeVisitor(node.body, visitor) + global.generatedEs2panda._VariableDeclaratorFlag(global.context, node.peer), + nodeVisitor(node.name, visitor), + nodeVisitor(node.initializer, visitor), ); } - if (isForOfStatement(node)) { - updated = true; - return factory.updateForOfStatement( + if (isArrowFunctionExpression(node)) { + return factory.updateArrowFunction( node, - nodeVisitor(node.left, visitor), - nodeVisitor(node.right, visitor), - nodeVisitor(node.body, visitor), - node.isAwait + nodeVisitor(node.scriptFunction, visitor), ); } - return node; -} - -function visitETSModule(node: AstNode, visitor: Visitor): AstNode { - if (updated) { - return node; - } - if (isEtsScript(node)) { - updated = true; - return factory.updateEtsScript(node, nodesVisitor(node.statements, visitor)); - } - return node; -} - -function visitDefinitionBody(node: AstNode, visitor: Visitor): AstNode { - if (updated) { - return node; - } - if (isScriptFunction(node)) { - updated = true; - return factory.updateScriptFunction( + if (isTSAsExpression(node)) { + return factory.updateTSAsExpression( node, - nodeVisitor(node.body, visitor), - factory.createFunctionSignature( - nodeVisitor(node.typeParams, visitor), - nodesVisitor(node.params, visitor), - nodeVisitor(node.returnTypeAnnotation, visitor), - node.hasReceiver - ), - node.flags, - node.modifiers + nodeVisitor(node.expr, visitor), + nodeVisitor(node.typeAnnotation, visitor), + node.isConst ); } if (isClassProperty(node)) { - updated = true; return factory.updateClassProperty( node, node.key, @@ -495,39 +326,21 @@ function visitDefinitionBody(node: AstNode, visitor: Visitor): AstNode { node.isComputed ); } - // TODO - return node; -} - -function visitLiteral(node: AstNode, visitor: Visitor): AstNode { - if (updated) { - return node; - } - if (isTemplateLiteral(node)) { - updated = true; - return factory.updateTemplateLiteral( + if (isClassProperty(node)) { + const _node = factory.updateClassProperty( node, - nodesVisitor(node.quasis, visitor), - nodesVisitor(node.expressions, visitor), - node.multilineString + node.key, + nodeVisitor(node.value, visitor), + node.typeAnnotation, + node.modifiers, + node.isComputed ); + if (hasModifierFlag(node, Es2pandaModifierFlags.MODIFIER_FLAGS_OPTIONAL)) { + classPropertySetOptional(_node, true); + } + _node.setAnnotations(node.annotations); + return _node; } - return node; -} - -// TODO: apply this to all nodes that does not require updating -function visitWithoutUpdate(node: T, visitor: Visitor): T { - if (updated) { - return node; - } - if (isImportDeclaration(node)) { - nodesVisitor(node.specifiers, visitor); - } - if (isETSFunctionType(node)) { - nodesVisitor(node.params, visitor); - } - if (isEtsParameterExpression(node)) { - nodeVisitor(node.type, visitor); - } - return node; + // TODO + return visitWithoutUpdate(node, visitor); } diff --git a/koala-wrapper/src/generated/Es2pandaEnums.ts b/koala-wrapper/src/generated/Es2pandaEnums.ts index 1e5ee0d2c..cc682d5a3 100644 --- a/koala-wrapper/src/generated/Es2pandaEnums.ts +++ b/koala-wrapper/src/generated/Es2pandaEnums.ts @@ -17,12 +17,13 @@ export enum Es2pandaContextState { ES2PANDA_STATE_NEW = 0, ES2PANDA_STATE_PARSED = 1, - ES2PANDA_STATE_BOUND = 2, - ES2PANDA_STATE_CHECKED = 3, - ES2PANDA_STATE_LOWERED = 4, - ES2PANDA_STATE_ASM_GENERATED = 5, - ES2PANDA_STATE_BIN_GENERATED = 6, - ES2PANDA_STATE_ERROR = 7 + ES2PANDA_STATE_SCOPE_INITED = 2, + ES2PANDA_STATE_BOUND = 3, + ES2PANDA_STATE_CHECKED = 4, + ES2PANDA_STATE_LOWERED = 5, + ES2PANDA_STATE_ASM_GENERATED = 6, + ES2PANDA_STATE_BIN_GENERATED = 7, + ES2PANDA_STATE_ERROR = 8 } // export enum Es2pandaAstNodeType { // AST_NODE_TYPE_ARROW_FUNCTION_EXPRESSION = 0, @@ -331,189 +332,190 @@ export enum Es2pandaId { ID_COUNT = 4 } export enum Es2pandaTokenType { - TOKEN_TYPE_EOS, - TOKEN_TYPE_LITERAL_IDENT, - TOKEN_TYPE_LITERAL_STRING, - TOKEN_TYPE_LITERAL_CHAR, - TOKEN_TYPE_LITERAL_NUMBER, - TOKEN_TYPE_LITERAL_REGEXP, - TOKEN_TYPE_PUNCTUATOR_BITWISE_AND, - TOKEN_TYPE_PUNCTUATOR_BITWISE_OR, - TOKEN_TYPE_PUNCTUATOR_MULTIPLY, - TOKEN_TYPE_PUNCTUATOR_DIVIDE, - TOKEN_TYPE_PUNCTUATOR_MINUS, - TOKEN_TYPE_PUNCTUATOR_EXCLAMATION_MARK, - TOKEN_TYPE_PUNCTUATOR_TILDE, - TOKEN_TYPE_PUNCTUATOR_MINUS_MINUS, - TOKEN_TYPE_PUNCTUATOR_LEFT_SHIFT, - TOKEN_TYPE_PUNCTUATOR_RIGHT_SHIFT, - TOKEN_TYPE_PUNCTUATOR_LESS_THAN_EQUAL, - TOKEN_TYPE_PUNCTUATOR_GREATER_THAN_EQUAL, - TOKEN_TYPE_PUNCTUATOR_MOD, - TOKEN_TYPE_PUNCTUATOR_BITWISE_XOR, - TOKEN_TYPE_PUNCTUATOR_EXPONENTIATION, - TOKEN_TYPE_PUNCTUATOR_MULTIPLY_EQUAL, - TOKEN_TYPE_PUNCTUATOR_EXPONENTIATION_EQUAL, - TOKEN_TYPE_PUNCTUATOR_ARROW, - TOKEN_TYPE_PUNCTUATOR_BACK_TICK, - TOKEN_TYPE_PUNCTUATOR_HASH_MARK, - TOKEN_TYPE_PUNCTUATOR_DIVIDE_EQUAL, - TOKEN_TYPE_PUNCTUATOR_MOD_EQUAL, - TOKEN_TYPE_PUNCTUATOR_MINUS_EQUAL, - TOKEN_TYPE_PUNCTUATOR_LEFT_SHIFT_EQUAL, - TOKEN_TYPE_PUNCTUATOR_RIGHT_SHIFT_EQUAL, - TOKEN_TYPE_PUNCTUATOR_UNSIGNED_RIGHT_SHIFT, - TOKEN_TYPE_PUNCTUATOR_UNSIGNED_RIGHT_SHIFT_EQUAL, - TOKEN_TYPE_PUNCTUATOR_BITWISE_AND_EQUAL, - TOKEN_TYPE_PUNCTUATOR_BITWISE_OR_EQUAL, - TOKEN_TYPE_PUNCTUATOR_LOGICAL_AND_EQUAL, - TOKEN_TYPE_PUNCTUATOR_NULLISH_COALESCING, - TOKEN_TYPE_PUNCTUATOR_LOGICAL_OR_EQUAL, - TOKEN_TYPE_PUNCTUATOR_LOGICAL_NULLISH_EQUAL, - TOKEN_TYPE_PUNCTUATOR_BITWISE_XOR_EQUAL, - TOKEN_TYPE_PUNCTUATOR_PLUS, - TOKEN_TYPE_PUNCTUATOR_PLUS_PLUS, - TOKEN_TYPE_PUNCTUATOR_PLUS_EQUAL, - TOKEN_TYPE_PUNCTUATOR_LESS_THAN, - TOKEN_TYPE_PUNCTUATOR_GREATER_THAN, - TOKEN_TYPE_PUNCTUATOR_EQUAL, - TOKEN_TYPE_PUNCTUATOR_NOT_EQUAL, - TOKEN_TYPE_PUNCTUATOR_STRICT_EQUAL, - TOKEN_TYPE_PUNCTUATOR_NOT_STRICT_EQUAL, - TOKEN_TYPE_PUNCTUATOR_LOGICAL_AND, - TOKEN_TYPE_PUNCTUATOR_LOGICAL_OR, - TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - TOKEN_TYPE_PUNCTUATOR_QUESTION_MARK, - TOKEN_TYPE_PUNCTUATOR_QUESTION_DOT, - TOKEN_TYPE_PUNCTUATOR_AT, - TOKEN_TYPE_PUNCTUATOR_FORMAT, - TOKEN_TYPE_PUNCTUATOR_RIGHT_PARENTHESIS, - TOKEN_TYPE_PUNCTUATOR_LEFT_PARENTHESIS, - TOKEN_TYPE_PUNCTUATOR_RIGHT_SQUARE_BRACKET, - TOKEN_TYPE_PUNCTUATOR_LEFT_SQUARE_BRACKET, - TOKEN_TYPE_PUNCTUATOR_RIGHT_BRACE, - TOKEN_TYPE_PUNCTUATOR_PERIOD, - TOKEN_TYPE_PUNCTUATOR_PERIOD_PERIOD_PERIOD, - TOKEN_TYPE_PUNCTUATOR_PERIOD_QUESTION, - TOKEN_TYPE_PUNCTUATOR_LEFT_BRACE, - TOKEN_TYPE_PUNCTUATOR_SEMI_COLON, - TOKEN_TYPE_PUNCTUATOR_COLON, - TOKEN_TYPE_PUNCTUATOR_COMMA, - TOKEN_TYPE_KEYW_ABSTRACT, - TOKEN_TYPE_KEYW_ANY, - TOKEN_TYPE_KEYW_ANYREF, - TOKEN_TYPE_KEYW_ARGUMENTS, - TOKEN_TYPE_KEYW_AS, - TOKEN_TYPE_KEYW_ASSERT, - TOKEN_TYPE_KEYW_ASSERTS, - TOKEN_TYPE_KEYW_ASYNC, - TOKEN_TYPE_KEYW_AWAIT, - TOKEN_TYPE_KEYW_BIGINT, - TOKEN_TYPE_KEYW_BOOLEAN, - TOKEN_TYPE_KEYW_BREAK, - TOKEN_TYPE_KEYW_BYTE, - TOKEN_TYPE_KEYW_CASE, - TOKEN_TYPE_KEYW_CATCH, - TOKEN_TYPE_KEYW_CHAR, - TOKEN_TYPE_KEYW_CLASS, - TOKEN_TYPE_KEYW_CONST, - TOKEN_TYPE_KEYW_CONSTRUCTOR, - TOKEN_TYPE_KEYW_CONTINUE, - TOKEN_TYPE_KEYW_DATAREF, - TOKEN_TYPE_KEYW_DEBUGGER, - TOKEN_TYPE_KEYW_DECLARE, - TOKEN_TYPE_KEYW_DEFAULT, - TOKEN_TYPE_KEYW_DELETE, - TOKEN_TYPE_KEYW_DO, - TOKEN_TYPE_KEYW_DOUBLE, - TOKEN_TYPE_KEYW_ELSE, - TOKEN_TYPE_KEYW_ENUM, - TOKEN_TYPE_KEYW_EQREF, - TOKEN_TYPE_KEYW_EVAL, - TOKEN_TYPE_KEYW_EXPORT, - TOKEN_TYPE_KEYW_EXTENDS, - TOKEN_TYPE_KEYW_EXTERNREF, - TOKEN_TYPE_KEYW_F32, - TOKEN_TYPE_KEYW_F64, - TOKEN_TYPE_LITERAL_FALSE, - TOKEN_TYPE_KEYW_FINALLY, - TOKEN_TYPE_KEYW_FLOAT, - TOKEN_TYPE_KEYW_FOR, - TOKEN_TYPE_KEYW_FROM, - TOKEN_TYPE_KEYW_FUNCREF, - TOKEN_TYPE_KEYW_FUNCTION, - TOKEN_TYPE_KEYW_GET, - TOKEN_TYPE_KEYW_GLOBAL, - TOKEN_TYPE_KEYW_I8, - TOKEN_TYPE_KEYW_I16, - TOKEN_TYPE_KEYW_I31REF, - TOKEN_TYPE_KEYW_I32, - TOKEN_TYPE_KEYW_I64, - TOKEN_TYPE_KEYW_IF, - TOKEN_TYPE_KEYW_IMPLEMENTS, - TOKEN_TYPE_KEYW_IMPORT, - TOKEN_TYPE_KEYW_IN, - TOKEN_TYPE_KEYW_INFER, - TOKEN_TYPE_KEYW_INSTANCEOF, - TOKEN_TYPE_KEYW_INT, - TOKEN_TYPE_KEYW_INTERFACE, - TOKEN_TYPE_KEYW_IS, - TOKEN_TYPE_KEYW_ISIZE, - TOKEN_TYPE_KEYW_KEYOF, - TOKEN_TYPE_KEYW_LET, - TOKEN_TYPE_KEYW_LONG, - TOKEN_TYPE_KEYW_META, - TOKEN_TYPE_KEYW_MODULE, - TOKEN_TYPE_KEYW_NAMESPACE, - TOKEN_TYPE_KEYW_NATIVE, - TOKEN_TYPE_KEYW_NEVER, - TOKEN_TYPE_KEYW_NEW, - TOKEN_TYPE_LITERAL_NULL, - TOKEN_TYPE_KEYW_NUMBER, - TOKEN_TYPE_KEYW_OBJECT, - TOKEN_TYPE_KEYW_OF, - TOKEN_TYPE_KEYW_FINAL, - TOKEN_TYPE_KEYW_OUT, - TOKEN_TYPE_KEYW_OVERRIDE, - TOKEN_TYPE_KEYW_PACKAGE, - TOKEN_TYPE_KEYW_INTERNAL, - TOKEN_TYPE_KEYW_PRIVATE, - TOKEN_TYPE_KEYW_PROTECTED, - TOKEN_TYPE_KEYW_PUBLIC, - TOKEN_TYPE_KEYW_READONLY, - TOKEN_TYPE_KEYW_RETHROWS, - TOKEN_TYPE_KEYW_RETURN, - TOKEN_TYPE_KEYW_REQUIRE, - TOKEN_TYPE_KEYW_SET, - TOKEN_TYPE_KEYW_SHORT, - TOKEN_TYPE_KEYW_STATIC, - TOKEN_TYPE_KEYW_STRING, - TOKEN_TYPE_KEYW_STRUCT, - TOKEN_TYPE_KEYW_SUPER, - TOKEN_TYPE_KEYW_SWITCH, - TOKEN_TYPE_KEYW_TARGET, - TOKEN_TYPE_KEYW_THIS, - TOKEN_TYPE_KEYW_THROW, - TOKEN_TYPE_KEYW_THROWS, - TOKEN_TYPE_LITERAL_TRUE, - TOKEN_TYPE_KEYW_TRY, - TOKEN_TYPE_KEYW_TYPE, - TOKEN_TYPE_KEYW_TYPEOF, - TOKEN_TYPE_KEYW_U8, - TOKEN_TYPE_KEYW_U16, - TOKEN_TYPE_KEYW_U32, - TOKEN_TYPE_KEYW_U64, - TOKEN_TYPE_KEYW_UNDEFINED, - TOKEN_TYPE_KEYW_UNKNOWN, - TOKEN_TYPE_KEYW_USIZE, - TOKEN_TYPE_KEYW_V128, - TOKEN_TYPE_KEYW_VAR, - TOKEN_TYPE_KEYW_VOID, - TOKEN_TYPE_KEYW_WHILE, - TOKEN_TYPE_KEYW_WITH, - TOKEN_TYPE_KEYW_YIELD, - TOKEN_TYPE_FIRST_PUNCTUATOR = Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_BITWISE_AND, - TOKEN_TYPE_FIRST_KEYW = Es2pandaTokenType.TOKEN_TYPE_KEYW_ABSTRACT + TOKEN_TYPE_EOS = 0, + TOKEN_TYPE_LITERAL_IDENT = 1, + TOKEN_TYPE_LITERAL_STRING = 2, + TOKEN_TYPE_LITERAL_CHAR = 3, + TOKEN_TYPE_LITERAL_NUMBER = 4, + TOKEN_TYPE_LITERAL_REGEXP = 5, + TOKEN_TYPE_PUNCTUATOR_BITWISE_AND = 6, + TOKEN_TYPE_PUNCTUATOR_BITWISE_OR = 7, + TOKEN_TYPE_PUNCTUATOR_MULTIPLY = 8, + TOKEN_TYPE_PUNCTUATOR_DIVIDE = 9, + TOKEN_TYPE_PUNCTUATOR_MINUS = 10, + TOKEN_TYPE_PUNCTUATOR_EXCLAMATION_MARK = 11, + TOKEN_TYPE_PUNCTUATOR_TILDE = 12, + TOKEN_TYPE_PUNCTUATOR_MINUS_MINUS = 13, + TOKEN_TYPE_PUNCTUATOR_LEFT_SHIFT = 14, + TOKEN_TYPE_PUNCTUATOR_RIGHT_SHIFT = 15, + TOKEN_TYPE_PUNCTUATOR_LESS_THAN_EQUAL = 16, + TOKEN_TYPE_PUNCTUATOR_GREATER_THAN_EQUAL = 17, + TOKEN_TYPE_PUNCTUATOR_MOD = 18, + TOKEN_TYPE_PUNCTUATOR_BITWISE_XOR = 19, + TOKEN_TYPE_PUNCTUATOR_EXPONENTIATION = 20, + TOKEN_TYPE_PUNCTUATOR_MULTIPLY_EQUAL = 21, + TOKEN_TYPE_PUNCTUATOR_EXPONENTIATION_EQUAL = 22, + TOKEN_TYPE_PUNCTUATOR_ARROW = 23, + TOKEN_TYPE_PUNCTUATOR_BACK_TICK = 24, + TOKEN_TYPE_PUNCTUATOR_HASH_MARK = 25, + TOKEN_TYPE_PUNCTUATOR_DIVIDE_EQUAL = 26, + TOKEN_TYPE_PUNCTUATOR_MOD_EQUAL = 27, + TOKEN_TYPE_PUNCTUATOR_MINUS_EQUAL = 28, + TOKEN_TYPE_PUNCTUATOR_LEFT_SHIFT_EQUAL = 29, + TOKEN_TYPE_PUNCTUATOR_RIGHT_SHIFT_EQUAL = 30, + TOKEN_TYPE_PUNCTUATOR_UNSIGNED_RIGHT_SHIFT = 31, + TOKEN_TYPE_PUNCTUATOR_UNSIGNED_RIGHT_SHIFT_EQUAL = 32, + TOKEN_TYPE_PUNCTUATOR_BITWISE_AND_EQUAL = 33, + TOKEN_TYPE_PUNCTUATOR_BITWISE_OR_EQUAL = 34, + TOKEN_TYPE_PUNCTUATOR_LOGICAL_AND_EQUAL = 35, + TOKEN_TYPE_PUNCTUATOR_NULLISH_COALESCING = 36, + TOKEN_TYPE_PUNCTUATOR_LOGICAL_OR_EQUAL = 37, + TOKEN_TYPE_PUNCTUATOR_LOGICAL_NULLISH_EQUAL = 38, + TOKEN_TYPE_PUNCTUATOR_BITWISE_XOR_EQUAL = 39, + TOKEN_TYPE_PUNCTUATOR_PLUS = 40, + TOKEN_TYPE_PUNCTUATOR_PLUS_PLUS = 41, + TOKEN_TYPE_PUNCTUATOR_PLUS_EQUAL = 42, + TOKEN_TYPE_PUNCTUATOR_LESS_THAN = 43, + TOKEN_TYPE_PUNCTUATOR_GREATER_THAN = 44, + TOKEN_TYPE_PUNCTUATOR_EQUAL = 45, + TOKEN_TYPE_PUNCTUATOR_NOT_EQUAL = 46, + TOKEN_TYPE_PUNCTUATOR_STRICT_EQUAL = 47, + TOKEN_TYPE_PUNCTUATOR_NOT_STRICT_EQUAL = 48, + TOKEN_TYPE_PUNCTUATOR_LOGICAL_AND = 49, + TOKEN_TYPE_PUNCTUATOR_LOGICAL_OR = 50, + TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION = 51, + TOKEN_TYPE_PUNCTUATOR_QUESTION_MARK = 52, + TOKEN_TYPE_PUNCTUATOR_QUESTION_DOT = 53, + TOKEN_TYPE_PUNCTUATOR_AT = 54, + TOKEN_TYPE_PUNCTUATOR_FORMAT = 55, + TOKEN_TYPE_PUNCTUATOR_RIGHT_PARENTHESIS = 56, + TOKEN_TYPE_PUNCTUATOR_LEFT_PARENTHESIS = 57, + TOKEN_TYPE_PUNCTUATOR_RIGHT_SQUARE_BRACKET = 58, + TOKEN_TYPE_PUNCTUATOR_LEFT_SQUARE_BRACKET = 59, + TOKEN_TYPE_PUNCTUATOR_RIGHT_BRACE = 60, + TOKEN_TYPE_PUNCTUATOR_PERIOD = 61, + TOKEN_TYPE_PUNCTUATOR_PERIOD_PERIOD_PERIOD = 62, + TOKEN_TYPE_PUNCTUATOR_PERIOD_QUESTION = 63, + TOKEN_TYPE_PUNCTUATOR_LEFT_BRACE = 64, + TOKEN_TYPE_PUNCTUATOR_SEMI_COLON = 65, + TOKEN_TYPE_PUNCTUATOR_COLON = 66, + TOKEN_TYPE_PUNCTUATOR_COMMA = 67, + TOKEN_TYPE_KEYW_ABSTRACT = 68, + TOKEN_TYPE_KEYW_ANY = 69, + TOKEN_TYPE_KEYW_ANYREF = 70, + TOKEN_TYPE_KEYW_ARGUMENTS = 71, + TOKEN_TYPE_KEYW_AS = 72, + TOKEN_TYPE_KEYW_ASSERT = 73, + TOKEN_TYPE_KEYW_ASSERTS = 74, + TOKEN_TYPE_KEYW_ASYNC = 75, + TOKEN_TYPE_KEYW_AWAIT = 76, + TOKEN_TYPE_KEYW_BIGINT = 77, + TOKEN_TYPE_KEYW_BOOLEAN = 78, + TOKEN_TYPE_KEYW_BREAK = 79, + TOKEN_TYPE_KEYW_BYTE = 80, + TOKEN_TYPE_KEYW_CASE = 81, + TOKEN_TYPE_KEYW_CATCH = 82, + TOKEN_TYPE_KEYW_CHAR = 83, + TOKEN_TYPE_KEYW_CLASS = 84, + TOKEN_TYPE_KEYW_CONST = 85, + TOKEN_TYPE_KEYW_CONSTRUCTOR = 86, + TOKEN_TYPE_KEYW_CONTINUE = 87, + TOKEN_TYPE_KEYW_DATAREF = 88, + TOKEN_TYPE_KEYW_DEBUGGER = 89, + TOKEN_TYPE_KEYW_DECLARE = 90, + TOKEN_TYPE_KEYW_DEFAULT = 91, + TOKEN_TYPE_KEYW_DELETE = 92, + TOKEN_TYPE_KEYW_DO = 93, + TOKEN_TYPE_KEYW_DOUBLE = 94, + TOKEN_TYPE_KEYW_ELSE = 95, + TOKEN_TYPE_KEYW_ENUM = 96, + TOKEN_TYPE_KEYW_EQREF = 97, + TOKEN_TYPE_KEYW_EVAL = 98, + TOKEN_TYPE_KEYW_EXPORT = 99, + TOKEN_TYPE_KEYW_EXTENDS = 100, + TOKEN_TYPE_KEYW_EXTERNREF = 101, + TOKEN_TYPE_KEYW_F32 = 102, + TOKEN_TYPE_KEYW_F64 = 103, + TOKEN_TYPE_LITERAL_FALSE = 104, + TOKEN_TYPE_KEYW_FINALLY = 105, + TOKEN_TYPE_KEYW_FLOAT = 106, + TOKEN_TYPE_KEYW_FOR = 107, + TOKEN_TYPE_KEYW_FROM = 108, + TOKEN_TYPE_KEYW_FUNCREF = 109, + TOKEN_TYPE_KEYW_FUNCTION = 110, + TOKEN_TYPE_KEYW_GET = 111, + TOKEN_TYPE_KEYW_GLOBAL = 112, + TOKEN_TYPE_KEYW_I8 = 113, + TOKEN_TYPE_KEYW_I16 = 114, + TOKEN_TYPE_KEYW_I31REF = 115, + TOKEN_TYPE_KEYW_I32 = 116, + TOKEN_TYPE_KEYW_I64 = 117, + TOKEN_TYPE_KEYW_IF = 118, + TOKEN_TYPE_KEYW_IMPLEMENTS = 119, + TOKEN_TYPE_KEYW_IMPORT = 120, + TOKEN_TYPE_KEYW_IN = 121, + TOKEN_TYPE_KEYW_INFER = 122, + TOKEN_TYPE_KEYW_INSTANCEOF = 123, + TOKEN_TYPE_KEYW_INT = 124, + TOKEN_TYPE_KEYW_INTERFACE = 125, + TOKEN_TYPE_KEYW_IS = 126, + TOKEN_TYPE_KEYW_ISIZE = 127, + TOKEN_TYPE_KEYW_KEYOF = 128, + TOKEN_TYPE_KEYW_LET = 129, + TOKEN_TYPE_KEYW_LAUNCH = 130, + TOKEN_TYPE_KEYW_LONG = 131, + TOKEN_TYPE_KEYW_META = 132, + TOKEN_TYPE_KEYW_MODULE = 133, + TOKEN_TYPE_KEYW_NAMESPACE = 134, + TOKEN_TYPE_KEYW_NATIVE = 135, + TOKEN_TYPE_KEYW_NEVER = 136, + TOKEN_TYPE_KEYW_NEW = 137, + TOKEN_TYPE_LITERAL_NULL = 138, + TOKEN_TYPE_KEYW_NUMBER = 139, + TOKEN_TYPE_KEYW_OBJECT = 140, + TOKEN_TYPE_KEYW_OF = 141, + TOKEN_TYPE_KEYW_FINAL = 142, + TOKEN_TYPE_KEYW_OUT = 143, + TOKEN_TYPE_KEYW_OVERRIDE = 144, + TOKEN_TYPE_KEYW_PACKAGE = 145, + TOKEN_TYPE_KEYW_INTERNAL = 146, + TOKEN_TYPE_KEYW_PRIVATE = 147, + TOKEN_TYPE_KEYW_PROTECTED = 148, + TOKEN_TYPE_KEYW_PUBLIC = 149, + TOKEN_TYPE_KEYW_READONLY = 150, + TOKEN_TYPE_KEYW_RETHROWS = 151, + TOKEN_TYPE_KEYW_RETURN = 152, + TOKEN_TYPE_KEYW_REQUIRE = 153, + TOKEN_TYPE_KEYW_SET = 154, + TOKEN_TYPE_KEYW_SHORT = 155, + TOKEN_TYPE_KEYW_STATIC = 156, + TOKEN_TYPE_KEYW_STRING = 157, + TOKEN_TYPE_KEYW_STRUCT = 158, + TOKEN_TYPE_KEYW_SUPER = 159, + TOKEN_TYPE_KEYW_SWITCH = 160, + TOKEN_TYPE_KEYW_TARGET = 161, + TOKEN_TYPE_KEYW_THIS = 162, + TOKEN_TYPE_KEYW_THROW = 163, + TOKEN_TYPE_KEYW_THROWS = 164, + TOKEN_TYPE_LITERAL_TRUE = 165, + TOKEN_TYPE_KEYW_TRY = 166, + TOKEN_TYPE_KEYW_TYPE = 167, + TOKEN_TYPE_KEYW_TYPEOF = 168, + TOKEN_TYPE_KEYW_U8 = 169, + TOKEN_TYPE_KEYW_U16 = 170, + TOKEN_TYPE_KEYW_U32 = 171, + TOKEN_TYPE_KEYW_U64 = 172, + TOKEN_TYPE_KEYW_UNDEFINED = 173, + TOKEN_TYPE_KEYW_UNKNOWN = 174, + TOKEN_TYPE_KEYW_USIZE = 175, + TOKEN_TYPE_KEYW_V128 = 176, + TOKEN_TYPE_KEYW_VAR = 177, + TOKEN_TYPE_KEYW_VOID = 178, + TOKEN_TYPE_KEYW_WHILE = 179, + TOKEN_TYPE_KEYW_WITH = 180, + TOKEN_TYPE_KEYW_YIELD = 181, + TOKEN_TYPE_FIRST_PUNCTUATOR = 6, + TOKEN_TYPE_FIRST_KEYW = 68 } export enum Es2pandaAstNodeFlags { AST_NODE_FLAGS_NO_OPTS = 0, diff --git a/koala-wrapper/src/generated/Es2pandaNativeModule.ts b/koala-wrapper/src/generated/Es2pandaNativeModule.ts index 4502c145f..51040c02b 100644 --- a/koala-wrapper/src/generated/Es2pandaNativeModule.ts +++ b/koala-wrapper/src/generated/Es2pandaNativeModule.ts @@ -2143,6 +2143,9 @@ export class Es2pandaNativeModule { _UpdateETSPackageDeclaration(context: KNativePointer, original: KNativePointer, name: KNativePointer): KNativePointer { throw new Error("'UpdateETSPackageDeclaration was not overloaded by native module initialization") } + _CreateETSImportDeclaration(context: KNativePointer, importPath: KNativePointer, specifiers: BigUint64Array, specifiersSequenceLength: KUInt, importKind: KInt): KNativePointer { + throw new Error("'CreateETSImportDeclaration was not overloaded by native module initialization") + } _UpdateETSImportDeclaration(context: KNativePointer, original: KNativePointer, source: KNativePointer, specifiers: BigUint64Array, specifiersSequenceLength: KUInt, importKind: KInt): KNativePointer { throw new Error("'UpdateETSImportDeclaration was not overloaded by native module initialization") } @@ -2308,6 +2311,18 @@ export class Es2pandaNativeModule { _UpdateEmptyStatement(context: KNativePointer, original: KNativePointer): KNativePointer { throw new Error("'UpdateEmptyStatement was not overloaded by native module initialization") } + _CreateETSLaunchExpression(context: KNativePointer, expr: KNativePointer): KNativePointer { + throw new Error("'CreateETSLaunchExpression was not overloaded by native module initialization") + } + _UpdateETSLaunchExpression(context: KNativePointer, original: KNativePointer, expr: KNativePointer): KNativePointer { + throw new Error("'UpdateETSLaunchExpression was not overloaded by native module initialization") + } + _ETSLaunchExpressionIsStaticCallConst(context: KNativePointer, receiver: KNativePointer): KBoolean { + throw new Error("'ETSLaunchExpressionIsStaticCallConst was not overloaded by native module initialization") + } + _ETSLaunchExpressionCallConst(context: KNativePointer, receiver: KNativePointer): KNativePointer { + throw new Error("'ETSLaunchExpressionCallConst was not overloaded by native module initialization") + } _CreateWhileStatement(context: KNativePointer, test: KNativePointer, body: KNativePointer): KNativePointer { throw new Error("'CreateWhileStatement was not overloaded by native module initialization") } @@ -3562,16 +3577,6 @@ export class Es2pandaNativeModule { _CreateForUpdateStatement(context: KNativePointer, init: KNativePointer, test: KNativePointer, update: KNativePointer, body: KNativePointer): KNativePointer { throw new Error("'CreateForUpdateStatement was not overloaded by native module initialization") } - _UpdateForUpdateStatement( - context: KNativePointer, - original: KNativePointer, - init: KNativePointer, - test: KNativePointer, - update: KNativePointer, - body: KNativePointer - ): KNativePointer { - throw new Error("'CreateForUpdateStatement was not overloaded by native module initialization"); - } _ForUpdateStatementInit(context: KNativePointer, receiver: KNativePointer): KNativePointer { throw new Error("'ForUpdateStatementInit was not overloaded by native module initialization") } @@ -3707,16 +3712,4 @@ export class Es2pandaNativeModule { _CreateFunctionDecl(context: KNativePointer, name: KStringPtr, node: KNativePointer): KNativePointer { throw new Error("'CreateFunctionDecl was not overloaded by native module initialization") } - _CreateTryStatement(context: KNativePointer, block: KNativePointer, catchClauses: BigUint64Array, catchClausesSequenceLength: KUInt, finalizer: KNativePointer, finalizerInsertionsLabelPair: BigUint64Array, finalizerInsertionsLabelPairSequenceLength: KUInt, finalizerInsertionsStatement: BigUint64Array, finalizerInsertionsStatementSequenceLength: KUInt): KNativePointer { - throw new Error("'CreateTryStatement was not overloaded by native module initialization") - } - _UpdateTryStatement(context: KNativePointer, original: KNativePointer, block: KNativePointer, catchClauses: BigUint64Array, catchClausesSequenceLength: KUInt, finalizer: KNativePointer, finalizerInsertionsLabelPair: BigUint64Array, finalizerInsertionsLabelPairSequenceLength: KUInt, finalizerInsertionsStatement: BigUint64Array, finalizerInsertionsStatementSequenceLength: KUInt): KNativePointer { - throw new Error("'UpdateTryStatement was not overloaded by native module initialization") - } - _CreateTryStatement1(context: KNativePointer, other: KNativePointer): KNativePointer { - throw new Error("'CreateTryStatement1 was not overloaded by native module initialization") - } - _UpdateTryStatement1(context: KNativePointer, original: KNativePointer, other: KNativePointer): KNativePointer { - throw new Error("'UpdateTryStatement1 was not overloaded by native module initialization") - } -} +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/index.ts b/koala-wrapper/src/generated/index.ts index 0416a0691..4b9ae3fc2 100644 --- a/koala-wrapper/src/generated/index.ts +++ b/koala-wrapper/src/generated/index.ts @@ -106,6 +106,7 @@ export * from "./peers/LoopStatement" export * from "./peers/AnnotationDeclaration" export * from "./peers/AnnotationUsage" export * from "./peers/EmptyStatement" +export * from "./peers/ETSLaunchExpression" export * from "./peers/WhileStatement" export * from "./peers/FunctionSignature" export * from "./peers/ChainExpression" @@ -188,4 +189,4 @@ export * from "./peers/TSThisType" export * from "./peers/ETSDynamicFunctionType" export * from "./peers/InterfaceDecl" export * from "./peers/FunctionDecl" -export * from "./peers/Context" +export * from "./peers/Context" \ No newline at end of file diff --git a/koala-wrapper/src/generated/node-map.ts b/koala-wrapper/src/generated/node-map.ts index d9de6e3b5..c8d894039 100644 --- a/koala-wrapper/src/generated/node-map.ts +++ b/koala-wrapper/src/generated/node-map.ts @@ -27,155 +27,156 @@ import { import * as peers from "./index" export const nodes = new Map([ - [Es2pandaAstNodeType.AST_NODE_TYPE_LABELLED_STATEMENT, peers.LabelledStatement], - [Es2pandaAstNodeType.AST_NODE_TYPE_THROW_STATEMENT, peers.ThrowStatement], - [Es2pandaAstNodeType.AST_NODE_TYPE_CLASS_PROPERTY, peers.ClassProperty], - [Es2pandaAstNodeType.AST_NODE_TYPE_TS_VOID_KEYWORD, peers.TSVoidKeyword], - [Es2pandaAstNodeType.AST_NODE_TYPE_ETS_FUNCTION_TYPE, peers.ETSFunctionType], - [Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_OPERATOR, peers.TSTypeOperator], - [Es2pandaAstNodeType.AST_NODE_TYPE_IF_STATEMENT, peers.IfStatement], - [Es2pandaAstNodeType.AST_NODE_TYPE_TS_CONSTRUCTOR_TYPE, peers.TSConstructorType], - [Es2pandaAstNodeType.AST_NODE_TYPE_DECORATOR, peers.Decorator], - [Es2pandaAstNodeType.AST_NODE_TYPE_TS_ENUM_DECLARATION, peers.TSEnumDeclaration], - [Es2pandaAstNodeType.AST_NODE_TYPE_TS_NEVER_KEYWORD, peers.TSNeverKeyword], - [Es2pandaAstNodeType.AST_NODE_TYPE_IMPORT_DEFAULT_SPECIFIER, peers.ImportDefaultSpecifier], - [Es2pandaAstNodeType.AST_NODE_TYPE_IMPORT_SPECIFIER, peers.ImportSpecifier], - [Es2pandaAstNodeType.AST_NODE_TYPE_CONDITIONAL_EXPRESSION, peers.ConditionalExpression], - [Es2pandaAstNodeType.AST_NODE_TYPE_CALL_EXPRESSION, peers.CallExpression], - [Es2pandaAstNodeType.AST_NODE_TYPE_BIGINT_LITERAL, peers.BigIntLiteral], - [Es2pandaAstNodeType.AST_NODE_TYPE_TS_IMPORT_TYPE, peers.TSImportType], - [Es2pandaAstNodeType.AST_NODE_TYPE_TAGGED_TEMPLATE_EXPRESSION, peers.TaggedTemplateExpression], - [Es2pandaAstNodeType.AST_NODE_TYPE_FUNCTION_DECLARATION, peers.FunctionDeclaration], - [Es2pandaAstNodeType.AST_NODE_TYPE_ETS_TYPE_REFERENCE, peers.ETSTypeReference], - [Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_REFERENCE, peers.TSTypeReference], - [Es2pandaAstNodeType.AST_NODE_TYPE_NAMED_TYPE, peers.NamedType], - [Es2pandaAstNodeType.AST_NODE_TYPE_NUMBER_LITERAL, peers.NumberLiteral], - [Es2pandaAstNodeType.AST_NODE_TYPE_TS_FUNCTION_TYPE, peers.TSFunctionType], - [Es2pandaAstNodeType.AST_NODE_TYPE_TEMPLATE_ELEMENT, peers.TemplateElement], - [Es2pandaAstNodeType.AST_NODE_TYPE_TS_INTERFACE_DECLARATION, peers.TSInterfaceDeclaration], - [Es2pandaAstNodeType.AST_NODE_TYPE_VARIABLE_DECLARATION, peers.VariableDeclaration], - [Es2pandaAstNodeType.AST_NODE_TYPE_UNDEFINED_LITERAL, peers.UndefinedLiteral], - [Es2pandaAstNodeType.AST_NODE_TYPE_MEMBER_EXPRESSION, peers.MemberExpression], - [Es2pandaAstNodeType.AST_NODE_TYPE_TS_CLASS_IMPLEMENTS, peers.TSClassImplements], - [Es2pandaAstNodeType.AST_NODE_TYPE_TS_OBJECT_KEYWORD, peers.TSObjectKeyword], - [Es2pandaAstNodeType.AST_NODE_TYPE_ETS_UNION_TYPE, peers.ETSUnionType], - [Es2pandaAstNodeType.AST_NODE_TYPE_TS_PROPERTY_SIGNATURE, peers.TSPropertySignature], - [Es2pandaAstNodeType.AST_NODE_TYPE_TS_CONDITIONAL_TYPE, peers.TSConditionalType], - [Es2pandaAstNodeType.AST_NODE_TYPE_TS_LITERAL_TYPE, peers.TSLiteralType], - [Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_ALIAS_DECLARATION, peers.TSTypeAliasDeclaration], - [Es2pandaAstNodeType.AST_NODE_TYPE_DEBUGGER_STATEMENT, peers.DebuggerStatement], - [Es2pandaAstNodeType.AST_NODE_TYPE_RETURN_STATEMENT, peers.ReturnStatement], - [Es2pandaAstNodeType.AST_NODE_TYPE_EXPORT_DEFAULT_DECLARATION, peers.ExportDefaultDeclaration], - [Es2pandaAstNodeType.AST_NODE_TYPE_SCRIPT_FUNCTION, peers.ScriptFunction], - [Es2pandaAstNodeType.AST_NODE_TYPE_CLASS_DEFINITION, peers.ClassDefinition], - [Es2pandaAstNodeType.AST_NODE_TYPE_TS_INTERFACE_BODY, peers.TSInterfaceBody], - [Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_QUERY, peers.TSTypeQuery], - [Es2pandaAstNodeType.AST_NODE_TYPE_TS_BIGINT_KEYWORD, peers.TSBigintKeyword], - [Es2pandaAstNodeType.AST_NODE_TYPE_PROPERTY, peers.Property], - [Es2pandaAstNodeType.AST_NODE_TYPE_VARIABLE_DECLARATOR, peers.VariableDeclarator], - [Es2pandaAstNodeType.AST_NODE_TYPE_STRING_LITERAL, peers.StringLiteral], - [Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_ASSERTION, peers.TSTypeAssertion], - [Es2pandaAstNodeType.AST_NODE_TYPE_TS_EXTERNAL_MODULE_REFERENCE, peers.TSExternalModuleReference], - [Es2pandaAstNodeType.AST_NODE_TYPE_TS_UNDEFINED_KEYWORD, peers.TSUndefinedKeyword], - [Es2pandaAstNodeType.AST_NODE_TYPE_ETS_TUPLE, peers.ETSTuple], - [Es2pandaAstNodeType.AST_NODE_TYPE_TRY_STATEMENT, peers.TryStatement], - [Es2pandaAstNodeType.AST_NODE_TYPE_UNARY_EXPRESSION, peers.UnaryExpression], - [Es2pandaAstNodeType.AST_NODE_TYPE_FOR_IN_STATEMENT, peers.ForInStatement], - [Es2pandaAstNodeType.AST_NODE_TYPE_THIS_EXPRESSION, peers.ThisExpression], - [Es2pandaAstNodeType.AST_NODE_TYPE_TS_METHOD_SIGNATURE, peers.TSMethodSignature], - [Es2pandaAstNodeType.AST_NODE_TYPE_BINARY_EXPRESSION, peers.BinaryExpression], - [Es2pandaAstNodeType.AST_NODE_TYPE_SUPER_EXPRESSION, peers.SuperExpression], - [Es2pandaAstNodeType.AST_NODE_TYPE_ASSERT_STATEMENT, peers.AssertStatement], - [Es2pandaAstNodeType.AST_NODE_TYPE_TS_STRING_KEYWORD, peers.TSStringKeyword], - [Es2pandaAstNodeType.AST_NODE_TYPE_EXPRESSION_STATEMENT, peers.ExpressionStatement], - [Es2pandaAstNodeType.AST_NODE_TYPE_ETS_MODULE, peers.ETSModule], - [Es2pandaAstNodeType.AST_NODE_TYPE_META_PROPERTY_EXPRESSION, peers.MetaProperty], - [Es2pandaAstNodeType.AST_NODE_TYPE_TS_ARRAY_TYPE, peers.TSArrayType], - [Es2pandaAstNodeType.AST_NODE_TYPE_TS_SIGNATURE_DECLARATION, peers.TSSignatureDeclaration], - [Es2pandaAstNodeType.AST_NODE_TYPE_EXPORT_ALL_DECLARATION, peers.ExportAllDeclaration], - [Es2pandaAstNodeType.AST_NODE_TYPE_EXPORT_SPECIFIER, peers.ExportSpecifier], - [Es2pandaAstNodeType.AST_NODE_TYPE_TS_TUPLE_TYPE, peers.TSTupleType], - [Es2pandaAstNodeType.AST_NODE_TYPE_FUNCTION_EXPRESSION, peers.FunctionExpression], - [Es2pandaAstNodeType.AST_NODE_TYPE_TS_INDEX_SIGNATURE, peers.TSIndexSignature], - [Es2pandaAstNodeType.AST_NODE_TYPE_TS_MODULE_DECLARATION, peers.TSModuleDeclaration], - [Es2pandaAstNodeType.AST_NODE_TYPE_IMPORT_DECLARATION, peers.ImportDeclaration], - [Es2pandaAstNodeType.AST_NODE_TYPE_TS_PARENT_TYPE, peers.TSParenthesizedType], - [Es2pandaAstNodeType.AST_NODE_TYPE_CHAR_LITERAL, peers.CharLiteral], - [Es2pandaAstNodeType.AST_NODE_TYPE_ETS_PACKAGE_DECLARATION, peers.ETSPackageDeclaration], - [Es2pandaAstNodeType.AST_NODE_TYPE_IMPORT_DECLARATION, peers.ETSImportDeclaration], - [Es2pandaAstNodeType.AST_NODE_TYPE_STRUCT_DECLARATION, peers.ETSStructDeclaration], - [Es2pandaAstNodeType.AST_NODE_TYPE_TS_MODULE_BLOCK, peers.TSModuleBlock], - [Es2pandaAstNodeType.AST_NODE_TYPE_ETS_NEW_ARRAY_INSTANCE_EXPRESSION, peers.ETSNewArrayInstanceExpression], - [Es2pandaAstNodeType.AST_NODE_TYPE_ANNOTATION_DECLARATION, peers.AnnotationDeclaration], - [Es2pandaAstNodeType.AST_NODE_TYPE_ANNOTATION_USAGE, peers.AnnotationUsage], - [Es2pandaAstNodeType.AST_NODE_TYPE_EMPTY_STATEMENT, peers.EmptyStatement], - [Es2pandaAstNodeType.AST_NODE_TYPE_WHILE_STATEMENT, peers.WhileStatement], - [Es2pandaAstNodeType.AST_NODE_TYPE_CHAIN_EXPRESSION, peers.ChainExpression], - [Es2pandaAstNodeType.AST_NODE_TYPE_TS_INTERSECTION_TYPE, peers.TSIntersectionType], - [Es2pandaAstNodeType.AST_NODE_TYPE_UPDATE_EXPRESSION, peers.UpdateExpression], - [Es2pandaAstNodeType.AST_NODE_TYPE_BLOCK_EXPRESSION, peers.BlockExpression], - [Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_LITERAL, peers.TSTypeLiteral], - [Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_PARAMETER, peers.TSTypeParameter], - [Es2pandaAstNodeType.AST_NODE_TYPE_BOOLEAN_LITERAL, peers.TSBooleanKeyword], - [Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_PREDICATE, peers.TSTypePredicate], - [Es2pandaAstNodeType.AST_NODE_TYPE_IMPORT_NAMESPACE_SPECIFIER, peers.ImportNamespaceSpecifier], - [Es2pandaAstNodeType.AST_NODE_TYPE_EXPORT_NAMED_DECLARATION, peers.ExportNamedDeclaration], - [Es2pandaAstNodeType.AST_NODE_TYPE_ETS_PARAMETER_EXPRESSION, peers.ETSParameterExpression], - [Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_PARAMETER_INSTANTIATION, peers.TSTypeParameterInstantiation], - [Es2pandaAstNodeType.AST_NODE_TYPE_NULL_LITERAL, peers.NullLiteral], - [Es2pandaAstNodeType.AST_NODE_TYPE_TS_INFER_TYPE, peers.TSInferType], - [Es2pandaAstNodeType.AST_NODE_TYPE_SWITCH_CASE_STATEMENT, peers.SwitchCaseStatement], - [Es2pandaAstNodeType.AST_NODE_TYPE_YIELD_EXPRESSION, peers.YieldExpression], - [Es2pandaAstNodeType.AST_NODE_TYPE_TS_IMPORT_EQUALS_DECLARATION, peers.TSImportEqualsDeclaration], - [Es2pandaAstNodeType.AST_NODE_TYPE_BOOLEAN_LITERAL, peers.BooleanLiteral], - [Es2pandaAstNodeType.AST_NODE_TYPE_TS_NUMBER_KEYWORD, peers.TSNumberKeyword], - [Es2pandaAstNodeType.AST_NODE_TYPE_CLASS_STATIC_BLOCK, peers.ClassStaticBlock], - [Es2pandaAstNodeType.AST_NODE_TYPE_TS_NON_NULL_EXPRESSION, peers.TSNonNullExpression], - [Es2pandaAstNodeType.AST_NODE_TYPE_PREFIX_ASSERTION_EXPRESSION, peers.PrefixAssertionExpression], - [Es2pandaAstNodeType.AST_NODE_TYPE_CLASS_EXPRESSION, peers.ClassExpression], - [Es2pandaAstNodeType.AST_NODE_TYPE_FOR_OF_STATEMENT, peers.ForOfStatement], - [Es2pandaAstNodeType.AST_NODE_TYPE_TEMPLATE_LITERAL, peers.TemplateLiteral], - [Es2pandaAstNodeType.AST_NODE_TYPE_TS_UNION_TYPE, peers.TSUnionType], - [Es2pandaAstNodeType.AST_NODE_TYPE_TS_UNKNOWN_KEYWORD, peers.TSUnknownKeyword], - [Es2pandaAstNodeType.AST_NODE_TYPE_IDENTIFIER, peers.Identifier], - [Es2pandaAstNodeType.AST_NODE_TYPE_OPAQUE_TYPE_NODE, peers.OpaqueTypeNode], - [Es2pandaAstNodeType.AST_NODE_TYPE_BLOCK_STATEMENT, peers.BlockStatement], - [Es2pandaAstNodeType.AST_NODE_TYPE_DIRECT_EVAL, peers.DirectEvalExpression], - [Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_PARAMETER_DECLARATION, peers.TSTypeParameterDeclaration], - [Es2pandaAstNodeType.AST_NODE_TYPE_METHOD_DEFINITION, peers.MethodDefinition], - [Es2pandaAstNodeType.AST_NODE_TYPE_TS_NULL_KEYWORD, peers.TSNullKeyword], - [Es2pandaAstNodeType.AST_NODE_TYPE_TS_INTERFACE_HERITAGE, peers.TSInterfaceHeritage], - [Es2pandaAstNodeType.AST_NODE_TYPE_ETS_CLASS_LITERAL, peers.ETSClassLiteral], - [Es2pandaAstNodeType.AST_NODE_TYPE_BREAK_STATEMENT, peers.BreakStatement], - [Es2pandaAstNodeType.AST_NODE_TYPE_REGEXP_LITERAL, peers.RegExpLiteral], - [Es2pandaAstNodeType.AST_NODE_TYPE_TS_MAPPED_TYPE, peers.TSMappedType], - [Es2pandaAstNodeType.AST_NODE_TYPE_TS_ANY_KEYWORD, peers.TSAnyKeyword], - [Es2pandaAstNodeType.AST_NODE_TYPE_CLASS_DECLARATION, peers.ClassDeclaration], - [Es2pandaAstNodeType.AST_NODE_TYPE_TS_INDEXED_ACCESS_TYPE, peers.TSIndexedAccessType], - [Es2pandaAstNodeType.AST_NODE_TYPE_TS_QUALIFIED_NAME, peers.TSQualifiedName], - [Es2pandaAstNodeType.AST_NODE_TYPE_AWAIT_EXPRESSION, peers.AwaitExpression], - [Es2pandaAstNodeType.AST_NODE_TYPE_CONTINUE_STATEMENT, peers.ContinueStatement], - [Es2pandaAstNodeType.AST_NODE_TYPE_ETS_NEW_MULTI_DIM_ARRAY_INSTANCE_EXPRESSION, peers.ETSNewMultiDimArrayInstanceExpression], - [Es2pandaAstNodeType.AST_NODE_TYPE_TS_NAMED_TUPLE_MEMBER, peers.TSNamedTupleMember], - [Es2pandaAstNodeType.AST_NODE_TYPE_IMPORT_EXPRESSION, peers.ImportExpression], - [Es2pandaAstNodeType.AST_NODE_TYPE_ETS_NULL_TYPE, peers.ETSNullType], - [Es2pandaAstNodeType.AST_NODE_TYPE_ETS_UNDEFINED_TYPE, peers.ETSUndefinedType], - [Es2pandaAstNodeType.AST_NODE_TYPE_TYPEOF_EXPRESSION, peers.TypeofExpression], - [Es2pandaAstNodeType.AST_NODE_TYPE_TS_ENUM_MEMBER, peers.TSEnumMember], - [Es2pandaAstNodeType.AST_NODE_TYPE_SWITCH_STATEMENT, peers.SwitchStatement], - [Es2pandaAstNodeType.AST_NODE_TYPE_DO_WHILE_STATEMENT, peers.DoWhileStatement], - [Es2pandaAstNodeType.AST_NODE_TYPE_CATCH_CLAUSE, peers.CatchClause], - [Es2pandaAstNodeType.AST_NODE_TYPE_SEQUENCE_EXPRESSION, peers.SequenceExpression], - [Es2pandaAstNodeType.AST_NODE_TYPE_ARROW_FUNCTION_EXPRESSION, peers.ArrowFunctionExpression], - [Es2pandaAstNodeType.AST_NODE_TYPE_OMITTED_EXPRESSION, peers.OmittedExpression], - [Es2pandaAstNodeType.AST_NODE_TYPE_ETS_NEW_CLASS_INSTANCE_EXPRESSION, peers.ETSNewClassInstanceExpression], - [Es2pandaAstNodeType.AST_NODE_TYPE_TS_AS_EXPRESSION, peers.TSAsExpression], - [Es2pandaAstNodeType.AST_NODE_TYPE_FOR_UPDATE_STATEMENT, peers.ForUpdateStatement], - [Es2pandaAstNodeType.AST_NODE_TYPE_ETS_TYPE_REFERENCE_PART, peers.ETSTypeReferencePart], - [Es2pandaAstNodeType.AST_NODE_TYPE_REEXPORT_STATEMENT, peers.ETSReExportDeclaration], - [Es2pandaAstNodeType.AST_NODE_TYPE_ETS_PRIMITIVE_TYPE, peers.ETSPrimitiveType], - [Es2pandaAstNodeType.AST_NODE_TYPE_NEW_EXPRESSION, peers.NewExpression], - [Es2pandaAstNodeType.AST_NODE_TYPE_TS_PARAMETER_PROPERTY, peers.TSParameterProperty], - [Es2pandaAstNodeType.AST_NODE_TYPE_ETS_WILDCARD_TYPE, peers.ETSWildcardType], - [Es2pandaAstNodeType.AST_NODE_TYPE_TS_THIS_TYPE, peers.TSThisType], -]) + [44, peers.LabelledStatement], + [146, peers.ThrowStatement], + [17, peers.ClassProperty], + [94, peers.TSVoidKeyword], + [66, peers.ETSFunctionType], + [117, peers.TSTypeOperator], + [38, peers.IfStatement], + [126, peers.TSConstructorType], + [22, peers.Decorator], + [87, peers.TSEnumDeclaration], + [99, peers.TSNeverKeyword], + [41, peers.ImportDefaultSpecifier], + [43, peers.ImportSpecifier], + [19, peers.ConditionalExpression], + [10, peers.CallExpression], + [5, peers.BigIntLiteral], + [112, peers.TSImportType], + [141, peers.TaggedTemplateExpression], + [34, peers.FunctionDeclaration], + [71, peers.ETSTypeReference], + [128, peers.TSTypeReference], + [48, peers.NamedType], + [52, peers.NumberLiteral], + [125, peers.TSFunctionType], + [142, peers.TemplateElement], + [131, peers.TSInterfaceDeclaration], + [150, peers.VariableDeclaration], + [51, peers.UndefinedLiteral], + [45, peers.MemberExpression], + [139, peers.TSClassImplements], + [97, peers.TSObjectKeyword], + [73, peers.ETSUnionType], + [105, peers.TSPropertySignature], + [111, peers.TSConditionalType], + [109, peers.TSLiteralType], + [127, peers.TSTypeAliasDeclaration], + [21, peers.DebuggerStatement], + [58, peers.ReturnStatement], + [27, peers.ExportDefaultDeclaration], + [59, peers.ScriptFunction], + [14, peers.ClassDefinition], + [132, peers.TSInterfaceBody], + [137, peers.TSTypeQuery], + [98, peers.TSBigintKeyword], + [55, peers.Property], + [151, peers.VariableDeclarator], + [61, peers.StringLiteral], + [140, peers.TSTypeAssertion], + [89, peers.TSExternalModuleReference], + [95, peers.TSUndefinedKeyword], + [81, peers.ETSTuple], + [147, peers.TryStatement], + [148, peers.UnaryExpression], + [31, peers.ForInStatement], + [144, peers.ThisExpression], + [106, peers.TSMethodSignature], + [6, peers.BinaryExpression], + [83, peers.SuperExpression], + [3, peers.AssertStatement], + [92, peers.TSStringKeyword], + [30, peers.ExpressionStatement], + [82, peers.ETSModule], + [46, peers.MetaProperty], + [102, peers.TSArrayType], + [107, peers.TSSignatureDeclaration], + [26, peers.ExportAllDeclaration], + [29, peers.ExportSpecifier], + [134, peers.TSTupleType], + [35, peers.FunctionExpression], + [136, peers.TSIndexSignature], + [123, peers.TSModuleDeclaration], + [39, peers.ImportDeclaration], + [108, peers.TSParenthesizedType], + [13, peers.CharLiteral], + [69, peers.ETSPackageDeclaration], + [79, peers.ETSImportDeclaration], + [84, peers.ETSStructDeclaration], + [115, peers.TSModuleBlock], + [76, peers.ETSNewArrayInstanceExpression], + [1, peers.AnnotationDeclaration], + [2, peers.AnnotationUsage], + [25, peers.EmptyStatement], + [75, peers.ETSLaunchExpression], + [152, peers.WhileStatement], + [12, peers.ChainExpression], + [113, peers.TSIntersectionType], + [149, peers.UpdateExpression], + [155, peers.BlockExpression], + [104, peers.TSTypeLiteral], + [118, peers.TSTypeParameter], + [93, peers.TSBooleanKeyword], + [121, peers.TSTypePredicate], + [42, peers.ImportNamespaceSpecifier], + [28, peers.ExportNamedDeclaration], + [80, peers.ETSParameterExpression], + [120, peers.TSTypeParameterInstantiation], + [50, peers.NullLiteral], + [110, peers.TSInferType], + [85, peers.SwitchCaseStatement], + [153, peers.YieldExpression], + [124, peers.TSImportEqualsDeclaration], + [8, peers.BooleanLiteral], + [90, peers.TSNumberKeyword], + [18, peers.ClassStaticBlock], + [100, peers.TSNonNullExpression], + [54, peers.PrefixAssertionExpression], + [16, peers.ClassExpression], + [32, peers.ForOfStatement], + [143, peers.TemplateLiteral], + [103, peers.TSUnionType], + [96, peers.TSUnknownKeyword], + [36, peers.Identifier], + [154, peers.OpaqueTypeNode], + [7, peers.BlockStatement], + [23, peers.DirectEvalExpression], + [119, peers.TSTypeParameterDeclaration], + [47, peers.MethodDefinition], + [101, peers.TSNullKeyword], + [133, peers.TSInterfaceHeritage], + [70, peers.ETSClassLiteral], + [9, peers.BreakStatement], + [56, peers.RegExpLiteral], + [114, peers.TSMappedType], + [91, peers.TSAnyKeyword], + [15, peers.ClassDeclaration], + [130, peers.TSIndexedAccessType], + [129, peers.TSQualifiedName], + [4, peers.AwaitExpression], + [20, peers.ContinueStatement], + [77, peers.ETSNewMultiDimArrayInstanceExpression], + [135, peers.TSNamedTupleMember], + [40, peers.ImportExpression], + [62, peers.ETSNullType], + [63, peers.ETSUndefinedType], + [145, peers.TypeofExpression], + [88, peers.TSEnumMember], + [86, peers.SwitchStatement], + [24, peers.DoWhileStatement], + [11, peers.CatchClause], + [60, peers.SequenceExpression], + [0, peers.ArrowFunctionExpression], + [53, peers.OmittedExpression], + [78, peers.ETSNewClassInstanceExpression], + [138, peers.TSAsExpression], + [33, peers.ForUpdateStatement], + [72, peers.ETSTypeReferencePart], + [57, peers.ETSReExportDeclaration], + [68, peers.ETSPrimitiveType], + [49, peers.NewExpression], + [122, peers.TSParameterProperty], + [67, peers.ETSWildcardType], + [116, peers.TSThisType], +]) \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/AnnotationUsage.ts b/koala-wrapper/src/generated/peers/AnnotationUsage.ts index e093c4617..1ee1f98b7 100644 --- a/koala-wrapper/src/generated/peers/AnnotationUsage.ts +++ b/koala-wrapper/src/generated/peers/AnnotationUsage.ts @@ -34,7 +34,7 @@ import { Expression } from "./Expression" import { Identifier } from "./Identifier" export class AnnotationUsage extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_ANNOTATION_USAGE) + assertValidPeer(pointer, 2) super(pointer) } @@ -73,6 +73,6 @@ export class AnnotationUsage extends Statement { export function isAnnotationUsage(node: AstNode): node is AnnotationUsage { return node instanceof AnnotationUsage } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_ANNOTATION_USAGE)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_ANNOTATION_USAGE, AnnotationUsage) -} +if (!nodeByType.has(2)) { + nodeByType.set(2, AnnotationUsage) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ArrayExpression.ts b/koala-wrapper/src/generated/peers/ArrayExpression.ts index 717ce5f45..200648cdb 100644 --- a/koala-wrapper/src/generated/peers/ArrayExpression.ts +++ b/koala-wrapper/src/generated/peers/ArrayExpression.ts @@ -26,81 +26,55 @@ import { KNativePointer, nodeByType, ArktsObject, - unpackString, -} from '../../reexport-for-generated'; + unpackString +} from "../../reexport-for-generated" -import { AnnotatedExpression } from './AnnotatedExpression'; -import { Expression } from './Expression'; -import { Decorator } from './Decorator'; -import { ValidationInfo } from './ValidationInfo'; -import { TypeNode } from './TypeNode'; +import { AnnotatedExpression } from "./AnnotatedExpression" +import { Expression } from "./Expression" +import { Decorator } from "./Decorator" +import { ValidationInfo } from "./ValidationInfo" +import { TypeNode } from "./TypeNode" export class ArrayExpression extends AnnotatedExpression { - constructor(pointer: KNativePointer) { - super(pointer); - } - static createArrayExpression(elements: readonly Expression[]): ArrayExpression { - return new ArrayExpression( - global.generatedEs2panda._CreateArrayExpression(global.context, passNodeArray(elements), elements.length) - ); - } - static updateArrayExpression( - original: ArrayExpression | undefined, - elements: readonly Expression[] - ): ArrayExpression { - return new ArrayExpression( - global.generatedEs2panda._UpdateArrayExpression( - global.context, - passNode(original), - passNodeArray(elements), - elements.length - ) - ); + constructor(pointer: KNativePointer) { + super(pointer) + } get elements(): readonly Expression[] { - return unpackNodeArray(global.generatedEs2panda._ArrayExpressionElementsConst(global.context, this.peer)); + return unpackNodeArray(global.generatedEs2panda._ArrayExpressionElementsConst(global.context, this.peer)) } /** @deprecated */ setElements(elements: readonly Expression[]): this { - global.generatedEs2panda._ArrayExpressionSetElements( - global.context, - this.peer, - passNodeArray(elements), - elements.length - ); - return this; + global.generatedEs2panda._ArrayExpressionSetElements(global.context, this.peer, passNodeArray(elements), elements.length) + return this } get isDeclaration(): boolean { - return global.generatedEs2panda._ArrayExpressionIsDeclarationConst(global.context, this.peer); + return global.generatedEs2panda._ArrayExpressionIsDeclarationConst(global.context, this.peer) } get isOptional(): boolean { - return global.generatedEs2panda._ArrayExpressionIsOptionalConst(global.context, this.peer); + return global.generatedEs2panda._ArrayExpressionIsOptionalConst(global.context, this.peer) } /** @deprecated */ setDeclaration(): this { - global.generatedEs2panda._ArrayExpressionSetDeclaration(global.context, this.peer); - return this; + global.generatedEs2panda._ArrayExpressionSetDeclaration(global.context, this.peer) + return this } /** @deprecated */ setOptional(optional_arg: boolean): this { - global.generatedEs2panda._ArrayExpressionSetOptional(global.context, this.peer, optional_arg); - return this; + global.generatedEs2panda._ArrayExpressionSetOptional(global.context, this.peer, optional_arg) + return this } get decorators(): readonly Decorator[] { - return unpackNodeArray(global.generatedEs2panda._ArrayExpressionDecoratorsConst(global.context, this.peer)); + return unpackNodeArray(global.generatedEs2panda._ArrayExpressionDecoratorsConst(global.context, this.peer)) } get typeAnnotation(): TypeNode | undefined { - return unpackNode(global.generatedEs2panda._ArrayExpressionTypeAnnotationConst(global.context, this.peer)); + return unpackNode(global.generatedEs2panda._ArrayExpressionTypeAnnotationConst(global.context, this.peer)) } /** @deprecated */ setTsTypeAnnotation(typeAnnotation: TypeNode): this { - global.generatedEs2panda._ArrayExpressionSetTsTypeAnnotation( - global.context, - this.peer, - passNode(typeAnnotation) - ); - return this; + global.generatedEs2panda._ArrayExpressionSetTsTypeAnnotation(global.context, this.peer, passNode(typeAnnotation)) + return this } } export function isArrayExpression(node: AstNode): node is ArrayExpression { - return global.es2panda._IsArrayExpression(node.peer); -} + return node instanceof ArrayExpression +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ArrowFunctionExpression.ts b/koala-wrapper/src/generated/peers/ArrowFunctionExpression.ts index 75393b037..7c8ca00f5 100644 --- a/koala-wrapper/src/generated/peers/ArrowFunctionExpression.ts +++ b/koala-wrapper/src/generated/peers/ArrowFunctionExpression.ts @@ -35,7 +35,7 @@ import { TypeNode } from "./TypeNode" import { AnnotationUsage } from "./AnnotationUsage" export class ArrowFunctionExpression extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_ARROW_FUNCTION_EXPRESSION) + assertValidPeer(pointer, 0) super(pointer) } @@ -66,6 +66,6 @@ export class ArrowFunctionExpression extends Expression { export function isArrowFunctionExpression(node: AstNode): node is ArrowFunctionExpression { return node instanceof ArrowFunctionExpression } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_ARROW_FUNCTION_EXPRESSION)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_ARROW_FUNCTION_EXPRESSION, ArrowFunctionExpression) -} +if (!nodeByType.has(0)) { + nodeByType.set(0, ArrowFunctionExpression) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/AssertStatement.ts b/koala-wrapper/src/generated/peers/AssertStatement.ts index 07f40d7c1..0d2dcfe05 100644 --- a/koala-wrapper/src/generated/peers/AssertStatement.ts +++ b/koala-wrapper/src/generated/peers/AssertStatement.ts @@ -33,7 +33,7 @@ import { Statement } from "./Statement" import { Expression } from "./Expression" export class AssertStatement extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_ASSERT_STATEMENT) + assertValidPeer(pointer, 3) super(pointer) } @@ -53,6 +53,6 @@ export class AssertStatement extends Statement { export function isAssertStatement(node: AstNode): node is AssertStatement { return node instanceof AssertStatement } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_ASSERT_STATEMENT)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_ASSERT_STATEMENT, AssertStatement) -} +if (!nodeByType.has(3)) { + nodeByType.set(3, AssertStatement) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/AwaitExpression.ts b/koala-wrapper/src/generated/peers/AwaitExpression.ts index b090abc87..1e5520228 100644 --- a/koala-wrapper/src/generated/peers/AwaitExpression.ts +++ b/koala-wrapper/src/generated/peers/AwaitExpression.ts @@ -32,7 +32,7 @@ import { import { Expression } from "./Expression" export class AwaitExpression extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_AWAIT_EXPRESSION) + assertValidPeer(pointer, 4) super(pointer) } @@ -49,6 +49,6 @@ export class AwaitExpression extends Expression { export function isAwaitExpression(node: AstNode): node is AwaitExpression { return node instanceof AwaitExpression } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_AWAIT_EXPRESSION)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_AWAIT_EXPRESSION, AwaitExpression) -} +if (!nodeByType.has(4)) { + nodeByType.set(4, AwaitExpression) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/BigIntLiteral.ts b/koala-wrapper/src/generated/peers/BigIntLiteral.ts index e03909d85..9d390c0c4 100644 --- a/koala-wrapper/src/generated/peers/BigIntLiteral.ts +++ b/koala-wrapper/src/generated/peers/BigIntLiteral.ts @@ -32,7 +32,7 @@ import { import { Literal } from "./Literal" export class BigIntLiteral extends Literal { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_BIGINT_LITERAL) + assertValidPeer(pointer, 5) super(pointer) } @@ -49,6 +49,6 @@ export class BigIntLiteral extends Literal { export function isBigIntLiteral(node: AstNode): node is BigIntLiteral { return node instanceof BigIntLiteral } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_BIGINT_LITERAL)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_BIGINT_LITERAL, BigIntLiteral) -} +if (!nodeByType.has(5)) { + nodeByType.set(5, BigIntLiteral) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/BinaryExpression.ts b/koala-wrapper/src/generated/peers/BinaryExpression.ts index b911d0c58..c524075b1 100644 --- a/koala-wrapper/src/generated/peers/BinaryExpression.ts +++ b/koala-wrapper/src/generated/peers/BinaryExpression.ts @@ -33,7 +33,7 @@ import { Expression } from "./Expression" import { Es2pandaTokenType } from "./../Es2pandaEnums" export class BinaryExpression extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_BINARY_EXPRESSION) + assertValidPeer(pointer, 6) super(pointer) } @@ -91,6 +91,6 @@ export class BinaryExpression extends Expression { export function isBinaryExpression(node: AstNode): node is BinaryExpression { return node instanceof BinaryExpression } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_BINARY_EXPRESSION)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_BINARY_EXPRESSION, BinaryExpression) -} +if (!nodeByType.has(6)) { + nodeByType.set(6, BinaryExpression) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/BlockExpression.ts b/koala-wrapper/src/generated/peers/BlockExpression.ts index 38520bcd3..7e22eef67 100644 --- a/koala-wrapper/src/generated/peers/BlockExpression.ts +++ b/koala-wrapper/src/generated/peers/BlockExpression.ts @@ -33,7 +33,7 @@ import { Expression } from "./Expression" import { Statement } from "./Statement" export class BlockExpression extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_BLOCK_EXPRESSION) + assertValidPeer(pointer, 155) super(pointer) } @@ -60,6 +60,6 @@ export class BlockExpression extends Expression { export function isBlockExpression(node: AstNode): node is BlockExpression { return node instanceof BlockExpression } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_BLOCK_EXPRESSION)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_BLOCK_EXPRESSION, BlockExpression) -} +if (!nodeByType.has(155)) { + nodeByType.set(155, BlockExpression) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/BlockStatement.ts b/koala-wrapper/src/generated/peers/BlockStatement.ts index 09948d77c..8d8ddf9fa 100644 --- a/koala-wrapper/src/generated/peers/BlockStatement.ts +++ b/koala-wrapper/src/generated/peers/BlockStatement.ts @@ -32,7 +32,7 @@ import { import { Statement } from "./Statement" export class BlockStatement extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_BLOCK_STATEMENT) + assertValidPeer(pointer, 7) super(pointer) } @@ -59,6 +59,6 @@ export class BlockStatement extends Statement { export function isBlockStatement(node: AstNode): node is BlockStatement { return node instanceof BlockStatement } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_BLOCK_STATEMENT)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_BLOCK_STATEMENT, BlockStatement) -} +if (!nodeByType.has(7)) { + nodeByType.set(7, BlockStatement) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/BooleanLiteral.ts b/koala-wrapper/src/generated/peers/BooleanLiteral.ts index f82d3a6ed..9995a9f89 100644 --- a/koala-wrapper/src/generated/peers/BooleanLiteral.ts +++ b/koala-wrapper/src/generated/peers/BooleanLiteral.ts @@ -32,7 +32,7 @@ import { import { Literal } from "./Literal" export class BooleanLiteral extends Literal { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_BOOLEAN_LITERAL) + assertValidPeer(pointer, 8) super(pointer) } @@ -49,6 +49,6 @@ export class BooleanLiteral extends Literal { export function isBooleanLiteral(node: AstNode): node is BooleanLiteral { return node instanceof BooleanLiteral } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_BOOLEAN_LITERAL)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_BOOLEAN_LITERAL, BooleanLiteral) -} +if (!nodeByType.has(8)) { + nodeByType.set(8, BooleanLiteral) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/BreakStatement.ts b/koala-wrapper/src/generated/peers/BreakStatement.ts index 77b609b0a..e293ddf59 100644 --- a/koala-wrapper/src/generated/peers/BreakStatement.ts +++ b/koala-wrapper/src/generated/peers/BreakStatement.ts @@ -33,7 +33,7 @@ import { Statement } from "./Statement" import { Identifier } from "./Identifier" export class BreakStatement extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_BLOCK_STATEMENT) + assertValidPeer(pointer, 9) super(pointer) } @@ -64,6 +64,6 @@ export class BreakStatement extends Statement { export function isBreakStatement(node: AstNode): node is BreakStatement { return node instanceof BreakStatement } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_BLOCK_STATEMENT)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_BLOCK_STATEMENT, BreakStatement) -} +if (!nodeByType.has(9)) { + nodeByType.set(9, BreakStatement) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/CallExpression.ts b/koala-wrapper/src/generated/peers/CallExpression.ts index 2a8422665..3a61208f9 100644 --- a/koala-wrapper/src/generated/peers/CallExpression.ts +++ b/koala-wrapper/src/generated/peers/CallExpression.ts @@ -35,7 +35,7 @@ import { TSTypeParameterInstantiation } from "./TSTypeParameterInstantiation" import { BlockStatement } from "./BlockStatement" export class CallExpression extends MaybeOptionalExpression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_CALL_EXPRESSION) + assertValidPeer(pointer, 10) super(pointer) } @@ -93,6 +93,6 @@ export class CallExpression extends MaybeOptionalExpression { export function isCallExpression(node: AstNode): node is CallExpression { return node instanceof CallExpression } -if (!nodeByType.has( Es2pandaAstNodeType.AST_NODE_TYPE_CALL_EXPRESSION)) { - nodeByType.set( Es2pandaAstNodeType.AST_NODE_TYPE_CALL_EXPRESSION, CallExpression) -} +if (!nodeByType.has(10)) { + nodeByType.set(10, CallExpression) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/CatchClause.ts b/koala-wrapper/src/generated/peers/CatchClause.ts index 270650213..068b1dd80 100644 --- a/koala-wrapper/src/generated/peers/CatchClause.ts +++ b/koala-wrapper/src/generated/peers/CatchClause.ts @@ -34,7 +34,7 @@ import { Expression } from "./Expression" import { BlockStatement } from "./BlockStatement" export class CatchClause extends TypedStatement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_CATCH_CLAUSE) + assertValidPeer(pointer, 11) super(pointer) } @@ -54,6 +54,6 @@ export class CatchClause extends TypedStatement { export function isCatchClause(node: AstNode): node is CatchClause { return node instanceof CatchClause } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_CATCH_CLAUSE)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_CATCH_CLAUSE, CatchClause) -} +if (!nodeByType.has(11)) { + nodeByType.set(11, CatchClause) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ChainExpression.ts b/koala-wrapper/src/generated/peers/ChainExpression.ts index 2c89dcd53..ae76f46e0 100644 --- a/koala-wrapper/src/generated/peers/ChainExpression.ts +++ b/koala-wrapper/src/generated/peers/ChainExpression.ts @@ -32,7 +32,7 @@ import { import { Expression } from "./Expression" export class ChainExpression extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_CHAIN_EXPRESSION) + assertValidPeer(pointer, 12) super(pointer) } @@ -49,6 +49,6 @@ export class ChainExpression extends Expression { export function isChainExpression(node: AstNode): node is ChainExpression { return node instanceof ChainExpression } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_CHAIN_EXPRESSION)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_CHAIN_EXPRESSION, ChainExpression) -} +if (!nodeByType.has(12)) { + nodeByType.set(12, ChainExpression) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/CharLiteral.ts b/koala-wrapper/src/generated/peers/CharLiteral.ts index 97c67d44e..7dbceda4c 100644 --- a/koala-wrapper/src/generated/peers/CharLiteral.ts +++ b/koala-wrapper/src/generated/peers/CharLiteral.ts @@ -32,7 +32,7 @@ import { import { Literal } from "./Literal" export class CharLiteral extends Literal { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_CHAR_LITERAL) + assertValidPeer(pointer, 13) super(pointer) } @@ -46,6 +46,6 @@ export class CharLiteral extends Literal { export function isCharLiteral(node: AstNode): node is CharLiteral { return node instanceof CharLiteral } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_CHAR_LITERAL)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_CHAR_LITERAL, CharLiteral) -} +if (!nodeByType.has(13)) { + nodeByType.set(13, CharLiteral) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ClassDeclaration.ts b/koala-wrapper/src/generated/peers/ClassDeclaration.ts index f163c2de3..1af101f1c 100644 --- a/koala-wrapper/src/generated/peers/ClassDeclaration.ts +++ b/koala-wrapper/src/generated/peers/ClassDeclaration.ts @@ -34,7 +34,7 @@ import { ClassDefinition } from "./ClassDefinition" import { Decorator } from "./Decorator" export class ClassDeclaration extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_CLASS_DECLARATION) + assertValidPeer(pointer, 15) super(pointer) } @@ -54,6 +54,6 @@ export class ClassDeclaration extends Statement { export function isClassDeclaration(node: AstNode): node is ClassDeclaration { return node instanceof ClassDeclaration } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_CLASS_DECLARATION)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_CLASS_DECLARATION, ClassDeclaration) -} +if (!nodeByType.has(15)) { + nodeByType.set(15, ClassDeclaration) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ClassDefinition.ts b/koala-wrapper/src/generated/peers/ClassDefinition.ts index fe51f912b..f1187001d 100644 --- a/koala-wrapper/src/generated/peers/ClassDefinition.ts +++ b/koala-wrapper/src/generated/peers/ClassDefinition.ts @@ -44,7 +44,7 @@ import { FunctionExpression } from "./FunctionExpression" import { AnnotationUsage } from "./AnnotationUsage" export class ClassDefinition extends TypedAstNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_CLASS_DEFINITION) + assertValidPeer(pointer, 14) super(pointer) } @@ -217,6 +217,6 @@ export class ClassDefinition extends TypedAstNode { export function isClassDefinition(node: AstNode): node is ClassDefinition { return node instanceof ClassDefinition } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_CLASS_DEFINITION)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_CLASS_DEFINITION, ClassDefinition) -} +if (!nodeByType.has(14)) { + nodeByType.set(14, ClassDefinition) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ClassExpression.ts b/koala-wrapper/src/generated/peers/ClassExpression.ts index e0e0bfef8..9b2f05b2e 100644 --- a/koala-wrapper/src/generated/peers/ClassExpression.ts +++ b/koala-wrapper/src/generated/peers/ClassExpression.ts @@ -33,7 +33,7 @@ import { Expression } from "./Expression" import { ClassDefinition } from "./ClassDefinition" export class ClassExpression extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_CLASS_EXPRESSION) + assertValidPeer(pointer, 16) super(pointer) } @@ -50,6 +50,6 @@ export class ClassExpression extends Expression { export function isClassExpression(node: AstNode): node is ClassExpression { return node instanceof ClassExpression } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_CLASS_EXPRESSION)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_CLASS_EXPRESSION, ClassExpression) -} +if (!nodeByType.has(16)) { + nodeByType.set(16, ClassExpression) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ClassProperty.ts b/koala-wrapper/src/generated/peers/ClassProperty.ts index 04648bd99..cac674bfb 100644 --- a/koala-wrapper/src/generated/peers/ClassProperty.ts +++ b/koala-wrapper/src/generated/peers/ClassProperty.ts @@ -36,7 +36,7 @@ import { Es2pandaModifierFlags } from "./../Es2pandaEnums" import { AnnotationUsage } from "./AnnotationUsage" export class ClassProperty extends ClassElement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_CLASS_PROPERTY) + assertValidPeer(pointer, 17) super(pointer) } @@ -66,6 +66,6 @@ export class ClassProperty extends ClassElement { export function isClassProperty(node: AstNode): node is ClassProperty { return node instanceof ClassProperty } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_CLASS_PROPERTY)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_CLASS_PROPERTY, ClassProperty) -} +if (!nodeByType.has(17)) { + nodeByType.set(17, ClassProperty) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ClassStaticBlock.ts b/koala-wrapper/src/generated/peers/ClassStaticBlock.ts index 5b2bef593..92ff36429 100644 --- a/koala-wrapper/src/generated/peers/ClassStaticBlock.ts +++ b/koala-wrapper/src/generated/peers/ClassStaticBlock.ts @@ -34,7 +34,7 @@ import { Expression } from "./Expression" import { ScriptFunction } from "./ScriptFunction" export class ClassStaticBlock extends ClassElement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_CLASS_STATIC_BLOCK) + assertValidPeer(pointer, 18) super(pointer) } @@ -48,6 +48,6 @@ export class ClassStaticBlock extends ClassElement { export function isClassStaticBlock(node: AstNode): node is ClassStaticBlock { return node instanceof ClassStaticBlock } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_CLASS_STATIC_BLOCK)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_CLASS_STATIC_BLOCK, ClassStaticBlock) -} +if (!nodeByType.has(18)) { + nodeByType.set(18, ClassStaticBlock) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ConditionalExpression.ts b/koala-wrapper/src/generated/peers/ConditionalExpression.ts index 998aa934d..20ab3b028 100644 --- a/koala-wrapper/src/generated/peers/ConditionalExpression.ts +++ b/koala-wrapper/src/generated/peers/ConditionalExpression.ts @@ -32,7 +32,7 @@ import { import { Expression } from "./Expression" export class ConditionalExpression extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_CONDITIONAL_EXPRESSION) + assertValidPeer(pointer, 19) super(pointer) } @@ -70,6 +70,6 @@ export class ConditionalExpression extends Expression { export function isConditionalExpression(node: AstNode): node is ConditionalExpression { return node instanceof ConditionalExpression } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_CONDITIONAL_EXPRESSION)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_CONDITIONAL_EXPRESSION, ConditionalExpression) -} +if (!nodeByType.has(19)) { + nodeByType.set(19, ConditionalExpression) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ContinueStatement.ts b/koala-wrapper/src/generated/peers/ContinueStatement.ts index 52cd73c0d..6d9f8a42e 100644 --- a/koala-wrapper/src/generated/peers/ContinueStatement.ts +++ b/koala-wrapper/src/generated/peers/ContinueStatement.ts @@ -33,7 +33,7 @@ import { Statement } from "./Statement" import { Identifier } from "./Identifier" export class ContinueStatement extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_CONTINUE_STATEMENT) + assertValidPeer(pointer, 20) super(pointer) } @@ -64,6 +64,6 @@ export class ContinueStatement extends Statement { export function isContinueStatement(node: AstNode): node is ContinueStatement { return node instanceof ContinueStatement } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_CONTINUE_STATEMENT)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_CONTINUE_STATEMENT, ContinueStatement) -} +if (!nodeByType.has(20)) { + nodeByType.set(20, ContinueStatement) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/DebuggerStatement.ts b/koala-wrapper/src/generated/peers/DebuggerStatement.ts index 7bebfba19..e74c35108 100644 --- a/koala-wrapper/src/generated/peers/DebuggerStatement.ts +++ b/koala-wrapper/src/generated/peers/DebuggerStatement.ts @@ -32,7 +32,7 @@ import { import { Statement } from "./Statement" export class DebuggerStatement extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_DEBUGGER_STATEMENT) + assertValidPeer(pointer, 21) super(pointer) } @@ -46,6 +46,6 @@ export class DebuggerStatement extends Statement { export function isDebuggerStatement(node: AstNode): node is DebuggerStatement { return node instanceof DebuggerStatement } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_DEBUGGER_STATEMENT)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_DEBUGGER_STATEMENT, DebuggerStatement) -} +if (!nodeByType.has(21)) { + nodeByType.set(21, DebuggerStatement) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/Decorator.ts b/koala-wrapper/src/generated/peers/Decorator.ts index 4f3366551..de635c11e 100644 --- a/koala-wrapper/src/generated/peers/Decorator.ts +++ b/koala-wrapper/src/generated/peers/Decorator.ts @@ -33,7 +33,7 @@ import { Statement } from "./Statement" import { Expression } from "./Expression" export class Decorator extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_DECORATOR) + assertValidPeer(pointer, 22) super(pointer) } @@ -50,6 +50,6 @@ export class Decorator extends Statement { export function isDecorator(node: AstNode): node is Decorator { return node instanceof Decorator } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_DECORATOR)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_DECORATOR, Decorator) -} +if (!nodeByType.has(22)) { + nodeByType.set(22, Decorator) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/DirectEvalExpression.ts b/koala-wrapper/src/generated/peers/DirectEvalExpression.ts index 0accb0b24..d432f9f0d 100644 --- a/koala-wrapper/src/generated/peers/DirectEvalExpression.ts +++ b/koala-wrapper/src/generated/peers/DirectEvalExpression.ts @@ -34,7 +34,7 @@ import { Expression } from "./Expression" import { TSTypeParameterInstantiation } from "./TSTypeParameterInstantiation" export class DirectEvalExpression extends CallExpression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_DIRECT_EVAL) + assertValidPeer(pointer, 23) super(pointer) } @@ -48,6 +48,6 @@ export class DirectEvalExpression extends CallExpression { export function isDirectEvalExpression(node: AstNode): node is DirectEvalExpression { return node instanceof DirectEvalExpression } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_DIRECT_EVAL)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_DIRECT_EVAL, DirectEvalExpression) -} +if (!nodeByType.has(23)) { + nodeByType.set(23, DirectEvalExpression) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/DoWhileStatement.ts b/koala-wrapper/src/generated/peers/DoWhileStatement.ts index 569c03d1f..c6ce8c8cd 100644 --- a/koala-wrapper/src/generated/peers/DoWhileStatement.ts +++ b/koala-wrapper/src/generated/peers/DoWhileStatement.ts @@ -34,7 +34,7 @@ import { Statement } from "./Statement" import { Expression } from "./Expression" export class DoWhileStatement extends LoopStatement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_DO_WHILE_STATEMENT) + assertValidPeer(pointer, 24) super(pointer) } @@ -54,6 +54,6 @@ export class DoWhileStatement extends LoopStatement { export function isDoWhileStatement(node: AstNode): node is DoWhileStatement { return node instanceof DoWhileStatement } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_DO_WHILE_STATEMENT)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_DO_WHILE_STATEMENT, DoWhileStatement) -} +if (!nodeByType.has(24)) { + nodeByType.set(24, DoWhileStatement) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ETSClassLiteral.ts b/koala-wrapper/src/generated/peers/ETSClassLiteral.ts index 80d2e86a7..d78af3b90 100644 --- a/koala-wrapper/src/generated/peers/ETSClassLiteral.ts +++ b/koala-wrapper/src/generated/peers/ETSClassLiteral.ts @@ -33,7 +33,7 @@ import { Expression } from "./Expression" import { TypeNode } from "./TypeNode" export class ETSClassLiteral extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_ETS_CLASS_LITERAL) + assertValidPeer(pointer, 70) super(pointer) } @@ -50,6 +50,6 @@ export class ETSClassLiteral extends Expression { export function isETSClassLiteral(node: AstNode): node is ETSClassLiteral { return node instanceof ETSClassLiteral } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_CLASS_LITERAL)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_CLASS_LITERAL, ETSClassLiteral) -} +if (!nodeByType.has(70)) { + nodeByType.set(70, ETSClassLiteral) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ETSFunctionType.ts b/koala-wrapper/src/generated/peers/ETSFunctionType.ts index 5a630295c..5354546f8 100644 --- a/koala-wrapper/src/generated/peers/ETSFunctionType.ts +++ b/koala-wrapper/src/generated/peers/ETSFunctionType.ts @@ -37,7 +37,7 @@ import { Expression } from "./Expression" import { TSInterfaceDeclaration } from "./TSInterfaceDeclaration" export class ETSFunctionType extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_ETS_FUNCTION_TYPE) + assertValidPeer(pointer, 66) super(pointer) } @@ -80,6 +80,6 @@ export class ETSFunctionType extends TypeNode { export function isETSFunctionType(node: AstNode): node is ETSFunctionType { return node instanceof ETSFunctionType } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_FUNCTION_TYPE)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_FUNCTION_TYPE, ETSFunctionType) -} +if (!nodeByType.has(66)) { + nodeByType.set(66, ETSFunctionType) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ETSImportDeclaration.ts b/koala-wrapper/src/generated/peers/ETSImportDeclaration.ts index 919394d2a..9261c82c6 100644 --- a/koala-wrapper/src/generated/peers/ETSImportDeclaration.ts +++ b/koala-wrapper/src/generated/peers/ETSImportDeclaration.ts @@ -33,15 +33,14 @@ import { ImportDeclaration } from "./ImportDeclaration" import { ImportSource } from "./ImportSource" import { Es2pandaImportKinds } from "./../Es2pandaEnums" import { StringLiteral } from "./StringLiteral" -import { Es2pandaImportFlags } from "./../../Es2pandaEnums" export class ETSImportDeclaration extends ImportDeclaration { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_ETS_IMPORT_DECLARATION) + assertValidPeer(pointer, 79) super(pointer) } - static createETSImportDeclaration(source: StringLiteral | undefined, specifiers: readonly AstNode[], importKind: Es2pandaImportKinds, program: ArktsObject, flags: Es2pandaImportFlags): ETSImportDeclaration { - return new ETSImportDeclaration(global.es2panda._CreateETSImportDeclaration(global.context, passNode(source), passNodeArray(specifiers), specifiers.length, importKind, passNode(program), flags)) + static createETSImportDeclaration(source: StringLiteral | undefined, specifiers: readonly AstNode[], importKind: Es2pandaImportKinds): ETSImportDeclaration { + return new ETSImportDeclaration(global.generatedEs2panda._CreateETSImportDeclaration(global.context, passNode(source), passNodeArray(specifiers), specifiers.length, importKind)) } static updateETSImportDeclaration(original: ETSImportDeclaration | undefined, source: StringLiteral | undefined, specifiers: readonly AstNode[], importKind: Es2pandaImportKinds): ETSImportDeclaration { return new ETSImportDeclaration(global.generatedEs2panda._UpdateETSImportDeclaration(global.context, passNode(original), passNode(source), passNodeArray(specifiers), specifiers.length, importKind)) @@ -65,6 +64,6 @@ export class ETSImportDeclaration extends ImportDeclaration { export function isETSImportDeclaration(node: AstNode): node is ETSImportDeclaration { return node instanceof ETSImportDeclaration } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_IMPORT_DECLARATION)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_IMPORT_DECLARATION, ETSImportDeclaration) -} +if (!nodeByType.has(79)) { + nodeByType.set(79, ETSImportDeclaration) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ETSModule.ts b/koala-wrapper/src/generated/peers/ETSModule.ts index 396edaac7..df693d3b1 100644 --- a/koala-wrapper/src/generated/peers/ETSModule.ts +++ b/koala-wrapper/src/generated/peers/ETSModule.ts @@ -34,7 +34,7 @@ import { Identifier } from "./Identifier" import { AnnotationUsage } from "./AnnotationUsage" export class ETSModule extends BlockStatement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_ETS_MODULE) + assertValidPeer(pointer, 82) super(pointer) } @@ -67,6 +67,6 @@ export class ETSModule extends BlockStatement { export function isETSModule(node: AstNode): node is ETSModule { return node instanceof ETSModule } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_MODULE)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_MODULE, ETSModule) -} +if (!nodeByType.has(82)) { + nodeByType.set(82, ETSModule) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ETSNewArrayInstanceExpression.ts b/koala-wrapper/src/generated/peers/ETSNewArrayInstanceExpression.ts index 63d66f230..05135647e 100644 --- a/koala-wrapper/src/generated/peers/ETSNewArrayInstanceExpression.ts +++ b/koala-wrapper/src/generated/peers/ETSNewArrayInstanceExpression.ts @@ -33,7 +33,7 @@ import { Expression } from "./Expression" import { TypeNode } from "./TypeNode" export class ETSNewArrayInstanceExpression extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_ETS_NEW_ARRAY_INSTANCE_EXPRESSION) + assertValidPeer(pointer, 76) super(pointer) } @@ -58,6 +58,6 @@ export class ETSNewArrayInstanceExpression extends Expression { export function isETSNewArrayInstanceExpression(node: AstNode): node is ETSNewArrayInstanceExpression { return node instanceof ETSNewArrayInstanceExpression } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_NEW_ARRAY_INSTANCE_EXPRESSION)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_NEW_ARRAY_INSTANCE_EXPRESSION, ETSNewArrayInstanceExpression) -} +if (!nodeByType.has(76)) { + nodeByType.set(76, ETSNewArrayInstanceExpression) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ETSNewClassInstanceExpression.ts b/koala-wrapper/src/generated/peers/ETSNewClassInstanceExpression.ts index a79deafb3..7e0bb389b 100644 --- a/koala-wrapper/src/generated/peers/ETSNewClassInstanceExpression.ts +++ b/koala-wrapper/src/generated/peers/ETSNewClassInstanceExpression.ts @@ -32,7 +32,7 @@ import { import { Expression } from "./Expression" export class ETSNewClassInstanceExpression extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_ETS_NEW_CLASS_INSTANCE_EXPRESSION) + assertValidPeer(pointer, 78) super(pointer) } @@ -68,6 +68,6 @@ export class ETSNewClassInstanceExpression extends Expression { export function isETSNewClassInstanceExpression(node: AstNode): node is ETSNewClassInstanceExpression { return node instanceof ETSNewClassInstanceExpression } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_NEW_CLASS_INSTANCE_EXPRESSION)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_NEW_CLASS_INSTANCE_EXPRESSION, ETSNewClassInstanceExpression) -} +if (!nodeByType.has(78)) { + nodeByType.set(78, ETSNewClassInstanceExpression) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ETSNewMultiDimArrayInstanceExpression.ts b/koala-wrapper/src/generated/peers/ETSNewMultiDimArrayInstanceExpression.ts index 5b599dce6..e99e3ed42 100644 --- a/koala-wrapper/src/generated/peers/ETSNewMultiDimArrayInstanceExpression.ts +++ b/koala-wrapper/src/generated/peers/ETSNewMultiDimArrayInstanceExpression.ts @@ -33,7 +33,7 @@ import { Expression } from "./Expression" import { TypeNode } from "./TypeNode" export class ETSNewMultiDimArrayInstanceExpression extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_ETS_NEW_MULTI_DIM_ARRAY_INSTANCE_EXPRESSION) + assertValidPeer(pointer, 77) super(pointer) } @@ -59,6 +59,6 @@ export class ETSNewMultiDimArrayInstanceExpression extends Expression { export function isETSNewMultiDimArrayInstanceExpression(node: AstNode): node is ETSNewMultiDimArrayInstanceExpression { return node instanceof ETSNewMultiDimArrayInstanceExpression } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_NEW_MULTI_DIM_ARRAY_INSTANCE_EXPRESSION)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_NEW_MULTI_DIM_ARRAY_INSTANCE_EXPRESSION, ETSNewMultiDimArrayInstanceExpression) -} +if (!nodeByType.has(77)) { + nodeByType.set(77, ETSNewMultiDimArrayInstanceExpression) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ETSNullType.ts b/koala-wrapper/src/generated/peers/ETSNullType.ts index 6619bf72a..edf561cf1 100644 --- a/koala-wrapper/src/generated/peers/ETSNullType.ts +++ b/koala-wrapper/src/generated/peers/ETSNullType.ts @@ -32,7 +32,7 @@ import { import { TypeNode } from "./TypeNode" export class ETSNullType extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_ETS_NULL_TYPE) + assertValidPeer(pointer, 62) super(pointer) } @@ -46,6 +46,6 @@ export class ETSNullType extends TypeNode { export function isETSNullType(node: AstNode): node is ETSNullType { return node instanceof ETSNullType } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_NULL_TYPE)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_NULL_TYPE, ETSNullType) -} +if (!nodeByType.has(62)) { + nodeByType.set(62, ETSNullType) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ETSPackageDeclaration.ts b/koala-wrapper/src/generated/peers/ETSPackageDeclaration.ts index dce8c6261..1148df88e 100644 --- a/koala-wrapper/src/generated/peers/ETSPackageDeclaration.ts +++ b/koala-wrapper/src/generated/peers/ETSPackageDeclaration.ts @@ -33,7 +33,7 @@ import { Statement } from "./Statement" import { Expression } from "./Expression" export class ETSPackageDeclaration extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_ETS_PACKAGE_DECLARATION) + assertValidPeer(pointer, 69) super(pointer) } @@ -47,6 +47,6 @@ export class ETSPackageDeclaration extends Statement { export function isETSPackageDeclaration(node: AstNode): node is ETSPackageDeclaration { return node instanceof ETSPackageDeclaration } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_PACKAGE_DECLARATION)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_PACKAGE_DECLARATION, ETSPackageDeclaration) -} +if (!nodeByType.has(69)) { + nodeByType.set(69, ETSPackageDeclaration) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ETSParameterExpression.ts b/koala-wrapper/src/generated/peers/ETSParameterExpression.ts index 7a16dc8e1..3b8c76a41 100644 --- a/koala-wrapper/src/generated/peers/ETSParameterExpression.ts +++ b/koala-wrapper/src/generated/peers/ETSParameterExpression.ts @@ -37,7 +37,7 @@ import { TypeNode } from "./TypeNode" import { AnnotationUsage } from "./AnnotationUsage" export class ETSParameterExpression extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_ETS_PARAMETER_EXPRESSION) + assertValidPeer(pointer, 80) super(pointer) } @@ -104,6 +104,6 @@ export class ETSParameterExpression extends Expression { export function isETSParameterExpression(node: AstNode): node is ETSParameterExpression { return node instanceof ETSParameterExpression } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_PARAMETER_EXPRESSION)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_PARAMETER_EXPRESSION, ETSParameterExpression) -} +if (!nodeByType.has(80)) { + nodeByType.set(80, ETSParameterExpression) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ETSPrimitiveType.ts b/koala-wrapper/src/generated/peers/ETSPrimitiveType.ts index 6d433dff4..82713f44b 100644 --- a/koala-wrapper/src/generated/peers/ETSPrimitiveType.ts +++ b/koala-wrapper/src/generated/peers/ETSPrimitiveType.ts @@ -33,7 +33,7 @@ import { TypeNode } from "./TypeNode" import { Es2pandaPrimitiveType } from "./../Es2pandaEnums" export class ETSPrimitiveType extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_ETS_PRIMITIVE_TYPE) + assertValidPeer(pointer, 68) super(pointer) } @@ -50,6 +50,6 @@ export class ETSPrimitiveType extends TypeNode { export function isETSPrimitiveType(node: AstNode): node is ETSPrimitiveType { return node instanceof ETSPrimitiveType } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_PRIMITIVE_TYPE)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_PRIMITIVE_TYPE, ETSPrimitiveType) -} +if (!nodeByType.has(68)) { + nodeByType.set(68, ETSPrimitiveType) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ETSReExportDeclaration.ts b/koala-wrapper/src/generated/peers/ETSReExportDeclaration.ts index 669a54af1..6e33931db 100644 --- a/koala-wrapper/src/generated/peers/ETSReExportDeclaration.ts +++ b/koala-wrapper/src/generated/peers/ETSReExportDeclaration.ts @@ -33,7 +33,7 @@ import { Statement } from "./Statement" import { ETSImportDeclaration } from "./ETSImportDeclaration" export class ETSReExportDeclaration extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_REEXPORT_STATEMENT) + assertValidPeer(pointer, 57) super(pointer) } @@ -47,6 +47,6 @@ export class ETSReExportDeclaration extends Statement { export function isETSReExportDeclaration(node: AstNode): node is ETSReExportDeclaration { return node instanceof ETSReExportDeclaration } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_REEXPORT_STATEMENT)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_REEXPORT_STATEMENT, ETSReExportDeclaration) -} +if (!nodeByType.has(57)) { + nodeByType.set(57, ETSReExportDeclaration) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ETSStructDeclaration.ts b/koala-wrapper/src/generated/peers/ETSStructDeclaration.ts index dfa10cf4c..9a060fdce 100644 --- a/koala-wrapper/src/generated/peers/ETSStructDeclaration.ts +++ b/koala-wrapper/src/generated/peers/ETSStructDeclaration.ts @@ -33,7 +33,7 @@ import { ClassDeclaration } from "./ClassDeclaration" import { ClassDefinition } from "./ClassDefinition" export class ETSStructDeclaration extends ClassDeclaration { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_STRUCT_DECLARATION) + assertValidPeer(pointer, 84) super(pointer) } @@ -47,6 +47,6 @@ export class ETSStructDeclaration extends ClassDeclaration { export function isETSStructDeclaration(node: AstNode): node is ETSStructDeclaration { return node instanceof ETSStructDeclaration } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_STRUCT_DECLARATION)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_STRUCT_DECLARATION, ETSStructDeclaration) -} +if (!nodeByType.has(84)) { + nodeByType.set(84, ETSStructDeclaration) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ETSTuple.ts b/koala-wrapper/src/generated/peers/ETSTuple.ts index 8eee89765..158eee3f8 100644 --- a/koala-wrapper/src/generated/peers/ETSTuple.ts +++ b/koala-wrapper/src/generated/peers/ETSTuple.ts @@ -32,7 +32,7 @@ import { import { TypeNode } from "./TypeNode" export class ETSTuple extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_ETS_TUPLE) + assertValidPeer(pointer, 81) super(pointer) } @@ -77,6 +77,6 @@ export class ETSTuple extends TypeNode { export function isETSTuple(node: AstNode): node is ETSTuple { return node instanceof ETSTuple } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_TUPLE)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_TUPLE, ETSTuple) -} +if (!nodeByType.has(81)) { + nodeByType.set(81, ETSTuple) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ETSTypeReference.ts b/koala-wrapper/src/generated/peers/ETSTypeReference.ts index 1089a11ab..f18f4c8b3 100644 --- a/koala-wrapper/src/generated/peers/ETSTypeReference.ts +++ b/koala-wrapper/src/generated/peers/ETSTypeReference.ts @@ -34,7 +34,7 @@ import { ETSTypeReferencePart } from "./ETSTypeReferencePart" import { Identifier } from "./Identifier" export class ETSTypeReference extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_ETS_TYPE_REFERENCE) + assertValidPeer(pointer, 71) super(pointer) } @@ -51,6 +51,6 @@ export class ETSTypeReference extends TypeNode { export function isETSTypeReference(node: AstNode): node is ETSTypeReference { return node instanceof ETSTypeReference } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_TYPE_REFERENCE)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_TYPE_REFERENCE, ETSTypeReference) -} +if (!nodeByType.has(71)) { + nodeByType.set(71, ETSTypeReference) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ETSTypeReferencePart.ts b/koala-wrapper/src/generated/peers/ETSTypeReferencePart.ts index 1a7f1968f..804642d30 100644 --- a/koala-wrapper/src/generated/peers/ETSTypeReferencePart.ts +++ b/koala-wrapper/src/generated/peers/ETSTypeReferencePart.ts @@ -34,7 +34,7 @@ import { Expression } from "./Expression" import { TSTypeParameterInstantiation } from "./TSTypeParameterInstantiation" export class ETSTypeReferencePart extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_ETS_TYPE_REFERENCE_PART) + assertValidPeer(pointer, 72) super(pointer) } @@ -63,6 +63,6 @@ export class ETSTypeReferencePart extends TypeNode { export function isETSTypeReferencePart(node: AstNode): node is ETSTypeReferencePart { return node instanceof ETSTypeReferencePart } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_TYPE_REFERENCE_PART)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_TYPE_REFERENCE_PART, ETSTypeReferencePart) -} +if (!nodeByType.has(72)) { + nodeByType.set(72, ETSTypeReferencePart) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ETSUndefinedType.ts b/koala-wrapper/src/generated/peers/ETSUndefinedType.ts index c42dcf76b..6f44b6a87 100644 --- a/koala-wrapper/src/generated/peers/ETSUndefinedType.ts +++ b/koala-wrapper/src/generated/peers/ETSUndefinedType.ts @@ -32,7 +32,7 @@ import { import { TypeNode } from "./TypeNode" export class ETSUndefinedType extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_ETS_UNDEFINED_TYPE) + assertValidPeer(pointer, 63) super(pointer) } @@ -46,6 +46,6 @@ export class ETSUndefinedType extends TypeNode { export function isETSUndefinedType(node: AstNode): node is ETSUndefinedType { return node instanceof ETSUndefinedType } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_UNDEFINED_TYPE)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_UNDEFINED_TYPE, ETSUndefinedType) -} +if (!nodeByType.has(63)) { + nodeByType.set(63, ETSUndefinedType) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ETSUnionType.ts b/koala-wrapper/src/generated/peers/ETSUnionType.ts index 59b73ebe7..18ea1f142 100644 --- a/koala-wrapper/src/generated/peers/ETSUnionType.ts +++ b/koala-wrapper/src/generated/peers/ETSUnionType.ts @@ -32,7 +32,7 @@ import { import { TypeNode } from "./TypeNode" export class ETSUnionType extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_ETS_UNION_TYPE) + assertValidPeer(pointer, 73) super(pointer) } @@ -49,6 +49,6 @@ export class ETSUnionType extends TypeNode { export function isETSUnionType(node: AstNode): node is ETSUnionType { return node instanceof ETSUnionType } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_UNION_TYPE)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_UNION_TYPE, ETSUnionType) -} +if (!nodeByType.has(73)) { + nodeByType.set(73, ETSUnionType) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ETSWildcardType.ts b/koala-wrapper/src/generated/peers/ETSWildcardType.ts index c34909ca7..7dd790f55 100644 --- a/koala-wrapper/src/generated/peers/ETSWildcardType.ts +++ b/koala-wrapper/src/generated/peers/ETSWildcardType.ts @@ -34,7 +34,7 @@ import { ETSTypeReference } from "./ETSTypeReference" import { Es2pandaModifierFlags } from "./../Es2pandaEnums" export class ETSWildcardType extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_ETS_WILDCARD_TYPE) + assertValidPeer(pointer, 67) super(pointer) } @@ -51,6 +51,6 @@ export class ETSWildcardType extends TypeNode { export function isETSWildcardType(node: AstNode): node is ETSWildcardType { return node instanceof ETSWildcardType } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_WILDCARD_TYPE)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_ETS_WILDCARD_TYPE, ETSWildcardType) -} +if (!nodeByType.has(67)) { + nodeByType.set(67, ETSWildcardType) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/EmptyStatement.ts b/koala-wrapper/src/generated/peers/EmptyStatement.ts index b0b5e74f6..9e3e61706 100644 --- a/koala-wrapper/src/generated/peers/EmptyStatement.ts +++ b/koala-wrapper/src/generated/peers/EmptyStatement.ts @@ -32,7 +32,7 @@ import { import { Statement } from "./Statement" export class EmptyStatement extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_EMPTY_STATEMENT) + assertValidPeer(pointer, 25) super(pointer) } @@ -46,6 +46,6 @@ export class EmptyStatement extends Statement { export function isEmptyStatement(node: AstNode): node is EmptyStatement { return node instanceof EmptyStatement } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_EMPTY_STATEMENT)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_EMPTY_STATEMENT, EmptyStatement) -} +if (!nodeByType.has(25)) { + nodeByType.set(25, EmptyStatement) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ExportAllDeclaration.ts b/koala-wrapper/src/generated/peers/ExportAllDeclaration.ts index b95b42687..631cdc354 100644 --- a/koala-wrapper/src/generated/peers/ExportAllDeclaration.ts +++ b/koala-wrapper/src/generated/peers/ExportAllDeclaration.ts @@ -34,7 +34,7 @@ import { StringLiteral } from "./StringLiteral" import { Identifier } from "./Identifier" export class ExportAllDeclaration extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_EXPORT_ALL_DECLARATION) + assertValidPeer(pointer, 26) super(pointer) } @@ -54,6 +54,6 @@ export class ExportAllDeclaration extends Statement { export function isExportAllDeclaration(node: AstNode): node is ExportAllDeclaration { return node instanceof ExportAllDeclaration } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_EXPORT_ALL_DECLARATION)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_EXPORT_ALL_DECLARATION, ExportAllDeclaration) -} +if (!nodeByType.has(26)) { + nodeByType.set(26, ExportAllDeclaration) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ExportDefaultDeclaration.ts b/koala-wrapper/src/generated/peers/ExportDefaultDeclaration.ts index 0a1600886..d4f07bb62 100644 --- a/koala-wrapper/src/generated/peers/ExportDefaultDeclaration.ts +++ b/koala-wrapper/src/generated/peers/ExportDefaultDeclaration.ts @@ -32,7 +32,7 @@ import { import { Statement } from "./Statement" export class ExportDefaultDeclaration extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_EXPORT_DEFAULT_DECLARATION) + assertValidPeer(pointer, 27) super(pointer) } @@ -52,6 +52,6 @@ export class ExportDefaultDeclaration extends Statement { export function isExportDefaultDeclaration(node: AstNode): node is ExportDefaultDeclaration { return node instanceof ExportDefaultDeclaration } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_EXPORT_DEFAULT_DECLARATION)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_EXPORT_DEFAULT_DECLARATION, ExportDefaultDeclaration) -} +if (!nodeByType.has(27)) { + nodeByType.set(27, ExportDefaultDeclaration) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ExportNamedDeclaration.ts b/koala-wrapper/src/generated/peers/ExportNamedDeclaration.ts index 8fe0ed593..d7f82f76a 100644 --- a/koala-wrapper/src/generated/peers/ExportNamedDeclaration.ts +++ b/koala-wrapper/src/generated/peers/ExportNamedDeclaration.ts @@ -34,7 +34,7 @@ import { StringLiteral } from "./StringLiteral" import { ExportSpecifier } from "./ExportSpecifier" export class ExportNamedDeclaration extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_EXPORT_NAMED_DECLARATION) + assertValidPeer(pointer, 28) super(pointer) } @@ -69,6 +69,6 @@ export class ExportNamedDeclaration extends Statement { export function isExportNamedDeclaration(node: AstNode): node is ExportNamedDeclaration { return node instanceof ExportNamedDeclaration } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_EXPORT_NAMED_DECLARATION)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_EXPORT_NAMED_DECLARATION, ExportNamedDeclaration) -} +if (!nodeByType.has(28)) { + nodeByType.set(28, ExportNamedDeclaration) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ExportSpecifier.ts b/koala-wrapper/src/generated/peers/ExportSpecifier.ts index d68740c1a..de59281d9 100644 --- a/koala-wrapper/src/generated/peers/ExportSpecifier.ts +++ b/koala-wrapper/src/generated/peers/ExportSpecifier.ts @@ -33,7 +33,7 @@ import { Statement } from "./Statement" import { Identifier } from "./Identifier" export class ExportSpecifier extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_EXPORT_SPECIFIER) + assertValidPeer(pointer, 29) super(pointer) } @@ -53,6 +53,6 @@ export class ExportSpecifier extends Statement { export function isExportSpecifier(node: AstNode): node is ExportSpecifier { return node instanceof ExportSpecifier } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_EXPORT_SPECIFIER)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_EXPORT_SPECIFIER, ExportSpecifier) -} +if (!nodeByType.has(29)) { + nodeByType.set(29, ExportSpecifier) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ExpressionStatement.ts b/koala-wrapper/src/generated/peers/ExpressionStatement.ts index d7f6ec665..6603e673e 100644 --- a/koala-wrapper/src/generated/peers/ExpressionStatement.ts +++ b/koala-wrapper/src/generated/peers/ExpressionStatement.ts @@ -33,7 +33,7 @@ import { Statement } from "./Statement" import { Expression } from "./Expression" export class ExpressionStatement extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_EXPRESSION_STATEMENT) + assertValidPeer(pointer, 30) super(pointer) } @@ -55,6 +55,6 @@ export class ExpressionStatement extends Statement { export function isExpressionStatement(node: AstNode): node is ExpressionStatement { return node instanceof ExpressionStatement } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_EXPRESSION_STATEMENT)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_EXPRESSION_STATEMENT, ExpressionStatement) -} +if (!nodeByType.has(30)) { + nodeByType.set(30, ExpressionStatement) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ForInStatement.ts b/koala-wrapper/src/generated/peers/ForInStatement.ts index 52d828bc1..ff051e35b 100644 --- a/koala-wrapper/src/generated/peers/ForInStatement.ts +++ b/koala-wrapper/src/generated/peers/ForInStatement.ts @@ -16,62 +16,47 @@ import { global, passNode, + passNodeArray, + unpackNonNullableNode, unpackNode, + unpackNodeArray, assertValidPeer, AstNode, Es2pandaAstNodeType, KNativePointer, nodeByType, -} from '../../reexport-for-generated'; + ArktsObject, + unpackString +} from "../../reexport-for-generated" -import { LoopStatement } from './LoopStatement'; -import { Expression } from './Expression'; -import { Statement } from './Statement'; +import { LoopStatement } from "./LoopStatement" +import { Expression } from "./Expression" +import { Statement } from "./Statement" export class ForInStatement extends LoopStatement { - constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_FOR_IN_STATEMENT); - super(pointer); + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 31) + super(pointer) + } static createForInStatement(left?: AstNode, right?: Expression, body?: Statement): ForInStatement { - return new ForInStatement( - global.generatedEs2panda._CreateForInStatement( - global.context, - passNode(left), - passNode(right), - passNode(body) - ) - ); + return new ForInStatement(global.generatedEs2panda._CreateForInStatement(global.context, passNode(left), passNode(right), passNode(body))) } - static updateForInStatement( - original?: ForInStatement, - left?: AstNode, - right?: Expression, - body?: Statement - ): ForInStatement { - return new ForInStatement( - global.generatedEs2panda._UpdateForInStatement( - global.context, - passNode(original), - passNode(left), - passNode(right), - passNode(body) - ) - ); + static updateForInStatement(original?: ForInStatement, left?: AstNode, right?: Expression, body?: Statement): ForInStatement { + return new ForInStatement(global.generatedEs2panda._UpdateForInStatement(global.context, passNode(original), passNode(left), passNode(right), passNode(body))) } get left(): AstNode | undefined { - return unpackNode(global.generatedEs2panda._ForInStatementLeft(global.context, this.peer)); + return unpackNode(global.generatedEs2panda._ForInStatementLeftConst(global.context, this.peer)) } get right(): Expression | undefined { - return unpackNode(global.generatedEs2panda._ForInStatementRight(global.context, this.peer)); + return unpackNode(global.generatedEs2panda._ForInStatementRightConst(global.context, this.peer)) } get body(): Statement | undefined { - return unpackNode(global.generatedEs2panda._ForInStatementBody(global.context, this.peer)); + return unpackNode(global.generatedEs2panda._ForInStatementBodyConst(global.context, this.peer)) } - protected readonly brandForInStatement: undefined; } -export function isForInStatement(node: object | undefined): node is ForInStatement { - return node instanceof ForInStatement; -} -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_FOR_IN_STATEMENT)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_FOR_IN_STATEMENT, ForInStatement); +export function isForInStatement(node: AstNode): node is ForInStatement { + return node instanceof ForInStatement } +if (!nodeByType.has(31)) { + nodeByType.set(31, ForInStatement) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ForOfStatement.ts b/koala-wrapper/src/generated/peers/ForOfStatement.ts index 4ff443a26..801178fd3 100644 --- a/koala-wrapper/src/generated/peers/ForOfStatement.ts +++ b/koala-wrapper/src/generated/peers/ForOfStatement.ts @@ -16,73 +16,50 @@ import { global, passNode, + passNodeArray, + unpackNonNullableNode, unpackNode, + unpackNodeArray, assertValidPeer, AstNode, Es2pandaAstNodeType, KNativePointer, nodeByType, -} from '../../reexport-for-generated'; + ArktsObject, + unpackString +} from "../../reexport-for-generated" -import { LoopStatement } from './LoopStatement'; -import { Expression } from './Expression'; -import { Statement } from './Statement'; +import { LoopStatement } from "./LoopStatement" +import { Expression } from "./Expression" +import { Statement } from "./Statement" export class ForOfStatement extends LoopStatement { - constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_FOR_OF_STATEMENT); - super(pointer); + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 32) + super(pointer) + } - static createForOfStatement( - left: AstNode | undefined, - right: Expression | undefined, - body: Statement | undefined, - isAwait: boolean - ): ForOfStatement { - return new ForOfStatement( - global.generatedEs2panda._CreateForOfStatement( - global.context, - passNode(left), - passNode(right), - passNode(body), - isAwait - ) - ); + static createForOfStatement(left: AstNode | undefined, right: Expression | undefined, body: Statement | undefined, isAwait: boolean): ForOfStatement { + return new ForOfStatement(global.generatedEs2panda._CreateForOfStatement(global.context, passNode(left), passNode(right), passNode(body), isAwait)) } - static updateForOfStatement( - original: ForOfStatement | undefined, - left: AstNode | undefined, - right: Expression | undefined, - body: Statement | undefined, - isAwait: boolean - ): ForOfStatement { - return new ForOfStatement( - global.generatedEs2panda._UpdateForOfStatement( - global.context, - passNode(original), - passNode(left), - passNode(right), - passNode(body), - isAwait - ) - ); + static updateForOfStatement(original: ForOfStatement | undefined, left: AstNode | undefined, right: Expression | undefined, body: Statement | undefined, isAwait: boolean): ForOfStatement { + return new ForOfStatement(global.generatedEs2panda._UpdateForOfStatement(global.context, passNode(original), passNode(left), passNode(right), passNode(body), isAwait)) } get left(): AstNode | undefined { - return unpackNode(global.generatedEs2panda._ForOfStatementLeft(global.context, this.peer)); + return unpackNode(global.generatedEs2panda._ForOfStatementLeftConst(global.context, this.peer)) } get right(): Expression | undefined { - return unpackNode(global.generatedEs2panda._ForOfStatementRight(global.context, this.peer)); + return unpackNode(global.generatedEs2panda._ForOfStatementRightConst(global.context, this.peer)) } get body(): Statement | undefined { - return unpackNode(global.generatedEs2panda._ForOfStatementBody(global.context, this.peer)); + return unpackNode(global.generatedEs2panda._ForOfStatementBodyConst(global.context, this.peer)) } get isAwait(): boolean { - return global.generatedEs2panda._ForOfStatementIsAwaitConst(global.context, this.peer); + return global.generatedEs2panda._ForOfStatementIsAwaitConst(global.context, this.peer) } - protected readonly brandForOfStatement: undefined; } -export function isForOfStatement(node: object | undefined): node is ForOfStatement { - return node instanceof ForOfStatement; -} -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_FOR_OF_STATEMENT)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_FOR_OF_STATEMENT, ForOfStatement); +export function isForOfStatement(node: AstNode): node is ForOfStatement { + return node instanceof ForOfStatement } +if (!nodeByType.has(32)) { + nodeByType.set(32, ForOfStatement) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ForUpdateStatement.ts b/koala-wrapper/src/generated/peers/ForUpdateStatement.ts index ae39482c3..dbf5a9686 100644 --- a/koala-wrapper/src/generated/peers/ForUpdateStatement.ts +++ b/koala-wrapper/src/generated/peers/ForUpdateStatement.ts @@ -16,77 +16,47 @@ import { global, passNode, + passNodeArray, + unpackNonNullableNode, unpackNode, + unpackNodeArray, assertValidPeer, AstNode, + Es2pandaAstNodeType, KNativePointer, nodeByType, - Es2pandaAstNodeType, -} from '../../reexport-for-generated'; -import { Expression } from './Expression'; -import { LoopStatement } from './LoopStatement'; -import { Statement } from './Statement'; + ArktsObject, + unpackString +} from "../../reexport-for-generated" +import { LoopStatement } from "./LoopStatement" +import { Expression } from "./Expression" +import { Statement } from "./Statement" export class ForUpdateStatement extends LoopStatement { - constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_FOR_UPDATE_STATEMENT); - super(pointer); + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 33) + super(pointer) + } - static createForUpdateStatement( - init?: AstNode, - test?: Expression, - update?: Expression, - body?: Statement - ): ForUpdateStatement { - return new ForUpdateStatement( - global.generatedEs2panda._CreateForUpdateStatement( - global.context, - passNode(init), - passNode(test), - passNode(update), - passNode(body) - ) - ); - } - - static updateForUpdateStatement( - original: ForUpdateStatement, - init?: AstNode, - test?: Expression, - update?: Expression, - body?: Statement - ): ForUpdateStatement { - return new ForUpdateStatement( - global.generatedEs2panda._UpdateForUpdateStatement( - global.context, - passNode(original), - passNode(init), - passNode(test), - passNode(update), - passNode(body) - ) - ); + static createForUpdateStatement(init?: AstNode, test?: Expression, update?: Expression, body?: Statement): ForUpdateStatement { + return new ForUpdateStatement(global.generatedEs2panda._CreateForUpdateStatement(global.context, passNode(init), passNode(test), passNode(update), passNode(body))) } - get init(): AstNode | undefined { - return unpackNode(global.generatedEs2panda._ForUpdateStatementInit(global.context, this.peer)); + return unpackNode(global.generatedEs2panda._ForUpdateStatementInitConst(global.context, this.peer)) } get test(): Expression | undefined { - return unpackNode(global.generatedEs2panda._ForUpdateStatementTest(global.context, this.peer)); + return unpackNode(global.generatedEs2panda._ForUpdateStatementTestConst(global.context, this.peer)) } get update(): Expression | undefined { - return unpackNode(global.generatedEs2panda._ForUpdateStatementUpdateConst(global.context, this.peer)); + return unpackNode(global.generatedEs2panda._ForUpdateStatementUpdateConst(global.context, this.peer)) } get body(): Statement | undefined { - return unpackNode(global.generatedEs2panda._ForUpdateStatementBody(global.context, this.peer)); + return unpackNode(global.generatedEs2panda._ForUpdateStatementBodyConst(global.context, this.peer)) } - protected readonly brandForUpdateStatement: undefined; -} - -export function isForUpdateStatement(node: object | undefined): node is ForUpdateStatement { - return node instanceof ForUpdateStatement; } - -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_FOR_UPDATE_STATEMENT)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_FOR_UPDATE_STATEMENT, ForUpdateStatement); +export function isForUpdateStatement(node: AstNode): node is ForUpdateStatement { + return node instanceof ForUpdateStatement } +if (!nodeByType.has(33)) { + nodeByType.set(33, ForUpdateStatement) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/FunctionDeclaration.ts b/koala-wrapper/src/generated/peers/FunctionDeclaration.ts index 598654f02..1265a281a 100644 --- a/koala-wrapper/src/generated/peers/FunctionDeclaration.ts +++ b/koala-wrapper/src/generated/peers/FunctionDeclaration.ts @@ -34,7 +34,7 @@ import { ScriptFunction } from "./ScriptFunction" import { AnnotationUsage } from "./AnnotationUsage" export class FunctionDeclaration extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_FUNCTION_DECLARATION) + assertValidPeer(pointer, 34) super(pointer) } @@ -68,6 +68,6 @@ export class FunctionDeclaration extends Statement { export function isFunctionDeclaration(node: AstNode): node is FunctionDeclaration { return node instanceof FunctionDeclaration } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_FUNCTION_DECLARATION)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_FUNCTION_DECLARATION, FunctionDeclaration) -} +if (!nodeByType.has(34)) { + nodeByType.set(34, FunctionDeclaration) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/FunctionExpression.ts b/koala-wrapper/src/generated/peers/FunctionExpression.ts index 65c4ee87b..d9e2b3886 100644 --- a/koala-wrapper/src/generated/peers/FunctionExpression.ts +++ b/koala-wrapper/src/generated/peers/FunctionExpression.ts @@ -34,7 +34,7 @@ import { ScriptFunction } from "./ScriptFunction" import { Identifier } from "./Identifier" export class FunctionExpression extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_FUNCTION_EXPRESSION) + assertValidPeer(pointer, 35) super(pointer) } @@ -63,6 +63,6 @@ export class FunctionExpression extends Expression { export function isFunctionExpression(node: AstNode): node is FunctionExpression { return node instanceof FunctionExpression } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_FUNCTION_EXPRESSION)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_FUNCTION_EXPRESSION, FunctionExpression) -} +if (!nodeByType.has(35)) { + nodeByType.set(35, FunctionExpression) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/Identifier.ts b/koala-wrapper/src/generated/peers/Identifier.ts index f6a3967f5..042688c12 100644 --- a/koala-wrapper/src/generated/peers/Identifier.ts +++ b/koala-wrapper/src/generated/peers/Identifier.ts @@ -35,7 +35,7 @@ import { Decorator } from "./Decorator" import { ValidationInfo } from "./ValidationInfo" export class Identifier extends AnnotatedExpression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_IDENTIFIER) + assertValidPeer(pointer, 36) super(pointer) } @@ -153,6 +153,6 @@ export class Identifier extends AnnotatedExpression { export function isIdentifier(node: AstNode): node is Identifier { return node instanceof Identifier } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_IDENTIFIER)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_IDENTIFIER, Identifier) -} +if (!nodeByType.has(36)) { + nodeByType.set(36, Identifier) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/IfStatement.ts b/koala-wrapper/src/generated/peers/IfStatement.ts index 2491ed7c6..056f095f6 100644 --- a/koala-wrapper/src/generated/peers/IfStatement.ts +++ b/koala-wrapper/src/generated/peers/IfStatement.ts @@ -33,7 +33,7 @@ import { Statement } from "./Statement" import { Expression } from "./Expression" export class IfStatement extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_IF_STATEMENT) + assertValidPeer(pointer, 38) super(pointer) } @@ -56,6 +56,6 @@ export class IfStatement extends Statement { export function isIfStatement(node: AstNode): node is IfStatement { return node instanceof IfStatement } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_IF_STATEMENT)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_IF_STATEMENT, IfStatement) -} +if (!nodeByType.has(38)) { + nodeByType.set(38, IfStatement) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ImportDeclaration.ts b/koala-wrapper/src/generated/peers/ImportDeclaration.ts index eaed6d450..3ce4b85d1 100644 --- a/koala-wrapper/src/generated/peers/ImportDeclaration.ts +++ b/koala-wrapper/src/generated/peers/ImportDeclaration.ts @@ -57,6 +57,6 @@ export class ImportDeclaration extends Statement { export function isImportDeclaration(node: AstNode): node is ImportDeclaration { return node instanceof ImportDeclaration } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_IMPORT_DECLARATION)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_IMPORT_DECLARATION, ImportDeclaration) -} +if (!nodeByType.has(39)) { + nodeByType.set(39, ImportDeclaration) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ImportDefaultSpecifier.ts b/koala-wrapper/src/generated/peers/ImportDefaultSpecifier.ts index 2ae1f64be..5b4ce34e9 100644 --- a/koala-wrapper/src/generated/peers/ImportDefaultSpecifier.ts +++ b/koala-wrapper/src/generated/peers/ImportDefaultSpecifier.ts @@ -33,7 +33,7 @@ import { Statement } from "./Statement" import { Identifier } from "./Identifier" export class ImportDefaultSpecifier extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_IMPORT_DEFAULT_SPECIFIER) + assertValidPeer(pointer, 41) super(pointer) } @@ -50,6 +50,6 @@ export class ImportDefaultSpecifier extends Statement { export function isImportDefaultSpecifier(node: AstNode): node is ImportDefaultSpecifier { return node instanceof ImportDefaultSpecifier } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_IMPORT_DEFAULT_SPECIFIER)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_IMPORT_DEFAULT_SPECIFIER, ImportDefaultSpecifier) -} +if (!nodeByType.has(41)) { + nodeByType.set(41, ImportDefaultSpecifier) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ImportExpression.ts b/koala-wrapper/src/generated/peers/ImportExpression.ts index 25ae47eef..fc70fd1cb 100644 --- a/koala-wrapper/src/generated/peers/ImportExpression.ts +++ b/koala-wrapper/src/generated/peers/ImportExpression.ts @@ -32,7 +32,7 @@ import { import { Expression } from "./Expression" export class ImportExpression extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_IMPORT_EXPRESSION) + assertValidPeer(pointer, 40) super(pointer) } @@ -49,6 +49,6 @@ export class ImportExpression extends Expression { export function isImportExpression(node: AstNode): node is ImportExpression { return node instanceof ImportExpression } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_IMPORT_EXPRESSION)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_IMPORT_EXPRESSION, ImportExpression) -} +if (!nodeByType.has(40)) { + nodeByType.set(40, ImportExpression) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ImportNamespaceSpecifier.ts b/koala-wrapper/src/generated/peers/ImportNamespaceSpecifier.ts index 4caa2e2e8..4f1e128bf 100644 --- a/koala-wrapper/src/generated/peers/ImportNamespaceSpecifier.ts +++ b/koala-wrapper/src/generated/peers/ImportNamespaceSpecifier.ts @@ -33,7 +33,7 @@ import { Statement } from "./Statement" import { Identifier } from "./Identifier" export class ImportNamespaceSpecifier extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_IMPORT_NAMESPACE_SPECIFIER) + assertValidPeer(pointer, 42) super(pointer) } @@ -50,6 +50,6 @@ export class ImportNamespaceSpecifier extends Statement { export function isImportNamespaceSpecifier(node: AstNode): node is ImportNamespaceSpecifier { return node instanceof ImportNamespaceSpecifier } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_IMPORT_NAMESPACE_SPECIFIER)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_IMPORT_NAMESPACE_SPECIFIER, ImportNamespaceSpecifier) -} +if (!nodeByType.has(42)) { + nodeByType.set(42, ImportNamespaceSpecifier) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ImportSpecifier.ts b/koala-wrapper/src/generated/peers/ImportSpecifier.ts index 828f1eebf..e2d49f139 100644 --- a/koala-wrapper/src/generated/peers/ImportSpecifier.ts +++ b/koala-wrapper/src/generated/peers/ImportSpecifier.ts @@ -33,7 +33,7 @@ import { Statement } from "./Statement" import { Identifier } from "./Identifier" export class ImportSpecifier extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_IMPORT_SPECIFIER) + assertValidPeer(pointer, 43) super(pointer) } @@ -53,6 +53,6 @@ export class ImportSpecifier extends Statement { export function isImportSpecifier(node: AstNode): node is ImportSpecifier { return node instanceof ImportSpecifier } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_IMPORT_SPECIFIER)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_IMPORT_SPECIFIER, ImportSpecifier) -} +if (!nodeByType.has(43)) { + nodeByType.set(43, ImportSpecifier) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/LabelPair.ts b/koala-wrapper/src/generated/peers/LabelPair.ts deleted file mode 100644 index c949e6fc1..000000000 --- a/koala-wrapper/src/generated/peers/LabelPair.ts +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (c) 2024 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { - global, - passNode, - passNodeArray, - unpackNonNullableNode, - unpackNode, - unpackNodeArray, - assertValidPeer, - AstNode, - KNativePointer, - nodeByType, - ArktsObject, - unpackString -} from "../../reexport-for-generated" - -export class LabelPair extends AstNode { - constructor(pointer: KNativePointer) { - super(pointer) - } -} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/LabelledStatement.ts b/koala-wrapper/src/generated/peers/LabelledStatement.ts index 9b9ac14b1..7dec2f9ee 100644 --- a/koala-wrapper/src/generated/peers/LabelledStatement.ts +++ b/koala-wrapper/src/generated/peers/LabelledStatement.ts @@ -33,7 +33,7 @@ import { Statement } from "./Statement" import { Identifier } from "./Identifier" export class LabelledStatement extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_LABELLED_STATEMENT) + assertValidPeer(pointer, 44) super(pointer) } @@ -53,6 +53,6 @@ export class LabelledStatement extends Statement { export function isLabelledStatement(node: AstNode): node is LabelledStatement { return node instanceof LabelledStatement } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_LABELLED_STATEMENT)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_LABELLED_STATEMENT, LabelledStatement) -} +if (!nodeByType.has(44)) { + nodeByType.set(44, LabelledStatement) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/MemberExpression.ts b/koala-wrapper/src/generated/peers/MemberExpression.ts index 530fc754e..40f74fe00 100644 --- a/koala-wrapper/src/generated/peers/MemberExpression.ts +++ b/koala-wrapper/src/generated/peers/MemberExpression.ts @@ -34,7 +34,7 @@ import { Expression } from "./Expression" import { Es2pandaMemberExpressionKind } from "./../Es2pandaEnums" export class MemberExpression extends MaybeOptionalExpression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_MEMBER_EXPRESSION) + assertValidPeer(pointer, 45) super(pointer) } @@ -88,6 +88,6 @@ export class MemberExpression extends MaybeOptionalExpression { export function isMemberExpression(node: AstNode): node is MemberExpression { return node instanceof MemberExpression } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_MEMBER_EXPRESSION)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_MEMBER_EXPRESSION, MemberExpression) -} +if (!nodeByType.has(45)) { + nodeByType.set(45, MemberExpression) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/MetaProperty.ts b/koala-wrapper/src/generated/peers/MetaProperty.ts index fbdb77b24..82c8bc8ae 100644 --- a/koala-wrapper/src/generated/peers/MetaProperty.ts +++ b/koala-wrapper/src/generated/peers/MetaProperty.ts @@ -33,7 +33,7 @@ import { Expression } from "./Expression" import { Es2pandaMetaPropertyKind } from "./../Es2pandaEnums" export class MetaProperty extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_META_PROPERTY_EXPRESSION) + assertValidPeer(pointer, 46) super(pointer) } @@ -50,6 +50,6 @@ export class MetaProperty extends Expression { export function isMetaProperty(node: AstNode): node is MetaProperty { return node instanceof MetaProperty } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_META_PROPERTY_EXPRESSION)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_META_PROPERTY_EXPRESSION, MetaProperty) -} +if (!nodeByType.has(46)) { + nodeByType.set(46, MetaProperty) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/MethodDefinition.ts b/koala-wrapper/src/generated/peers/MethodDefinition.ts index 0cfbcff23..40dd13888 100644 --- a/koala-wrapper/src/generated/peers/MethodDefinition.ts +++ b/koala-wrapper/src/generated/peers/MethodDefinition.ts @@ -36,7 +36,7 @@ import { Es2pandaModifierFlags } from "./../Es2pandaEnums" import { ScriptFunction } from "./ScriptFunction" export class MethodDefinition extends ClassElement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_METHOD_DEFINITION) + assertValidPeer(pointer, 47) super(pointer) } @@ -93,6 +93,6 @@ export class MethodDefinition extends ClassElement { export function isMethodDefinition(node: AstNode): node is MethodDefinition { return node instanceof MethodDefinition } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_METHOD_DEFINITION)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_METHOD_DEFINITION, MethodDefinition) -} +if (!nodeByType.has(47)) { + nodeByType.set(47, MethodDefinition) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/NamedType.ts b/koala-wrapper/src/generated/peers/NamedType.ts index a95328543..ce6ee368e 100644 --- a/koala-wrapper/src/generated/peers/NamedType.ts +++ b/koala-wrapper/src/generated/peers/NamedType.ts @@ -34,7 +34,7 @@ import { Identifier } from "./Identifier" import { TSTypeParameterInstantiation } from "./TSTypeParameterInstantiation" export class NamedType extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_NAMED_TYPE) + assertValidPeer(pointer, 48) super(pointer) } @@ -72,6 +72,6 @@ export class NamedType extends TypeNode { export function isNamedType(node: AstNode): node is NamedType { return node instanceof NamedType } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_NAMED_TYPE)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_NAMED_TYPE, NamedType) -} +if (!nodeByType.has(48)) { + nodeByType.set(48, NamedType) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/NewExpression.ts b/koala-wrapper/src/generated/peers/NewExpression.ts index f09cf3d6e..c267a581d 100644 --- a/koala-wrapper/src/generated/peers/NewExpression.ts +++ b/koala-wrapper/src/generated/peers/NewExpression.ts @@ -32,7 +32,7 @@ import { import { Expression } from "./Expression" export class NewExpression extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_NEW_EXPRESSION) + assertValidPeer(pointer, 49) super(pointer) } @@ -52,6 +52,6 @@ export class NewExpression extends Expression { export function isNewExpression(node: AstNode): node is NewExpression { return node instanceof NewExpression } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_NEW_EXPRESSION)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_NEW_EXPRESSION, NewExpression) -} +if (!nodeByType.has(49)) { + nodeByType.set(49, NewExpression) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/NullLiteral.ts b/koala-wrapper/src/generated/peers/NullLiteral.ts index 11f751021..a8047b711 100644 --- a/koala-wrapper/src/generated/peers/NullLiteral.ts +++ b/koala-wrapper/src/generated/peers/NullLiteral.ts @@ -32,7 +32,7 @@ import { import { Literal } from "./Literal" export class NullLiteral extends Literal { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_NULL_LITERAL) + assertValidPeer(pointer, 50) super(pointer) } @@ -46,6 +46,6 @@ export class NullLiteral extends Literal { export function isNullLiteral(node: AstNode): node is NullLiteral { return node instanceof NullLiteral } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_NULL_LITERAL)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_NULL_LITERAL, NullLiteral) -} +if (!nodeByType.has(50)) { + nodeByType.set(50, NullLiteral) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/NumberLiteral.ts b/koala-wrapper/src/generated/peers/NumberLiteral.ts index 0930bbc02..e14e174d9 100644 --- a/koala-wrapper/src/generated/peers/NumberLiteral.ts +++ b/koala-wrapper/src/generated/peers/NumberLiteral.ts @@ -32,14 +32,17 @@ import { import { Literal } from "./Literal" export class NumberLiteral extends Literal { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_NUMBER_LITERAL) + assertValidPeer(pointer, 52) super(pointer) } + get str(): string { + return unpackString(global.generatedEs2panda._NumberLiteralStrConst(global.context, this.peer)) + } } export function isNumberLiteral(node: AstNode): node is NumberLiteral { return node instanceof NumberLiteral } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_NUMBER_LITERAL)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_NUMBER_LITERAL, NumberLiteral) -} +if (!nodeByType.has(52)) { + nodeByType.set(52, NumberLiteral) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/OmittedExpression.ts b/koala-wrapper/src/generated/peers/OmittedExpression.ts index 4449960a1..339202ae3 100644 --- a/koala-wrapper/src/generated/peers/OmittedExpression.ts +++ b/koala-wrapper/src/generated/peers/OmittedExpression.ts @@ -32,7 +32,7 @@ import { import { Expression } from "./Expression" export class OmittedExpression extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_OMITTED_EXPRESSION) + assertValidPeer(pointer, 53) super(pointer) } @@ -46,6 +46,6 @@ export class OmittedExpression extends Expression { export function isOmittedExpression(node: AstNode): node is OmittedExpression { return node instanceof OmittedExpression } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_OMITTED_EXPRESSION)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_OMITTED_EXPRESSION, OmittedExpression) -} +if (!nodeByType.has(53)) { + nodeByType.set(53, OmittedExpression) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/OpaqueTypeNode.ts b/koala-wrapper/src/generated/peers/OpaqueTypeNode.ts index 8fbc0101b..ba2d646dc 100644 --- a/koala-wrapper/src/generated/peers/OpaqueTypeNode.ts +++ b/koala-wrapper/src/generated/peers/OpaqueTypeNode.ts @@ -32,7 +32,7 @@ import { import { TypeNode } from "./TypeNode" export class OpaqueTypeNode extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_OPAQUE_TYPE_NODE) + assertValidPeer(pointer, 154) super(pointer) } @@ -46,6 +46,6 @@ export class OpaqueTypeNode extends TypeNode { export function isOpaqueTypeNode(node: AstNode): node is OpaqueTypeNode { return node instanceof OpaqueTypeNode } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_OPAQUE_TYPE_NODE)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_OPAQUE_TYPE_NODE, OpaqueTypeNode) -} +if (!nodeByType.has(154)) { + nodeByType.set(154, OpaqueTypeNode) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/PrefixAssertionExpression.ts b/koala-wrapper/src/generated/peers/PrefixAssertionExpression.ts index 30dc3d43a..03a093531 100644 --- a/koala-wrapper/src/generated/peers/PrefixAssertionExpression.ts +++ b/koala-wrapper/src/generated/peers/PrefixAssertionExpression.ts @@ -33,7 +33,7 @@ import { Expression } from "./Expression" import { TypeNode } from "./TypeNode" export class PrefixAssertionExpression extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_PREFIX_ASSERTION_EXPRESSION) + assertValidPeer(pointer, 54) super(pointer) } @@ -53,6 +53,6 @@ export class PrefixAssertionExpression extends Expression { export function isPrefixAssertionExpression(node: AstNode): node is PrefixAssertionExpression { return node instanceof PrefixAssertionExpression } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_PREFIX_ASSERTION_EXPRESSION)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_PREFIX_ASSERTION_EXPRESSION, PrefixAssertionExpression) -} +if (!nodeByType.has(54)) { + nodeByType.set(54, PrefixAssertionExpression) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/Property.ts b/koala-wrapper/src/generated/peers/Property.ts index 6a576762b..982cb0241 100644 --- a/koala-wrapper/src/generated/peers/Property.ts +++ b/koala-wrapper/src/generated/peers/Property.ts @@ -34,7 +34,7 @@ import { Es2pandaPropertyKind } from "./../Es2pandaEnums" import { ValidationInfo } from "./ValidationInfo" export class Property extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_PROPERTY) + assertValidPeer(pointer, 55) super(pointer) } @@ -75,6 +75,6 @@ export class Property extends Expression { export function isProperty(node: AstNode): node is Property { return node instanceof Property } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_PROPERTY)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_PROPERTY, Property) -} +if (!nodeByType.has(55)) { + nodeByType.set(55, Property) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/RegExpLiteral.ts b/koala-wrapper/src/generated/peers/RegExpLiteral.ts index 0d91a57d9..5ae04143b 100644 --- a/koala-wrapper/src/generated/peers/RegExpLiteral.ts +++ b/koala-wrapper/src/generated/peers/RegExpLiteral.ts @@ -33,7 +33,7 @@ import { Literal } from "./Literal" import { Es2pandaRegExpFlags } from "./../Es2pandaEnums" export class RegExpLiteral extends Literal { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_REGEXP_LITERAL) + assertValidPeer(pointer, 56) super(pointer) } @@ -53,6 +53,6 @@ export class RegExpLiteral extends Literal { export function isRegExpLiteral(node: AstNode): node is RegExpLiteral { return node instanceof RegExpLiteral } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_REGEXP_LITERAL)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_REGEXP_LITERAL, RegExpLiteral) -} +if (!nodeByType.has(56)) { + nodeByType.set(56, RegExpLiteral) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ReturnStatement.ts b/koala-wrapper/src/generated/peers/ReturnStatement.ts index 4607dbe40..6489e99df 100644 --- a/koala-wrapper/src/generated/peers/ReturnStatement.ts +++ b/koala-wrapper/src/generated/peers/ReturnStatement.ts @@ -33,7 +33,7 @@ import { Statement } from "./Statement" import { Expression } from "./Expression" export class ReturnStatement extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_RETURN_STATEMENT) + assertValidPeer(pointer, 58) super(pointer) } @@ -61,6 +61,6 @@ export class ReturnStatement extends Statement { export function isReturnStatement(node: AstNode): node is ReturnStatement { return node instanceof ReturnStatement } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_RETURN_STATEMENT)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_RETURN_STATEMENT, ReturnStatement) -} +if (!nodeByType.has(58)) { + nodeByType.set(58, ReturnStatement) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ScriptFunction.ts b/koala-wrapper/src/generated/peers/ScriptFunction.ts index 42c4c9343..28b262008 100644 --- a/koala-wrapper/src/generated/peers/ScriptFunction.ts +++ b/koala-wrapper/src/generated/peers/ScriptFunction.ts @@ -40,7 +40,7 @@ import { Es2pandaModifierFlags } from "./../Es2pandaEnums" import { AnnotationUsage } from "./AnnotationUsage" export class ScriptFunction extends AstNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_SCRIPT_FUNCTION) + assertValidPeer(pointer, 59) super(pointer) } @@ -194,6 +194,6 @@ export class ScriptFunction extends AstNode { export function isScriptFunction(node: AstNode): node is ScriptFunction { return node instanceof ScriptFunction } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_SCRIPT_FUNCTION)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_SCRIPT_FUNCTION, ScriptFunction) -} +if (!nodeByType.has(59)) { + nodeByType.set(59, ScriptFunction) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/SequenceExpression.ts b/koala-wrapper/src/generated/peers/SequenceExpression.ts index dc814dd4d..fb0f1a9c0 100644 --- a/koala-wrapper/src/generated/peers/SequenceExpression.ts +++ b/koala-wrapper/src/generated/peers/SequenceExpression.ts @@ -32,7 +32,7 @@ import { import { Expression } from "./Expression" export class SequenceExpression extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_SEQUENCE_EXPRESSION) + assertValidPeer(pointer, 60) super(pointer) } @@ -49,6 +49,6 @@ export class SequenceExpression extends Expression { export function isSequenceExpression(node: AstNode): node is SequenceExpression { return node instanceof SequenceExpression } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_SEQUENCE_EXPRESSION)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_SEQUENCE_EXPRESSION, SequenceExpression) -} +if (!nodeByType.has(60)) { + nodeByType.set(60, SequenceExpression) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/StringLiteral.ts b/koala-wrapper/src/generated/peers/StringLiteral.ts index cf03dca5c..6eed3c9e4 100644 --- a/koala-wrapper/src/generated/peers/StringLiteral.ts +++ b/koala-wrapper/src/generated/peers/StringLiteral.ts @@ -31,7 +31,7 @@ import { import { Literal } from "./Literal" export class StringLiteral extends Literal { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_STRING_LITERAL) + assertValidPeer(pointer, 61) super(pointer) } @@ -54,6 +54,6 @@ export class StringLiteral extends Literal { export function isStringLiteral(node: AstNode): node is StringLiteral { return node instanceof StringLiteral } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_STRING_LITERAL)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_STRING_LITERAL, StringLiteral) -} +if (!nodeByType.has(61)) { + nodeByType.set(61, StringLiteral) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/SuperExpression.ts b/koala-wrapper/src/generated/peers/SuperExpression.ts index 6f7c877c0..57b35074d 100644 --- a/koala-wrapper/src/generated/peers/SuperExpression.ts +++ b/koala-wrapper/src/generated/peers/SuperExpression.ts @@ -32,7 +32,7 @@ import { import { Expression } from "./Expression" export class SuperExpression extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_SUPER_EXPRESSION) + assertValidPeer(pointer, 83) super(pointer) } @@ -46,6 +46,6 @@ export class SuperExpression extends Expression { export function isSuperExpression(node: AstNode): node is SuperExpression { return node instanceof SuperExpression } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_SUPER_EXPRESSION)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_SUPER_EXPRESSION, SuperExpression) -} +if (!nodeByType.has(83)) { + nodeByType.set(83, SuperExpression) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/SwitchCaseStatement.ts b/koala-wrapper/src/generated/peers/SwitchCaseStatement.ts index 27f1d7e98..93ff25f08 100644 --- a/koala-wrapper/src/generated/peers/SwitchCaseStatement.ts +++ b/koala-wrapper/src/generated/peers/SwitchCaseStatement.ts @@ -33,7 +33,7 @@ import { Statement } from "./Statement" import { Expression } from "./Expression" export class SwitchCaseStatement extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_SWITCH_CASE_STATEMENT) + assertValidPeer(pointer, 85) super(pointer) } @@ -53,6 +53,6 @@ export class SwitchCaseStatement extends Statement { export function isSwitchCaseStatement(node: AstNode): node is SwitchCaseStatement { return node instanceof SwitchCaseStatement } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_SWITCH_CASE_STATEMENT)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_SWITCH_CASE_STATEMENT, SwitchCaseStatement) -} +if (!nodeByType.has(85)) { + nodeByType.set(85, SwitchCaseStatement) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/SwitchStatement.ts b/koala-wrapper/src/generated/peers/SwitchStatement.ts index d7c9289cd..d11afaf4a 100644 --- a/koala-wrapper/src/generated/peers/SwitchStatement.ts +++ b/koala-wrapper/src/generated/peers/SwitchStatement.ts @@ -34,7 +34,7 @@ import { Expression } from "./Expression" import { SwitchCaseStatement } from "./SwitchCaseStatement" export class SwitchStatement extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_SWITCH_STATEMENT) + assertValidPeer(pointer, 86) super(pointer) } @@ -54,6 +54,6 @@ export class SwitchStatement extends Statement { export function isSwitchStatement(node: AstNode): node is SwitchStatement { return node instanceof SwitchStatement } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_SWITCH_STATEMENT)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_SWITCH_STATEMENT, SwitchStatement) -} +if (!nodeByType.has(86)) { + nodeByType.set(86, SwitchStatement) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSAnyKeyword.ts b/koala-wrapper/src/generated/peers/TSAnyKeyword.ts index 7f0133efb..ffb19bebf 100644 --- a/koala-wrapper/src/generated/peers/TSAnyKeyword.ts +++ b/koala-wrapper/src/generated/peers/TSAnyKeyword.ts @@ -32,7 +32,7 @@ import { import { TypeNode } from "./TypeNode" export class TSAnyKeyword extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_ANY_KEYWORD) + assertValidPeer(pointer, 91) super(pointer) } @@ -46,6 +46,6 @@ export class TSAnyKeyword extends TypeNode { export function isTSAnyKeyword(node: AstNode): node is TSAnyKeyword { return node instanceof TSAnyKeyword } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_ANY_KEYWORD)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_ANY_KEYWORD, TSAnyKeyword) -} +if (!nodeByType.has(91)) { + nodeByType.set(91, TSAnyKeyword) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSArrayType.ts b/koala-wrapper/src/generated/peers/TSArrayType.ts index 475b248cc..a727d24fc 100644 --- a/koala-wrapper/src/generated/peers/TSArrayType.ts +++ b/koala-wrapper/src/generated/peers/TSArrayType.ts @@ -32,7 +32,7 @@ import { import { TypeNode } from "./TypeNode" export class TSArrayType extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_ARRAY_TYPE) + assertValidPeer(pointer, 102) super(pointer) } @@ -49,6 +49,6 @@ export class TSArrayType extends TypeNode { export function isTSArrayType(node: AstNode): node is TSArrayType { return node instanceof TSArrayType } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_ARRAY_TYPE)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_ARRAY_TYPE, TSArrayType) -} +if (!nodeByType.has(102)) { + nodeByType.set(102, TSArrayType) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSAsExpression.ts b/koala-wrapper/src/generated/peers/TSAsExpression.ts index 99c58edd4..718b9427b 100644 --- a/koala-wrapper/src/generated/peers/TSAsExpression.ts +++ b/koala-wrapper/src/generated/peers/TSAsExpression.ts @@ -34,7 +34,7 @@ import { Expression } from "./Expression" import { TypeNode } from "./TypeNode" export class TSAsExpression extends AnnotatedExpression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_AS_EXPRESSION) + assertValidPeer(pointer, 138) super(pointer) } @@ -72,6 +72,6 @@ export class TSAsExpression extends AnnotatedExpression { export function isTSAsExpression(node: AstNode): node is TSAsExpression { return node instanceof TSAsExpression } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_AS_EXPRESSION)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_AS_EXPRESSION, TSAsExpression) -} +if (!nodeByType.has(138)) { + nodeByType.set(138, TSAsExpression) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSBigintKeyword.ts b/koala-wrapper/src/generated/peers/TSBigintKeyword.ts index 12da1be06..371719a14 100644 --- a/koala-wrapper/src/generated/peers/TSBigintKeyword.ts +++ b/koala-wrapper/src/generated/peers/TSBigintKeyword.ts @@ -32,7 +32,7 @@ import { import { TypeNode } from "./TypeNode" export class TSBigintKeyword extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_BIGINT_KEYWORD) + assertValidPeer(pointer, 98) super(pointer) } @@ -46,6 +46,6 @@ export class TSBigintKeyword extends TypeNode { export function isTSBigintKeyword(node: AstNode): node is TSBigintKeyword { return node instanceof TSBigintKeyword } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_BIGINT_KEYWORD)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_BIGINT_KEYWORD, TSBigintKeyword) -} +if (!nodeByType.has(98)) { + nodeByType.set(98, TSBigintKeyword) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSBooleanKeyword.ts b/koala-wrapper/src/generated/peers/TSBooleanKeyword.ts index 6459f6fdb..cc4c077b3 100644 --- a/koala-wrapper/src/generated/peers/TSBooleanKeyword.ts +++ b/koala-wrapper/src/generated/peers/TSBooleanKeyword.ts @@ -32,7 +32,7 @@ import { import { TypeNode } from "./TypeNode" export class TSBooleanKeyword extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_BOOLEAN_KEYWORD) + assertValidPeer(pointer, 93) super(pointer) } @@ -46,6 +46,6 @@ export class TSBooleanKeyword extends TypeNode { export function isTSBooleanKeyword(node: AstNode): node is TSBooleanKeyword { return node instanceof TSBooleanKeyword } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_BOOLEAN_KEYWORD)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_BOOLEAN_KEYWORD, TSBooleanKeyword) -} +if (!nodeByType.has(93)) { + nodeByType.set(93, TSBooleanKeyword) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSClassImplements.ts b/koala-wrapper/src/generated/peers/TSClassImplements.ts index ed621c260..b06a578a1 100644 --- a/koala-wrapper/src/generated/peers/TSClassImplements.ts +++ b/koala-wrapper/src/generated/peers/TSClassImplements.ts @@ -33,7 +33,7 @@ import { Expression } from "./Expression" import { TSTypeParameterInstantiation } from "./TSTypeParameterInstantiation" export class TSClassImplements extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_CLASS_IMPLEMENTS) + assertValidPeer(pointer, 139) super(pointer) } @@ -59,6 +59,6 @@ export class TSClassImplements extends Expression { export function isTSClassImplements(node: AstNode): node is TSClassImplements { return node instanceof TSClassImplements } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_CLASS_IMPLEMENTS)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_CLASS_IMPLEMENTS, TSClassImplements) -} +if (!nodeByType.has(139)) { + nodeByType.set(139, TSClassImplements) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSConditionalType.ts b/koala-wrapper/src/generated/peers/TSConditionalType.ts index 6b6ab8f22..f03de8600 100644 --- a/koala-wrapper/src/generated/peers/TSConditionalType.ts +++ b/koala-wrapper/src/generated/peers/TSConditionalType.ts @@ -33,7 +33,7 @@ import { TypeNode } from "./TypeNode" import { Expression } from "./Expression" export class TSConditionalType extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_CONDITIONAL_TYPE) + assertValidPeer(pointer, 111) super(pointer) } @@ -59,6 +59,6 @@ export class TSConditionalType extends TypeNode { export function isTSConditionalType(node: AstNode): node is TSConditionalType { return node instanceof TSConditionalType } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_CONDITIONAL_TYPE)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_CONDITIONAL_TYPE, TSConditionalType) -} +if (!nodeByType.has(111)) { + nodeByType.set(111, TSConditionalType) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSConstructorType.ts b/koala-wrapper/src/generated/peers/TSConstructorType.ts index be2be772c..896ccf390 100644 --- a/koala-wrapper/src/generated/peers/TSConstructorType.ts +++ b/koala-wrapper/src/generated/peers/TSConstructorType.ts @@ -35,7 +35,7 @@ import { TSTypeParameterDeclaration } from "./TSTypeParameterDeclaration" import { Expression } from "./Expression" export class TSConstructorType extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_CONSTRUCTOR_TYPE) + assertValidPeer(pointer, 126) super(pointer) } @@ -61,6 +61,6 @@ export class TSConstructorType extends TypeNode { export function isTSConstructorType(node: AstNode): node is TSConstructorType { return node instanceof TSConstructorType } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_CONSTRUCTOR_TYPE)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_CONSTRUCTOR_TYPE, TSConstructorType) -} +if (!nodeByType.has(126)) { + nodeByType.set(126, TSConstructorType) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSEnumDeclaration.ts b/koala-wrapper/src/generated/peers/TSEnumDeclaration.ts index 707334a8c..ecebdceed 100644 --- a/koala-wrapper/src/generated/peers/TSEnumDeclaration.ts +++ b/koala-wrapper/src/generated/peers/TSEnumDeclaration.ts @@ -35,7 +35,7 @@ import { ClassDefinition } from "./ClassDefinition" import { Decorator } from "./Decorator" export class TSEnumDeclaration extends TypedStatement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_ENUM_DECLARATION) + assertValidPeer(pointer, 87) super(pointer) } @@ -77,6 +77,6 @@ export class TSEnumDeclaration extends TypedStatement { export function isTSEnumDeclaration(node: AstNode): node is TSEnumDeclaration { return node instanceof TSEnumDeclaration } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_ENUM_DECLARATION)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_ENUM_DECLARATION, TSEnumDeclaration) -} +if (!nodeByType.has(87)) { + nodeByType.set(87, TSEnumDeclaration) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSEnumMember.ts b/koala-wrapper/src/generated/peers/TSEnumMember.ts index 862e08867..c0332c509 100644 --- a/koala-wrapper/src/generated/peers/TSEnumMember.ts +++ b/koala-wrapper/src/generated/peers/TSEnumMember.ts @@ -33,7 +33,7 @@ import { Statement } from "./Statement" import { Expression } from "./Expression" export class TSEnumMember extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_ENUM_MEMBER) + assertValidPeer(pointer, 88) super(pointer) } @@ -62,6 +62,6 @@ export class TSEnumMember extends Statement { export function isTSEnumMember(node: AstNode): node is TSEnumMember { return node instanceof TSEnumMember } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_ENUM_MEMBER)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_ENUM_MEMBER, TSEnumMember) -} +if (!nodeByType.has(88)) { + nodeByType.set(88, TSEnumMember) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSExternalModuleReference.ts b/koala-wrapper/src/generated/peers/TSExternalModuleReference.ts index 44303a741..eae8cfabc 100644 --- a/koala-wrapper/src/generated/peers/TSExternalModuleReference.ts +++ b/koala-wrapper/src/generated/peers/TSExternalModuleReference.ts @@ -32,7 +32,7 @@ import { import { Expression } from "./Expression" export class TSExternalModuleReference extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_EXTERNAL_MODULE_REFERENCE) + assertValidPeer(pointer, 89) super(pointer) } @@ -49,6 +49,6 @@ export class TSExternalModuleReference extends Expression { export function isTSExternalModuleReference(node: AstNode): node is TSExternalModuleReference { return node instanceof TSExternalModuleReference } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_EXTERNAL_MODULE_REFERENCE)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_EXTERNAL_MODULE_REFERENCE, TSExternalModuleReference) -} +if (!nodeByType.has(89)) { + nodeByType.set(89, TSExternalModuleReference) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSFunctionType.ts b/koala-wrapper/src/generated/peers/TSFunctionType.ts index 6f2df8cb4..f65d2fa56 100644 --- a/koala-wrapper/src/generated/peers/TSFunctionType.ts +++ b/koala-wrapper/src/generated/peers/TSFunctionType.ts @@ -35,7 +35,7 @@ import { TSTypeParameterDeclaration } from "./TSTypeParameterDeclaration" import { Expression } from "./Expression" export class TSFunctionType extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_FUNCTION_TYPE) + assertValidPeer(pointer, 125) super(pointer) } @@ -63,6 +63,6 @@ export class TSFunctionType extends TypeNode { export function isTSFunctionType(node: AstNode): node is TSFunctionType { return node instanceof TSFunctionType } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_FUNCTION_TYPE)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_FUNCTION_TYPE, TSFunctionType) -} +if (!nodeByType.has(125)) { + nodeByType.set(125, TSFunctionType) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSImportEqualsDeclaration.ts b/koala-wrapper/src/generated/peers/TSImportEqualsDeclaration.ts index 6f561a769..a04b88379 100644 --- a/koala-wrapper/src/generated/peers/TSImportEqualsDeclaration.ts +++ b/koala-wrapper/src/generated/peers/TSImportEqualsDeclaration.ts @@ -34,7 +34,7 @@ import { Identifier } from "./Identifier" import { Expression } from "./Expression" export class TSImportEqualsDeclaration extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_IMPORT_EQUALS_DECLARATION) + assertValidPeer(pointer, 124) super(pointer) } @@ -57,6 +57,6 @@ export class TSImportEqualsDeclaration extends Statement { export function isTSImportEqualsDeclaration(node: AstNode): node is TSImportEqualsDeclaration { return node instanceof TSImportEqualsDeclaration } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_IMPORT_EQUALS_DECLARATION)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_IMPORT_EQUALS_DECLARATION, TSImportEqualsDeclaration) -} +if (!nodeByType.has(124)) { + nodeByType.set(124, TSImportEqualsDeclaration) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSImportType.ts b/koala-wrapper/src/generated/peers/TSImportType.ts index 7f57afe79..43e08e49a 100644 --- a/koala-wrapper/src/generated/peers/TSImportType.ts +++ b/koala-wrapper/src/generated/peers/TSImportType.ts @@ -34,7 +34,7 @@ import { Expression } from "./Expression" import { TSTypeParameterInstantiation } from "./TSTypeParameterInstantiation" export class TSImportType extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_IMPORT_TYPE) + assertValidPeer(pointer, 112) super(pointer) } @@ -60,6 +60,6 @@ export class TSImportType extends TypeNode { export function isTSImportType(node: AstNode): node is TSImportType { return node instanceof TSImportType } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_IMPORT_TYPE)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_IMPORT_TYPE, TSImportType) -} +if (!nodeByType.has(112)) { + nodeByType.set(112, TSImportType) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSIndexSignature.ts b/koala-wrapper/src/generated/peers/TSIndexSignature.ts index 827218b25..6a7bf5ea9 100644 --- a/koala-wrapper/src/generated/peers/TSIndexSignature.ts +++ b/koala-wrapper/src/generated/peers/TSIndexSignature.ts @@ -35,7 +35,7 @@ import { TypeNode } from "./TypeNode" import { Es2pandaTSIndexSignatureKind } from "./../Es2pandaEnums" export class TSIndexSignature extends TypedAstNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_INDEX_SIGNATURE) + assertValidPeer(pointer, 136) super(pointer) } @@ -58,6 +58,6 @@ export class TSIndexSignature extends TypedAstNode { export function isTSIndexSignature(node: AstNode): node is TSIndexSignature { return node instanceof TSIndexSignature } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_INDEX_SIGNATURE)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_INDEX_SIGNATURE, TSIndexSignature) -} +if (!nodeByType.has(136)) { + nodeByType.set(136, TSIndexSignature) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSIndexedAccessType.ts b/koala-wrapper/src/generated/peers/TSIndexedAccessType.ts index 7faab853a..edb3a5c1f 100644 --- a/koala-wrapper/src/generated/peers/TSIndexedAccessType.ts +++ b/koala-wrapper/src/generated/peers/TSIndexedAccessType.ts @@ -32,7 +32,7 @@ import { import { TypeNode } from "./TypeNode" export class TSIndexedAccessType extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_INDEXED_ACCESS_TYPE) + assertValidPeer(pointer, 130) super(pointer) } @@ -52,6 +52,6 @@ export class TSIndexedAccessType extends TypeNode { export function isTSIndexedAccessType(node: AstNode): node is TSIndexedAccessType { return node instanceof TSIndexedAccessType } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_INDEXED_ACCESS_TYPE)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_INDEXED_ACCESS_TYPE, TSIndexedAccessType) -} +if (!nodeByType.has(130)) { + nodeByType.set(130, TSIndexedAccessType) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSInferType.ts b/koala-wrapper/src/generated/peers/TSInferType.ts index aea447732..f2a5d6597 100644 --- a/koala-wrapper/src/generated/peers/TSInferType.ts +++ b/koala-wrapper/src/generated/peers/TSInferType.ts @@ -33,7 +33,7 @@ import { TypeNode } from "./TypeNode" import { TSTypeParameter } from "./TSTypeParameter" export class TSInferType extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_INFER_TYPE) + assertValidPeer(pointer, 110) super(pointer) } @@ -50,6 +50,6 @@ export class TSInferType extends TypeNode { export function isTSInferType(node: AstNode): node is TSInferType { return node instanceof TSInferType } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_INFER_TYPE)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_INFER_TYPE, TSInferType) -} +if (!nodeByType.has(110)) { + nodeByType.set(110, TSInferType) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSInterfaceBody.ts b/koala-wrapper/src/generated/peers/TSInterfaceBody.ts index fa9c4e80a..103fa4a1a 100644 --- a/koala-wrapper/src/generated/peers/TSInterfaceBody.ts +++ b/koala-wrapper/src/generated/peers/TSInterfaceBody.ts @@ -32,7 +32,7 @@ import { import { Expression } from "./Expression" export class TSInterfaceBody extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_INTERFACE_BODY) + assertValidPeer(pointer, 132) super(pointer) } @@ -52,6 +52,6 @@ export class TSInterfaceBody extends Expression { export function isTSInterfaceBody(node: AstNode): node is TSInterfaceBody { return node instanceof TSInterfaceBody } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_INTERFACE_BODY)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_INTERFACE_BODY, TSInterfaceBody) -} +if (!nodeByType.has(132)) { + nodeByType.set(132, TSInterfaceBody) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSInterfaceDeclaration.ts b/koala-wrapper/src/generated/peers/TSInterfaceDeclaration.ts index a44a0c8e6..21c064fcf 100644 --- a/koala-wrapper/src/generated/peers/TSInterfaceDeclaration.ts +++ b/koala-wrapper/src/generated/peers/TSInterfaceDeclaration.ts @@ -39,7 +39,7 @@ import { ClassDeclaration } from "./ClassDeclaration" import { AnnotationUsage } from "./AnnotationUsage" export class TSInterfaceDeclaration extends TypedStatement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_INTERFACE_DECLARATION) + assertValidPeer(pointer, 131) super(pointer) } @@ -98,6 +98,6 @@ export class TSInterfaceDeclaration extends TypedStatement { export function isTSInterfaceDeclaration(node: AstNode): node is TSInterfaceDeclaration { return node instanceof TSInterfaceDeclaration } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_INTERFACE_DECLARATION)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_INTERFACE_DECLARATION, TSInterfaceDeclaration) -} +if (!nodeByType.has(131)) { + nodeByType.set(131, TSInterfaceDeclaration) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSInterfaceHeritage.ts b/koala-wrapper/src/generated/peers/TSInterfaceHeritage.ts index 4b22c6eaa..4af6bfb0f 100644 --- a/koala-wrapper/src/generated/peers/TSInterfaceHeritage.ts +++ b/koala-wrapper/src/generated/peers/TSInterfaceHeritage.ts @@ -33,7 +33,7 @@ import { Expression } from "./Expression" import { TypeNode } from "./TypeNode" export class TSInterfaceHeritage extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_INTERFACE_HERITAGE) + assertValidPeer(pointer, 133) super(pointer) } @@ -50,6 +50,6 @@ export class TSInterfaceHeritage extends Expression { export function isTSInterfaceHeritage(node: AstNode): node is TSInterfaceHeritage { return node instanceof TSInterfaceHeritage } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_INTERFACE_HERITAGE)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_INTERFACE_HERITAGE, TSInterfaceHeritage) -} +if (!nodeByType.has(133)) { + nodeByType.set(133, TSInterfaceHeritage) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSIntersectionType.ts b/koala-wrapper/src/generated/peers/TSIntersectionType.ts index 8f58edf65..d21f48d7a 100644 --- a/koala-wrapper/src/generated/peers/TSIntersectionType.ts +++ b/koala-wrapper/src/generated/peers/TSIntersectionType.ts @@ -33,7 +33,7 @@ import { TypeNode } from "./TypeNode" import { Expression } from "./Expression" export class TSIntersectionType extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_INTERSECTION_TYPE) + assertValidPeer(pointer, 113) super(pointer) } @@ -50,6 +50,6 @@ export class TSIntersectionType extends TypeNode { export function isTSIntersectionType(node: AstNode): node is TSIntersectionType { return node instanceof TSIntersectionType } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_INTERSECTION_TYPE)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_INTERSECTION_TYPE, TSIntersectionType) -} +if (!nodeByType.has(113)) { + nodeByType.set(113, TSIntersectionType) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSLiteralType.ts b/koala-wrapper/src/generated/peers/TSLiteralType.ts index a3ea5c9c1..f9ecdf774 100644 --- a/koala-wrapper/src/generated/peers/TSLiteralType.ts +++ b/koala-wrapper/src/generated/peers/TSLiteralType.ts @@ -33,7 +33,7 @@ import { TypeNode } from "./TypeNode" import { Expression } from "./Expression" export class TSLiteralType extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_LITERAL_TYPE) + assertValidPeer(pointer, 109) super(pointer) } @@ -50,6 +50,6 @@ export class TSLiteralType extends TypeNode { export function isTSLiteralType(node: AstNode): node is TSLiteralType { return node instanceof TSLiteralType } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_LITERAL_TYPE)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_LITERAL_TYPE, TSLiteralType) -} +if (!nodeByType.has(109)) { + nodeByType.set(109, TSLiteralType) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSMappedType.ts b/koala-wrapper/src/generated/peers/TSMappedType.ts index dc8344d7c..e8a2202dc 100644 --- a/koala-wrapper/src/generated/peers/TSMappedType.ts +++ b/koala-wrapper/src/generated/peers/TSMappedType.ts @@ -34,7 +34,7 @@ import { TSTypeParameter } from "./TSTypeParameter" import { Es2pandaMappedOption } from "./../Es2pandaEnums" export class TSMappedType extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_MAPPED_TYPE) + assertValidPeer(pointer, 114) super(pointer) } @@ -60,6 +60,6 @@ export class TSMappedType extends TypeNode { export function isTSMappedType(node: AstNode): node is TSMappedType { return node instanceof TSMappedType } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_MAPPED_TYPE)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_MAPPED_TYPE, TSMappedType) -} +if (!nodeByType.has(114)) { + nodeByType.set(114, TSMappedType) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSMethodSignature.ts b/koala-wrapper/src/generated/peers/TSMethodSignature.ts index f0d05604b..d16351da0 100644 --- a/koala-wrapper/src/generated/peers/TSMethodSignature.ts +++ b/koala-wrapper/src/generated/peers/TSMethodSignature.ts @@ -35,7 +35,7 @@ import { TSTypeParameterDeclaration } from "./TSTypeParameterDeclaration" import { TypeNode } from "./TypeNode" export class TSMethodSignature extends AstNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_METHOD_SIGNATURE) + assertValidPeer(pointer, 106) super(pointer) } @@ -67,6 +67,6 @@ export class TSMethodSignature extends AstNode { export function isTSMethodSignature(node: AstNode): node is TSMethodSignature { return node instanceof TSMethodSignature } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_METHOD_SIGNATURE)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_METHOD_SIGNATURE, TSMethodSignature) -} +if (!nodeByType.has(106)) { + nodeByType.set(106, TSMethodSignature) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSModuleBlock.ts b/koala-wrapper/src/generated/peers/TSModuleBlock.ts index 57f8c51a3..d25d54f36 100644 --- a/koala-wrapper/src/generated/peers/TSModuleBlock.ts +++ b/koala-wrapper/src/generated/peers/TSModuleBlock.ts @@ -32,7 +32,7 @@ import { import { Statement } from "./Statement" export class TSModuleBlock extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_MODULE_BLOCK) + assertValidPeer(pointer, 115) super(pointer) } @@ -49,6 +49,6 @@ export class TSModuleBlock extends Statement { export function isTSModuleBlock(node: AstNode): node is TSModuleBlock { return node instanceof TSModuleBlock } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_MODULE_BLOCK)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_MODULE_BLOCK, TSModuleBlock) -} +if (!nodeByType.has(115)) { + nodeByType.set(115, TSModuleBlock) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSModuleDeclaration.ts b/koala-wrapper/src/generated/peers/TSModuleDeclaration.ts index f78854027..c4582a84c 100644 --- a/koala-wrapper/src/generated/peers/TSModuleDeclaration.ts +++ b/koala-wrapper/src/generated/peers/TSModuleDeclaration.ts @@ -33,7 +33,7 @@ import { Statement } from "./Statement" import { Expression } from "./Expression" export class TSModuleDeclaration extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_MODULE_DECLARATION) + assertValidPeer(pointer, 123) super(pointer) } @@ -59,6 +59,6 @@ export class TSModuleDeclaration extends Statement { export function isTSModuleDeclaration(node: AstNode): node is TSModuleDeclaration { return node instanceof TSModuleDeclaration } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_MODULE_DECLARATION)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_MODULE_DECLARATION, TSModuleDeclaration) -} +if (!nodeByType.has(123)) { + nodeByType.set(123, TSModuleDeclaration) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSNamedTupleMember.ts b/koala-wrapper/src/generated/peers/TSNamedTupleMember.ts index 93085dfa1..3252f8a47 100644 --- a/koala-wrapper/src/generated/peers/TSNamedTupleMember.ts +++ b/koala-wrapper/src/generated/peers/TSNamedTupleMember.ts @@ -33,7 +33,7 @@ import { TypeNode } from "./TypeNode" import { Expression } from "./Expression" export class TSNamedTupleMember extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_NAMED_TUPLE_MEMBER) + assertValidPeer(pointer, 135) super(pointer) } @@ -56,6 +56,6 @@ export class TSNamedTupleMember extends TypeNode { export function isTSNamedTupleMember(node: AstNode): node is TSNamedTupleMember { return node instanceof TSNamedTupleMember } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_NAMED_TUPLE_MEMBER)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_NAMED_TUPLE_MEMBER, TSNamedTupleMember) -} +if (!nodeByType.has(135)) { + nodeByType.set(135, TSNamedTupleMember) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSNeverKeyword.ts b/koala-wrapper/src/generated/peers/TSNeverKeyword.ts index 039db43d4..39b7de7ff 100644 --- a/koala-wrapper/src/generated/peers/TSNeverKeyword.ts +++ b/koala-wrapper/src/generated/peers/TSNeverKeyword.ts @@ -32,7 +32,7 @@ import { import { TypeNode } from "./TypeNode" export class TSNeverKeyword extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_NEVER_KEYWORD) + assertValidPeer(pointer, 99) super(pointer) } @@ -46,6 +46,6 @@ export class TSNeverKeyword extends TypeNode { export function isTSNeverKeyword(node: AstNode): node is TSNeverKeyword { return node instanceof TSNeverKeyword } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_NEVER_KEYWORD)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_NEVER_KEYWORD, TSNeverKeyword) -} +if (!nodeByType.has(99)) { + nodeByType.set(99, TSNeverKeyword) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSNonNullExpression.ts b/koala-wrapper/src/generated/peers/TSNonNullExpression.ts index 6ed71ba17..21bc3e670 100644 --- a/koala-wrapper/src/generated/peers/TSNonNullExpression.ts +++ b/koala-wrapper/src/generated/peers/TSNonNullExpression.ts @@ -32,7 +32,7 @@ import { import { Expression } from "./Expression" export class TSNonNullExpression extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_NON_NULL_EXPRESSION) + assertValidPeer(pointer, 100) super(pointer) } @@ -54,6 +54,6 @@ export class TSNonNullExpression extends Expression { export function isTSNonNullExpression(node: AstNode): node is TSNonNullExpression { return node instanceof TSNonNullExpression } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_NON_NULL_EXPRESSION)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_NON_NULL_EXPRESSION, TSNonNullExpression) -} +if (!nodeByType.has(100)) { + nodeByType.set(100, TSNonNullExpression) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSNullKeyword.ts b/koala-wrapper/src/generated/peers/TSNullKeyword.ts index 2abd26dfe..c3b161938 100644 --- a/koala-wrapper/src/generated/peers/TSNullKeyword.ts +++ b/koala-wrapper/src/generated/peers/TSNullKeyword.ts @@ -32,7 +32,7 @@ import { import { TypeNode } from "./TypeNode" export class TSNullKeyword extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_NULL_KEYWORD) + assertValidPeer(pointer, 101) super(pointer) } @@ -46,6 +46,6 @@ export class TSNullKeyword extends TypeNode { export function isTSNullKeyword(node: AstNode): node is TSNullKeyword { return node instanceof TSNullKeyword } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_NULL_KEYWORD)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_NULL_KEYWORD, TSNullKeyword) -} +if (!nodeByType.has(101)) { + nodeByType.set(101, TSNullKeyword) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSNumberKeyword.ts b/koala-wrapper/src/generated/peers/TSNumberKeyword.ts index 6620e5c98..ff3c783af 100644 --- a/koala-wrapper/src/generated/peers/TSNumberKeyword.ts +++ b/koala-wrapper/src/generated/peers/TSNumberKeyword.ts @@ -32,7 +32,7 @@ import { import { TypeNode } from "./TypeNode" export class TSNumberKeyword extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_NUMBER_KEYWORD) + assertValidPeer(pointer, 90) super(pointer) } @@ -46,6 +46,6 @@ export class TSNumberKeyword extends TypeNode { export function isTSNumberKeyword(node: AstNode): node is TSNumberKeyword { return node instanceof TSNumberKeyword } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_NUMBER_KEYWORD)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_NUMBER_KEYWORD, TSNumberKeyword) -} +if (!nodeByType.has(90)) { + nodeByType.set(90, TSNumberKeyword) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSObjectKeyword.ts b/koala-wrapper/src/generated/peers/TSObjectKeyword.ts index 0a345482b..2279f62af 100644 --- a/koala-wrapper/src/generated/peers/TSObjectKeyword.ts +++ b/koala-wrapper/src/generated/peers/TSObjectKeyword.ts @@ -32,7 +32,7 @@ import { import { TypeNode } from "./TypeNode" export class TSObjectKeyword extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_OBJECT_KEYWORD) + assertValidPeer(pointer, 97) super(pointer) } @@ -46,6 +46,6 @@ export class TSObjectKeyword extends TypeNode { export function isTSObjectKeyword(node: AstNode): node is TSObjectKeyword { return node instanceof TSObjectKeyword } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_OBJECT_KEYWORD)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_OBJECT_KEYWORD, TSObjectKeyword) -} +if (!nodeByType.has(97)) { + nodeByType.set(97, TSObjectKeyword) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSParameterProperty.ts b/koala-wrapper/src/generated/peers/TSParameterProperty.ts index fc86857ec..9efa642c8 100644 --- a/koala-wrapper/src/generated/peers/TSParameterProperty.ts +++ b/koala-wrapper/src/generated/peers/TSParameterProperty.ts @@ -33,7 +33,7 @@ import { Expression } from "./Expression" import { Es2pandaAccessibilityOption } from "./../Es2pandaEnums" export class TSParameterProperty extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_PARAMETER_PROPERTY) + assertValidPeer(pointer, 122) super(pointer) } @@ -62,6 +62,6 @@ export class TSParameterProperty extends Expression { export function isTSParameterProperty(node: AstNode): node is TSParameterProperty { return node instanceof TSParameterProperty } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_PARAMETER_PROPERTY)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_PARAMETER_PROPERTY, TSParameterProperty) -} +if (!nodeByType.has(122)) { + nodeByType.set(122, TSParameterProperty) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSParenthesizedType.ts b/koala-wrapper/src/generated/peers/TSParenthesizedType.ts index 1171f2f04..043431f71 100644 --- a/koala-wrapper/src/generated/peers/TSParenthesizedType.ts +++ b/koala-wrapper/src/generated/peers/TSParenthesizedType.ts @@ -33,7 +33,7 @@ import { TypeNode } from "./TypeNode" import { Expression } from "./Expression" export class TSParenthesizedType extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_PARENT_TYPE) + assertValidPeer(pointer, 108) super(pointer) } @@ -50,6 +50,6 @@ export class TSParenthesizedType extends TypeNode { export function isTSParenthesizedType(node: AstNode): node is TSParenthesizedType { return node instanceof TSParenthesizedType } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_PARENT_TYPE)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_PARENT_TYPE, TSParenthesizedType) -} +if (!nodeByType.has(108)) { + nodeByType.set(108, TSParenthesizedType) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSPropertySignature.ts b/koala-wrapper/src/generated/peers/TSPropertySignature.ts index cf57e262d..b2725a964 100644 --- a/koala-wrapper/src/generated/peers/TSPropertySignature.ts +++ b/koala-wrapper/src/generated/peers/TSPropertySignature.ts @@ -34,7 +34,7 @@ import { Expression } from "./Expression" import { TypeNode } from "./TypeNode" export class TSPropertySignature extends AnnotatedAstNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_PROPERTY_SIGNATURE) + assertValidPeer(pointer, 105) super(pointer) } @@ -68,6 +68,6 @@ export class TSPropertySignature extends AnnotatedAstNode { export function isTSPropertySignature(node: AstNode): node is TSPropertySignature { return node instanceof TSPropertySignature } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_PROPERTY_SIGNATURE)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_PROPERTY_SIGNATURE, TSPropertySignature) -} +if (!nodeByType.has(105)) { + nodeByType.set(105, TSPropertySignature) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSQualifiedName.ts b/koala-wrapper/src/generated/peers/TSQualifiedName.ts index e9e4806ef..e0f4d87ea 100644 --- a/koala-wrapper/src/generated/peers/TSQualifiedName.ts +++ b/koala-wrapper/src/generated/peers/TSQualifiedName.ts @@ -33,7 +33,7 @@ import { Expression } from "./Expression" import { Identifier } from "./Identifier" export class TSQualifiedName extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_QUALIFIED_NAME) + assertValidPeer(pointer, 129) super(pointer) } @@ -53,6 +53,6 @@ export class TSQualifiedName extends Expression { export function isTSQualifiedName(node: AstNode): node is TSQualifiedName { return node instanceof TSQualifiedName } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_QUALIFIED_NAME)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_QUALIFIED_NAME, TSQualifiedName) -} +if (!nodeByType.has(129)) { + nodeByType.set(129, TSQualifiedName) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSSignatureDeclaration.ts b/koala-wrapper/src/generated/peers/TSSignatureDeclaration.ts index 053a2dc3d..e70bbf176 100644 --- a/koala-wrapper/src/generated/peers/TSSignatureDeclaration.ts +++ b/koala-wrapper/src/generated/peers/TSSignatureDeclaration.ts @@ -37,7 +37,7 @@ import { Expression } from "./Expression" import { TypeNode } from "./TypeNode" export class TSSignatureDeclaration extends TypedAstNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_SIGNATURE_DECLARATION) + assertValidPeer(pointer, 107) super(pointer) } @@ -63,6 +63,6 @@ export class TSSignatureDeclaration extends TypedAstNode { export function isTSSignatureDeclaration(node: AstNode): node is TSSignatureDeclaration { return node instanceof TSSignatureDeclaration } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_SIGNATURE_DECLARATION)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_SIGNATURE_DECLARATION, TSSignatureDeclaration) -} +if (!nodeByType.has(107)) { + nodeByType.set(107, TSSignatureDeclaration) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSStringKeyword.ts b/koala-wrapper/src/generated/peers/TSStringKeyword.ts index 71fb6c6b1..6f749be33 100644 --- a/koala-wrapper/src/generated/peers/TSStringKeyword.ts +++ b/koala-wrapper/src/generated/peers/TSStringKeyword.ts @@ -32,7 +32,7 @@ import { import { TypeNode } from "./TypeNode" export class TSStringKeyword extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_STRING_KEYWORD) + assertValidPeer(pointer, 92) super(pointer) } @@ -46,6 +46,6 @@ export class TSStringKeyword extends TypeNode { export function isTSStringKeyword(node: AstNode): node is TSStringKeyword { return node instanceof TSStringKeyword } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_STRING_KEYWORD)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_STRING_KEYWORD, TSStringKeyword) -} +if (!nodeByType.has(92)) { + nodeByType.set(92, TSStringKeyword) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSThisType.ts b/koala-wrapper/src/generated/peers/TSThisType.ts index 7a87d159c..e57be0ab0 100644 --- a/koala-wrapper/src/generated/peers/TSThisType.ts +++ b/koala-wrapper/src/generated/peers/TSThisType.ts @@ -32,7 +32,7 @@ import { import { TypeNode } from "./TypeNode" export class TSThisType extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_THIS_TYPE) + assertValidPeer(pointer, 116) super(pointer) } @@ -46,6 +46,6 @@ export class TSThisType extends TypeNode { export function isTSThisType(node: AstNode): node is TSThisType { return node instanceof TSThisType } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_THIS_TYPE)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_THIS_TYPE, TSThisType) -} +if (!nodeByType.has(116)) { + nodeByType.set(116, TSThisType) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSTupleType.ts b/koala-wrapper/src/generated/peers/TSTupleType.ts index 8780f3e66..11bafff08 100644 --- a/koala-wrapper/src/generated/peers/TSTupleType.ts +++ b/koala-wrapper/src/generated/peers/TSTupleType.ts @@ -32,7 +32,7 @@ import { import { TypeNode } from "./TypeNode" export class TSTupleType extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_TUPLE_TYPE) + assertValidPeer(pointer, 134) super(pointer) } @@ -49,6 +49,6 @@ export class TSTupleType extends TypeNode { export function isTSTupleType(node: AstNode): node is TSTupleType { return node instanceof TSTupleType } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_TUPLE_TYPE)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_TUPLE_TYPE, TSTupleType) -} +if (!nodeByType.has(134)) { + nodeByType.set(134, TSTupleType) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSTypeAliasDeclaration.ts b/koala-wrapper/src/generated/peers/TSTypeAliasDeclaration.ts index 025686869..58e381c2d 100644 --- a/koala-wrapper/src/generated/peers/TSTypeAliasDeclaration.ts +++ b/koala-wrapper/src/generated/peers/TSTypeAliasDeclaration.ts @@ -37,7 +37,7 @@ import { Decorator } from "./Decorator" import { AnnotationUsage } from "./AnnotationUsage" export class TSTypeAliasDeclaration extends AnnotatedStatement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_ALIAS_DECLARATION) + assertValidPeer(pointer, 127) super(pointer) } @@ -87,6 +87,6 @@ export class TSTypeAliasDeclaration extends AnnotatedStatement { export function isTSTypeAliasDeclaration(node: AstNode): node is TSTypeAliasDeclaration { return node instanceof TSTypeAliasDeclaration } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_ALIAS_DECLARATION)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_ALIAS_DECLARATION, TSTypeAliasDeclaration) -} +if (!nodeByType.has(127)) { + nodeByType.set(127, TSTypeAliasDeclaration) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSTypeAssertion.ts b/koala-wrapper/src/generated/peers/TSTypeAssertion.ts index 05bb8207b..e01615f9b 100644 --- a/koala-wrapper/src/generated/peers/TSTypeAssertion.ts +++ b/koala-wrapper/src/generated/peers/TSTypeAssertion.ts @@ -34,7 +34,7 @@ import { TypeNode } from "./TypeNode" import { Expression } from "./Expression" export class TSTypeAssertion extends AnnotatedExpression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_ASSERTION) + assertValidPeer(pointer, 140) super(pointer) } @@ -59,6 +59,6 @@ export class TSTypeAssertion extends AnnotatedExpression { export function isTSTypeAssertion(node: AstNode): node is TSTypeAssertion { return node instanceof TSTypeAssertion } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_ASSERTION)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_ASSERTION, TSTypeAssertion) -} +if (!nodeByType.has(140)) { + nodeByType.set(140, TSTypeAssertion) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSTypeLiteral.ts b/koala-wrapper/src/generated/peers/TSTypeLiteral.ts index c6f790a26..20e3a4f22 100644 --- a/koala-wrapper/src/generated/peers/TSTypeLiteral.ts +++ b/koala-wrapper/src/generated/peers/TSTypeLiteral.ts @@ -32,7 +32,7 @@ import { import { TypeNode } from "./TypeNode" export class TSTypeLiteral extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_LITERAL_TYPE) + assertValidPeer(pointer, 104) super(pointer) } @@ -49,6 +49,6 @@ export class TSTypeLiteral extends TypeNode { export function isTSTypeLiteral(node: AstNode): node is TSTypeLiteral { return node instanceof TSTypeLiteral } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_LITERAL_TYPE)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_LITERAL_TYPE, TSTypeLiteral) -} +if (!nodeByType.has(104)) { + nodeByType.set(104, TSTypeLiteral) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSTypeOperator.ts b/koala-wrapper/src/generated/peers/TSTypeOperator.ts index e082c1075..3f94d244f 100644 --- a/koala-wrapper/src/generated/peers/TSTypeOperator.ts +++ b/koala-wrapper/src/generated/peers/TSTypeOperator.ts @@ -33,7 +33,7 @@ import { TypeNode } from "./TypeNode" import { Es2pandaTSOperatorType } from "./../Es2pandaEnums" export class TSTypeOperator extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_OPERATOR) + assertValidPeer(pointer, 117) super(pointer) } @@ -59,6 +59,6 @@ export class TSTypeOperator extends TypeNode { export function isTSTypeOperator(node: AstNode): node is TSTypeOperator { return node instanceof TSTypeOperator } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_OPERATOR)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_OPERATOR, TSTypeOperator) +if (!nodeByType.has(117)) { + nodeByType.set(117, TSTypeOperator) } \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSTypeParameter.ts b/koala-wrapper/src/generated/peers/TSTypeParameter.ts index 7451ad017..28012faf1 100644 --- a/koala-wrapper/src/generated/peers/TSTypeParameter.ts +++ b/koala-wrapper/src/generated/peers/TSTypeParameter.ts @@ -36,7 +36,7 @@ import { Es2pandaModifierFlags } from "./../Es2pandaEnums" import { AnnotationUsage } from "./AnnotationUsage" export class TSTypeParameter extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_PARAMETER) + assertValidPeer(pointer, 118) super(pointer) } @@ -83,6 +83,6 @@ export class TSTypeParameter extends Expression { export function isTSTypeParameter(node: AstNode): node is TSTypeParameter { return node instanceof TSTypeParameter } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_PARAMETER)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_PARAMETER, TSTypeParameter) +if (!nodeByType.has(118)) { + nodeByType.set(118, TSTypeParameter) } \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSTypeParameterDeclaration.ts b/koala-wrapper/src/generated/peers/TSTypeParameterDeclaration.ts index 61f91a8b6..59f4ab594 100644 --- a/koala-wrapper/src/generated/peers/TSTypeParameterDeclaration.ts +++ b/koala-wrapper/src/generated/peers/TSTypeParameterDeclaration.ts @@ -33,7 +33,7 @@ import { Expression } from "./Expression" import { TSTypeParameter } from "./TSTypeParameter" export class TSTypeParameterDeclaration extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_PARAMETER_DECLARATION) + assertValidPeer(pointer, 119) super(pointer) } @@ -58,6 +58,6 @@ export class TSTypeParameterDeclaration extends Expression { export function isTSTypeParameterDeclaration(node: AstNode): node is TSTypeParameterDeclaration { return node instanceof TSTypeParameterDeclaration } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_PARAMETER_DECLARATION)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_PARAMETER_DECLARATION, TSTypeParameterDeclaration) +if (!nodeByType.has(119)) { + nodeByType.set(119, TSTypeParameterDeclaration) } \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSTypeParameterInstantiation.ts b/koala-wrapper/src/generated/peers/TSTypeParameterInstantiation.ts index 8c30a3aa0..b6a23b329 100644 --- a/koala-wrapper/src/generated/peers/TSTypeParameterInstantiation.ts +++ b/koala-wrapper/src/generated/peers/TSTypeParameterInstantiation.ts @@ -33,7 +33,7 @@ import { Expression } from "./Expression" import { TypeNode } from "./TypeNode" export class TSTypeParameterInstantiation extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_PARAMETER_INSTANTIATION) + assertValidPeer(pointer, 120) super(pointer) } @@ -50,6 +50,6 @@ export class TSTypeParameterInstantiation extends Expression { export function isTSTypeParameterInstantiation(node: AstNode): node is TSTypeParameterInstantiation { return node instanceof TSTypeParameterInstantiation } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_PARAMETER_INSTANTIATION)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_PARAMETER_INSTANTIATION, TSTypeParameterInstantiation) +if (!nodeByType.has(120)) { + nodeByType.set(120, TSTypeParameterInstantiation) } \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSTypePredicate.ts b/koala-wrapper/src/generated/peers/TSTypePredicate.ts index 27ce97a73..551d62f98 100644 --- a/koala-wrapper/src/generated/peers/TSTypePredicate.ts +++ b/koala-wrapper/src/generated/peers/TSTypePredicate.ts @@ -33,7 +33,7 @@ import { TypeNode } from "./TypeNode" import { Expression } from "./Expression" export class TSTypePredicate extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_PREDICATE) + assertValidPeer(pointer, 121) super(pointer) } @@ -56,6 +56,6 @@ export class TSTypePredicate extends TypeNode { export function isTSTypePredicate(node: AstNode): node is TSTypePredicate { return node instanceof TSTypePredicate } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_PREDICATE)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_PREDICATE, TSTypePredicate) +if (!nodeByType.has(121)) { + nodeByType.set(121, TSTypePredicate) } \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSTypeQuery.ts b/koala-wrapper/src/generated/peers/TSTypeQuery.ts index 603124f7f..d4576d1fa 100644 --- a/koala-wrapper/src/generated/peers/TSTypeQuery.ts +++ b/koala-wrapper/src/generated/peers/TSTypeQuery.ts @@ -33,7 +33,7 @@ import { TypeNode } from "./TypeNode" import { Expression } from "./Expression" export class TSTypeQuery extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_QUERY) + assertValidPeer(pointer, 137) super(pointer) } @@ -50,6 +50,6 @@ export class TSTypeQuery extends TypeNode { export function isTSTypeQuery(node: AstNode): node is TSTypeQuery { return node instanceof TSTypeQuery } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_QUERY)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_QUERY, TSTypeQuery) +if (!nodeByType.has(137)) { + nodeByType.set(137, TSTypeQuery) } \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSTypeReference.ts b/koala-wrapper/src/generated/peers/TSTypeReference.ts index f70f708c7..50e62aafb 100644 --- a/koala-wrapper/src/generated/peers/TSTypeReference.ts +++ b/koala-wrapper/src/generated/peers/TSTypeReference.ts @@ -35,7 +35,7 @@ import { TSTypeParameterInstantiation } from "./TSTypeParameterInstantiation" import { Identifier } from "./Identifier" export class TSTypeReference extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_REFERENCE) + assertValidPeer(pointer, 128) super(pointer) } @@ -55,6 +55,6 @@ export class TSTypeReference extends TypeNode { export function isTSTypeReference(node: AstNode): node is TSTypeReference { return node instanceof TSTypeReference } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_REFERENCE)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_TYPE_REFERENCE, TSTypeReference) +if (!nodeByType.has(128)) { + nodeByType.set(128, TSTypeReference) } \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSUndefinedKeyword.ts b/koala-wrapper/src/generated/peers/TSUndefinedKeyword.ts index c7809258a..9129d02d9 100644 --- a/koala-wrapper/src/generated/peers/TSUndefinedKeyword.ts +++ b/koala-wrapper/src/generated/peers/TSUndefinedKeyword.ts @@ -32,7 +32,7 @@ import { import { TypeNode } from "./TypeNode" export class TSUndefinedKeyword extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_UNDEFINED_KEYWORD) + assertValidPeer(pointer, 95) super(pointer) } @@ -46,6 +46,6 @@ export class TSUndefinedKeyword extends TypeNode { export function isTSUndefinedKeyword(node: AstNode): node is TSUndefinedKeyword { return node instanceof TSUndefinedKeyword } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_UNDEFINED_KEYWORD)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_UNDEFINED_KEYWORD, TSUndefinedKeyword) +if (!nodeByType.has(95)) { + nodeByType.set(95, TSUndefinedKeyword) } \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSUnionType.ts b/koala-wrapper/src/generated/peers/TSUnionType.ts index df5479501..406ecc416 100644 --- a/koala-wrapper/src/generated/peers/TSUnionType.ts +++ b/koala-wrapper/src/generated/peers/TSUnionType.ts @@ -32,7 +32,7 @@ import { import { TypeNode } from "./TypeNode" export class TSUnionType extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_UNION_TYPE) + assertValidPeer(pointer, 103) super(pointer) } @@ -49,6 +49,6 @@ export class TSUnionType extends TypeNode { export function isTSUnionType(node: AstNode): node is TSUnionType { return node instanceof TSUnionType } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_UNION_TYPE)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_UNION_TYPE, TSUnionType) +if (!nodeByType.has(103)) { + nodeByType.set(103, TSUnionType) } \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSUnknownKeyword.ts b/koala-wrapper/src/generated/peers/TSUnknownKeyword.ts index 0eb71b7d2..0371b243c 100644 --- a/koala-wrapper/src/generated/peers/TSUnknownKeyword.ts +++ b/koala-wrapper/src/generated/peers/TSUnknownKeyword.ts @@ -32,7 +32,7 @@ import { import { TypeNode } from "./TypeNode" export class TSUnknownKeyword extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_UNKNOWN_KEYWORD) + assertValidPeer(pointer, 96) super(pointer) } @@ -46,6 +46,6 @@ export class TSUnknownKeyword extends TypeNode { export function isTSUnknownKeyword(node: AstNode): node is TSUnknownKeyword { return node instanceof TSUnknownKeyword } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_UNKNOWN_KEYWORD)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_UNKNOWN_KEYWORD, TSUnknownKeyword) +if (!nodeByType.has(96)) { + nodeByType.set(96, TSUnknownKeyword) } \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TSVoidKeyword.ts b/koala-wrapper/src/generated/peers/TSVoidKeyword.ts index 1cfe4091d..605cceb11 100644 --- a/koala-wrapper/src/generated/peers/TSVoidKeyword.ts +++ b/koala-wrapper/src/generated/peers/TSVoidKeyword.ts @@ -32,7 +32,7 @@ import { import { TypeNode } from "./TypeNode" export class TSVoidKeyword extends TypeNode { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TS_VOID_KEYWORD) + assertValidPeer(pointer, 94) super(pointer) } @@ -46,6 +46,6 @@ export class TSVoidKeyword extends TypeNode { export function isTSVoidKeyword(node: AstNode): node is TSVoidKeyword { return node instanceof TSVoidKeyword } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TS_VOID_KEYWORD)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TS_VOID_KEYWORD, TSVoidKeyword) +if (!nodeByType.has(94)) { + nodeByType.set(94, TSVoidKeyword) } \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TaggedTemplateExpression.ts b/koala-wrapper/src/generated/peers/TaggedTemplateExpression.ts index 1f1a7dcc1..0ccbf0f08 100644 --- a/koala-wrapper/src/generated/peers/TaggedTemplateExpression.ts +++ b/koala-wrapper/src/generated/peers/TaggedTemplateExpression.ts @@ -34,7 +34,7 @@ import { TemplateLiteral } from "./TemplateLiteral" import { TSTypeParameterInstantiation } from "./TSTypeParameterInstantiation" export class TaggedTemplateExpression extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TAGGED_TEMPLATE_EXPRESSION) + assertValidPeer(pointer, 141) super(pointer) } @@ -57,6 +57,6 @@ export class TaggedTemplateExpression extends Expression { export function isTaggedTemplateExpression(node: AstNode): node is TaggedTemplateExpression { return node instanceof TaggedTemplateExpression } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TAGGED_TEMPLATE_EXPRESSION)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TAGGED_TEMPLATE_EXPRESSION, TaggedTemplateExpression) -} +if (!nodeByType.has(141)) { + nodeByType.set(141, TaggedTemplateExpression) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TemplateElement.ts b/koala-wrapper/src/generated/peers/TemplateElement.ts index 32602cccc..0c4108f47 100644 --- a/koala-wrapper/src/generated/peers/TemplateElement.ts +++ b/koala-wrapper/src/generated/peers/TemplateElement.ts @@ -32,7 +32,7 @@ import { import { Expression } from "./Expression" export class TemplateElement extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TEMPLATE_ELEMENT) + assertValidPeer(pointer, 142) super(pointer) } @@ -58,6 +58,6 @@ export class TemplateElement extends Expression { export function isTemplateElement(node: AstNode): node is TemplateElement { return node instanceof TemplateElement } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TEMPLATE_ELEMENT)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TEMPLATE_ELEMENT, TemplateElement) -} +if (!nodeByType.has(142)) { + nodeByType.set(142, TemplateElement) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TemplateLiteral.ts b/koala-wrapper/src/generated/peers/TemplateLiteral.ts index b51bb606f..58039a87e 100644 --- a/koala-wrapper/src/generated/peers/TemplateLiteral.ts +++ b/koala-wrapper/src/generated/peers/TemplateLiteral.ts @@ -33,7 +33,7 @@ import { Expression } from "./Expression" import { TemplateElement } from "./TemplateElement" export class TemplateLiteral extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TEMPLATE_LITERAL) + assertValidPeer(pointer, 143) super(pointer) } @@ -49,13 +49,10 @@ export class TemplateLiteral extends Expression { get expressions(): readonly Expression[] { return unpackNodeArray(global.generatedEs2panda._TemplateLiteralExpressionsConst(global.context, this.peer)) } - get multilineString(): string { - return unpackString(global.generatedEs2panda._TemplateLiteralGetMultilineStringConst(global.context, this.peer)); - } } export function isTemplateLiteral(node: AstNode): node is TemplateLiteral { return node instanceof TemplateLiteral } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TEMPLATE_LITERAL)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TEMPLATE_LITERAL, TemplateLiteral) -} +if (!nodeByType.has(143)) { + nodeByType.set(143, TemplateLiteral) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ThisExpression.ts b/koala-wrapper/src/generated/peers/ThisExpression.ts index c16668c4f..1ec6476d8 100644 --- a/koala-wrapper/src/generated/peers/ThisExpression.ts +++ b/koala-wrapper/src/generated/peers/ThisExpression.ts @@ -32,7 +32,7 @@ import { import { Expression } from "./Expression" export class ThisExpression extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_THIS_EXPRESSION) + assertValidPeer(pointer, 144) super(pointer) } @@ -46,6 +46,6 @@ export class ThisExpression extends Expression { export function isThisExpression(node: AstNode): node is ThisExpression { return node instanceof ThisExpression } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_THIS_EXPRESSION)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_THIS_EXPRESSION, ThisExpression) -} +if (!nodeByType.has(144)) { + nodeByType.set(144, ThisExpression) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/ThrowStatement.ts b/koala-wrapper/src/generated/peers/ThrowStatement.ts index e4f40a1fb..74cc30e59 100644 --- a/koala-wrapper/src/generated/peers/ThrowStatement.ts +++ b/koala-wrapper/src/generated/peers/ThrowStatement.ts @@ -33,7 +33,7 @@ import { Statement } from "./Statement" import { Expression } from "./Expression" export class ThrowStatement extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_THROW_STATEMENT) + assertValidPeer(pointer, 146) super(pointer) } @@ -50,6 +50,6 @@ export class ThrowStatement extends Statement { export function isThrowStatement(node: AstNode): node is ThrowStatement { return node instanceof ThrowStatement } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_THROW_STATEMENT)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_THROW_STATEMENT, ThrowStatement) -} +if (!nodeByType.has(146)) { + nodeByType.set(146, ThrowStatement) +} \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TryStatement.ts b/koala-wrapper/src/generated/peers/TryStatement.ts index 5c7c1a756..c855b8bfa 100644 --- a/koala-wrapper/src/generated/peers/TryStatement.ts +++ b/koala-wrapper/src/generated/peers/TryStatement.ts @@ -22,30 +22,21 @@ import { unpackNodeArray, assertValidPeer, AstNode, + Es2pandaAstNodeType, KNativePointer, nodeByType, ArktsObject, - unpackString, - Es2pandaAstNodeType -} from "../../reexport-for-generated"; + unpackString +} from "../../reexport-for-generated" -import { BlockStatement } from "./BlockStatement"; -import { CatchClause } from "./CatchClause"; -import { LabelPair } from "./LabelPair"; -import { Statement } from "./Statement"; +import { Statement } from "./Statement" +import { BlockStatement } from "./BlockStatement" +import { CatchClause } from "./CatchClause" export class TryStatement extends Statement { - constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TRY_STATEMENT) + constructor(pointer: KNativePointer) { + assertValidPeer(pointer, 147) super(pointer) - } - static createTryStatement(block: BlockStatement | undefined, catchClauses: readonly CatchClause[], finalizer: BlockStatement | undefined, finalizerInsertionsLabelPair: readonly LabelPair[], finalizerInsertionsStatement: readonly Statement[]): TryStatement { - return new TryStatement(global.generatedEs2panda._CreateTryStatement(global.context, passNode(block), passNodeArray(catchClauses), catchClauses.length, passNode(finalizer), passNodeArray(finalizerInsertionsLabelPair), finalizerInsertionsLabelPair.length, passNodeArray(finalizerInsertionsStatement), finalizerInsertionsStatement.length)) - } - static updateTryStatement(original: TryStatement | undefined, block: BlockStatement | undefined, catchClauses: readonly CatchClause[], finalizer: BlockStatement | undefined, finalizerInsertionsLabelPair: readonly LabelPair[], finalizerInsertionsStatement: readonly Statement[]): TryStatement { - return new TryStatement(global.generatedEs2panda._UpdateTryStatement(global.context, passNode(original), passNode(block), passNodeArray(catchClauses), catchClauses.length, passNode(finalizer), passNodeArray(finalizerInsertionsLabelPair), finalizerInsertionsLabelPair.length, passNodeArray(finalizerInsertionsStatement), finalizerInsertionsStatement.length)) - } - static update1TryStatement(original?: TryStatement, other?: TryStatement): TryStatement { - return new TryStatement(global.generatedEs2panda._UpdateTryStatement1(global.context, passNode(original), passNode(other))) + } get finallyBlock(): BlockStatement | undefined { return unpackNode(global.generatedEs2panda._TryStatementFinallyBlockConst(global.context, this.peer)) @@ -56,9 +47,6 @@ export class TryStatement extends Statement { get hasFinalizer(): boolean { return global.generatedEs2panda._TryStatementHasFinalizerConst(global.context, this.peer) } - get hasDefaultCatchClause(): boolean { - return global.generatedEs2panda._TryStatementHasDefaultCatchClauseConst(global.context, this.peer); - } get catchClauses(): readonly CatchClause[] { return unpackNodeArray(global.generatedEs2panda._TryStatementCatchClausesConst(global.context, this.peer)) } @@ -71,9 +59,9 @@ export class TryStatement extends Statement { return this } } -export function isTryStatement(node: object | undefined): node is TryStatement { +export function isTryStatement(node: AstNode): node is TryStatement { return node instanceof TryStatement } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TRY_STATEMENT)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TRY_STATEMENT, TryStatement) +if (!nodeByType.has(147)) { + nodeByType.set(147, TryStatement) } \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/TypeofExpression.ts b/koala-wrapper/src/generated/peers/TypeofExpression.ts index 8496fe19c..0c80ae8e8 100644 --- a/koala-wrapper/src/generated/peers/TypeofExpression.ts +++ b/koala-wrapper/src/generated/peers/TypeofExpression.ts @@ -32,7 +32,7 @@ import { import { Expression } from "./Expression" export class TypeofExpression extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_TYPEOF_EXPRESSION) + assertValidPeer(pointer, 145) super(pointer) } @@ -49,6 +49,6 @@ export class TypeofExpression extends Expression { export function isTypeofExpression(node: AstNode): node is TypeofExpression { return node instanceof TypeofExpression } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_TYPEOF_EXPRESSION)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_TYPEOF_EXPRESSION, TypeofExpression) +if (!nodeByType.has(145)) { + nodeByType.set(145, TypeofExpression) } \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/UnaryExpression.ts b/koala-wrapper/src/generated/peers/UnaryExpression.ts index 88a9071dc..2b2d1aec7 100644 --- a/koala-wrapper/src/generated/peers/UnaryExpression.ts +++ b/koala-wrapper/src/generated/peers/UnaryExpression.ts @@ -33,7 +33,7 @@ import { Expression } from "./Expression" import { Es2pandaTokenType } from "./../Es2pandaEnums" export class UnaryExpression extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_UNARY_EXPRESSION) + assertValidPeer(pointer, 148) super(pointer) } @@ -53,6 +53,6 @@ export class UnaryExpression extends Expression { export function isUnaryExpression(node: AstNode): node is UnaryExpression { return node instanceof UnaryExpression } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_UNARY_EXPRESSION)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_UNARY_EXPRESSION, UnaryExpression) +if (!nodeByType.has(148)) { + nodeByType.set(148, UnaryExpression) } \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/UndefinedLiteral.ts b/koala-wrapper/src/generated/peers/UndefinedLiteral.ts index b50432720..833805c1f 100644 --- a/koala-wrapper/src/generated/peers/UndefinedLiteral.ts +++ b/koala-wrapper/src/generated/peers/UndefinedLiteral.ts @@ -32,7 +32,7 @@ import { import { Literal } from "./Literal" export class UndefinedLiteral extends Literal { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_UNDEFINED_LITERAL) + assertValidPeer(pointer, 51) super(pointer) } @@ -46,6 +46,6 @@ export class UndefinedLiteral extends Literal { export function isUndefinedLiteral(node: AstNode): node is UndefinedLiteral { return node instanceof UndefinedLiteral } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_UNDEFINED_LITERAL)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_UNDEFINED_LITERAL, UndefinedLiteral) +if (!nodeByType.has(51)) { + nodeByType.set(51, UndefinedLiteral) } \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/UpdateExpression.ts b/koala-wrapper/src/generated/peers/UpdateExpression.ts index 30d9f1839..5c1b8d6f1 100644 --- a/koala-wrapper/src/generated/peers/UpdateExpression.ts +++ b/koala-wrapper/src/generated/peers/UpdateExpression.ts @@ -33,7 +33,7 @@ import { Expression } from "./Expression" import { Es2pandaTokenType } from "./../Es2pandaEnums" export class UpdateExpression extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_UPDATE_EXPRESSION) + assertValidPeer(pointer, 149) super(pointer) } @@ -56,6 +56,6 @@ export class UpdateExpression extends Expression { export function isUpdateExpression(node: AstNode): node is UpdateExpression { return node instanceof UpdateExpression } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_UPDATE_EXPRESSION)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_UPDATE_EXPRESSION, UpdateExpression) +if (!nodeByType.has(149)) { + nodeByType.set(149, UpdateExpression) } \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/VariableDeclaration.ts b/koala-wrapper/src/generated/peers/VariableDeclaration.ts index 6699e1f55..751968ae5 100644 --- a/koala-wrapper/src/generated/peers/VariableDeclaration.ts +++ b/koala-wrapper/src/generated/peers/VariableDeclaration.ts @@ -36,7 +36,7 @@ import { Decorator } from "./Decorator" import { AnnotationUsage } from "./AnnotationUsage" export class VariableDeclaration extends Statement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_VARIABLE_DECLARATION) + assertValidPeer(pointer, 150) super(pointer) } @@ -67,6 +67,6 @@ export class VariableDeclaration extends Statement { export function isVariableDeclaration(node: AstNode): node is VariableDeclaration { return node instanceof VariableDeclaration } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_VARIABLE_DECLARATION)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_VARIABLE_DECLARATION, VariableDeclaration) +if (!nodeByType.has(150)) { + nodeByType.set(150, VariableDeclaration) } \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/VariableDeclarator.ts b/koala-wrapper/src/generated/peers/VariableDeclarator.ts index 3913fc3d6..e0d9cb077 100644 --- a/koala-wrapper/src/generated/peers/VariableDeclarator.ts +++ b/koala-wrapper/src/generated/peers/VariableDeclarator.ts @@ -34,7 +34,7 @@ import { Es2pandaVariableDeclaratorFlag } from "./../Es2pandaEnums" import { Expression } from "./Expression" export class VariableDeclarator extends TypedStatement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_VARIABLE_DECLARATOR) + assertValidPeer(pointer, 151) super(pointer) } @@ -68,6 +68,6 @@ export class VariableDeclarator extends TypedStatement { export function isVariableDeclarator(node: AstNode): node is VariableDeclarator { return node instanceof VariableDeclarator } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_VARIABLE_DECLARATOR)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_VARIABLE_DECLARATOR, VariableDeclarator) +if (!nodeByType.has(151)) { + nodeByType.set(151, VariableDeclarator) } \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/WhileStatement.ts b/koala-wrapper/src/generated/peers/WhileStatement.ts index 548fd8bf2..f71a1d5dd 100644 --- a/koala-wrapper/src/generated/peers/WhileStatement.ts +++ b/koala-wrapper/src/generated/peers/WhileStatement.ts @@ -34,7 +34,7 @@ import { Expression } from "./Expression" import { Statement } from "./Statement" export class WhileStatement extends LoopStatement { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_WHILE_STATEMENT) + assertValidPeer(pointer, 152) super(pointer) } @@ -54,6 +54,6 @@ export class WhileStatement extends LoopStatement { export function isWhileStatement(node: AstNode): node is WhileStatement { return node instanceof WhileStatement } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_WHILE_STATEMENT)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_WHILE_STATEMENT, WhileStatement) +if (!nodeByType.has(152)) { + nodeByType.set(152, WhileStatement) } \ No newline at end of file diff --git a/koala-wrapper/src/generated/peers/YieldExpression.ts b/koala-wrapper/src/generated/peers/YieldExpression.ts index 90846a933..55c0b9022 100644 --- a/koala-wrapper/src/generated/peers/YieldExpression.ts +++ b/koala-wrapper/src/generated/peers/YieldExpression.ts @@ -32,7 +32,7 @@ import { import { Expression } from "./Expression" export class YieldExpression extends Expression { constructor(pointer: KNativePointer) { - assertValidPeer(pointer, Es2pandaAstNodeType.AST_NODE_TYPE_YIELD_EXPRESSION) + assertValidPeer(pointer, 153) super(pointer) } @@ -52,6 +52,6 @@ export class YieldExpression extends Expression { export function isYieldExpression(node: AstNode): node is YieldExpression { return node instanceof YieldExpression } -if (!nodeByType.has(Es2pandaAstNodeType.AST_NODE_TYPE_YIELD_EXPRESSION)) { - nodeByType.set(Es2pandaAstNodeType.AST_NODE_TYPE_YIELD_EXPRESSION, YieldExpression) +if (!nodeByType.has(153)) { + nodeByType.set(153, YieldExpression) } \ No newline at end of file -- Gitee