From 8b34adbc9ca6627bcada4896587ca5bd6913b4f8 Mon Sep 17 00:00:00 2001 From: Aleksandr Veselov Date: Fri, 8 Aug 2025 07:42:34 +0000 Subject: [PATCH 01/39] !1 Tracking PR for libarkts migration Signed-off-by: Aleksandr Veselov --- .../collectors/memo-collectors/factory.ts | 4 +- .../memo-collectors/function-collector.ts | 49 +-- .../collectors/memo-collectors/utils.ts | 211 ++++++------ arkui-plugins/common/arkts-utils.ts | 23 +- arkui-plugins/common/declaration-collector.ts | 6 +- arkui-plugins/common/etsglobal-remover.ts | 4 +- arkui-plugins/common/import-collector.ts | 23 +- arkui-plugins/common/log-collector.ts | 2 +- arkui-plugins/common/node-cache.ts | 100 ++++++ arkui-plugins/common/plugin-context.ts | 6 +- arkui-plugins/common/program-skipper.ts | 12 +- arkui-plugins/common/program-visitor.ts | 52 ++- .../interop-plugins/decl_transformer.ts | 43 +-- .../interop-plugins/emit_transformer.ts | 2 +- arkui-plugins/interop-plugins/index.ts | 21 +- arkui-plugins/interop-plugins/types.ts | 6 +- .../memo-plugins/function-transformer.ts | 133 ++++---- .../memo-plugins/import-transformer.ts | 4 +- arkui-plugins/memo-plugins/index.ts | 11 +- .../memo-plugins/memo-cache-factory.ts | 27 +- arkui-plugins/memo-plugins/memo-factory.ts | 120 ++++--- .../memo-plugins/memo-transformer.ts | 4 +- .../memo-plugins/parameter-transformer.ts | 16 +- .../memo-plugins/return-transformer.ts | 6 +- .../memo-plugins/signature-transformer.ts | 30 +- arkui-plugins/memo-plugins/utils.ts | 28 +- .../test/ut/common/annotation.test.ts | 14 +- arkui-plugins/test/utils/compile.ts | 4 +- .../utils/plugins/before-memo-no-recheck.ts | 4 +- .../plugins/builder-lambda-no-recheck.ts | 4 +- .../test/utils/plugins/memo-no-recheck.ts | 7 +- arkui-plugins/test/utils/plugins/recheck.ts | 4 +- .../test/utils/plugins/struct-no-recheck.ts | 4 +- .../test/utils/plugins/struct-to-component.ts | 4 +- .../test/utils/plugins/ui-no-recheck.ts | 4 +- .../builder-factory.ts | 17 +- .../builder-lambda-transformer.ts | 5 +- .../condition-scope-visitor.ts | 2 +- .../builder-lambda-translators/factory.ts | 276 ++++++++------- .../builder-lambda-translators/utils.ts | 68 ++-- .../ui-plugins/checked-transformer.ts | 15 +- .../ui-plugins/component-transformer.ts | 99 +++--- .../ui-plugins/entry-translators/factory.ts | 167 ++++----- arkui-plugins/ui-plugins/index.ts | 28 +- .../ui-plugins/interop/builder-interop.ts | 135 ++++---- .../ui-plugins/interop/initstatevar.ts | 19 +- arkui-plugins/ui-plugins/interop/interop.ts | 223 ++++++------ .../ui-plugins/interop/legacy-transformer.ts | 123 +++---- arkui-plugins/ui-plugins/interop/utils.ts | 64 ++-- arkui-plugins/ui-plugins/name-collector.ts | 4 +- .../ui-plugins/printer-transformer.ts | 2 +- .../ui-plugins/property-translators/base.ts | 6 +- .../property-translators/builderParam.ts | 47 +-- .../cache/monitorCache.ts | 2 +- .../cache/propertyCache.ts | 6 +- .../property-translators/computed.ts | 12 +- .../property-translators/consume.ts | 12 +- .../property-translators/consumer.ts | 12 +- .../property-translators/factory.ts | 242 +++++++------ .../ui-plugins/property-translators/link.ts | 10 +- .../ui-plugins/property-translators/local.ts | 10 +- .../localStoragePropRef.ts | 24 +- .../property-translators/localstoragelink.ts | 24 +- .../property-translators/monitor.ts | 6 +- .../property-translators/objectlink.ts | 16 +- .../property-translators/observedTrack.ts | 40 ++- .../property-translators/observedV2Trace.ts | 52 +-- .../ui-plugins/property-translators/once.ts | 10 +- .../ui-plugins/property-translators/param.ts | 10 +- .../property-translators/propRef.ts | 10 +- .../property-translators/provide.ts | 12 +- .../property-translators/provider.ts | 12 +- .../property-translators/regularProperty.ts | 16 +- .../ui-plugins/property-translators/state.ts | 10 +- .../property-translators/storagePropRef.ts | 24 +- .../property-translators/storagelink.ts | 16 +- .../ui-plugins/property-translators/types.ts | 2 +- .../ui-plugins/property-translators/utils.ts | 72 ++-- .../ui-plugins/struct-translators/factory.ts | 320 ++++++++++-------- .../struct-translators/struct-transformer.ts | 7 +- .../ui-plugins/struct-translators/utils.ts | 6 +- arkui-plugins/ui-plugins/ui-factory.ts | 126 ++++--- arkui-plugins/ui-plugins/utils.ts | 24 +- arkui-plugins/ui-syntax-plugins/index.ts | 8 +- .../ui-syntax-plugins/processor/index.ts | 4 +- .../rules/build-root-node.ts | 10 +- .../rules/builderparam-decorator-check.ts | 8 +- .../check-construct-private-parameter.ts | 8 +- .../rules/check-decorated-property-type.ts | 4 +- .../rules/check-property-modifiers.ts | 6 +- .../rules/component-componentV2-init-check.ts | 6 +- .../component-componentV2-mix-use-check.ts | 4 +- .../rules/componentV2-mix-check.ts | 2 +- .../componentV2-state-usage-validation.ts | 18 +- .../rules/computed-decorator-check.ts | 30 +- .../rules/construct-parameter-literal.ts | 8 +- .../rules/construct-parameter.ts | 20 +- .../consumer-provider-decorator-check.ts | 26 +- .../rules/custom-dialog-missing-controller.ts | 6 +- .../rules/entry-localstorage-check.ts | 6 +- .../rules/entry-struct-no-export.ts | 2 +- .../rules/main-pages-entry-check.ts | 6 +- .../rules/monitor-decorator-check.ts | 16 +- .../rules/nested-relationship.ts | 2 +- .../rules/nested-reuse-component-check.ts | 28 +- .../rules/no-child-in-button.ts | 2 +- .../rules/no-duplicate-entry.ts | 4 +- .../rules/no-duplicate-id.ts | 2 +- .../rules/no-duplicate-preview.ts | 4 +- .../rules/no-prop-link-objectlink-in-entry.ts | 6 +- .../rules/no-same-as-built-in-attribute.ts | 2 +- .../observedV2-trace-usage-validation.ts | 10 +- .../rules/old-new-decorator-mix-use-check.ts | 10 +- .../rules/once-decorator-check.ts | 6 +- .../rules/one-decorator-on-function-method.ts | 20 +- .../ui-syntax-plugins/rules/property-type.ts | 32 +- .../rules/require-decorator-regular.ts | 6 +- .../rules/reusable-component-in-V2-check.ts | 12 +- .../rules/reusableV2-decorator-check.ts | 4 +- .../rules/reuse-attribute-check.ts | 6 +- .../rules/specific-component-children.ts | 8 +- .../rules/static-param-require.ts | 8 +- .../rules/struct-missing-decorator.ts | 4 +- .../rules/struct-no-extends.ts | 4 +- .../rules/struct-property-decorator.ts | 14 +- .../rules/track-decorator-check.ts | 10 +- .../rules/ui-consistent-check.ts | 40 +-- .../rules/validate-build-in-struct.ts | 22 +- .../rules/validate-decorator-target.ts | 4 +- ...nitialization-via-component-constructor.ts | 16 +- .../rules/watch-decorator-function.ts | 18 +- .../rules/watch-decorator-regular.ts | 6 +- .../rules/wrap-builder-check.ts | 10 +- .../ui-syntax-plugins/utils/index.ts | 8 +- 134 files changed, 2150 insertions(+), 1813 deletions(-) create mode 100644 arkui-plugins/common/node-cache.ts diff --git a/arkui-plugins/collectors/memo-collectors/factory.ts b/arkui-plugins/collectors/memo-collectors/factory.ts index 71546a6ff..475911bd9 100644 --- a/arkui-plugins/collectors/memo-collectors/factory.ts +++ b/arkui-plugins/collectors/memo-collectors/factory.ts @@ -143,7 +143,7 @@ export class factory { let found: boolean = false; if (findCanAddMemoFromMethod(node)) { found = true; - addMemoAnnotation(node.scriptFunction); + addMemoAnnotation(node.function!); } if (found && !!rewriteFn) { return rewriteFn(node, arkts.Es2pandaAstNodeType.AST_NODE_TYPE_METHOD_DEFINITION); @@ -165,7 +165,7 @@ export class factory { let found: boolean = false; if (findCanAddMemoFromArrowFunction(node)) { found = true; - addMemoAnnotation(node.scriptFunction); + addMemoAnnotation(node.function!); } if (found && !!rewriteFn) { return rewriteFn(node, arkts.Es2pandaAstNodeType.AST_NODE_TYPE_ARROW_FUNCTION_EXPRESSION); diff --git a/arkui-plugins/collectors/memo-collectors/function-collector.ts b/arkui-plugins/collectors/memo-collectors/function-collector.ts index 2f9d07b8c..5cffd6186 100644 --- a/arkui-plugins/collectors/memo-collectors/function-collector.ts +++ b/arkui-plugins/collectors/memo-collectors/function-collector.ts @@ -27,6 +27,7 @@ import { getDeclResolveAlias, MemoableInfo, } from './utils'; +import { NodeCache } from '../../common/node-cache'; export class MemoFunctionCollector extends AbstractVisitor { private returnMemoableInfo: MemoableInfo | undefined; @@ -57,14 +58,14 @@ export class MemoFunctionCollector extends AbstractVisitor { private collectMemoAstNode(node: arkts.AstNode, info: MemoableInfo): void { if (checkIsMemoFromMemoableInfo(info, false)) { - arkts.NodeCache.getInstance().collect(node); + NodeCache.getInstance().collect(node); } } private collectCallWithDeclaredPeerInParamMap(node: arkts.CallExpression, peer: arkts.AstNode['peer']): void { const memoableInfo = this.paramMemoableInfoMap!.get(peer)!; if (checkIsMemoFromMemoableInfo(memoableInfo, true)) { - arkts.NodeCache.getInstance().collect(node); + NodeCache.getInstance().collect(node); } } @@ -73,26 +74,26 @@ export class MemoFunctionCollector extends AbstractVisitor { declarator: arkts.VariableDeclarator ): void { const shouldCollect = - arkts.NodeCache.getInstance().has(declarator) || - (!!declarator.initializer && arkts.NodeCache.getInstance().has(declarator.initializer)); + NodeCache.getInstance().has(declarator) || + (!!declarator.init && NodeCache.getInstance().has(declarator.init)); if (shouldCollect) { - arkts.NodeCache.getInstance().collect(node); + NodeCache.getInstance().collect(node); } } private visitVariableDeclarator(node: arkts.VariableDeclarator): arkts.AstNode { let memoableInfo: MemoableInfo; - if (this.paramMemoableInfoMap?.has(node.name.peer)) { - memoableInfo = this.paramMemoableInfoMap.get(node.name.peer)!; + if (this.paramMemoableInfoMap?.has(node.id!.peer)) { + memoableInfo = this.paramMemoableInfoMap.get(node.id!.peer)!; } else { memoableInfo = collectMemoableInfoInVariableDeclarator(node); } this.collectMemoAstNode(node, memoableInfo); - if (!node.initializer) { + if (!node.init) { return node; } - if (arkts.isArrowFunctionExpression(node.initializer)) { - const func = node.initializer.scriptFunction; + if (arkts.isArrowFunctionExpression(node.init)) { + const func = node.init.function!; const localInfo = collectMemoableInfoInScriptFunction(func); const shouldCollectParameter = (localInfo.hasBuilder || localInfo.hasMemo) && !localInfo.hasMemoEntry && !localInfo.hasMemoIntrinsic; @@ -117,32 +118,32 @@ export class MemoFunctionCollector extends AbstractVisitor { return node; } this.shouldCollectReturn = !!memoableInfo.hasMemo || !!memoableInfo.hasBuilder; - this.visitor(node.initializer); + this.visitor(node.init); return node; } private visitCallExpression(node: arkts.CallExpression): arkts.AstNode { - if (arkts.NodeCache.getInstance().has(node)) { + if (NodeCache.getInstance().has(node)) { this.disableCollectReturnBeforeCallback(() => { this.visitEachChild(node); }); return node; } - const expr = findIdentifierFromCallee(node.expression); - const decl = (expr && getDeclResolveAlias(expr)) ?? node.expression; + const expr = findIdentifierFromCallee(node.callee); + const decl = (expr && getDeclResolveAlias(expr)) ?? node.callee; if (!decl) { this.disableCollectReturnBeforeCallback(() => { this.visitEachChild(node); }); return node; } - if (arkts.NodeCache.getInstance().has(decl)) { - arkts.NodeCache.getInstance().collect(node); + if (NodeCache.getInstance().has(decl)) { + NodeCache.getInstance().collect(node); } if (this.paramMemoableInfoMap?.has(decl.peer)) { this.collectCallWithDeclaredPeerInParamMap(node, decl.peer); - } else if (arkts.isEtsParameterExpression(decl) && this.paramMemoableInfoMap?.has(decl.identifier.peer)) { - this.collectCallWithDeclaredPeerInParamMap(node, decl.identifier.peer); + } else if (arkts.isETSParameterExpression(decl) && this.paramMemoableInfoMap?.has(decl.ident!.peer)) { + this.collectCallWithDeclaredPeerInParamMap(node, decl.ident!.peer); } else if (arkts.isIdentifier(decl) && !!decl.parent && arkts.isVariableDeclarator(decl.parent)) { this.collectCallWithDeclaredIdInVariableDeclarator(node, decl.parent); } @@ -158,9 +159,9 @@ export class MemoFunctionCollector extends AbstractVisitor { return node; } if (this.paramMemoableInfoMap?.has(decl.peer)) { - arkts.NodeCache.getInstance().collect(node); - } else if (arkts.isEtsParameterExpression(decl) && this.paramMemoableInfoMap?.has(decl.identifier.peer)) { - arkts.NodeCache.getInstance().collect(node); + NodeCache.getInstance().collect(node); + } else if (arkts.isETSParameterExpression(decl) && this.paramMemoableInfoMap?.has(decl.ident!.peer)) { + NodeCache.getInstance().collect(node); } return node; } @@ -169,7 +170,7 @@ export class MemoFunctionCollector extends AbstractVisitor { if (!!this.returnMemoableInfo && !!node.argument && arkts.isArrowFunctionExpression(node.argument)) { this.collectMemoAstNode(node.argument, this.returnMemoableInfo); } - arkts.NodeCache.getInstance().collect(node); + NodeCache.getInstance().collect(node); this.visitEachChild(node); return node; } @@ -216,8 +217,8 @@ export class MemoFunctionCollector extends AbstractVisitor { } if ( arkts.isArrowFunctionExpression(node) && - !arkts.NodeCache.getInstance().has(node) && - !arkts.NodeCache.getInstance().has(node.scriptFunction) + !NodeCache.getInstance().has(node) && + !NodeCache.getInstance().has(node.function!) ) { this.shouldCollectReturn = false; } diff --git a/arkui-plugins/collectors/memo-collectors/utils.ts b/arkui-plugins/collectors/memo-collectors/utils.ts index c8cf3fa23..dbe386649 100644 --- a/arkui-plugins/collectors/memo-collectors/utils.ts +++ b/arkui-plugins/collectors/memo-collectors/utils.ts @@ -18,6 +18,7 @@ import { annotation, forEachArgWithParam, isDecoratorAnnotation } from '../../co import { ImportCollector } from '../../common/import-collector'; import { DecoratorNames, GenSymPrefix, MEMO_IMPORT_SOURCE_NAME } from '../../common/predefines'; import { MemoFunctionCollector } from './function-collector'; +import { NodeCache } from '../../common/node-cache'; export enum MemoNames { MEMO = 'memo', @@ -71,7 +72,7 @@ export function addMemoAnnotation(node: T, memoName: Memo const skipNames = [MemoNames.MEMO_SKIP, MemoNames.MEMO_SKIP_UI]; collectMemoAnnotationSource(memoName); if (arkts.isETSUnionType(node)) { - return arkts.factory.updateUnionType( + return arkts.factory.updateETSUnionType( node, node.types.map((type) => { if (arkts.isETSFunctionType(type)) { @@ -87,15 +88,15 @@ export function addMemoAnnotation(node: T, memoName: Memo ]; collectMemoAnnotationImport(memoName); if (arkts.isEtsParameterExpression(node)) { - node.annotations = newAnnotations; + node.setAnnotations(newAnnotations); if (!skipNames.includes(memoName)) { - arkts.NodeCache.getInstance().collect(node); + NodeCache.getInstance().collect(node); } return node; } const newNode = node.setAnnotations(newAnnotations) as T; if (!skipNames.includes(memoName)) { - arkts.NodeCache.getInstance().collect(newNode); + NodeCache.getInstance().collect(newNode); } return newNode; } @@ -135,7 +136,7 @@ export function collectMemoAnnotationSource(memoName: MemoNames = MemoNames.MEMO export function collectMemoableInfoInUnionType(node: arkts.AstNode, info?: MemoableInfo): MemoableInfo { let currInfo = info ?? {}; - if (arkts.NodeCache.getInstance().has(node)) { + if (NodeCache.getInstance().has(node)) { return { ...currInfo, hasMemo: true, hasProperType: true }; } if (!arkts.isETSUnionType(node)) { @@ -179,8 +180,8 @@ function collectMemoableInfoInTypeReferencePart(node: arkts.ETSTypeReferencePart export function collectMemoableInfoInTypeReference(node: arkts.AstNode, info?: MemoableInfo): MemoableInfo { let currInfo = info ?? {}; - if (arkts.NodeCache.getInstance().has(node)) { - const metadata = arkts.NodeCache.getInstance().get(node)?.metadata; + if (NodeCache.getInstance().has(node)) { + const metadata = NodeCache.getInstance().get(node)?.metadata; return { ...currInfo, ...metadata }; } if (!arkts.isETSTypeReference(node) || !node.part || !arkts.isETSTypeReferencePart(node.part)) { @@ -203,7 +204,7 @@ export function collectMemoableInfoInTypeReference(node: arkts.AstNode, info?: M export function collectMemoableInfoInFunctionType(node: arkts.AstNode, info?: MemoableInfo): MemoableInfo { let currInfo = info ?? {}; - if (arkts.NodeCache.getInstance().has(node)) { + if (NodeCache.getInstance().has(node)) { return { ...currInfo, hasMemo: true, hasProperType: true }; } if (!arkts.isETSFunctionType(node)) { @@ -216,7 +217,7 @@ export function collectMemoableInfoInFunctionType(node: arkts.AstNode, info?: Me export function collectMemoableInfoInTypeAlias(node: arkts.AstNode, info?: MemoableInfo): MemoableInfo { let currInfo = info ?? {}; - if (arkts.NodeCache.getInstance().has(node)) { + if (NodeCache.getInstance().has(node)) { return { ...currInfo, hasMemo: true, hasProperType: true }; } if (!arkts.isTSTypeAliasDeclaration(node)) { @@ -237,21 +238,21 @@ export function collectMemoableInfoInTypeAlias(node: arkts.AstNode, info?: Memoa export function collectMemoableInfoInParameter(node: arkts.AstNode, info?: MemoableInfo): MemoableInfo { let currInfo = info ?? {}; - if (arkts.NodeCache.getInstance().has(node)) { - const metadata = arkts.NodeCache.getInstance().get(node)?.metadata; + if (NodeCache.getInstance().has(node)) { + const metadata = NodeCache.getInstance().get(node)?.metadata; return { ...currInfo, hasMemo: true, hasProperType: true, ...metadata }; } - if (!arkts.isEtsParameterExpression(node)) { + if (!arkts.isETSParameterExpression(node)) { return currInfo; } currInfo = { ...currInfo, ...hasMemoableAnnotation(node), }; - if (!!node.type) { + if (!!node.typeAnnotation) { currInfo = { ...currInfo, - ...collectMemoableInfoInType(node.type), + ...collectMemoableInfoInType(node.typeAnnotation), }; } if (!!node.initializer) { @@ -262,29 +263,29 @@ export function collectMemoableInfoInParameter(node: arkts.AstNode, info?: Memoa } if (!!currInfo.isWithinTypeParams) { const forbidTypeRewrite = !checkIsMemoFromMemoableInfo(currInfo); - arkts.NodeCache.getInstance().collect(node, { forbidTypeRewrite, isWithinTypeParams: true }); + NodeCache.getInstance().collect(node, { forbidTypeRewrite, isWithinTypeParams: true }); } return currInfo; } export function collectMemoableInfoInVariableDeclarator(node: arkts.AstNode, info?: MemoableInfo): MemoableInfo { let currInfo = info ?? {}; - if (arkts.NodeCache.getInstance().has(node)) { + if (NodeCache.getInstance().has(node)) { return { ...currInfo, hasMemo: true, hasProperType: true }; } if (!arkts.isVariableDeclarator(node)) { return currInfo; } - if (!!node.name.typeAnnotation) { + if (!!node.id!.asTypeNode) { currInfo = { ...currInfo, - ...collectMemoableInfoInType(node.name.typeAnnotation), + ...collectMemoableInfoInType(node.id!.asTypeNode), }; } - if (!!node.initializer && arkts.isArrowFunctionExpression(node.initializer)) { + if (!!node.init && arkts.isArrowFunctionExpression(node.init)) { currInfo = { ...currInfo, - ...collectMemoableInfoInArrowFunction(node.initializer), + ...collectMemoableInfoInArrowFunction(node.init), }; } if (!!node.parent && arkts.isVariableDeclaration(node.parent)) { @@ -293,14 +294,14 @@ export function collectMemoableInfoInVariableDeclarator(node: arkts.AstNode, inf ...hasMemoableAnnotation(node.parent), }; } - const decl = arkts.getDecl(node.name); + const decl = arkts.getDecl(node.id!); if (!decl) { return currInfo; } if (arkts.isMethodDefinition(decl)) { currInfo = { ...currInfo, - ...collectMemoableInfoInScriptFunction(decl.scriptFunction), + ...collectMemoableInfoInScriptFunction(decl.function!), }; } else if (arkts.isClassProperty(decl)) { currInfo = { @@ -313,7 +314,7 @@ export function collectMemoableInfoInVariableDeclarator(node: arkts.AstNode, inf export function collectMemoableInfoInProperty(node: arkts.AstNode, info?: MemoableInfo): MemoableInfo { let currInfo = info ?? {}; - if (arkts.NodeCache.getInstance().has(node)) { + if (NodeCache.getInstance().has(node)) { const property = node as arkts.Property; const hasProperType = !!property.value && arkts.isArrowFunctionExpression(property.value); return { ...currInfo, hasMemo: true, hasProperType }; @@ -337,7 +338,7 @@ export function collectMemoableInfoInProperty(node: arkts.AstNode, info?: Memoab currInfo.hasProperType = true; currInfo = { ...currInfo, - ...collectMemoableInfoInScriptFunction(node.value.scriptFunction), + ...collectMemoableInfoInScriptFunction(node.value.function!), }; } return currInfo; @@ -345,7 +346,7 @@ export function collectMemoableInfoInProperty(node: arkts.AstNode, info?: Memoab export function collectMemoableInfoInClassProperty(node: arkts.AstNode, info?: MemoableInfo): MemoableInfo { let currInfo = info ?? {}; - if (arkts.NodeCache.getInstance().has(node)) { + if (NodeCache.getInstance().has(node)) { return { ...currInfo, hasMemo: true, hasProperType: true }; } if (!arkts.isClassProperty(node)) { @@ -369,7 +370,7 @@ export function collectMemoableInfoInClassProperty(node: arkts.AstNode, info?: M export function collectMemoableInfoInArrowFunction(node: arkts.AstNode, info?: MemoableInfo): MemoableInfo { let currInfo = info ?? {}; - if (arkts.NodeCache.getInstance().has(node)) { + if (NodeCache.getInstance().has(node)) { return { ...currInfo, hasMemo: true, hasProperType: true }; } if (!arkts.isArrowFunctionExpression(node)) { @@ -377,15 +378,15 @@ export function collectMemoableInfoInArrowFunction(node: arkts.AstNode, info?: M } currInfo.hasProperType = true; currInfo = { ...currInfo, ...hasMemoableAnnotation(node) }; - if (!!node.scriptFunction) { + if (!!node.function!) { currInfo = { ...currInfo, - ...collectMemoableInfoInScriptFunction(node.scriptFunction), + ...collectMemoableInfoInScriptFunction(node.function!), }; } if (!!node.parent && arkts.isAssignmentExpression(node.parent) && !!node.parent.left) { const expr = arkts.isMemberExpression(node.parent.left) ? node.parent.left.property : node.parent.left; - const decl = arkts.getDecl(expr); + const decl = arkts.getDecl(expr!); if (!decl) { return currInfo; } @@ -401,7 +402,7 @@ export function collectMemoableInfoInArrowFunction(node: arkts.AstNode, info?: M export function collectMemoableInfoInScriptFunction(node: arkts.AstNode, info?: MemoableInfo): MemoableInfo { let currInfo = info ?? {}; - if (arkts.NodeCache.getInstance().has(node)) { + if (NodeCache.getInstance().has(node)) { return { ...currInfo, hasMemo: true, hasProperType: true }; } if (!arkts.isScriptFunction(node)) { @@ -413,20 +414,20 @@ export function collectMemoableInfoInScriptFunction(node: arkts.AstNode, info?: } export function collectMemoableInfoInMethod(node: arkts.MethodDefinition): MemoableInfo { - const hasReceiver = node.scriptFunction.hasReceiver; + const hasReceiver = node.function!.hasReceiver; const isSetter = node.kind === arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_SET; const isGetter = node.kind === arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_GET; let info: MemoableInfo = {}; - if (isSetter && node.scriptFunction.params.length > 0) { - if (hasReceiver && node.scriptFunction.params.length === 2) { - info = collectMemoableInfoInParameter(node.scriptFunction.params.at(1)!); + if (isSetter && node.function!.params.length > 0) { + if (hasReceiver && node.function!.params.length === 2) { + info = collectMemoableInfoInParameter(node.function!.params.at(1)!); } else { - info = collectMemoableInfoInParameter(node.scriptFunction.params.at(0)!); + info = collectMemoableInfoInParameter(node.function!.params.at(0)!); } } else if (isGetter) { - info = collectMemoableInfoInFunctionReturnType(node.scriptFunction); + info = collectMemoableInfoInFunctionReturnType(node.function!); } - return collectMemoableInfoInScriptFunction(node.scriptFunction, info); + return collectMemoableInfoInScriptFunction(node.function!, info); } export function collectMemoableInfoInType(node: arkts.AstNode, info?: MemoableInfo): MemoableInfo { @@ -442,13 +443,13 @@ export function collectMemoableInfoInType(node: arkts.AstNode, info?: MemoableIn export function collectMemoableInfoInFunctionReturnType(node: arkts.ScriptFunction): MemoableInfo { if (!!node.returnTypeAnnotation) { let memoableInfo: MemoableInfo; - if (arkts.NodeCache.getInstance().has(node.returnTypeAnnotation)) { + if (NodeCache.getInstance().has(node.returnTypeAnnotation)) { memoableInfo = { hasMemo: true, hasProperType: true }; } else { memoableInfo = collectMemoableInfoInType(node.returnTypeAnnotation); } if ((memoableInfo.hasMemo || memoableInfo.hasBuilder) && memoableInfo.hasProperType) { - arkts.NodeCache.getInstance().collect(node.returnTypeAnnotation); + NodeCache.getInstance().collect(node.returnTypeAnnotation); } return memoableInfo; } @@ -457,14 +458,14 @@ export function collectMemoableInfoInFunctionReturnType(node: arkts.ScriptFuncti export function collectScriptFunctionReturnTypeFromInfo(node: arkts.ScriptFunction, info: MemoableInfo): void { const returnType = node.returnTypeAnnotation; - if (!returnType || arkts.NodeCache.getInstance().has(returnType)) { + if (!returnType || NodeCache.getInstance().has(returnType)) { return; } const isMemoReturnType = checkIsMemoFromMemoableInfo(info); const isWithinTypeParams = info.isWithinTypeParams; if (isMemoReturnType || isWithinTypeParams) { const forbidTypeRewrite = !isMemoReturnType; - arkts.NodeCache.getInstance().collect(returnType, { forbidTypeRewrite, isWithinTypeParams }); + NodeCache.getInstance().collect(returnType, { forbidTypeRewrite, isWithinTypeParams }); } } @@ -472,8 +473,8 @@ export function collectGensymDeclarator(declarator: arkts.VariableDeclarator, in if (!info.hasMemo && !info.hasBuilder) { return; } - arkts.NodeCache.getInstance().collect(declarator); - const initializer = declarator.initializer; + NodeCache.getInstance().collect(declarator); + const initializer = declarator.init; if (!initializer || !arkts.isConditionalExpression(initializer)) { return; } @@ -488,7 +489,7 @@ export function collectGensymDeclarator(declarator: arkts.VariableDeclarator, in arrowFunc = alternate; } if (!!arrowFunc) { - const func = arrowFunc.scriptFunction; + const func = arrowFunc.function!; const returnMemoableInfo = collectMemoableInfoInFunctionReturnType(func); collectScriptFunctionReturnTypeFromInfo(func, returnMemoableInfo); const [paramMemoableInfoMap, gensymCount] = collectMemoableInfoMapInFunctionParams(func); @@ -537,8 +538,8 @@ function collectMemoableInfoInFunctionParam( const peers: arkts.AstNode['peer'][] = []; let memoableInfo: MemoableInfo; const _param = param as arkts.ETSParameterExpression; - if (arkts.NodeCache.getInstance().has(_param)) { - const metadata = arkts.NodeCache.getInstance().get(_param)!.metadata ?? {}; + if (NodeCache.getInstance().has(_param)) { + const metadata = NodeCache.getInstance().get(_param)!.metadata ?? {}; const { hasMemoSkip } = metadata; memoableInfo = { hasMemo: true, hasMemoSkip, hasProperType: true }; } else { @@ -547,22 +548,22 @@ function collectMemoableInfoInFunctionParam( if (shouldEnforceMemoSkip) { memoableInfo.hasMemoSkip = true; } - if (_param.identifier.name.startsWith(GenSymPrefix.INTRINSIC) && !!node.body && arkts.isBlockStatement(node.body)) { + if (_param.ident!.name.startsWith(GenSymPrefix.INTRINSIC) && !!node.body && arkts.isBlockStatement(node.body)) { const declaration = node.body.statements.at(gensymCount); if (!!declaration && arkts.isVariableDeclaration(declaration) && declaration.declarators.length > 0) { const declarator = declaration.declarators[0]; collectGensymDeclarator(declarator, memoableInfo); if (!memoableInfo.hasMemoSkip && shouldCollectParameter) { - peers.push(declarator.name.peer); + peers.push(declarator.id!.peer); } gensymCount++; } } if (checkIsMemoFromMemoableInfo(memoableInfo)) { - arkts.NodeCache.getInstance().collect(_param, { hasMemoSkip: memoableInfo.hasMemoSkip }); + NodeCache.getInstance().collect(_param, { hasMemoSkip: memoableInfo.hasMemoSkip }); } if (!memoableInfo.hasMemoSkip && shouldCollectParameter) { - peers.push(_param.identifier.peer); + peers.push(_param.ident!.peer); } return { peers, memoableInfo, gensymCount }; } @@ -581,7 +582,7 @@ export function findCanAddMemoFromTypeAnnotation( } const memoableInfo = collectMemoableInfoInType(typeAnnotation); if (!!memoableInfo.hasMemo && !!memoableInfo.hasProperType) { - arkts.NodeCache.getInstance().collect(typeAnnotation); + NodeCache.getInstance().collect(typeAnnotation); } return !!memoableInfo.hasBuilder && !memoableInfo.hasMemo && !!memoableInfo.hasProperType; } @@ -595,7 +596,7 @@ export function findCanAddMemoFromTypeAnnotation( export function findCanAddMemoFromProperty(property: arkts.AstNode): property is arkts.Property { const memoableInfo = collectMemoableInfoInProperty(property); if (!!memoableInfo.hasMemo && !!memoableInfo.hasProperType) { - arkts.NodeCache.getInstance().collect(property); + NodeCache.getInstance().collect(property); } const hasBuilder = !!memoableInfo.hasBuilder || !!memoableInfo.hasBuilderParam; return hasBuilder && !memoableInfo.hasMemo && !!memoableInfo.hasProperType; @@ -610,11 +611,11 @@ export function findCanAddMemoFromProperty(property: arkts.AstNode): property is export function findCanAddMemoFromClassProperty(property: arkts.AstNode): property is arkts.ClassProperty { const memoableInfo = collectMemoableInfoInClassProperty(property); if (!!memoableInfo.hasMemo && !!memoableInfo.hasProperType) { - arkts.NodeCache.getInstance().collect(property); + NodeCache.getInstance().collect(property); } const hasBuilderType = !!memoableInfo.hasBuilder || !!memoableInfo.hasBuilderParam; if (!!memoableInfo.isWithinTypeParams) { - arkts.NodeCache.getInstance().collect(property, { isWithinTypeParams: true }); + NodeCache.getInstance().collect(property, { isWithinTypeParams: true }); } return hasBuilderType && !memoableInfo.hasMemo && !!memoableInfo.hasProperType && !memoableInfo.isWithinTypeParams; } @@ -631,7 +632,7 @@ export function findCanAddMemoFromParameter(param: arkts.AstNode | undefined): p } const memoableInfo = collectMemoableInfoInParameter(param); if (!!memoableInfo.hasMemo && !!memoableInfo.hasProperType) { - arkts.NodeCache.getInstance().collect(param, { hasMemoSkip: memoableInfo.hasMemoSkip }); + NodeCache.getInstance().collect(param, { hasMemoSkip: memoableInfo.hasMemoSkip }); } return !!memoableInfo.hasBuilder && !memoableInfo.hasMemo && !!memoableInfo.hasProperType; } @@ -648,7 +649,7 @@ export function findCanAddMemoFromArrowFunction(node: arkts.AstNode): node is ar } const memoableInfo = collectMemoableInfoInArrowFunction(node); const { hasMemoEntry, hasMemoIntrinsic } = memoableInfo; - const func = node.scriptFunction; + const func = node.function!; const returnMemoableInfo = collectMemoableInfoInFunctionReturnType(func); collectScriptFunctionReturnTypeFromInfo(func, returnMemoableInfo); const [paramMemoableInfoMap, gensymCount] = collectMemoableInfoMapInFunctionParams( @@ -656,8 +657,8 @@ export function findCanAddMemoFromArrowFunction(node: arkts.AstNode): node is ar !hasMemoEntry && !hasMemoIntrinsic ); const isMemo = checkIsMemoFromMemoableInfo(memoableInfo); - if (isMemo && !arkts.NodeCache.getInstance().has(node)) { - arkts.NodeCache.getInstance().collect(node, { hasMemoEntry, hasMemoIntrinsic }); + if (isMemo && !NodeCache.getInstance().has(node)) { + NodeCache.getInstance().collect(node, { hasMemoEntry, hasMemoIntrinsic }); const body = func.body; if (!!body && arkts.isBlockStatement(body)) { const disableCollectReturn = hasMemoEntry || hasMemoIntrinsic; @@ -682,7 +683,7 @@ export function findCanAddMemoFromArrowFunction(node: arkts.AstNode): node is ar export function findCanAddMemoFromTypeAlias(node: arkts.AstNode): node is arkts.TSTypeAliasDeclaration { const memoableInfo = collectMemoableInfoInTypeAlias(node); if (!!memoableInfo.hasMemo && !!memoableInfo.hasProperType) { - arkts.NodeCache.getInstance().collect(node); + NodeCache.getInstance().collect(node); } return !!memoableInfo.hasBuilder && !memoableInfo.hasMemo && !!memoableInfo.hasProperType; } @@ -699,7 +700,7 @@ export function findCanAddMemoFromMethod(node: arkts.AstNode): node is arkts.Met } const memoableInfo = collectMemoableInfoInMethod(node); const { hasMemoEntry, hasMemoIntrinsic } = memoableInfo; - const func = node.scriptFunction; + const func = node.function!; const returnMemoableInfo = collectMemoableInfoInFunctionReturnType(func); collectScriptFunctionReturnTypeFromInfo(func, returnMemoableInfo); const shouldEnforceMemoSkip = !!memoableInfo.hasBuilder; @@ -709,9 +710,9 @@ export function findCanAddMemoFromMethod(node: arkts.AstNode): node is arkts.Met shouldEnforceMemoSkip ); const isMemo = checkIsMemoFromMemoableInfo(memoableInfo); - if (isMemo && !arkts.NodeCache.getInstance().has(node)) { + if (isMemo && !NodeCache.getInstance().has(node)) { const metadata = collectMetadataInMethod(node); - arkts.NodeCache.getInstance().collect(node, { + NodeCache.getInstance().collect(node, { ...metadata, hasMemoEntry, hasMemoIntrinsic, @@ -740,7 +741,7 @@ export function collectMemoFromTSTypeParameterInstantiation(node: arkts.TSTypePa node.params.forEach((t) => { const typeInfo = collectMemoableInfoInType(t); if (checkIsMemoFromMemoableInfo(typeInfo)) { - arkts.NodeCache.getInstance().collect(t); + NodeCache.getInstance().collect(t); } }); } @@ -751,13 +752,13 @@ export function collectMemoFromTSTypeParameterInstantiation(node: arkts.TSTypePa * @param node `arkts.ETSNewClassInstanceExpression` node. */ export function collectMemoFromNewClass(node: arkts.ETSNewClassInstanceExpression): void { - const typeRef = node.getTypeRef; + const typeRef = node.typeRef; if (!typeRef || !arkts.isETSTypeReference(typeRef)) { return; } const typeInfo = collectMemoableInfoInTypeReference(typeRef); if (typeInfo.isWithinTypeParams) { - arkts.NodeCache.getInstance().collect(typeRef, { isWithinTypeParams: true }); + NodeCache.getInstance().collect(typeRef, { isWithinTypeParams: true }); } } @@ -768,21 +769,21 @@ export function collectMemoFromNewClass(node: arkts.ETSNewClassInstanceExpressio * @param node `arkts.CallExpression` node. */ export function collectMemoFromCallExpression(node: arkts.CallExpression): boolean { - if (arkts.NodeCache.getInstance().has(node)) { + if (NodeCache.getInstance().has(node)) { return false; } const typeParams = node.typeParams; if (!!typeParams) { collectMemoFromTSTypeParameterInstantiation(typeParams); } - const expr = findIdentifierFromCallee(node.expression); - const decl = (expr && getDeclResolveAlias(expr)) ?? node.expression; + const expr = findIdentifierFromCallee(node.callee); + const decl = (expr && getDeclResolveAlias(expr)) ?? node.callee; if (!decl) { return false; } let isCollected: boolean = false; - if (arkts.NodeCache.getInstance().has(decl)) { - arkts.NodeCache.getInstance().collect(node); + if (NodeCache.getInstance().has(decl)) { + NodeCache.getInstance().collect(node); isCollected = true; } if (arkts.isMethodDefinition(decl)) { @@ -790,42 +791,42 @@ export function collectMemoFromCallExpression(node: arkts.CallExpression): boole } else if (arkts.isClassProperty(decl)) { isCollected = collectCallWithDeclaredClassProperty(node, decl); } - if (isCollected && arkts.isTSAsExpression(node.expression) && node.expression.typeAnnotation) { - arkts.NodeCache.getInstance().collect(node.expression.typeAnnotation); + if (isCollected && arkts.isTSAsExpression(node.callee) && node.callee.typeAnnotation) { + NodeCache.getInstance().collect(node.callee.typeAnnotation); } return isCollected; } export function collectCallWithDeclaredClassProperty(node: arkts.CallExpression, decl: arkts.ClassProperty): boolean { - if (arkts.NodeCache.getInstance().has(decl)) { - arkts.NodeCache.getInstance().collect(node); + if (NodeCache.getInstance().has(decl)) { + NodeCache.getInstance().collect(node); return true; } const memoableInfo = collectMemoableInfoInClassProperty(decl); if (checkIsMemoFromMemoableInfo(memoableInfo, false) || memoableInfo.hasBuilder || memoableInfo.hasBuilderParam) { - arkts.NodeCache.getInstance().collect(node); + NodeCache.getInstance().collect(node); return true; } return false; } export function collectCallWithDeclaredMethod(node: arkts.CallExpression, decl: arkts.MethodDefinition): boolean { - const hasReceiver = decl.scriptFunction.hasReceiver; - const params = decl.scriptFunction.params; + const hasReceiver = decl.function!.hasReceiver; + const params = decl.function!.params; const args = node.arguments; - const hasRestParameter = decl.scriptFunction.hasRestParameter; + const hasRestParameter = decl.function!.hasRestParameter; const isTrailingCall = node.isTrailingCall; const options = { hasRestParameter, isTrailingCall }; forEachArgWithParam(args, params, collectCallArgsWithMethodParams, options); - if (arkts.NodeCache.getInstance().has(decl)) { - const { hasMemoEntry, hasMemoIntrinsic } = arkts.NodeCache.getInstance().get(decl)!.metadata ?? {}; - arkts.NodeCache.getInstance().collect(node, { hasReceiver, hasMemoEntry, hasMemoIntrinsic }); + if (NodeCache.getInstance().has(decl)) { + const { hasMemoEntry, hasMemoIntrinsic } = NodeCache.getInstance().get(decl)!.metadata ?? {}; + NodeCache.getInstance().collect(node, { hasReceiver, hasMemoEntry, hasMemoIntrinsic }); return true; } else { - const memoableInfo = collectMemoableInfoInScriptFunction(decl.scriptFunction); + const memoableInfo = collectMemoableInfoInScriptFunction(decl.function!); if (checkIsMemoFromMemoableInfo(memoableInfo, true)) { const { hasMemoEntry, hasMemoIntrinsic } = memoableInfo; - arkts.NodeCache.getInstance().collect(node, { hasReceiver, hasMemoEntry, hasMemoIntrinsic }); + NodeCache.getInstance().collect(node, { hasReceiver, hasMemoEntry, hasMemoIntrinsic }); return true; } } @@ -837,14 +838,14 @@ export function collectCallArgsWithMethodParams(arg: arkts.Expression | undefine return; } let info: MemoableInfo; - if (arkts.NodeCache.getInstance().has(param)) { + if (NodeCache.getInstance().has(param)) { info = { hasMemo: true, hasProperType: true }; } else { info = collectMemoableInfoInParameter(param); } if (checkIsMemoFromMemoableInfo(info) && arkts.isArrowFunctionExpression(arg)) { - arkts.NodeCache.getInstance().collect(arg); - const func = arg.scriptFunction; + NodeCache.getInstance().collect(arg); + const func = arg.function!; const returnMemoableInfo = collectMemoableInfoInFunctionReturnType(func); collectScriptFunctionReturnTypeFromInfo(func, returnMemoableInfo); const [paramMemoableInfoMap, gensymCount] = collectMemoableInfoMapInFunctionParams(func); @@ -894,9 +895,27 @@ export function collectMemoScriptFunctionBody( }); } -export function collectMetadataInMethod(node: arkts.MethodDefinition): arkts.AstNodeCacheValue['metadata'] { - const callName = node.name.name; - const hasReceiver = node.scriptFunction.hasReceiver; +export interface AstNodeCacheValue { + peer: arkts.KNativePointer; + type: arkts.Es2pandaAstNodeType; + metadata?: AstNodeCacheValueMetadata; +} + +export interface AstNodeCacheValueMetadata { + callName?: string; + hasReceiver?: boolean; + isSetter?: boolean; + isGetter?: boolean; + forbidTypeRewrite?: boolean; + isWithinTypeParams?: boolean; + hasMemoSkip?: boolean; + hasMemoIntrinsic?: boolean; + hasMemoEntry?: boolean; +} + +export function collectMetadataInMethod(node: arkts.MethodDefinition): AstNodeCacheValueMetadata { + const callName = node.id!.name; + const hasReceiver = node.function!.hasReceiver; const isSetter = node.kind === arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_SET; const isGetter = node.kind === arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_GET; return { callName, hasReceiver, isSetter, isGetter }; @@ -912,18 +931,18 @@ export function checkIsMemoFromMemoableInfo(info: MemoableInfo, ignoreType: bool 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.init && arkts.isIdentifier(decl.parent.init)) { + return getDeclResolveAlias(decl.parent.init); } - if (!!decl.parent.initializer && arkts.isMemberExpression(decl.parent.initializer)) { - return getDeclResolveAlias(decl.parent.initializer.property); + if (!!decl.parent.init && arkts.isMemberExpression(decl.parent.init)) { + return getDeclResolveAlias(decl.parent.init.property!); } } return decl; } export function parametersBlockHasReceiver(params: readonly arkts.Expression[]): boolean { - return params.length > 0 && arkts.isEtsParameterExpression(params[0]) && isThisParam(params[0]); + return params.length > 0 && arkts.isETSParameterExpression(params[0]) && isThisParam(params[0]); } export function parametrizedNodeHasReceiver(node: arkts.ScriptFunction | arkts.ETSFunctionType | undefined): boolean { @@ -934,8 +953,8 @@ export function parametrizedNodeHasReceiver(node: arkts.ScriptFunction | arkts.E } function isThisParam(node: arkts.Expression | undefined): boolean { - if (node === undefined || !arkts.isEtsParameterExpression(node)) { + if (node === undefined || !arkts.isETSParameterExpression(node)) { return false; } - return node.identifier?.isReceiver ?? false; + return node.ident?.isReceiver ?? false; } diff --git a/arkui-plugins/common/arkts-utils.ts b/arkui-plugins/common/arkts-utils.ts index aae9ddc43..670eed2e6 100644 --- a/arkui-plugins/common/arkts-utils.ts +++ b/arkui-plugins/common/arkts-utils.ts @@ -43,34 +43,13 @@ export function coerceToAstNode(node: arkts.AstNode): T return node as T; } -/** - * create and insert `import { as } from ` to the top of script's statements. - */ -export function createAndInsertImportDeclaration( - source: arkts.StringLiteral, - imported: arkts.Identifier, - local: arkts.Identifier, - importKind: arkts.Es2pandaImportKinds, - program: arkts.Program -): void { - const importDecl: arkts.ETSImportDeclaration = arkts.factory.createImportDeclaration( - source, - [arkts.factory.createImportSpecifier(imported, local)], - importKind, - program, - arkts.Es2pandaImportFlags.IMPORT_FLAGS_NONE - ); - arkts.importDeclarationInsert(importDecl, program); - return; -} - export function isNumeric(str: string): boolean { return /^\d+$/.test(str); } export function annotation(name: string): arkts.AnnotationUsage { const ident: arkts.Identifier = arkts.factory.createIdentifier(name).setAnnotationUsage(); - const annotation: arkts.AnnotationUsage = arkts.factory.createAnnotationUsage(ident); + const annotation: arkts.AnnotationUsage = arkts.factory.createAnnotationUsage(ident, []); annotation.modifiers = arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_ANNOTATION_USAGE; ident.parent = annotation; diff --git a/arkui-plugins/common/declaration-collector.ts b/arkui-plugins/common/declaration-collector.ts index d65f0d40d..0ac8cb543 100644 --- a/arkui-plugins/common/declaration-collector.ts +++ b/arkui-plugins/common/declaration-collector.ts @@ -51,13 +51,13 @@ export class DeclarationCollector { if (arkts.isAnnotationDeclaration(decl) && !!decl.expr && arkts.isIdentifier(decl.expr)) { declName = decl.expr.name; } else if (arkts.isMethodDefinition(decl)) { - declName = decl.name.name; + declName = decl.id!.name; } else if (arkts.isIdentifier(decl)) { declName = decl.name; } else if (arkts.isClassProperty(decl) && !!decl.key && arkts.isIdentifier(decl.key)) { declName = decl.key.name; - } else if (arkts.isEtsParameterExpression(decl)) { - declName = decl.identifier.name; + } else if (arkts.isETSParameterExpression(decl)) { + declName = decl.ident!.name; } if (!declName) { return; diff --git a/arkui-plugins/common/etsglobal-remover.ts b/arkui-plugins/common/etsglobal-remover.ts index 3d9711799..cf70bd3ad 100644 --- a/arkui-plugins/common/etsglobal-remover.ts +++ b/arkui-plugins/common/etsglobal-remover.ts @@ -20,11 +20,11 @@ const ETSGLOBAL = 'ETSGLOBAL'; export class EtsglobalRemover extends AbstractVisitor { visitor(node: arkts.AstNode): arkts.AstNode { - if (arkts.isEtsScript(node)) { + if (arkts.isETSModule(node)) { const keep = node.statements.filter((it) => { return !(arkts.isClassDeclaration(it) && it.definition?.ident?.name == ETSGLOBAL); }); - return arkts.factory.updateEtsScript(node, keep); + return arkts.factory.updateETSModule(node, keep, node.ident, node.getNamespaceFlag(), node.program); } return node; } diff --git a/arkui-plugins/common/import-collector.ts b/arkui-plugins/common/import-collector.ts index 935b339af..6705ee925 100644 --- a/arkui-plugins/common/import-collector.ts +++ b/arkui-plugins/common/import-collector.ts @@ -14,7 +14,6 @@ */ import * as arkts from '@koalaui/libarkts'; -import { createAndInsertImportDeclaration } from './arkts-utils'; interface ImportInfo { imported: string; @@ -23,15 +22,15 @@ interface ImportInfo { kind: arkts.Es2pandaImportKinds; } -function insertImport(importInfo: ImportInfo, program?: arkts.Program): void { - const source: arkts.StringLiteral = arkts.factory.create1StringLiteral(importInfo.source); +function createImport(importInfo: ImportInfo): arkts.ETSImportDeclaration { + const source: arkts.StringLiteral = arkts.factory.createStringLiteral(importInfo.source); const imported: arkts.Identifier = arkts.factory.createIdentifier(importInfo.imported); const local: arkts.Identifier = arkts.factory.createIdentifier(importInfo.local); - // Insert this import at the top of the script's statements. - if (!program) { - throw Error('Failed to insert import: Transformer has no program'); - } - createAndInsertImportDeclaration(source, imported, local, importInfo.kind, program); + return arkts.factory.createETSImportDeclaration( + source, + [arkts.factory.createImportSpecifier(imported, local)], + importInfo.kind + ); } export class ImportCollector { @@ -73,7 +72,7 @@ export class ImportCollector { collectImport( imported: string, local?: string, - kind: arkts.Es2pandaImportKinds = arkts.Es2pandaImportKinds.IMPORT_KINDS_TYPE + kind: arkts.Es2pandaImportKinds = arkts.Es2pandaImportKinds.IMPORT_KINDS_TYPES ): void { if (!this.sourceMap.has(imported)) { throw new Error(`ImportCollector: import ${imported}'s source haven't been collected yet.`); @@ -97,9 +96,7 @@ export class ImportCollector { return this.localMap.get(imported); } - insertCurrentImports(program?: arkts.Program): void { - this.importInfos.forEach((importInfo) => { - insertImport(importInfo, program); - }); + getImportStatements(): arkts.ETSImportDeclaration[] { + return this.importInfos.map((importInfo) => createImport(importInfo)); } } diff --git a/arkui-plugins/common/log-collector.ts b/arkui-plugins/common/log-collector.ts index 5fa9ed7af..03f66565a 100644 --- a/arkui-plugins/common/log-collector.ts +++ b/arkui-plugins/common/log-collector.ts @@ -63,7 +63,7 @@ export class LogCollector { return; } this.logInfos.forEach((logItem: LogInfo) => { - arkts.Diagnostic.logDiagnostic(generateDiagnosticKind(logItem), arkts.getStartPosition(logItem.node)); + arkts.Diagnostic.logDiagnostic(generateDiagnosticKind(logItem), logItem.node.startPosition); }); } diff --git a/arkui-plugins/common/node-cache.ts b/arkui-plugins/common/node-cache.ts new file mode 100644 index 000000000..baba1fa82 --- /dev/null +++ b/arkui-plugins/common/node-cache.ts @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from '@koalaui/libarkts'; + +export interface AstNodeCacheValue { + peer: arkts.KNativePointer; + type: arkts.Es2pandaAstNodeType; + metadata?: AstNodeCacheValueMetadata; +} + +export interface AstNodeCacheValueMetadata { + callName?: string; + hasReceiver?: boolean; + isSetter?: boolean; + isGetter?: boolean; + forbidTypeRewrite?: boolean; + isWithinTypeParams?: boolean; + hasMemoSkip?: boolean; + hasMemoIntrinsic?: boolean; + hasMemoEntry?: boolean; +} + +export class NodeCache { + private _isCollected: boolean = false; + private cacheMap: Map; + private static instance: NodeCache; + + private constructor() { + this.cacheMap = new Map(); + } + + static getInstance(): NodeCache { + if (!this.instance) { + this.instance = new NodeCache(); + } + return this.instance; + } + + collect(node: arkts.AstNode, metadata?: AstNodeCacheValueMetadata): void { + const peer = node.peer; + const type = arkts.arktsGlobal.generatedEs2panda._AstNodeTypeConst(arkts.arktsGlobal.context, node.peer); + let currMetadata: AstNodeCacheValueMetadata | undefined = metadata ?? {}; + if (this.cacheMap.has(peer)) { + const oldMetadata = this.cacheMap.get(peer)!.metadata ?? {}; + currMetadata = { ...oldMetadata, ...currMetadata }; + } + currMetadata = Object.keys(currMetadata).length === 0 ? undefined : currMetadata; + this.cacheMap.set(peer, { peer, type, metadata: currMetadata }); + this._isCollected = true; + } + + refresh(original: arkts.AstNode, node: arkts.AstNode): void { + let metadata: AstNodeCacheValueMetadata | undefined; + if (this.has(original)) { + metadata = this.get(original)?.metadata; + this.cacheMap.delete(original.peer); + } + this.collect(node, metadata); + } + + isCollected(): boolean { + return this._isCollected; + } + + has(node: arkts.AstNode): boolean { + return this.cacheMap.has(node.peer); + } + + get(node: arkts.AstNode): AstNodeCacheValue | undefined { + return this.cacheMap.get(node.peer); + } + + clear(): void { + this.cacheMap.clear(); + this._isCollected = false; + } + + visualize(): void { + Array.from(this.cacheMap.values()).forEach(({ peer, type, metadata }) => { + const src = arkts.arktsGlobal.generatedEs2panda._AstNodeDumpEtsSrcConst(arkts.arktsGlobal.context, peer) + console.log( + `[NODE CACHE] ptr ${peer}, type: ${type}, metadata: ${JSON.stringify(metadata)}, node: `, + arkts.unpackString(src) + ); + }); + } +} diff --git a/arkui-plugins/common/plugin-context.ts b/arkui-plugins/common/plugin-context.ts index ffe81012d..4ce622b51 100644 --- a/arkui-plugins/common/plugin-context.ts +++ b/arkui-plugins/common/plugin-context.ts @@ -18,7 +18,7 @@ import { FileManager } from './file-manager'; // This is the same plugin-context in the build-system. export class PluginContext { - private ast: arkts.EtsScript | undefined; + private ast: arkts.ETSModule | undefined; private program: arkts.Program | undefined; private projectConfig: ProjectConfig | undefined; private contextPtr: number | undefined; @@ -41,14 +41,14 @@ export class PluginContext { /** * @deprecated */ - public setArkTSAst(ast: arkts.EtsScript): void { + public setArkTSAst(ast: arkts.ETSModule): void { this.ast = ast; } /** * @deprecated */ - public getArkTSAst(): arkts.EtsScript | undefined { + public getArkTSAst(): arkts.ETSModule | undefined { return this.ast; } diff --git a/arkui-plugins/common/program-skipper.ts b/arkui-plugins/common/program-skipper.ts index dc77fc5a2..60557e4cf 100644 --- a/arkui-plugins/common/program-skipper.ts +++ b/arkui-plugins/common/program-skipper.ts @@ -22,8 +22,8 @@ const ARKUI = 'arkui'; export class ProgramSkipper { private static _absName2programs: Map = new Map(); - private static _uiProgramSet: Set = new Set(); - private static _edges: Map = new Map(); + private static _uiProgramSet: Set = new Set(); + private static _edges: Map = new Map(); private static _initedCanSkip: boolean = false; private static dfs(program: arkts.Program): void { @@ -39,7 +39,7 @@ export class ProgramSkipper { } private static addEdges(program: arkts.Program): void { - for (const statement of program.astNode.statements) { + for (const statement of program.ast.statements) { if (arkts.isETSImportDeclaration(statement)) { const absName = statement.resolvedSource; if (!absName || !this._absName2programs.has(absName)) { @@ -55,7 +55,7 @@ export class ProgramSkipper { } private static addProgramToMap(program: arkts.Program): void { - const absName = program.absName; + const absName = program.absoluteName; const name2programs = this._absName2programs.get(absName) || []; name2programs.push(program); this._absName2programs.set(absName, name2programs); @@ -74,7 +74,7 @@ export class ProgramSkipper { programs.forEach(p => this.addProgramToMap(p)); programs.forEach(p => this.addEdges(p)); programs.forEach(p => { - if (p.absName.endsWith(LIB_SUFFIX) && p.absName.includes(ARKUI)) { + if (p.absoluteName.endsWith(LIB_SUFFIX) && p.absoluteName.includes(ARKUI)) { this.dfs(p); } }); @@ -96,7 +96,7 @@ export class ProgramSkipper { return false; } if (!this._initedCanSkip) { - const programs = [...arkts.arktsGlobal.compilerContext?.program.externalSources.flatMap(s => s.programs)!, program]; + const programs = [...arkts.arktsGlobal.compilerContext?.program.getExternalSources().flatMap(s => s.programs)!, program]; this.initCanSkip(programs); this._initedCanSkip = true; this._absName2programs.clear(); diff --git a/arkui-plugins/common/program-visitor.ts b/arkui-plugins/common/program-visitor.ts index 9327b9075..4516df8cf 100644 --- a/arkui-plugins/common/program-visitor.ts +++ b/arkui-plugins/common/program-visitor.ts @@ -71,7 +71,7 @@ export class ProgramVisitor extends AbstractVisitor { private readonly visitors: AbstractVisitor[]; private readonly skipPrefixNames: (string | RegExp)[]; private readonly hooks?: ProgramHooks; - private filenames: Map; + private filenames: Map; private pluginContext?: PluginContext; private legacyModuleList: string[] = []; private legacyStructMap: Map; @@ -136,7 +136,7 @@ export class ProgramVisitor extends AbstractVisitor { private visitLegacyInExternalSource(currProgram: arkts.Program, name: string): void { if (this.state === arkts.Es2pandaContextState.ES2PANDA_STATE_PARSED) { - const structList = this.visitorLegacy(currProgram.astNode, currProgram, name); + const structList = this.visitorLegacy(currProgram.ast, currProgram, name); const moduleName = name.split('/')[0]; const structMap = this.legacyStructMap.get(moduleName)!; for (const struct of structList) { @@ -152,8 +152,8 @@ export class ProgramVisitor extends AbstractVisitor { cachePath?: string ): void { const extensionName: string = program.fileNameWithExtension; - this.dumpExternalSource(currProgram.astNode, name, cachePath, 'ORI', extensionName); - const script = this.visitor(currProgram.astNode, currProgram, name); + this.dumpExternalSource(currProgram.ast, name, cachePath, 'ORI', extensionName); + const script = this.visitor(currProgram.ast, currProgram, name); if (script) { this.dumpExternalSource(script, name, cachePath, this.pluginName, extensionName); } @@ -182,7 +182,7 @@ export class ProgramVisitor extends AbstractVisitor { this.getLegacyModule(); while (queue.length > 0) { const currProgram = queue.shift()!; - if (visited.has(currProgram.peer) || currProgram.isASTLowered()) { + if (visited.has(currProgram.peer) || currProgram.isASTLowered) { continue; } if (currProgram.peer !== program.peer) { @@ -195,7 +195,7 @@ export class ProgramVisitor extends AbstractVisitor { } } visited.add(currProgram.peer); - for (const externalSource of currProgram.externalSources) { + for (const externalSource of currProgram.getExternalSources()) { if (matchPrefix(this.skipPrefixNames, externalSource.getName())) { continue; } @@ -207,7 +207,7 @@ export class ProgramVisitor extends AbstractVisitor { programVisitor(program: arkts.Program): arkts.Program { this.visitExternalSources(program, [program]); - let programScript = program.astNode; + let programScript = program.ast; programScript = this.visitor(programScript, program, this.externalSourceName); const visitorsToReset = flattenVisitorsInHooks(this.hooks, this.state); @@ -222,7 +222,7 @@ export class ProgramVisitor extends AbstractVisitor { program?: arkts.Program, externalSourceName?: string ): void { - let script: arkts.EtsScript = node as arkts.EtsScript; + let script: arkts.ETSModule = node as arkts.ETSModule; const preVisitors = hook?.pre?.visitors ?? []; for (const transformer of preVisitors) { this.visitTransformer(transformer, script, externalSourceName, program); @@ -238,7 +238,7 @@ export class ProgramVisitor extends AbstractVisitor { program?: arkts.Program, externalSourceName?: string ): void { - let script: arkts.EtsScript = node as arkts.EtsScript; + let script: arkts.ETSModule = node as arkts.ETSModule; const postVisitors = hook?.post?.visitors ?? []; for (const transformer of postVisitors) { this.visitTransformer(transformer, script, externalSourceName, program); @@ -248,16 +248,16 @@ export class ProgramVisitor extends AbstractVisitor { } } - visitor(node: arkts.AstNode, program?: arkts.Program, externalSourceName?: string): arkts.EtsScript { + visitor(node: arkts.AstNode, program?: arkts.Program, externalSourceName?: string): arkts.ETSModule { if (!this.isFrameworkMode && ProgramSkipper.canSkipProgram(program)) { - debugLog('can skip file: ', program?.absName); - return node as arkts.EtsScript; + debugLog('can skip file: ', program?.absoluteName); + return node as arkts.ETSModule; } - debugLog('cant skip file: ', program?.absName); + debugLog('cant skip file: ', program?.absoluteName); let hook: ProgramHookLifeCycle | undefined; - let script: arkts.EtsScript = node as arkts.EtsScript; + let script: arkts.ETSModule = node as arkts.ETSModule; let count: number = 0; const isExternal: boolean = !!externalSourceName; @@ -271,6 +271,7 @@ export class ProgramVisitor extends AbstractVisitor { } this.visitTransformer(transformer, script, externalSourceName, program); arkts.setAllParents(script); + transformer.reset(); if (!transformer.isExternal) { debugDumpAstNode( script, @@ -300,16 +301,33 @@ export class ProgramVisitor extends AbstractVisitor { private visitTransformer( transformer: AbstractVisitor, - script: arkts.EtsScript, + script: arkts.ETSModule, externalSourceName?: string, program?: arkts.Program - ): arkts.EtsScript { + ): arkts.ETSModule { transformer.isExternal = !!externalSourceName; transformer.externalSourceName = externalSourceName; transformer.program = program; transformer.init(); - const newScript = transformer.visitor(script) as arkts.EtsScript; + const importStorage = new arkts.ImportStorage(program!, true) + const newScript = transformer.visitor(script) as arkts.ETSModule; + program?.setAst(newScript) + arkts.setAllParents(newScript); + importStorage.update(); transformer.reset(); return newScript; } } + +export class CanSkipPhasesCache { + static resultCache = new Map() + + static check(program: arkts.Program) { + if (!CanSkipPhasesCache.resultCache.has(program)) { + const result = arkts.global.es2panda._ProgramCanSkipPhases(arkts.global.context, program.peer); + CanSkipPhasesCache.resultCache.set(program, result); + } + return CanSkipPhasesCache.resultCache.get(program); + } +} + diff --git a/arkui-plugins/interop-plugins/decl_transformer.ts b/arkui-plugins/interop-plugins/decl_transformer.ts index 32d6a610e..1a16a6adf 100644 --- a/arkui-plugins/interop-plugins/decl_transformer.ts +++ b/arkui-plugins/interop-plugins/decl_transformer.ts @@ -24,7 +24,7 @@ export class DeclTransformer extends AbstractVisitor { super(); } - processComponent(node: arkts.StructDeclaration): arkts.ClassDeclaration { + processComponent(node: arkts.ETSStructDeclaration): arkts.ClassDeclaration { const className = node.definition?.ident?.name; if (!className) { throw 'Non Empty className expected for Component'; @@ -52,62 +52,65 @@ export class DeclTransformer extends AbstractVisitor { visitor(beforeChildren: arkts.AstNode): arkts.AstNode { let astNode: arkts.AstNode = beforeChildren; - if (arkts.isEtsScript(astNode)) { + if (arkts.isETSModule(astNode)) { astNode = this.transformImportDecl(astNode); } const node = this.visitEachChild(astNode); - if (arkts.isStructDeclaration(node)) { - debugLog(`DeclTransformer:before:flag:${arkts.classDefinitionIsFromStructConst(node.definition!)}`); - arkts.classDefinitionSetFromStructModifier(node.definition!); + if (arkts.isETSStructDeclaration(node)) { + debugLog(`DeclTransformer:before:flag:${node.definition?.isFromStruct!}`); + node.definition!.setFromStructModifier(); let newnode = this.processComponent(node); - debugLog(`DeclTransformer:after:flag:${arkts.classDefinitionIsFromStructConst(newnode.definition!)}`); + debugLog(`DeclTransformer:after:flag:${node.definition?.isFromStruct!}`); return newnode; } else if (arkts.isETSImportDeclaration(astNode)) { return this.updateImportDeclaration(astNode); } else if (arkts.isMethodDefinition(astNode)) { - if (astNode.name?.name === 'build' ) { + if (astNode.id?.name === 'build' ) { return this.transformMethodDefinition(astNode); } return astNode; - } else if (arkts.isClassProperty(astNode)) { - astNode.setAnnotations([]); } return node; } transformImportDecl(astNode: arkts.AstNode):arkts.AstNode { - if (!arkts.isEtsScript(astNode)) { + if (!arkts.isETSModule(astNode)) { return astNode; } let statements = astNode.statements.filter(node => this.isImportDeclarationNeedFilter(node)); - return arkts.factory.updateEtsScript(astNode, statements); + return arkts.factory.updateETSModule(astNode, statements, astNode.ident, astNode.getNamespaceFlag(),astNode.program); } transformMethodDefinition(node: arkts.MethodDefinition): arkts.AstNode { - const func: arkts.ScriptFunction = node.scriptFunction; + const func: arkts.ScriptFunction = node.function!; const isFunctionCall: boolean = false; - const typeNode: arkts.TypeNode | undefined = node.scriptFunction?.returnTypeAnnotation; + const typeNode: arkts.TypeNode | undefined = node.function?.returnTypeAnnotation; const updateFunc = arkts.factory.updateScriptFunction( func, !!func.body && arkts.isBlockStatement(func.body) - ? arkts.factory.updateBlock( + ? arkts.factory.updateBlockStatement( func.body, func.body.statements.filter((st) => false) ) : undefined, - arkts.FunctionSignature.createFunctionSignature(func.typeParams, func.params, func.returnTypeAnnotation, false), + func.typeParams, + func.params, + func.returnTypeAnnotation, + false, func?.flags, - func?.modifiers + func?.modifiers, + undefined, + undefined ); return arkts.factory.updateMethodDefinition( node, node.kind, arkts.factory.updateIdentifier( - node.name, - node.name?.name + node.id!, + node.id?.name! ), - updateFunc, + arkts.factory.createFunctionExpression(func.id?.clone(), updateFunc), node.modifiers, false ); @@ -127,7 +130,7 @@ export class DeclTransformer extends AbstractVisitor { astNode.specifiers.forEach((element) => { if (arkts.isImportSpecifier(element)) { if (ARKUI_DECLARE_LIST.has(element.imported?.name as string)) { - arkts.ImportSpecifierSetRemovable(element); + element.setRemovable(true); } } }); diff --git a/arkui-plugins/interop-plugins/emit_transformer.ts b/arkui-plugins/interop-plugins/emit_transformer.ts index d68dfbc2f..c43605263 100644 --- a/arkui-plugins/interop-plugins/emit_transformer.ts +++ b/arkui-plugins/interop-plugins/emit_transformer.ts @@ -52,7 +52,7 @@ export class EmitTransformer extends AbstractVisitor { visitor(beforeChildren: arkts.AstNode): arkts.AstNode { const node = this.visitEachChild(beforeChildren); - if (arkts.isClassDeclaration(node) && arkts.classDefinitionIsFromStructConst(node.definition!)) { + if (arkts.isClassDeclaration(node) && node.definition?.isFromStruct) { return this.processComponent(node); } return node; diff --git a/arkui-plugins/interop-plugins/index.ts b/arkui-plugins/interop-plugins/index.ts index dc69677c9..3504eaaa1 100644 --- a/arkui-plugins/interop-plugins/index.ts +++ b/arkui-plugins/interop-plugins/index.ts @@ -34,8 +34,8 @@ export function interopTransform():Plugins { }; } -function parsedTransform(this: PluginContext): arkts.EtsScript | undefined { - let script: arkts.EtsScript | undefined; +function parsedTransform(this: PluginContext): arkts.ETSModule | undefined { + let script: arkts.ETSModule | undefined; debugLog('interopTransform:parsed'); const contextPtr = arkts.arktsGlobal.compilerContext?.peer ?? this.getContextPtr(); if (!!contextPtr) { @@ -57,7 +57,7 @@ function parsedTransform(this: PluginContext): arkts.EtsScript | undefined { program = programVisitor.programVisitor(program); script = program.astNode; - this.setArkTSAst(script); + this.setArkTSAst(script as arkts.ETSModule); debugLog('interopTransform:parsed exit'); return script; } @@ -66,13 +66,12 @@ function parsedTransform(this: PluginContext): arkts.EtsScript | undefined { return script; } -function checkedTransform(this: PluginContext): arkts.EtsScript | undefined { - let script: arkts.EtsScript | undefined; +function checkedTransform(this: PluginContext): arkts.ETSModule | undefined { debugLog('interopTransform:checked'); const contextPtr = arkts.arktsGlobal.compilerContext?.peer ?? this.getContextPtr(); if (!!contextPtr) { - let program = arkts.getOrUpdateGlobalContext(contextPtr).program; - script = program.astNode; + let program: arkts.Program = arkts.getOrUpdateGlobalContext(contextPtr).program; + let script = program.ast; if (script) { const emitTransformer = new EmitTransformer({ arkui: '@koalaui.arkts-arkui.EmitBase' as interop.TransfromerName @@ -87,13 +86,13 @@ function checkedTransform(this: PluginContext): arkts.EtsScript | undefined { }); program = programVisitor.programVisitor(program); - script = program.astNode; + script = program.ast; arkts.recheckSubtree(script); - this.setArkTSAst(script); + this.setArkTSAst(script as arkts.ETSModule); debugLog('interopTransform:checked exit'); - return script; + return script as arkts.ETSModule; } } debugLog('interopTransform:checked exit with no transform'); - return script; + return undefined; } diff --git a/arkui-plugins/interop-plugins/types.ts b/arkui-plugins/interop-plugins/types.ts index 49b257dc5..4da0eff9b 100644 --- a/arkui-plugins/interop-plugins/types.ts +++ b/arkui-plugins/interop-plugins/types.ts @@ -36,12 +36,12 @@ namespace interop { dumpSrc(): string; } - export interface EtsScript extends Node {} + export interface ETSModule extends Node {} export interface Plugin { name: string; - parsed?(context: PluginContext): EtsScript | undefined; - checked?(context: PluginContext): EtsScript | undefined; + parsed?(context: PluginContext): ETSModule | undefined; + checked?(context: PluginContext): ETSModule | undefined; } export type TransfromerName = string & { __TransfromerNameBrand: any }; diff --git a/arkui-plugins/memo-plugins/function-transformer.ts b/arkui-plugins/memo-plugins/function-transformer.ts index f8e056161..4a0f601f5 100644 --- a/arkui-plugins/memo-plugins/function-transformer.ts +++ b/arkui-plugins/memo-plugins/function-transformer.ts @@ -55,6 +55,7 @@ import { SignatureTransformer } from './signature-transformer'; import { moveToFront } from '../common/arkts-utils'; import { InternalsTransformer } from './internal-transformer'; import { CachedMetadata, rewriteByType } from './memo-cache-factory'; +import { NodeCache } from '../common/node-cache'; interface ScopeInfo extends MemoInfo { regardAsSameScope?: boolean; @@ -241,16 +242,18 @@ export class FunctionTransformer extends AbstractVisitor { return arkts.factory.updateScriptFunction( scriptFunction, afterInternalsTransformer, - arkts.factory.createFunctionSignature( - scriptFunction.typeParams, - scriptFunction.params, - scriptFunction.returnTypeAnnotation, - scriptFunction.hasReceiver - ), + scriptFunction.typeParams, + scriptFunction.params, + scriptFunction.returnTypeAnnotation, + scriptFunction.hasReceiver, scriptFunction.flags, - scriptFunction.modifiers + scriptFunction.modifiers, + scriptFunction.id ?? undefined, + scriptFunction.annotations ?? undefined, + scriptFunction.getSignaturePointer?.() ?? undefined, + scriptFunction.getPreferredReturnTypePointer?.() ?? undefined ); - } + } updateScriptFunction(scriptFunction: arkts.ScriptFunction, name: string = ''): arkts.ScriptFunction { if (!scriptFunction.body || !arkts.isBlockStatement(scriptFunction.body)) { @@ -298,17 +301,17 @@ export class FunctionTransformer extends AbstractVisitor { private updateMethodDefinition(node: arkts.MethodDefinition): arkts.MethodDefinition { let updateMethod: arkts.MethodDefinition; const isMemo = - hasMemoAnnotation(node.scriptFunction) || - hasMemoIntrinsicAnnotation(node.scriptFunction) || - hasMemoEntryAnnotation(node.scriptFunction); - if (isMemo && node.scriptFunction.body) { - const hasIntrinsic = hasMemoIntrinsicAnnotation(node.scriptFunction); + hasMemoAnnotation(node.function!) || + hasMemoIntrinsicAnnotation(node.function!) || + hasMemoEntryAnnotation(node.function!); + if (isMemo && node.function!.body) { + const hasIntrinsic = hasMemoIntrinsicAnnotation(node.function!); updateMethod = arkts.factory.updateMethodDefinition( node, node.kind, node.name, this.signatureTransformer.visitor( - removeMemoAnnotation(this.updateScriptFunction(node.scriptFunction, node.name.name)), + removeMemoAnnotation(this.updateScriptFunction(node.function!, node.name.name)), hasIntrinsic ), node.modifiers, @@ -319,7 +322,7 @@ export class FunctionTransformer extends AbstractVisitor { node, node.kind, node.name, - this.signatureTransformer.visitor(node.scriptFunction), + this.signatureTransformer.visitor(node.function!), node.modifiers, false ); @@ -334,16 +337,16 @@ export class FunctionTransformer extends AbstractVisitor { 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)) { + const param = decl.function!.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.enterAnonymousScope(it.function!); + const res = this.updateScriptFunction(it.function!); this.exitAnonymousScope(); this.modified = true; - return arkts.factory.updateArrowFunction(it, res); + return arkts.factory.updateArrowFunctionExpression(it, res); } return it; }); @@ -355,10 +358,10 @@ export class FunctionTransformer extends AbstractVisitor { ]; } const isMemo = - hasMemoAnnotation(decl.scriptFunction) || - hasMemoIntrinsicAnnotation(decl.scriptFunction) || - hasMemoEntryAnnotation(decl.scriptFunction); - if (parametrizedNodeHasReceiver(decl.scriptFunction) && isMemo) { + hasMemoAnnotation(decl.function!) || + hasMemoIntrinsicAnnotation(decl.function!) || + hasMemoEntryAnnotation(decl.function!); + if (parametrizedNodeHasReceiver(decl.function!) && isMemo) { updatedArguments = moveToFront(updatedArguments, 2); } this.modified = true; @@ -373,19 +376,19 @@ export class FunctionTransformer extends AbstractVisitor { private updateAnonymousCallWithMemoParams(node: arkts.CallExpression): arkts.CallExpression { let newExpression: arkts.AstNode = node.expression; if (isStandaloneArrowFunction(node.expression)) { - newExpression = arkts.factory.updateArrowFunction( + newExpression = arkts.factory.updateArrowFunctionExpression( node.expression, - this.signatureTransformer.visitor(node.expression.scriptFunction) + this.signatureTransformer.visitor(node.expression.function!) ); } const that = this; const updatedArguments: arkts.AstNode[] = node.arguments.map((it) => { if (arkts.isArrowFunctionExpression(it) && isMemoArrowFunction(it)) { - that.enterAnonymousScope(it.scriptFunction); - const res = that.updateScriptFunction(it.scriptFunction); + that.enterAnonymousScope(it.function!); + const res = that.updateScriptFunction(it.function!); that.exitAnonymousScope(); that.modified = true; - return arkts.factory.updateArrowFunction(it, res); + return arkts.factory.updateArrowFunctionExpression(it, res); } return it; }); @@ -398,7 +401,7 @@ export class FunctionTransformer extends AbstractVisitor { expression: arkts.ArrowFunctionExpression ): arkts.CallExpression { const scope = this.scopes[this.scopes.length - 1]; - const isValidScope = !!scope && scope.name === expression.scriptFunction.id?.name; + const isValidScope = !!scope && scope.name === expression.function!.id?.name; if (!isValidScope) { return node; } @@ -408,15 +411,15 @@ export class FunctionTransformer extends AbstractVisitor { } this.checkMemoCallInFunction(); - this.enterAnonymousScope(expression.scriptFunction); - const res = this.updateScriptFunction(expression.scriptFunction, expression.scriptFunction.id?.name); + this.enterAnonymousScope(expression.function!); + const res = this.updateScriptFunction(expression.function!, expression.function!.id?.name); this.exitAnonymousScope(); const newNode = this.updateAnonymousCallWithMemoParams(node); this.modified = true; return arkts.factory.updateCallExpression( node, - arkts.factory.updateArrowFunction(expression, res), + arkts.factory.updateArrowFunctionExpression(expression, res), newNode.typeArguments, [...factory.createHiddenArguments(this.positionalIdTracker.id()), ...newNode.arguments] ); @@ -452,7 +455,7 @@ export class FunctionTransformer extends AbstractVisitor { ) { return this.updateDeclaredCallWithName(node, decl.key.name); } - if (arkts.isEtsParameterExpression(decl) && isMemoETSParameterExpression(decl)) { + if (arkts.isETSParameterExpression(decl) && isMemoETSParameterExpression(decl)) { return this.updateDeclaredCallWithName(node, decl.identifier.name); } return this.updateCallExpressionWithNoDecl(node); @@ -471,8 +474,8 @@ export class FunctionTransformer extends AbstractVisitor { let res: arkts.ScriptFunction | undefined; if (!!node.value && arkts.isArrowFunctionExpression(node.value)) { - this.enterAnonymousScope(node.value.scriptFunction); - res = this.updateScriptFunction(node.value.scriptFunction, key.name); + this.enterAnonymousScope(node.value.function!); + res = this.updateScriptFunction(node.value.function!, key.name); this.exitAnonymousScope(); } @@ -486,7 +489,7 @@ export class FunctionTransformer extends AbstractVisitor { return arkts.factory.updateClassProperty( node, node.key, - res ? arkts.factory.updateArrowFunction(castArrowFunctionExpression(node.value), res) : undefined, + res ? arkts.factory.updateArrowFunctionExpression(castArrowFunctionExpression(node.value), res) : undefined, typeAnnotation, node.modifiers, node.isComputed @@ -526,21 +529,21 @@ export class FunctionTransformer extends AbstractVisitor { private updateStandaloneArrowFunction(node: arkts.ArrowFunctionExpression): arkts.ArrowFunctionExpression { const scope = this.scopes[this.scopes.length - 1]; - const isValidScope = !!scope && scope.name === node.scriptFunction.id?.name; + const isValidScope = !!scope && scope.name === node.function!.id?.name; if (!isValidScope) { return node; } this.exitAnonymousScope(); if (!scope.isMemo) { - return arkts.factory.updateArrowFunction(node, this.signatureTransformer.visitor(node.scriptFunction)); + return arkts.factory.updateArrowFunctionExpression(node, this.signatureTransformer.visitor(node.function!)); } - this.enterAnonymousScope(node.scriptFunction); - const res = this.updateScriptFunction(node.scriptFunction, node.scriptFunction.id?.name); + this.enterAnonymousScope(node.function!); + const res = this.updateScriptFunction(node.function!, node.function!.id?.name); this.exitAnonymousScope(); this.modified = true; - return arkts.factory.updateArrowFunction(node, this.signatureTransformer.visitor(res)); + return arkts.factory.updateArrowFunctionExpression(node, this.signatureTransformer.visitor(res)); } private updateVariableDeclarator(node: arkts.VariableDeclarator): arkts.VariableDeclarator { @@ -556,9 +559,9 @@ export class FunctionTransformer extends AbstractVisitor { node, node.flag, node.name, - arkts.factory.updateArrowFunction( + arkts.factory.updateArrowFunctionExpression( node.initializer, - this.signatureTransformer.visitor(node.initializer.scriptFunction) + this.signatureTransformer.visitor(node.initializer.function!) ) ); } @@ -576,10 +579,10 @@ export class FunctionTransformer extends AbstractVisitor { 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.enterAnonymousScope(initializer.function!); + const res = this.updateScriptFunction(initializer.function!, initializer.function!.id?.name); this.exitAnonymousScope(); - initializer = arkts.factory.updateArrowFunction(initializer, res); + initializer = arkts.factory.updateArrowFunctionExpression(initializer, res); } this.modified = true; @@ -605,8 +608,8 @@ export class FunctionTransformer extends AbstractVisitor { return node; } - this.enterAnonymousScope(expr.scriptFunction); - const res = this.updateScriptFunction(expr.scriptFunction, expr.scriptFunction.id?.name); + this.enterAnonymousScope(expr.function!); + const res = this.updateScriptFunction(expr.function!, expr.function!.id?.name); this.exitAnonymousScope(); let typeAnnotation: arkts.TypeNode | undefined; @@ -618,7 +621,7 @@ export class FunctionTransformer extends AbstractVisitor { this.modified = true; return arkts.factory.updateTSAsExpression( node, - arkts.factory.updateArrowFunction(expr, res), + arkts.factory.updateArrowFunctionExpression(expr, res), typeAnnotation, node.isConst ); @@ -638,14 +641,20 @@ export class FunctionTransformer extends AbstractVisitor { if (!scope.isMemo) { return node; } - - this.enterAnonymousScope(value.scriptFunction); - const res = this.updateScriptFunction(value.scriptFunction, value.scriptFunction.id?.name); + this.enterAnonymousScope(value.function!); + const res = this.updateScriptFunction(value.function!, value.function!.id?.name); this.exitAnonymousScope(); this.modified = true; - return arkts.factory.updateProperty(node, key, arkts.factory.updateArrowFunction(value, res)); - } + return arkts.factory.updateProperty( + node, + node.kind, + key, + arkts.factory.updateArrowFunctionExpression(value, res), + node.isMethod, + node.isComputed + ); + } private updateThisAttributeAssignment( node: arkts.AssignmentExpression, @@ -662,8 +671,8 @@ export class FunctionTransformer extends AbstractVisitor { return node; } - this.enterAnonymousScope(right.scriptFunction); - const res = this.updateScriptFunction(right.scriptFunction, right.scriptFunction.id?.name); + this.enterAnonymousScope(right.function!); + const res = this.updateScriptFunction(right.function!, right.function!.id?.name); this.exitAnonymousScope(); this.modified = true; @@ -671,21 +680,21 @@ export class FunctionTransformer extends AbstractVisitor { node, node.left!, node.operatorType, - arkts.factory.updateArrowFunction(right, res) + arkts.factory.updateArrowFunctionExpression(right, res) ); } private visitorWithCache(beforeChildren: arkts.AstNode): arkts.AstNode { const node = this.visitEachChild(beforeChildren); - if (arkts.NodeCache.getInstance().has(node)) { - const value = arkts.NodeCache.getInstance().get(node)!; + if (NodeCache.getInstance().has(node)) { + const value = NodeCache.getInstance().get(node)!; if (rewriteByType.has(value.type)) { this.modified = true; const metadata: CachedMetadata = { ...value.metadata, internalsTransformer: this.internalsTransformer }; return rewriteByType.get(value.type)!(node, metadata); } } - if (arkts.isEtsScript(node) && this.modified) { + if (arkts.isETSModule(node) && this.modified) { factory.createContextTypesImportDeclaration(this.program); } return node; @@ -726,7 +735,7 @@ export class FunctionTransformer extends AbstractVisitor { const thisAttribute = findThisAttribute(node.left!)!; return this.updateThisAttributeAssignment(node, thisAttribute, node.right); } - if (arkts.isEtsScript(node) && this.modified) { + if (arkts.isETSModule(node) && this.modified) { factory.createContextTypesImportDeclaration(this.program); } return node; diff --git a/arkui-plugins/memo-plugins/import-transformer.ts b/arkui-plugins/memo-plugins/import-transformer.ts index ac8adfaf0..6b28f707a 100644 --- a/arkui-plugins/memo-plugins/import-transformer.ts +++ b/arkui-plugins/memo-plugins/import-transformer.ts @@ -19,9 +19,9 @@ import { factory } from './memo-factory'; export class ImportTransformer extends AbstractVisitor { visitor(node: arkts.AstNode): arkts.AstNode { - if (node instanceof arkts.EtsScript) { + if (arkts.isETSModule(node)) { factory.createContextTypesImportDeclaration(arkts.arktsGlobal.compilerContext?.program); - return arkts.factory.updateEtsScript(node, node.statements); + return arkts.factory.updateETSModule(node, node.statements, node.ident, node.getNamespaceFlag(), node.program); } return node; } diff --git a/arkui-plugins/memo-plugins/index.ts b/arkui-plugins/memo-plugins/index.ts index ca4c52e15..e3546a30d 100644 --- a/arkui-plugins/memo-plugins/index.ts +++ b/arkui-plugins/memo-plugins/index.ts @@ -19,12 +19,13 @@ import { FunctionTransformer } from './function-transformer'; import { PositionalIdTracker } from './utils'; import { ReturnTransformer } from './return-transformer'; import { ParameterTransformer } from './parameter-transformer'; -import { ProgramVisitor } from '../common/program-visitor'; +import { CanSkipPhasesCache, ProgramVisitor } from '../common/program-visitor'; import { EXTERNAL_SOURCE_PREFIX_NAMES, EXTERNAL_SOURCE_PREFIX_NAMES_FOR_FRAMEWORK } from '../common/predefines'; import { debugLog } from '../common/debug'; import { SignatureTransformer } from './signature-transformer'; import { InternalsTransformer } from './internal-transformer'; import { ProgramSkipper } from "../common/program-skipper"; +import { NodeCache } from '../common/node-cache'; export function unmemoizeTransform(): Plugins { return { @@ -37,7 +38,7 @@ export function unmemoizeTransform(): Plugins { }; } -function checkedTransform(this: PluginContext): arkts.EtsScript | undefined { +function checkedTransform(this: PluginContext): arkts.ETSModule | undefined { console.log('[MEMO PLUGIN] AFTER CHECKED ENTER'); arkts.Performance.getInstance().memoryTrackerReset(); arkts.Performance.getInstance().startMemRecord('Node:UIPlugin:Memo-AfterCheck'); @@ -46,7 +47,7 @@ function checkedTransform(this: PluginContext): arkts.EtsScript | undefined { let program = arkts.getOrUpdateGlobalContext(contextPtr).program; let script = program.astNode; const isFrameworkMode = !!this.getProjectConfig()?.frameworkMode; - const canSkipPhases = !isFrameworkMode && program.canSkipPhases(); + const canSkipPhases = !isFrameworkMode && CanSkipPhasesCache.check(program); arkts.Performance.getInstance().createEvent('memo-checked'); program = checkedProgramVisit(program, this, canSkipPhases, isFrameworkMode); @@ -96,7 +97,7 @@ function checkedProgramVisit( returnTransformer, signatureTransformer, internalsTransformer, - useCache: arkts.NodeCache.getInstance().isCollected(), + useCache: NodeCache.getInstance().isCollected(), }); const skipPrefixNames = isFrameworkMode ? EXTERNAL_SOURCE_PREFIX_NAMES_FOR_FRAMEWORK @@ -110,7 +111,7 @@ function checkedProgramVisit( isFrameworkMode }); program = programVisitor.programVisitor(program); - arkts.NodeCache.getInstance().clear(); + NodeCache.getInstance().clear(); } return program; } diff --git a/arkui-plugins/memo-plugins/memo-cache-factory.ts b/arkui-plugins/memo-plugins/memo-cache-factory.ts index 1152c365b..9d0194640 100644 --- a/arkui-plugins/memo-plugins/memo-cache-factory.ts +++ b/arkui-plugins/memo-plugins/memo-cache-factory.ts @@ -30,14 +30,15 @@ import { } from './utils'; import { InternalsTransformer } from './internal-transformer'; import { GenSymPrefix } from '../common/predefines'; +import { AstNodeCacheValueMetadata } from 'collectors/memo-collectors/utils'; -export interface CachedMetadata extends arkts.AstNodeCacheValueMetadata { +export interface CachedMetadata extends AstNodeCacheValueMetadata { internalsTransformer?: InternalsTransformer; } export class RewriteFactory { static rewriteUnionType(node: arkts.ETSUnionType, metadata?: CachedMetadata): arkts.ETSUnionType { - return arkts.factory.updateUnionType( + return arkts.factory.updateETSUnionType( node, node.types.map((t) => { if (arkts.isETSFunctionType(t)) { @@ -124,8 +125,16 @@ export class RewriteFactory { if (!node.value || !arkts.isArrowFunctionExpression(node.value)) { return node; } - return arkts.factory.updateProperty(node, node.key, RewriteFactory.rewriteArrowFunction(node.value, metadata)); - } + const newValue = RewriteFactory.rewriteArrowFunction(node.value, metadata); + return arkts.factory.updateProperty( + node, + node.kind, + node.key, + newValue, + node.isMethod, + node.isComputed + ); + } static rewriteClassProperty(node: arkts.ClassProperty, metadata?: CachedMetadata): arkts.ClassProperty { const newType = !!node.typeAnnotation ? RewriteFactory.rewriteType(node.typeAnnotation, metadata) : undefined; @@ -141,9 +150,9 @@ export class RewriteFactory { metadata?: arkts.AstNodeCacheValueMetadata, expectReturn?: arkts.TypeNode ): arkts.ArrowFunctionExpression { - return arkts.factory.updateArrowFunction( + return arkts.factory.updateArrowFunctionExpression( node, - RewriteFactory.rewriteScriptFunction(node.scriptFunction, metadata, expectReturn) + RewriteFactory.rewriteScriptFunction(node.function!, metadata, expectReturn) ); } @@ -173,7 +182,7 @@ export class RewriteFactory { const returnType = node.returnTypeAnnotation ?? expectReturn ?? - arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID); + arkts.factory.createETSPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID); const _isVoidReturn = isVoidType(returnType); const scopeDeclaration = factory.createScopeDeclaration( returnType, @@ -191,7 +200,7 @@ export class RewriteFactory { const lastReturn = mayAddLastReturn(body) ? factory.createWrappedReturnStatement(factory.createRecacheCall(), _isVoidReturn) : undefined; - return arkts.factory.updateBlock(body, [ + return arkts.factory.updateBlockStatement(body, [ ...body.statements.slice(0, _gensymCount), scopeDeclaration, ...(!!memoParametersDeclaration ? [memoParametersDeclaration] : []), @@ -254,7 +263,7 @@ export class RewriteFactory { node, node.kind, node.name, - RewriteFactory.rewriteScriptFunction(node.scriptFunction, { + RewriteFactory.rewriteScriptFunction(node.function!, { callName: node.name.name, ...metadata, isSetter, diff --git a/arkui-plugins/memo-plugins/memo-factory.ts b/arkui-plugins/memo-plugins/memo-factory.ts index 948fb082e..27cdc9b9d 100644 --- a/arkui-plugins/memo-plugins/memo-factory.ts +++ b/arkui-plugins/memo-plugins/memo-factory.ts @@ -45,7 +45,7 @@ export class factory { const importDecl: arkts.ETSImportDeclaration = arkts.factory.createImportDeclaration( source, [factory.createContextTypeImportSpecifier(), factory.createIdTypeImportSpecifier()], - arkts.Es2pandaImportKinds.IMPORT_KINDS_TYPE, + arkts.Es2pandaImportKinds.IMPORT_KINDS_TYPES, program!, arkts.Es2pandaImportFlags.IMPORT_FLAGS_NONE ); @@ -62,8 +62,8 @@ export class factory { return arkts.factory.createParameterDeclaration( arkts.factory.createIdentifier( RuntimeNames.CONTEXT, - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart(arkts.factory.createIdentifier(RuntimeNames.CONTEXT_TYPE)) + arkts.factory.createETSTypeReference( + arkts.factory.createETSTypeReferencePart(arkts.factory.createIdentifier(RuntimeNames.CONTEXT_TYPE)) ) ), undefined @@ -73,8 +73,8 @@ export class factory { return arkts.factory.createParameterDeclaration( arkts.factory.createIdentifier( RuntimeNames.ID, - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart(arkts.factory.createIdentifier(RuntimeNames.ID_TYPE)) + arkts.factory.createETSTypeReference( + arkts.factory.createETSTypeReferencePart(arkts.factory.createIdentifier(RuntimeNames.ID_TYPE)) ) ), undefined @@ -117,23 +117,25 @@ export class factory { func: arkts.ScriptFunction, newBody?: arkts.AstNode | undefined, returnType?: arkts.TypeNode | undefined - ): arkts.ScriptFunction { + ): 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.typeParams, + factory.createHiddenParameterIfNotAdded(func.params, parametrizedNodeHasReceiver(func)), + returnType ?? func.returnTypeAnnotation, + func.hasReceiver, func.flags, - func.modifiers - ); + func.modifierFlags, + func.id ?? undefined, + func.annotations ?? undefined, + func.getSignaturePointer?.() ?? undefined, + func.getPreferredReturnTypePointer?.() ?? undefined + ); } // Arguments - static createContextArgument(): arkts.AstNode { + static createContextArgument(): arkts.Expression { return arkts.factory.createIdentifier(RuntimeNames.CONTEXT); } static createIdArgument(hash: arkts.NumberLiteral | arkts.StringLiteral): arkts.AstNode { @@ -170,11 +172,14 @@ export class factory { false, false ), - undefined, - [arkts.factory.createNumericLiteral(id), originalIdent] + [arkts.factory.createNumberLiteral(id), originalIdent], + undefined, + false, + false ) ); } + static createMemoParameterDeclaration(parameters: string[]): arkts.VariableDeclaration { return arkts.factory.createVariableDeclaration( arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, @@ -193,8 +198,10 @@ export class factory { false ); } + static createMemoParameterAccessCall(name: string, passArgs?: arkts.AstNode[]): arkts.CallExpression { - const updatedArgs = passArgs ? passArgs : []; + const updatedArgs = (passArgs ?? []) as arkts.Expression[]; + return arkts.factory.createCallExpression( arkts.factory.createMemberExpression( factory.createMemoParameterIdentifier(name), @@ -203,11 +210,13 @@ export class factory { false, false ), - undefined, - [...updatedArgs] + updatedArgs, + undefined, // typeParams + false, // optional_arg + false // trailingComma ); - } - + } + // Recache static createScopeDeclaration( returnTypeAnnotation: arkts.TypeNode | undefined, @@ -229,15 +238,20 @@ export class factory { false, false ), + [ + factory.createIdArgument(hash) as arkts.Expression, + arkts.factory.createNumberLiteral(cnt) as arkts.Expression + ], returnTypeAnnotation ? [returnTypeAnnotation] - : [arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID)], - [factory.createIdArgument(hash), arkts.factory.createNumericLiteral(cnt)] + : [arkts.factory.createETSPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID)], + false, + false ) ), ] ); - } + } static createRecacheCall(arg?: arkts.AstNode): arkts.CallExpression { return arkts.factory.createCallExpression( arkts.factory.createMemberExpression( @@ -247,12 +261,14 @@ export class factory { false, false ), - undefined, - arg ? [arg] : undefined + arg ? [arg as arkts.Expression] : [], + undefined, // typeParams + false, // optional_arg + false // trailingComma ); - } + } static createReturnThis(): arkts.BlockStatement { - return arkts.factory.createBlock([ + return arkts.factory.createBlockStatement([ arkts.factory.createExpressionStatement(factory.createRecacheCall()), arkts.factory.createReturnStatement(arkts.factory.createThisExpression()), ]); @@ -269,7 +285,7 @@ export class factory { ) ); } - return arkts.factory.createBlock([ + return arkts.factory.createBlockStatement([ arkts.factory.createMemberExpression( arkts.factory.createIdentifier(RuntimeNames.SCOPE), arkts.factory.createIdentifier(RuntimeNames.INTERNAL_VALUE), @@ -286,7 +302,7 @@ export class factory { ): arkts.IfStatement { let returnStatement = syntheticReturnStatement; if (isVoidValue && arkts.isReturnStatement(syntheticReturnStatement)) { - returnStatement = arkts.factory.createBlock([ + returnStatement = arkts.factory.createBlockStatement([ arkts.factory.createExpressionStatement(syntheticReturnStatement.argument!), arkts.factory.createReturnStatement(), ]); @@ -309,23 +325,30 @@ export class factory { if (!isReturnVoid) { return arkts.factory.createReturnStatement(argument); } - return arkts.factory.createBlock([ + return arkts.factory.createBlockStatement([ arkts.factory.createExpressionStatement(argument), arkts.factory.createReturnStatement(), ]); } - // Compute static createLambdaWrapper(node: arkts.Expression): arkts.ArrowFunctionExpression { - return arkts.factory.createArrowFunction( + return arkts.factory.createArrowFunctionExpression( arkts.factory.createScriptFunction( - arkts.factory.createBlock([arkts.factory.createReturnStatement(node)]), - arkts.factory.createFunctionSignature(undefined, [], undefined, false), + arkts.factory.createBlockStatement([ + arkts.factory.createReturnStatement(node) + ]), + undefined, // typeParams + [], // params + undefined, // returnTypeAnnotation + false, // hasReceiver arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, + undefined, // ident + undefined // annotations ) ); - } + } + static createComputeExpression( hash: arkts.NumberLiteral | arkts.StringLiteral, node: arkts.Expression @@ -338,11 +361,16 @@ export class factory { false, false ), - undefined, - [factory.createIdArgument(hash), factory.createLambdaWrapper(node)] + [ // _arguments + factory.createIdArgument(hash) as arkts.Expression, + factory.createLambdaWrapper(node) as arkts.Expression + ], + undefined, // typeParams + false, // optional_arg + false // trailingComma ); } - + static updateFunctionBody( node: arkts.BlockStatement, parameters: arkts.ETSParameterExpression[], @@ -368,7 +396,7 @@ export class factory { isVoidValue ); return [ - arkts.factory.updateBlock(node, [ + arkts.factory.updateBlockStatement(node, [ ...node.statements.slice(0, gensymParamsCount), scopeDeclaration, ...(memoParametersDeclaration ? [memoParametersDeclaration] : []), @@ -412,6 +440,12 @@ export class factory { if (!!hasReceiver) { updatedArguments = moveToFront(updatedArguments, 2); } - return arkts.factory.updateCallExpression(node, node.expression, node.typeArguments, updatedArguments); + const expressionArgs = updatedArguments as arkts.Expression[]; + return arkts.factory.updateCallExpression( + node, + node.expression, + expressionArgs, + node.typeArguments + ); } } diff --git a/arkui-plugins/memo-plugins/memo-transformer.ts b/arkui-plugins/memo-plugins/memo-transformer.ts index 430148fc2..66f1eb797 100644 --- a/arkui-plugins/memo-plugins/memo-transformer.ts +++ b/arkui-plugins/memo-plugins/memo-transformer.ts @@ -28,10 +28,10 @@ export interface TransformerOptions { } export default function memoTransformer(userPluginOptions?: TransformerOptions) { - return (node0: arkts.EtsScript) => { + return (node0: arkts.ETSModule) => { const node = ( userPluginOptions?.removeEtsglobal ? new EtsglobalRemover().visitor(node0) : node0 - ) as arkts.EtsScript; + ) as arkts.ETSModule; const positionalIdTracker = new PositionalIdTracker(arkts.getFileName(), false); const parameterTransformer = new ParameterTransformer({ positionalIdTracker, diff --git a/arkui-plugins/memo-plugins/parameter-transformer.ts b/arkui-plugins/memo-plugins/parameter-transformer.ts index 1947b60d1..f9d2cb043 100644 --- a/arkui-plugins/memo-plugins/parameter-transformer.ts +++ b/arkui-plugins/memo-plugins/parameter-transformer.ts @@ -36,16 +36,16 @@ export interface ParameterTransformerOptions extends VisitorOptions { } interface RewriteMemoInfo extends MemoInfo { - rewritePeer: number; + rewritePeer: arkts.KNativePointer; } export class ParameterTransformer extends AbstractVisitor { - private rewriteIdentifiers?: Map arkts.MemberExpression | arkts.Identifier>; - private rewriteCalls?: Map arkts.CallExpression>; - private rewriteMemoInfos?: Map; + private rewriteIdentifiers?: Map arkts.MemberExpression | arkts.Identifier>; + private rewriteCalls?: Map arkts.CallExpression>; + private rewriteMemoInfos?: Map; private rewriteThis?: boolean; private skipNode?: arkts.VariableDeclaration; - private visited: Set; + private visited: Set; private positionalIdTracker: PositionalIdTracker; @@ -135,7 +135,7 @@ export class ParameterTransformer extends AbstractVisitor { initializer: arkts.ArrowFunctionExpression, returnType: arkts.TypeNode | undefined ): arkts.ArrowFunctionExpression { - const scriptFunction = initializer.scriptFunction; + const scriptFunction = initializer.function!; if (!scriptFunction.body || !arkts.isBlockStatement(scriptFunction.body)) { return initializer; } @@ -173,7 +173,7 @@ export class ParameterTransformer extends AbstractVisitor { paramaterTransformer.reset(); returnTransformer.reset(); this.track(updateScriptFunction.body); - return arkts.factory.updateArrowFunction(initializer, updateScriptFunction); + return arkts.factory.updateArrowFunctionExpression(initializer, updateScriptFunction); } private updateVariableDeclareInit( @@ -211,7 +211,7 @@ export class ParameterTransformer extends AbstractVisitor { return node; } const decl = arkts.getPeerDecl(memoInfo.rewritePeer); - if (!decl || !arkts.isEtsParameterExpression(decl)) { + if (!decl || !arkts.isETSParameterExpression(decl)) { return node; } diff --git a/arkui-plugins/memo-plugins/return-transformer.ts b/arkui-plugins/memo-plugins/return-transformer.ts index c2c0fac2e..f11701677 100644 --- a/arkui-plugins/memo-plugins/return-transformer.ts +++ b/arkui-plugins/memo-plugins/return-transformer.ts @@ -60,7 +60,7 @@ export class ReturnTransformer extends AbstractVisitor { return factory.createReturnThis(); } if (node.argument === undefined) { - return arkts.factory.createBlock([ + return arkts.factory.createBlockStatement([ arkts.factory.createExpressionStatement(factory.createRecacheCall()), node, ]); @@ -72,9 +72,9 @@ export class ReturnTransformer extends AbstractVisitor { this.returnTypeInfo.isMemo && arkts.isArrowFunctionExpression(argument) ) { - argument = arkts.factory.updateArrowFunction( + argument = arkts.factory.updateArrowFunctionExpression( argument, - factory.updateScriptFunctionWithMemoParameters(argument.scriptFunction) + factory.updateScriptFunctionWithMemoParameters(argument.function!) ); } diff --git a/arkui-plugins/memo-plugins/signature-transformer.ts b/arkui-plugins/memo-plugins/signature-transformer.ts index 6c15cce2d..f552fa4d8 100644 --- a/arkui-plugins/memo-plugins/signature-transformer.ts +++ b/arkui-plugins/memo-plugins/signature-transformer.ts @@ -67,23 +67,25 @@ export class SignatureTransformer extends AbstractVisitor { return arkts.factory.updateScriptFunction( node, node.body, - arkts.factory.createFunctionSignature( - node.typeParams, - shouldAddMemoParam - ? factory.createHiddenParameterIfNotAdded(newParams, parametrizedNodeHasReceiver(node)) - : newParams, - node.returnTypeAnnotation - ? this.visitor(node.returnTypeAnnotation, shouldApplyMemoToReturnType) - : memo - ? arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID) - : undefined, - node.hasReceiver - ), + node.typeParams, + shouldAddMemoParam + ? factory.createHiddenParameterIfNotAdded(newParams, parametrizedNodeHasReceiver(node)) + : newParams, + node.returnTypeAnnotation + ? this.visitor(node.returnTypeAnnotation, shouldApplyMemoToReturnType) + : memo + ? arkts.factory.createETSPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID) + : undefined, + node.hasReceiver, node.flags, - node.modifiers + node.modifiers, + node.id ?? undefined, + node.annotations ?? undefined, + node.getSignaturePointer?.() ?? undefined, + node.getPreferredReturnTypePointer?.() ?? undefined ) as any as T; } - if (arkts.isEtsParameterExpression(node)) { + if (arkts.isETSParameterExpression(node)) { const memo = hasMemoAnnotation(node) || hasMemoIntrinsicAnnotation(node) || applyMemo; if (!node.type) { if (memo) { diff --git a/arkui-plugins/memo-plugins/utils.ts b/arkui-plugins/memo-plugins/utils.ts index 3a6823daa..81a0628b6 100644 --- a/arkui-plugins/memo-plugins/utils.ts +++ b/arkui-plugins/memo-plugins/utils.ts @@ -108,7 +108,7 @@ export class PositionalIdTracker { return this.stableForTests ? arkts.factory.createStringLiteral(positionId) - : arkts.factory.createNumericLiteral(parseInt(positionId, 16)); + : arkts.factory.createNumberLiteral(parseInt(positionId, 16)); } } @@ -162,7 +162,7 @@ export function removeMemoAnnotation(node: T): T { const newAnnotations: arkts.AnnotationUsage[] = node.annotations.filter( (it) => !isMemoAnnotation(it, RuntimeNames.ANNOTATION) && !isMemoAnnotation(it, RuntimeNames.ANNOTATION_STABLE) ); - if (arkts.isEtsParameterExpression(node)) { + if (arkts.isETSParameterExpression(node)) { node.annotations = newAnnotations; return node; } @@ -354,9 +354,9 @@ export function isMemoClassProperty(node: arkts.ClassProperty): boolean { export function isMemoMethodDefinition(node: arkts.MethodDefinition): boolean { return ( - hasMemoAnnotation(node.scriptFunction) || - hasMemoIntrinsicAnnotation(node.scriptFunction) || - hasMemoEntryAnnotation(node.scriptFunction) + hasMemoAnnotation(node.function!) || + hasMemoIntrinsicAnnotation(node.function!) || + hasMemoEntryAnnotation(node.function!) ); } @@ -429,19 +429,19 @@ export function isMemoProperty(node: arkts.Property, value: arkts.ArrowFunctionE export function isMemoDeclaredMethod(decl: arkts.MethodDefinition): boolean { if ( decl.kind === arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_GET && - findMemoFromTypeAnnotation(decl.scriptFunction.returnTypeAnnotation) + findMemoFromTypeAnnotation(decl.function!.returnTypeAnnotation) ) { return true; } - return !hasMemoEntryAnnotation(decl.scriptFunction) && isMemoMethodDefinition(decl); + return !hasMemoEntryAnnotation(decl.function!) && 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); + return decl.function!.params.some((param) => { + return arkts.isETSParameterExpression(param) && isMemoETSParameterExpression(param); }); } @@ -569,11 +569,11 @@ export function fixGensymParams(params: ParamInfo[], body: arkts.BlockStatement) } export function isMemoContextParamAdded(param: arkts.Expression): boolean { - return arkts.isEtsParameterExpression(param) && param.identifier.name === RuntimeNames.CONTEXT; + return arkts.isETSParameterExpression(param) && param.identifier.name === RuntimeNames.CONTEXT; } export function isMemoIdParamAdded(param: arkts.Expression): boolean { - return arkts.isEtsParameterExpression(param) && param.identifier.name === RuntimeNames.ID; + return arkts.isETSParameterExpression(param) && param.identifier.name === RuntimeNames.ID; } export function isUnmemoizedInFunctionParams(params?: readonly arkts.Expression[], hasReceiver?: boolean): boolean { @@ -618,7 +618,7 @@ export function buildReturnTypeInfo( ): ReturnTypeInfo { const newReturnType = !!returnType ? returnType.clone() - : arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID); + : arkts.factory.createETSPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID); return { node: newReturnType, isMemo, @@ -638,7 +638,7 @@ export function buildeParamInfos(parameters: readonly arkts.ETSParameterExpressi } export function parametersBlockHasReceiver(params: readonly arkts.Expression[]): boolean { - return params.length > 0 && arkts.isEtsParameterExpression(params[0]) && isThisParam(params[0]); + return params.length > 0 && arkts.isETSParameterExpression(params[0]) && isThisParam(params[0]); } export function parametrizedNodeHasReceiver(node: arkts.ScriptFunction | arkts.ETSFunctionType | undefined): boolean { @@ -649,7 +649,7 @@ export function parametrizedNodeHasReceiver(node: arkts.ScriptFunction | arkts.E } function isThisParam(node: arkts.Expression | undefined): boolean { - if (node === undefined || !arkts.isEtsParameterExpression(node)) { + if (node === undefined || !arkts.isETSParameterExpression(node)) { return false; } return node.identifier?.isReceiver ?? false; diff --git a/arkui-plugins/test/ut/common/annotation.test.ts b/arkui-plugins/test/ut/common/annotation.test.ts index 538c961d6..d99bae124 100644 --- a/arkui-plugins/test/ut/common/annotation.test.ts +++ b/arkui-plugins/test/ut/common/annotation.test.ts @@ -57,7 +57,7 @@ class AnnotationVisitor extends AbstractVisitor { } addTestAnnotation(node: AnnotationAstNode): void { - if (arkts.isEtsParameterExpression(node)) { + if (arkts.isETSParameterExpression(node)) { node.annotations = [this.testAnnotation()]; } else if (arkts.isMethodDefinition(node)) { node.scriptFunction.setAnnotations([this.testAnnotation()]); @@ -67,7 +67,7 @@ class AnnotationVisitor extends AbstractVisitor { } removeTestAnnotation(node: AnnotationAstNode): void { - if (arkts.isEtsParameterExpression(node)) { + if (arkts.isETSParameterExpression(node)) { node.annotations = []; } else if (arkts.isMethodDefinition(node)) { node.scriptFunction.setAnnotations([]); @@ -81,7 +81,7 @@ class AnnotationVisitor extends AbstractVisitor { arkts.isClassDefinition(node) || arkts.isClassProperty(node) || arkts.isMethodDefinition(node) || - arkts.isEtsParameterExpression(node) || + arkts.isETSParameterExpression(node) || arkts.isArrowFunctionExpression(node) || arkts.isMethodDefinition(node) || arkts.isVariableDeclaration(node) || @@ -102,8 +102,8 @@ class AnnotationVisitor extends AbstractVisitor { } } -function addAnnotationTransform(this: PluginContext): arkts.EtsScript | undefined { - let script: arkts.EtsScript | undefined; +function addAnnotationTransform(this: PluginContext): arkts.ETSModule | undefined { + let script: arkts.ETSModule | undefined; const contextPtr = this.getContextPtr() ?? arkts.arktsGlobal.compilerContext?.peer; if (!!contextPtr) { let program = arkts.getOrUpdateGlobalContext(contextPtr).program; @@ -122,8 +122,8 @@ function addAnnotationTransform(this: PluginContext): arkts.EtsScript | undefine return script; } -function removeAnnotationTransform(this: PluginContext): arkts.EtsScript | undefined { - let script: arkts.EtsScript | undefined; +function removeAnnotationTransform(this: PluginContext): arkts.ETSModule | undefined { + let script: arkts.ETSModule | undefined; const contextPtr = this.getContextPtr() ?? arkts.arktsGlobal.compilerContext?.peer; if (!!contextPtr) { let program = arkts.getOrUpdateGlobalContext(contextPtr).program; diff --git a/arkui-plugins/test/utils/compile.ts b/arkui-plugins/test/utils/compile.ts index afa55219a..4594b3b87 100644 --- a/arkui-plugins/test/utils/compile.ts +++ b/arkui-plugins/test/utils/compile.ts @@ -44,7 +44,7 @@ function insertPlugin(driver: PluginDriver, plugin: PluginExecutor | undefined): function collectPluginTextContextFromSourceProgram(program: arkts.Program, tracing: TraceOptions): PluginTestContext { const pluginTestContext: PluginTestContext = {}; - const script: arkts.EtsScript = program.astNode; + const script: arkts.ETSModule = program.astNode; pluginTestContext.scriptSnapshot = script.dumpSrc(); return pluginTestContext; } @@ -75,7 +75,7 @@ function collectPluginTextContextFromExternalSource( ); } else { const sourceTestContext: SingleProgramContext = {}; - const script: arkts.EtsScript = sourceProgram.astNode; + const script: arkts.ETSModule = sourceProgram.astNode; const scriptSnapshot = script.dumpSrc(); sourceTestContext.scriptSnapshot = scriptSnapshot; declContexts[name] = sourceTestContext; diff --git a/arkui-plugins/test/utils/plugins/before-memo-no-recheck.ts b/arkui-plugins/test/utils/plugins/before-memo-no-recheck.ts index f6a2c0c13..89db0d3b2 100644 --- a/arkui-plugins/test/utils/plugins/before-memo-no-recheck.ts +++ b/arkui-plugins/test/utils/plugins/before-memo-no-recheck.ts @@ -24,8 +24,8 @@ import { MemoVisitor } from '../../../collectors/memo-collectors/memo-visitor'; */ export const beforeMemoNoRecheck: Plugins = { name: 'before-memo-no-recheck', - checked(this: PluginContext): arkts.EtsScript | undefined { - let script: arkts.EtsScript | undefined; + checked(this: PluginContext): arkts.ETSModule | undefined { + let script: arkts.ETSModule | undefined; const contextPtr = this.getContextPtr() ?? arkts.arktsGlobal.compilerContext?.peer; if (!!contextPtr) { let program = arkts.getOrUpdateGlobalContext(contextPtr).program; diff --git a/arkui-plugins/test/utils/plugins/builder-lambda-no-recheck.ts b/arkui-plugins/test/utils/plugins/builder-lambda-no-recheck.ts index a770c96b0..d4ab2f66c 100644 --- a/arkui-plugins/test/utils/plugins/builder-lambda-no-recheck.ts +++ b/arkui-plugins/test/utils/plugins/builder-lambda-no-recheck.ts @@ -24,8 +24,8 @@ import { BuilderLambdaTransformer } from '../../../ui-plugins/builder-lambda-tra */ export const builderLambdaNoRecheck: Plugins = { name: 'builder-lambda-no-recheck', - checked(this: PluginContext): arkts.EtsScript | undefined { - let script: arkts.EtsScript | undefined; + checked(this: PluginContext): arkts.ETSModule | undefined { + let script: arkts.ETSModule | undefined; const contextPtr = this.getContextPtr() ?? arkts.arktsGlobal.compilerContext?.peer; if (!!contextPtr) { let program = arkts.getOrUpdateGlobalContext(contextPtr).program; diff --git a/arkui-plugins/test/utils/plugins/memo-no-recheck.ts b/arkui-plugins/test/utils/plugins/memo-no-recheck.ts index 9396b34e5..81d03479f 100644 --- a/arkui-plugins/test/utils/plugins/memo-no-recheck.ts +++ b/arkui-plugins/test/utils/plugins/memo-no-recheck.ts @@ -23,13 +23,14 @@ import { ReturnTransformer } from '../../../memo-plugins/return-transformer'; import { SignatureTransformer } from '../../../memo-plugins/signature-transformer'; import { FunctionTransformer } from '../../../memo-plugins/function-transformer'; import { InternalsTransformer } from '../../../memo-plugins/internal-transformer'; +import { NodeCache } from '../../../common/node-cache'; /** * AfterCheck unmemoizeTransform with no recheck AST. */ export const memoNoRecheck: Plugins = { name: 'memo-no-recheck', - checked(this: PluginContext): arkts.EtsScript | undefined { + checked(this: PluginContext): arkts.ETSModule | undefined { const contextPtr = this.getContextPtr() ?? arkts.arktsGlobal.compilerContext?.peer; if (!!contextPtr) { const isFrameworkMode = !!this.getProjectConfig()?.frameworkMode; @@ -51,7 +52,7 @@ export const memoNoRecheck: Plugins = { returnTransformer, signatureTransformer, internalsTransformer, - useCache: arkts.NodeCache.getInstance().isCollected() + useCache: NodeCache.getInstance().isCollected() }); const skipPrefixNames = isFrameworkMode ? EXTERNAL_SOURCE_PREFIX_NAMES_FOR_FRAMEWORK @@ -64,7 +65,7 @@ export const memoNoRecheck: Plugins = { pluginContext: this, }); program = programVisitor.programVisitor(program); - arkts.NodeCache.getInstance().clear(); + NodeCache.getInstance().clear(); script = program.astNode; return script; } diff --git a/arkui-plugins/test/utils/plugins/recheck.ts b/arkui-plugins/test/utils/plugins/recheck.ts index 2c3559df4..be4ac8bf6 100644 --- a/arkui-plugins/test/utils/plugins/recheck.ts +++ b/arkui-plugins/test/utils/plugins/recheck.ts @@ -21,8 +21,8 @@ import { PluginContext, Plugins } from '../../../common/plugin-context'; */ export const recheck: Plugins = { name: 'recheck', - checked(this: PluginContext): arkts.EtsScript | undefined { - let script: arkts.EtsScript | undefined; + checked(this: PluginContext): arkts.ETSModule | undefined { + let script: arkts.ETSModule | undefined; const contextPtr = this.getContextPtr() ?? arkts.arktsGlobal.compilerContext?.peer; if (!!contextPtr) { let program = arkts.getOrUpdateGlobalContext(contextPtr).program; diff --git a/arkui-plugins/test/utils/plugins/struct-no-recheck.ts b/arkui-plugins/test/utils/plugins/struct-no-recheck.ts index 87a7bdbd0..d2c139628 100644 --- a/arkui-plugins/test/utils/plugins/struct-no-recheck.ts +++ b/arkui-plugins/test/utils/plugins/struct-no-recheck.ts @@ -24,8 +24,8 @@ import { StructTransformer } from '../../../ui-plugins/struct-translators/struct */ export const structNoRecheck: Plugins = { name: 'struct-no-recheck', - checked(this: PluginContext): arkts.EtsScript | undefined { - let script: arkts.EtsScript | undefined; + checked(this: PluginContext): arkts.ETSModule | undefined { + let script: arkts.ETSModule | undefined; const contextPtr = this.getContextPtr() ?? arkts.arktsGlobal.compilerContext?.peer; if (!!contextPtr) { let program = arkts.getOrUpdateGlobalContext(contextPtr).program; diff --git a/arkui-plugins/test/utils/plugins/struct-to-component.ts b/arkui-plugins/test/utils/plugins/struct-to-component.ts index ddb0281d2..a0998d1f4 100644 --- a/arkui-plugins/test/utils/plugins/struct-to-component.ts +++ b/arkui-plugins/test/utils/plugins/struct-to-component.ts @@ -24,8 +24,8 @@ import { ComponentTransformer } from '../../../ui-plugins/component-transformer' */ export const structToComponent: Plugins = { name: 'struct-to-component', - parsed(this: PluginContext): arkts.EtsScript | undefined { - let script: arkts.EtsScript | undefined; + parsed(this: PluginContext): arkts.ETSModule | undefined { + let script: arkts.ETSModule | undefined; const contextPtr = this.getContextPtr() ?? arkts.arktsGlobal.compilerContext?.peer; if (!!contextPtr) { let program = arkts.getOrUpdateGlobalContext(contextPtr).program; diff --git a/arkui-plugins/test/utils/plugins/ui-no-recheck.ts b/arkui-plugins/test/utils/plugins/ui-no-recheck.ts index 5fbc6c3fb..343752782 100644 --- a/arkui-plugins/test/utils/plugins/ui-no-recheck.ts +++ b/arkui-plugins/test/utils/plugins/ui-no-recheck.ts @@ -24,8 +24,8 @@ import { CheckedTransformer } from '../../../ui-plugins/checked-transformer'; */ export const uiNoRecheck: Plugins = { name: 'ui-no-recheck', - checked(this: PluginContext): arkts.EtsScript | undefined { - let script: arkts.EtsScript | undefined; + checked(this: PluginContext): arkts.ETSModule | undefined { + let script: arkts.ETSModule | undefined; const contextPtr = this.getContextPtr() ?? arkts.arktsGlobal.compilerContext?.peer; if (!!contextPtr) { let program = arkts.getOrUpdateGlobalContext(contextPtr).program; diff --git a/arkui-plugins/ui-plugins/builder-lambda-translators/builder-factory.ts b/arkui-plugins/ui-plugins/builder-lambda-translators/builder-factory.ts index 081001428..3e7277def 100644 --- a/arkui-plugins/ui-plugins/builder-lambda-translators/builder-factory.ts +++ b/arkui-plugins/ui-plugins/builder-lambda-translators/builder-factory.ts @@ -37,12 +37,12 @@ export class BuilderFactory { return _node; } const conditionScopeVisitor = ConditionScopeVisitor.getInstance(); - funcBody = arkts.factory.updateBlock( + funcBody = arkts.factory.updateBlockStatement( funcBody, funcBody.statements.map((st) => { const newNode = conditionScopeVisitor.visitor(st); conditionScopeVisitor.reset(); - return newNode; + return coerceToAstNode(newNode); }) ); return UIFactory.updateScriptFunction(_node, { params, body: funcBody }); @@ -53,8 +53,9 @@ export class BuilderFactory { */ static rewriteBuilderMethod(node: T): arkts.MethodDefinition { const _node = coerceToAstNode(node); - const newFunc = BuilderFactory.rewriteBuilderScriptFunction(_node.scriptFunction); - return arkts.factory.updateMethodDefinition(_node, _node.kind, _node.name, newFunc, _node.modifiers, false); + const newFunc = BuilderFactory.rewriteBuilderScriptFunction(_node.function!); + const newFuncExpr = arkts.factory.createFunctionExpression(newFunc.id?.clone(), newFunc); + return arkts.factory.updateMethodDefinition(_node, _node.kind, _node.id, newFuncExpr, _node.modifierFlags, false, _node.overloads); } /** @@ -87,7 +88,7 @@ export class BuilderFactory { return _node; } const newValue = BuilderFactory.rewriteBuilderArrowFunction(value); - return arkts.factory.updateProperty(_node, _node.key, newValue); + return arkts.factory.updateProperty(_node, _node.kind, _node.key, newValue, _node.isMethod, _node.isComputed); } /** @@ -97,8 +98,8 @@ export class BuilderFactory { node: T ): arkts.ArrowFunctionExpression { const _node = coerceToAstNode(node); - const newFunc = BuilderFactory.rewriteBuilderScriptFunction(_node.scriptFunction); - return arkts.factory.updateArrowFunction(_node, newFunc); + const newFunc = BuilderFactory.rewriteBuilderScriptFunction(_node.function!); + return arkts.factory.updateArrowFunctionExpression(_node, newFunc); } /** @@ -113,7 +114,7 @@ export class BuilderFactory { return _node; } const newInitializer = BuilderFactory.rewriteBuilderArrowFunction(initializer); - return arkts.factory.updateParameterDeclaration(_node, _node.identifier, newInitializer); + return arkts.factory.updateETSParameterExpression(_node, _node.ident, _node.isOptional, newInitializer, _node.annotations); } /** 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 aba68967c..c623bc500 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 @@ -42,8 +42,9 @@ export class BuilderLambdaTransformer extends AbstractVisitor { return this.visitEachChild(lambda); } const node = this.visitEachChild(beforeChildren); - if (arkts.isEtsScript(node) && ImportCollector.getInstance().importInfos.length > 0) { - ImportCollector.getInstance().insertCurrentImports(this.program); + if (arkts.isETSModule(node) && ImportCollector.getInstance().importInfos.length > 0) { + let imports = ImportCollector.getInstance().getImportStatements(); + return arkts.factory.updateETSModule(node, [...imports, ...node.statements], node.ident, node.getNamespaceFlag(), node.program); } return node; } diff --git a/arkui-plugins/ui-plugins/builder-lambda-translators/condition-scope-visitor.ts b/arkui-plugins/ui-plugins/builder-lambda-translators/condition-scope-visitor.ts index 86ec83025..69e6b759e 100644 --- a/arkui-plugins/ui-plugins/builder-lambda-translators/condition-scope-visitor.ts +++ b/arkui-plugins/ui-plugins/builder-lambda-translators/condition-scope-visitor.ts @@ -77,7 +77,7 @@ export class ConditionScopeVisitor extends AbstractVisitor { const newStatements = node.statements.map((st) => BuilderLambdaFactory.updateContentBodyInBuilderLambda(st, true, true) ); - return arkts.factory.updateBlock(node, newStatements); + return arkts.factory.updateBlockStatement(node, newStatements); } if ( arkts.isArrowFunctionExpression(node) && diff --git a/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts b/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts index fb5650213..282a0727b 100644 --- a/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts +++ b/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts @@ -24,6 +24,7 @@ import { annotation, collect, } from '../../common/arkts-utils'; +import { NodeCache } from '../../common/node-cache'; import { BuilderLambdaDeclInfo, builderLambdaFunctionName, @@ -94,10 +95,11 @@ export class factory { node: arkts.MethodDefinition, prefixArgs: arkts.ETSParameterExpression[], newAnno: arkts.AnnotationUsage[], - newName: string | undefined + newName: string | undefined, + overloads: arkts.MethodDefinition[] ): arkts.MethodDefinition { - const func: arkts.ScriptFunction = node.scriptFunction; - const ident: arkts.Identifier = node.name; + const func: arkts.ScriptFunction = node.function; + const ident: arkts.Identifier = node.id!; const name: string = ident.name; const isFunctionCall: boolean = name !== BuilderLambdaNames.ORIGIN_METHOD_NAME; const newParams: arkts.Expression[] = [...prefixArgs, ...func.params]; @@ -105,24 +107,27 @@ export class factory { .updateScriptFunction( func, func.body, - arkts.FunctionSignature.createFunctionSignature( - func.typeParams, - newParams, - arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), - false - ), + func.typeParams, + newParams, + arkts.factory.createETSPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), + false, func.flags, - func.modifiers - ) - .setAnnotations(newAnno); - + func.modifiers, + newName ? arkts.factory.createIdentifier(newName) : func.id, + newAnno + ); + const scriptFunc = node.id!.name === BuilderLambdaNames.ORIGIN_METHOD_NAME ? addMemoAnnotation(updateFunc) : updateFunc; return arkts.factory.updateMethodDefinition( node, node.kind, - arkts.factory.updateIdentifier(ident, newName ?? name), - isFunctionCall ? updateFunc : addMemoAnnotation(updateFunc), + newName ? arkts.factory.createIdentifier(newName) : node.id, + arkts.factory.createFunctionExpression( + newName ? arkts.factory.createIdentifier(newName) : func.id?.clone(), + isFunctionCall ? updateFunc : addMemoAnnotation(updateFunc) + ), node.modifiers, - false + false, + overloads ); } @@ -130,13 +135,13 @@ export class factory { * transform arguments in style node. */ static getTransformedStyle(call: arkts.CallExpression): BuilderLambdaChainingCallArgInfo[] { - const decl = arkts.getDecl(call.expression); + const decl = arkts.getDecl(call.callee!); if (!decl || !arkts.isMethodDefinition(decl)) { return call.arguments.map((arg) => ({ arg })); } const argInfo: BuilderLambdaChainingCallArgInfo[] = []; const args = call.arguments; - const params = decl.scriptFunction.params; + const params = decl.function!.params; const isTrailingCall = call.isTrailingCall; forEachArgWithParam( args, @@ -164,41 +169,42 @@ export class factory { */ static updateBindableStyleArguments(bindableArg: arkts.Expression): arkts.Expression { const valueType: arkts.TypeNode = getArgumentType(bindableArg); - const objExp: arkts.ObjectExpression = arkts.factory.createObjectExpression( - arkts.Es2pandaAstNodeType.AST_NODE_TYPE_OBJECT_EXPRESSION, - [factory.generateValueProperty(bindableArg), factory.generateOnChangeArrowFunc(bindableArg, valueType)], - false - ); + const objExp: arkts.ObjectExpression = arkts.factory.createObjectExpression([ + factory.generateValueProperty(bindableArg), + factory.generateOnChangeArrowFunc(bindableArg, valueType), + ]); 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): arkts.CallExpression { + static createStyleLambdaBody(lambdaBody: arkts.Expression, callInfo: InstanceCallInfo): arkts.CallExpression { if (!callInfo.isReceiver) { const argInfos: BuilderLambdaChainingCallArgInfo[] = factory.getTransformedStyle(callInfo.call); return arkts.factory.createCallExpression( arkts.factory.createMemberExpression( lambdaBody, - callInfo.call.expression, + callInfo.call.callee, arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, false, false ), - undefined, argInfos.map((info) => { if (arkts.isArrowFunctionExpression(info.arg)) { return this.processArgArrowFunction(info.arg, info.hasBuilder); } return info.arg; - }) + }), + undefined, + false, + false ); } else { - return arkts.factory.createCallExpression(callInfo.call.expression, callInfo.call.typeArguments, [ + return arkts.factory.createCallExpression(callInfo.call.callee, [ lambdaBody, ...callInfo.call.arguments.slice(1), - ]); + ], callInfo.call.typeParams, false, false); } } @@ -264,31 +270,32 @@ export class factory { collectComponentAttributeImport(typeNode, moduleName); const safeType: arkts.TypeNode | undefined = isSafeType(typeNode) ? typeNode : undefined; - const styleLambdaParam: arkts.ETSParameterExpression = arkts.factory.createParameterDeclaration( + const styleLambdaParam: arkts.ETSParameterExpression = arkts.factory.createETSParameterExpression( arkts.factory.createIdentifier(BuilderLambdaNames.STYLE_ARROW_PARAM_NAME, safeType), + false, undefined ); const returnStatement = arkts.factory.createReturnStatement(); - arkts.NodeCache.getInstance().collect(returnStatement); - const body: arkts.BlockStatement = arkts.factory.createBlock([ + NodeCache.getInstance().collect(returnStatement); + const body: arkts.BlockStatement = arkts.factory.createBlockStatement([ arkts.factory.createExpressionStatement(lambdaBody), returnStatement, ]); const func = arkts.factory.createScriptFunction( body, - arkts.FunctionSignature.createFunctionSignature( - undefined, - [styleLambdaParam], - arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), - false - ), + undefined, + [styleLambdaParam], + arkts.factory.createETSPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), + false, arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, + undefined, + undefined ); - return addMemoAnnotation(arkts.factory.createArrowFunction(func)); + return addMemoAnnotation(arkts.factory.createArrowFunctionExpression(func)); } /** @@ -298,28 +305,28 @@ export class factory { typeNode: arkts.TypeNode | undefined, isFunctionCall?: boolean ): arkts.ETSParameterExpression { - const styleLambdaParam: arkts.ETSParameterExpression = arkts.factory.createParameterDeclaration( + const styleLambdaParam: arkts.ETSParameterExpression = arkts.factory.createETSParameterExpression( arkts.factory.createIdentifier(BuilderLambdaNames.STYLE_ARROW_PARAM_NAME, typeNode), + false, undefined ); - const funcType = arkts.factory.createFunctionType( - arkts.FunctionSignature.createFunctionSignature( - undefined, - [styleLambdaParam], - arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), - false - ), + const funcType = arkts.factory.createETSFunctionType( + undefined, + [styleLambdaParam], + arkts.factory.createETSPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), + false, arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW ); addMemoAnnotation(funcType); let parameter: arkts.ETSParameterExpression; - const optionalFuncType = arkts.factory.createUnionType([funcType, arkts.factory.createETSUndefinedType()]); - parameter = arkts.factory.createParameterDeclaration( + const optionalFuncType = arkts.factory.createETSUnionType([funcType, arkts.factory.createETSUndefinedType()]); + parameter = arkts.factory.createETSParameterExpression( arkts.factory.createIdentifier(BuilderLambdaNames.STYLE_PARAM_NAME, optionalFuncType), + false, undefined ); - arkts.NodeCache.getInstance().collect(parameter); + NodeCache.getInstance().collect(parameter); return parameter; } @@ -356,25 +363,25 @@ export class factory { arg: arkts.ArrowFunctionExpression, hasBuilder?: boolean ): arkts.ArrowFunctionExpression { - const func: arkts.ScriptFunction = arg.scriptFunction; + const func: arkts.ScriptFunction = arg.function!; const updateFunc = arkts.factory.updateScriptFunction( func, !!func.body && arkts.isBlockStatement(func.body) - ? arkts.factory.updateBlock( + ? arkts.factory.updateBlockStatement( func.body, func.body.statements.map((st) => this.updateContentBodyInBuilderLambda(st, hasBuilder)) ) : undefined, - arkts.FunctionSignature.createFunctionSignature( - func.typeParams, - func.params, - func.returnTypeAnnotation, - false - ), + func.typeParams, + func.params, + func.returnTypeAnnotation, + false, func.flags, - func.modifiers + func.modifierFlags, + func.id, + func.annotations ); - return arkts.factory.updateArrowFunction(arg, updateFunc); + return arkts.factory.updateArrowFunctionExpression(arg, updateFunc); } /** @@ -425,7 +432,7 @@ export class factory { } let isBuilderParam: boolean = false; let isLinkIntrinsic: boolean = false; - propertyDecl.scriptFunction.annotations.forEach((anno) => { + propertyDecl.function.annotations.forEach((anno) => { isBuilderParam ||= isDecoratorAnnotation(anno, DecoratorNames.BUILDER_PARAM); isLinkIntrinsic ||= isDecoratorIntrinsicAnnotation(anno, DecoratorIntrinsicNames.LINK); }); @@ -474,11 +481,11 @@ export class factory { * If the corresponding argument is not provided, fill-in an `undefined` to it. */ static createOrUpdateArgInBuilderLambda( - fallback: arkts.AstNode | undefined, + fallback: arkts.Expression | undefined, arg: arkts.Expression | undefined, param: arkts.Expression, declInfo?: BuilderLambdaDeclInfo - ): arkts.AstNode | undefined { + ): arkts.Expression | undefined { if (!arg) { return fallback; } @@ -498,7 +505,7 @@ export class factory { return arg; } - static createSecondLastArgInBuilderLambda(argInfo: BuilderLambdaSecondLastArgInfo): arkts.AstNode | undefined { + static createSecondLastArgInBuilderLambda(argInfo: BuilderLambdaSecondLastArgInfo): arkts.Expression | undefined { if (!!argInfo.isReusable && !!argInfo.reuseId) { const reuseIdNode = arkts.factory.createStringLiteral(argInfo.reuseId); return reuseIdNode; @@ -515,11 +522,11 @@ export class factory { leaf: arkts.CallExpression, lambdaBodyInfo: BuilderLambdaStyleBodyInfo, declInfo: BuilderLambdaDeclInfo - ): (arkts.AstNode | undefined)[] { + ): (arkts.Expression | undefined)[] { const { isFunctionCall, params, returnType, moduleName, isFromCommonMethod } = declInfo; const type: arkts.Identifier | undefined = builderLambdaType(leaf); - const args: (arkts.AstNode | undefined)[] = []; - const modifiedArgs: (arkts.AstNode | undefined)[] = []; + const args: (arkts.Expression | undefined)[] = []; + const modifiedArgs: (arkts.Expression | undefined)[] = []; const secondLastArgInfo = buildSecondLastArgInfo(type, isFunctionCall); const isTrailingCall = leaf.isTrailingCall; const typeArguments = leaf.typeArguments; @@ -528,7 +535,7 @@ export class factory { leaf.arguments, params, (arg, param, index) => { - let modifiedArg: arkts.AstNode | undefined; + let modifiedArg: arkts.Expression | undefined; if (index === params.length - 2 && !arg) { modifiedArg = this.createSecondLastArgInBuilderLambda(secondLastArgInfo); } @@ -668,16 +675,16 @@ export class factory { * update if-else in a builder lambda call's arguments. */ static updateIfElseContentBodyInBuilderLambda( - statement: arkts.AstNode, + statement: arkts.Statement, shouldWrap?: boolean, stopAtBuilderLambda?: boolean - ): arkts.AstNode { + ): arkts.Statement { if (arkts.isIfStatement(statement)) { const alternate = !!statement.alternate ? this.updateIfElseContentBodyInBuilderLambda(statement.alternate, shouldWrap, stopAtBuilderLambda) : statement.alternate; const consequence = this.updateIfElseContentBodyInBuilderLambda( - statement.consequent, + statement.consequent!, shouldWrap, stopAtBuilderLambda ); @@ -700,7 +707,7 @@ export class factory { const afterBreak = breakIndex > 0 ? statements.slice(breakIndex) : []; statements = [beforeBreak, ...afterBreak]; } - return arkts.factory.updateBlock(statement, statements); + return arkts.factory.updateBlockStatement(statement, statements); } return statement; } @@ -740,7 +747,7 @@ export class factory { return statement; } - static createBreakBetweenConditionStatements(): arkts.AstNode[] { + static createBreakBetweenConditionStatements(): arkts.Statement[] { const cache = ConditionBreakCache.getInstance(); if (cache.shouldBreak) { return [arkts.factory.createBreakStatement()]; @@ -773,19 +780,19 @@ export class factory { /** * wrap `ConditionScope` or `ConditionBranch` builder function to the block statements. */ - static wrapConditionToBlock(statements: readonly arkts.AstNode[], condition: ConditionNames): arkts.AstNode { - const contentArg = arkts.factory.createArrowFunction( + static wrapConditionToBlock(statements: readonly arkts.Statement[], condition: ConditionNames): arkts.Statement { + const contentArg = arkts.factory.createArrowFunctionExpression( UIFactory.createScriptFunction({ - body: arkts.factory.createBlock(statements), + body: arkts.factory.createBlockStatement(statements), flags: arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, modifiers: arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, }) ); addMemoAnnotation(contentArg); - const newCall = arkts.factory.createCallExpression(arkts.factory.createIdentifier(condition), undefined, [ + const newCall = arkts.factory.createCallExpression(arkts.factory.createIdentifier(condition), [ contentArg, - ]); - arkts.NodeCache.getInstance().collect(newCall); + ], undefined, false, false); + NodeCache.getInstance().collect(newCall); ImportCollector.getInstance().collectSource(condition, ARKUI_BUILDER_SOURCE_NAME); ImportCollector.getInstance().collectImport(condition); return arkts.factory.createExpressionStatement(newCall); @@ -822,7 +829,7 @@ export class factory { const newStatements = statement.statements.map((st) => this.updateContentBodyInBuilderLambda(st, hasBuilder, stopAtBuilderLambda) ); - return arkts.factory.updateBlock(statement, newStatements); + return arkts.factory.updateBlockStatement(statement, newStatements); } if (arkts.isBreakStatement(statement) && statement.parent && arkts.isBlockStatement(statement.parent)) { ConditionBreakCache.getInstance().collectBreak(); @@ -841,7 +848,7 @@ export class factory { if (!callIsGoodForBuilderLambda(leaf) || !declInfo) { return undefined; } - const node = leaf.expression; + const node = leaf.callee; const funcName = builderLambdaFunctionName(leaf); if (!funcName) { return undefined; @@ -857,8 +864,8 @@ export class factory { node.object, arkts.factory.createIdentifier(funcName), arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, - node.computed, - node.optional + node.isComputed, + node.isOptional ); } return undefined; @@ -868,8 +875,8 @@ export class factory { * transform `@ComponentBuilder` in declared methods. */ static transformBuilderLambdaMethodDecl(node: arkts.MethodDefinition): arkts.MethodDefinition { - const nameNode: arkts.Identifier | undefined = node.name; - const func: arkts.ScriptFunction = node.scriptFunction; + const nameNode: arkts.Identifier | undefined = node.id; + const func: arkts.ScriptFunction = node.function!; const isFunctionCall: boolean = isBuilderLambdaFunctionCall(nameNode); if (isFunctionCall) { ComponentAttributeCache.getInstance().collect(node); @@ -882,8 +889,9 @@ export class factory { node, [this.createStyleArgInBuilderLambdaDecl(typeNode, isFunctionCall)], removeAnnotationByName(func.annotations, BuilderLambdaNames.ANNOTATION_NAME), - replaceBuilderLambdaDeclMethodName(nameNode.name) - ).setOverloads(newOverloads); + replaceBuilderLambdaDeclMethodName(nameNode!.name), + newOverloads + ); arkts.NodeCache.getInstance().collect(newNode); return newNode; } @@ -900,17 +908,21 @@ export class factory { curIdx++; continue; } - const property: arkts.Identifier = instanceCalls[curIdx].call.expression as arkts.Identifier; + const property: arkts.Identifier = instanceCalls[curIdx].call.callee as arkts.Identifier; if (property.name === AnimationNames.ANIMATION) { const aniStart: arkts.CallExpression = arkts.factory.createCallExpression( arkts.factory.createIdentifier(AnimationNames.ANIMATION_START), + instanceCalls[curIdx].call.arguments, undefined, - instanceCalls[curIdx].call.arguments + false, + false ); const aniStop: arkts.CallExpression = arkts.factory.createCallExpression( arkts.factory.createIdentifier(AnimationNames.ANIMATION_STOP), + instanceCalls[curIdx].call.arguments.map((arg) => arg.clone()), undefined, - instanceCalls[curIdx].call.arguments.map((arg) => arg.clone()) + false, + false ); instanceCalls.splice(lastAniIdx, 0, { isReceiver: false, call: aniStart }); instanceCalls[curIdx + 1] = { isReceiver: false, call: aniStop }; @@ -925,7 +937,7 @@ export class factory { /** * transform `@ComponentBuilder` in non-declared calls. */ - static transformBuilderLambda(node: arkts.CallExpression): arkts.AstNode { + static transformBuilderLambda(node: arkts.CallExpression): arkts.Expression { let instanceCalls: InstanceCallInfo[] = []; let leaf: arkts.CallExpression = node; while (isStyleChainedCall(leaf) || isStyleWithReceiverCall(leaf)) { @@ -933,17 +945,19 @@ export class factory { instanceCalls.push({ isReceiver: false, call: arkts.factory.createCallExpression( - (leaf.expression as arkts.MemberExpression).property, - leaf.typeArguments, - leaf.arguments + (leaf.callee as arkts.MemberExpression).property, + leaf.arguments, + leaf.typeParams, + leaf.isOptional, + leaf.hasTrailingComma ), }); - leaf = (leaf.expression as arkts.MemberExpression).object as arkts.CallExpression; + leaf = (leaf.callee as arkts.MemberExpression).object as arkts.CallExpression; } if (isStyleWithReceiverCall(leaf)) { instanceCalls.push({ isReceiver: true, - call: arkts.factory.createCallExpression(leaf.expression, leaf.typeArguments, leaf.arguments), + call: arkts.factory.createCallExpression(leaf.callee, leaf.arguments, leaf.typeParams, leaf.isOptional, leaf.hasTrailingComma), }); leaf = leaf.arguments[0] as arkts.CallExpression; } @@ -970,9 +984,10 @@ export class factory { }); } lambdaBodyInfo.lambdaBody = lambdaBody; - const args: (arkts.AstNode | undefined)[] = this.generateArgsInBuilderLambda(leaf, lambdaBodyInfo, declInfo); - const newNode = arkts.factory.updateCallExpression(node, replace, leaf.typeArguments, filterDefined(args)); - arkts.NodeCache.getInstance().collect(newNode); + + const args: (arkts.Expression | undefined)[] = this.generateArgsInBuilderLambda(leaf, lambdaBodyInfo, declInfo); + const newNode = arkts.factory.updateCallExpression(node, replace, filterDefined(args), leaf.typeParams); + NodeCache.getInstance().collect(newNode); return newNode; } @@ -998,22 +1013,24 @@ export class factory { return prop; } const asObjProp: arkts.TSAsExpression = arkts.factory.createTSAsExpression( - arkts.ObjectExpression.createObjectExpression( - arkts.Es2pandaAstNodeType.AST_NODE_TYPE_OBJECT_EXPRESSION, - res, - false - ), + arkts.factory.createObjectExpression(res), factory.createBindableType(valueType), false ); - return arkts.factory.updateProperty(prop, prop.key, asObjProp); + return arkts.factory.updateProperty(prop, prop.kind, prop.key, asObjProp, prop.isMethod, prop.isComputed); } /* * generate `value: ` in object. */ static generateValueProperty(bindableArg: arkts.Expression): arkts.Property { - return arkts.factory.createProperty(arkts.factory.createIdentifier('value'), bindableArg.clone()); + return arkts.factory.createProperty( + arkts.Es2pandaPropertyKind.PROPERTY_KIND_INIT, + arkts.factory.createIdentifier('value'), + bindableArg.clone(), + false, + false, + ); } /* @@ -1021,12 +1038,14 @@ export class factory { */ static generateOnChangeArrowFunc(bindableArg: arkts.Expression, valueType: arkts.TypeNode): arkts.Property { return arkts.factory.createProperty( + arkts.Es2pandaPropertyKind.PROPERTY_KIND_INIT, arkts.factory.createIdentifier('onChange'), PropertyFactory.createArrowFunctionWithParamsAndBody( undefined, [ - arkts.factory.createParameterDeclaration( + arkts.factory.createETSParameterExpression( arkts.factory.createIdentifier('value', valueType.clone()), + false, undefined ), ], @@ -1036,12 +1055,14 @@ export class factory { arkts.factory.createExpressionStatement( arkts.factory.createAssignmentExpression( bindableArg.clone(), - arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - arkts.factory.createIdentifier('value') + arkts.factory.createIdentifier('value'), + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION ) ), ] - ) + ), + false, + false ); } @@ -1051,8 +1072,8 @@ export class factory { static createBindableType(valueType: arkts.TypeNode): arkts.ETSTypeReference { const transformedKey = BindableDecl.BINDABLE; ImportCollector.getInstance().collectImport(transformedKey); - return arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( + return arkts.factory.createETSTypeReference( + arkts.factory.createETSTypeReferencePart( arkts.factory.createIdentifier(transformedKey), arkts.factory.createTSTypeParameterInstantiation([valueType.clone()]) ) @@ -1071,25 +1092,24 @@ export class factory { arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_STATIC | arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_DECLARE | arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_EXPORT; - const param = arkts.factory.createParameterDeclaration( + const param = arkts.factory.createETSParameterExpression( arkts.factory.createIdentifier( BuilderLambdaNames.CONTENT_PARAM_NAME, - arkts.factory.createFunctionType( - arkts.factory.createFunctionSignature( - undefined, - [], - arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), - false - ), + arkts.factory.createETSFunctionType( + undefined, + [], + arkts.factory.createETSPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), + false, arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW ) ), - undefined + false, + undefined, + [annotation(DecoratorNames.BUILDER)] ); - param.annotations = [annotation(DecoratorNames.BUILDER)]; - arkts.NodeCache.getInstance().collect(param); + NodeCache.getInstance().collect(param); const method = UIFactory.createMethodDefinition({ - key, + key: key.clone(), kind: arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_NONE, function: { key, @@ -1101,7 +1121,7 @@ export class factory { }, modifiers, }); - arkts.NodeCache.getInstance().collect(method); + NodeCache.getInstance().collect(method); return method; } @@ -1113,11 +1133,11 @@ export class factory { static addConditionBuilderDecls(): arkts.MethodDefinition[] { const conditionScope = this.createBuilderWithTrailingLambdaDecl( ConditionNames.CONDITION_SCOPE, - arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID) + arkts.factory.createETSPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID) ); const conditionBranch = this.createBuilderWithTrailingLambdaDecl( ConditionNames.CONDITION_BRANCH, - arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID) + arkts.factory.createETSPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID) ); return [conditionScope, conditionBranch]; } diff --git a/arkui-plugins/ui-plugins/builder-lambda-translators/utils.ts b/arkui-plugins/ui-plugins/builder-lambda-translators/utils.ts index 9c4a7531a..9b0dc7bf4 100644 --- a/arkui-plugins/ui-plugins/builder-lambda-translators/utils.ts +++ b/arkui-plugins/ui-plugins/builder-lambda-translators/utils.ts @@ -143,8 +143,8 @@ export function isBuilderLambda(node: arkts.AstNode, nodeDecl?: arkts.AstNode | * @param node method definition node */ export function isFunctionWithReceiver(node: arkts.MethodDefinition): boolean { - if (node.scriptFunction && arkts.isScriptFunction(node.scriptFunction)) { - return node.scriptFunction.hasReceiver; + if (node.function! && arkts.isScriptFunction(node.function!)) { + return node.function!.hasReceiver; } return false; } @@ -169,9 +169,9 @@ export function isFunctionWithReceiverCall(node: arkts.Identifier): boolean { */ export function isStyleChainedCall(node: arkts.CallExpression): boolean { return ( - arkts.isMemberExpression(node.expression) && - arkts.isIdentifier(node.expression.property) && - arkts.isCallExpression(node.expression.object) + arkts.isMemberExpression(node.callee) && + arkts.isIdentifier(node.callee.property) && + arkts.isCallExpression(node.callee.object) ); } @@ -182,8 +182,8 @@ export function isStyleChainedCall(node: arkts.CallExpression): boolean { */ export function isStyleWithReceiverCall(node: arkts.CallExpression): boolean { return ( - arkts.isIdentifier(node.expression) && - isFunctionWithReceiverCall(node.expression) && + arkts.isIdentifier(node.callee) && + isFunctionWithReceiverCall(node.callee) && !!node.arguments.length && arkts.isCallExpression(node.arguments[0]) ); @@ -211,10 +211,10 @@ export function getDeclForBuilderLambdaMethodDecl(node: arkts.AstNode): arkts.As return undefined; } - const isBuilderLambda: boolean = !!node.name && isBuilderLambdaCall(node.name); + const isBuilderLambda: boolean = !!node.id && isBuilderLambdaCall(node.id); const isMethodDecl: boolean = - !!node.scriptFunction && - arkts.hasModifierFlag(node.scriptFunction, arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_DECLARE); + !!node.function! && + arkts.hasModifierFlag(node.function!, arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_DECLARE); if (isBuilderLambda && isMethodDecl) { return node; } @@ -229,14 +229,14 @@ export function getDeclForBuilderLambda( return undefined; } - let currNode: arkts.AstNode = node; + let currNode: arkts.Expression = node; while ( !!currNode && arkts.isCallExpression(currNode) && - !!currNode.expression && - arkts.isMemberExpression(currNode.expression) + !!currNode.callee && + arkts.isMemberExpression(currNode.callee) ) { - const _node: arkts.MemberExpression = currNode.expression; + const _node: arkts.MemberExpression = currNode.callee; if (!!_node.property && arkts.isIdentifier(_node.property) && isBuilderLambdaCall(_node.property)) { return node; @@ -246,7 +246,7 @@ export function getDeclForBuilderLambda( return node; } - currNode = _node.object; + currNode = _node.object!; } if (isBuilderLambdaCall(node, nodeDecl)) { @@ -261,8 +261,8 @@ export function isBuilderLambdaCall( ): boolean { let decl = nodeDecl; if (decl === undefined) { - const expr = arkts.isIdentifier(node) ? node : node.expression; - decl = arkts.getDecl(expr); + const expr = arkts.isIdentifier(node) ? node : node.callee; + decl = expr && arkts.getDecl(expr); } if (!decl) { @@ -290,7 +290,7 @@ export function isBuilderLambdaMethod(node: arkts.MethodDefinition): boolean { return false; } - const result = hasBuilderLambdaAnnotation(node.scriptFunction); + const result = hasBuilderLambdaAnnotation(node.function!); if (result) { return true; } @@ -318,7 +318,7 @@ export function findBuilderLambdaInMethod(node: arkts.MethodDefinition): arkts.A if (!node || !arkts.isMethodDefinition(node)) { return undefined; } - const result = findBuilderLambdaAnnotation(node.scriptFunction); + const result = findBuilderLambdaAnnotation(node.function!); if (!!result) { return result; } @@ -349,8 +349,8 @@ export function findBuilderLambdaInCall( } export function findBuilderLambdaDecl(node: arkts.CallExpression | arkts.Identifier): arkts.AstNode | undefined { - const expr = arkts.isIdentifier(node) ? node : node.expression; - const decl = arkts.getDecl(expr); + const expr = arkts.isIdentifier(node) ? node : node.callee; + const decl = expr && arkts.getDecl(expr); if (!decl) { return undefined; } @@ -389,8 +389,8 @@ export function findBuilderLambdaDeclInfo(decl: arkts.AstNode | undefined): Buil if (!arkts.isMethodDefinition(decl)) { return undefined; } - const func = decl.scriptFunction; - const nameNode = decl.name; + const func = decl.function!; + const nameNode = decl.id!; const originType = func.returnTypeAnnotation; const params = func.params.map((p) => p.clone()); const isFunctionCall = isBuilderLambdaFunctionCall(nameNode); @@ -438,7 +438,7 @@ export function isBuilderLambdaFunctionCall(nameNode: arkts.Identifier | undefin } export function callIsGoodForBuilderLambda(leaf: arkts.CallExpression): boolean { - const node = leaf.expression; + const node = leaf.callee; return arkts.isIdentifier(node) || arkts.isMemberExpression(node); } @@ -454,17 +454,17 @@ export function isSafeType(type: arkts.TypeNode | undefined): boolean { } export function builderLambdaMethodDeclType(method: arkts.MethodDefinition): arkts.TypeNode | undefined { - if (!method || !method.scriptFunction) { + if (!method || !method.function!) { return undefined; } - return method.scriptFunction.returnTypeAnnotation; + return method.function!.returnTypeAnnotation; } export function builderLambdaType(leaf: arkts.CallExpression): arkts.Identifier | undefined { if (!callIsGoodForBuilderLambda(leaf)) { return undefined; } - const node = leaf.expression; + const node = leaf.callee; let name: arkts.Identifier | undefined; if (arkts.isIdentifier(node)) { name = node; @@ -480,13 +480,13 @@ export function builderLambdaFunctionName(node: arkts.CallExpression): string | if (!annotation) { return undefined; } - if (arkts.isIdentifier(node.expression)) { - return getTransformedComponentName(node.expression.name); + if (arkts.isIdentifier(node.callee)) { + return getTransformedComponentName(node.callee.name); } if ( - arkts.isMemberExpression(node.expression) && - arkts.isIdentifier(node.expression.property) && - node.expression.property.name === BuilderLambdaNames.ORIGIN_METHOD_NAME + arkts.isMemberExpression(node.callee) && + arkts.isIdentifier(node.callee.property) && + node.callee.property.name === BuilderLambdaNames.ORIGIN_METHOD_NAME ) { return BuilderLambdaNames.TRANSFORM_METHOD_NAME; } @@ -506,12 +506,12 @@ export function isDoubleDollarCall( return false; } if ( - !(!!value.expression && arkts.isIdentifier(value.expression) && value.expression.name === Dollars.DOLLAR_DOLLAR) + !(!!value.callee && arkts.isIdentifier(value.callee) && value.callee.name === Dollars.DOLLAR_DOLLAR) ) { return false; } if (!ignoreDecl) { - const decl = arkts.getDecl(value.expression); + const decl = arkts.getDecl(value.callee); if (!decl) { return false; } diff --git a/arkui-plugins/ui-plugins/checked-transformer.ts b/arkui-plugins/ui-plugins/checked-transformer.ts index 6ad631797..7b1b01803 100644 --- a/arkui-plugins/ui-plugins/checked-transformer.ts +++ b/arkui-plugins/ui-plugins/checked-transformer.ts @@ -108,7 +108,7 @@ export class CheckedTransformer extends AbstractVisitor { } } if (arkts.isMethodDefinition(node) && this.scope.customComponents.length > 0) { - const name = node.name.name; + const name = node.id!.name; const scopeInfo = this.scope.customComponents.pop()!; scopeInfo.hasInitializeStruct ||= name === CustomComponentNames.COMPONENT_INITIALIZE_STRUCT; scopeInfo.hasUpdateStruct ||= name === CustomComponentNames.COMPONENT_UPDATE_STRUCT; @@ -138,7 +138,7 @@ export class CheckedTransformer extends AbstractVisitor { let isFrom1_1 = false; if (arkts.isMethodDefinition(decl)) { - const annotations = decl.scriptFunction.annotations; + const annotations = decl.function!.annotations; const decorators: string[] = annotations.map((annotation) => { return (annotation.expr as arkts.Identifier).name; }); @@ -160,11 +160,11 @@ export class CheckedTransformer extends AbstractVisitor { visitor(beforeChildren: arkts.AstNode): arkts.AstNode { this.enter(beforeChildren); if (arkts.isCallExpression(beforeChildren)) { - const decl = arkts.getDecl(beforeChildren.expression); - if (arkts.isIdentifier(beforeChildren.expression) && this.isFromBuilder1_1(decl)) { + const decl = arkts.getDecl(beforeChildren.callee!); + if (arkts.isIdentifier(beforeChildren.callee!) && this.isFromBuilder1_1(decl)) { // Builder this.addcompatibleComponentImport(); - return generateBuilderCompatible(beforeChildren, beforeChildren.expression.name); + return generateBuilderCompatible(beforeChildren, beforeChildren.callee!.name); } else if (isBuilderLambda(beforeChildren, decl)) { const lambda = builderLambdaFactory.transformBuilderLambda(beforeChildren); return this.visitEachChild(lambda); @@ -211,10 +211,11 @@ export class CheckedTransformer extends AbstractVisitor { return structFactory.transformCustomDialogController(node); } - if (arkts.isEtsScript(node) && ImportCollector.getInstance().importInfos.length > 0) { - ImportCollector.getInstance().insertCurrentImports(this.program); + if (arkts.isETSModule(node) && ImportCollector.getInstance().importInfos.length > 0) { + let imports = ImportCollector.getInstance().getImportStatements(); LogCollector.getInstance().shouldIgnoreError(this.projectConfig?.ignoreError); LogCollector.getInstance().emitLogInfo(); + return arkts.factory.updateETSModule(node, [...imports, ...node.statements], node.ident, node.getNamespaceFlag(), node.program); } return node; } diff --git a/arkui-plugins/ui-plugins/component-transformer.ts b/arkui-plugins/ui-plugins/component-transformer.ts index ae383cc16..61c9f071d 100644 --- a/arkui-plugins/ui-plugins/component-transformer.ts +++ b/arkui-plugins/ui-plugins/component-transformer.ts @@ -14,9 +14,6 @@ */ import * as arkts from '@koalaui/libarkts'; -import { getInteropPath } from '../path'; -const interop = require(getInteropPath()); -const nullptr = interop.nullptr; import { AbstractVisitor, VisitorOptions } from '../common/abstract-visitor'; import { CustomComponentNames, @@ -35,7 +32,6 @@ import { annotation, filterDefined, collect, - createAndInsertImportDeclaration, isDecoratorAnnotation, } from '../common/arkts-utils'; import { ProjectConfig } from '../common/plugin-context'; @@ -55,6 +51,7 @@ import { EntryWrapperNames, } from '../common/predefines'; import { generateInstantiateInterop } from './interop/interop'; +import { ImportCollector } from '../common/import-collector'; export interface ComponentTransformerOptions extends VisitorOptions { arkui?: string; @@ -95,6 +92,7 @@ export class ComponentTransformer extends AbstractVisitor { hasCustomDialog: false, hasCustomLayout: false, }; + private imports: arkts.ETSImportDeclaration[] = [] constructor(options?: ComponentTransformerOptions) { const _options: ComponentTransformerOptions = options ?? {}; @@ -127,7 +125,7 @@ export class ComponentTransformer extends AbstractVisitor { } enter(node: arkts.AstNode) { - if (arkts.isStructDeclaration(node) && !!node.definition.ident) { + if (arkts.isETSStructDeclaration(node) && !!node.definition?.ident) { const info: ScopeInfo | undefined = collectCustomComponentScopeInfo(node); if (info) { this.scopeInfos.push(info); @@ -178,7 +176,7 @@ export class ComponentTransformer extends AbstractVisitor { } exit(node: arkts.AstNode) { - if (arkts.isStructDeclaration(node) || arkts.isClassDeclaration(node)) { + if (arkts.isETSStructDeclaration(node) || arkts.isClassDeclaration(node)) { if (!node.definition || !node.definition.ident || this.scopeInfos.length === 0) return; if (this.scopeInfos[this.scopeInfos.length - 1]?.name === node.definition.ident.name) { this.scopeInfos.pop(); @@ -186,32 +184,34 @@ export class ComponentTransformer extends AbstractVisitor { } } - createImportDeclaration(sourceName: string, importedName: string): void { - const source: arkts.StringLiteral = arkts.factory.create1StringLiteral(sourceName); + createImportDeclaration(sourceName: string, importedName: string, localName = importedName) { + const source: arkts.StringLiteral = arkts.factory.createStringLiteral(sourceName); const imported: arkts.Identifier = arkts.factory.createIdentifier(importedName); - // Insert this import at the top of the script's statements. - if (!this.program) { - throw Error('Failed to insert import: Transformer has no program'); - } - createAndInsertImportDeclaration( - source, - imported, - imported, - arkts.Es2pandaImportKinds.IMPORT_KINDS_VALUE, - this.program - ); + const local: arkts.Identifier = arkts.factory.createIdentifier(localName); + this.imports.push( + arkts.factory.createETSImportDeclaration( + source, + [ + arkts.factory.createImportSpecifier( + imported, + local, + ), + ], + arkts.Es2pandaImportKinds.IMPORT_KINDS_ALL, + ) + ) } - processEtsScript(node: arkts.EtsScript): arkts.EtsScript { + processEtsScript(node: arkts.ETSModule): arkts.ETSModule { if (this.isExternal && this.externalSourceName === ENTRY_POINT_IMPORT_SOURCE_NAME) { const navInterface = entryFactory.createNavInterface(); navInterface.modifiers = arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_EXPORT; - return arkts.factory.updateEtsScript(node, [...node.statements, navInterface]); + return arkts.factory.updateETSModule(node, [...this.imports, ...node.statements, navInterface], node.ident, node.getNamespaceFlag(), node.program); } if (this.isExternal && this.componentInterfaceCollection.length === 0 && this.entryNames.length === 0) { return node; } - const updateStatements: arkts.AstNode[] = []; + const updateStatements: arkts.Statement[] = []; if (this.shouldAddLinkIntrinsic) { const expr = arkts.factory.createIdentifier(DecoratorIntrinsicNames.LINK); updateStatements.push(factory.createIntrinsicAnnotationDeclaration({ expr })); @@ -222,19 +222,20 @@ export class ComponentTransformer extends AbstractVisitor { } if (this.entryNames.length > 0) { - if (!this.isEntryPointImported) entryFactory.createAndInsertEntryPointImport(this.program); + if (!this.isEntryPointImported) this.imports.push(entryFactory.createAndInsertEntryPointImport(this.program)); // normally, we should only have at most one @Entry component in a single file. // probably need to handle error message here. if (!this.isPageLifeCycleImported) this.createImportDeclaration(CUSTOM_COMPONENT_IMPORT_SOURCE_NAME, CustomComponentNames.PAGE_LIFE_CYCLE); updateStatements.push(...this.entryNames.map(entryFactory.generateEntryWrapper)); updateStatements.push( - entryFactory.callRegisterNamedRouter(this.entryRouteName, this.projectConfig, this.program?.absName) + entryFactory.callRegisterNamedRouter(this.entryRouteName, this.projectConfig, this.program?.absoluteName) ); this.createImportDeclaration(ENTRY_POINT_IMPORT_SOURCE_NAME, NavigationNames.NAVINTERFACE); } - if (updateStatements.length > 0) { - return arkts.factory.updateEtsScript(node, [...node.statements, ...updateStatements]); + + if (updateStatements.length > 0 || this.imports.length > 0) { + return arkts.factory.updateETSModule(node, [...this.imports, ...node.statements, ...updateStatements], node.ident, node.getNamespaceFlag(), node.program); } return node; } @@ -290,21 +291,21 @@ export class ComponentTransformer extends AbstractVisitor { arkts.classDefinitionFlags(definition) | arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC | arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_STATIC; - const body = isDecl ? undefined : arkts.factory.createBlock([arkts.factory.createReturnStatement()]); - const param: arkts.ETSParameterExpression = arkts.factory.createParameterDeclaration( + const body = isDecl ? undefined : arkts.factory.createBlockStatement([arkts.factory.createReturnStatement()]); + const param: arkts.ETSParameterExpression = arkts.factory.createETSParameterExpression( arkts.factory.createIdentifier( CustomComponentNames.OPTIONS, factory.createTypeReferenceFromString(getCustomComponentOptionsName(definition.ident!.name)) ), - undefined + false ); - const returnTypeAnnotation = arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID); + const returnTypeAnnotation = arkts.factory.createETSPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID); const flags = arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD; const kind = arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_METHOD; const key = arkts.factory.createIdentifier(CustomComponentNames.BUILDCOMPATIBLENODE); return factory.createMethodDefinition({ - key, + key: key.clone(), kind, function: { key, @@ -319,14 +320,14 @@ export class ComponentTransformer extends AbstractVisitor { } processComponent( - node: arkts.ClassDeclaration | arkts.StructDeclaration - ): arkts.ClassDeclaration | arkts.StructDeclaration { + node: arkts.ClassDeclaration | arkts.ETSStructDeclaration + ): arkts.ClassDeclaration | arkts.ETSStructDeclaration { const scopeInfo = this.scopeInfos[this.scopeInfos.length - 1]; const className = node.definition?.ident?.name; if (!className || scopeInfo?.name !== className) { return node; } - if (arkts.isStructDeclaration(node)) { + if (arkts.isETSStructDeclaration(node)) { this.collectComponentMembers(node, className); } const customComponentInterface = this.generateComponentInterface( @@ -352,8 +353,8 @@ export class ComponentTransformer extends AbstractVisitor { newDefinitionBody ); - if (arkts.isStructDeclaration(node)) { - arkts.classDefinitionSetFromStructModifier(newDefinition); + if (arkts.isETSStructDeclaration(node)) { + newDefinition.setFromStructModifier() const _node = arkts.factory.createClassDeclaration(newDefinition); _node.modifiers = node.modifiers; _node.startPosition = node.startPosition; @@ -365,7 +366,7 @@ export class ComponentTransformer extends AbstractVisitor { } createNewDefinition( - node: arkts.ClassDeclaration | arkts.StructDeclaration, + node: arkts.ClassDeclaration | arkts.ETSStructDeclaration, className: string, definition: arkts.ClassDefinition, newDefinitionBody: arkts.AstNode[] @@ -389,8 +390,8 @@ export class ComponentTransformer extends AbstractVisitor { undefined, // superTypeParams doen't work [...definition.implements, ...factory.generateImplementsForStruct(scopeInfo.annotations)], undefined, - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( + arkts.factory.createETSTypeReference( + arkts.factory.createETSTypeReferencePart( arkts.factory.createIdentifier(extendsName), arkts.factory.createTSTypeParameterInstantiation([ factory.createTypeReferenceFromString(className), @@ -422,8 +423,8 @@ export class ComponentTransformer extends AbstractVisitor { .createInterfaceDeclaration( [], arkts.factory.createIdentifier(getCustomComponentOptionsName(name)), - nullptr, - arkts.factory.createInterfaceBody([...(this.structMembersMap.get(name) || [])]), + undefined, + arkts.factory.createTSInterfaceBody([...(this.structMembersMap.get(name) || [])]), false, false ) @@ -432,10 +433,10 @@ export class ComponentTransformer extends AbstractVisitor { return interfaceNode; } - collectComponentMembers(node: arkts.StructDeclaration, className: string): void { + collectComponentMembers(node: arkts.ETSStructDeclaration, className: string): void { const members = filterDefined( collect( - ...node.definition.body.filter(arkts.isClassProperty).map((it) => { + ...node.definition!.body.filter(arkts.isClassProperty).map((it) => { if (hasDecoratorName(it, DecoratorNames.PROVIDE)) { factory.processNoAliasProvideVariable(it); } @@ -505,14 +506,14 @@ export class ComponentTransformer extends AbstractVisitor { } processInteropCall(node: arkts.CallExpression): arkts.CallExpression { - const ident = node.expression; - if (!(ident instanceof arkts.Identifier)) { + const ident = node.callee; + if (!arkts.isIdentifier(ident)) { return node; } const className = ident.name; const trailingBlock = node.trailingBlock; const content = trailingBlock - ? arkts.factory.createArrowFunction( + ? arkts.factory.createArrowFunctionExpression( factory.createScriptFunction({ body: trailingBlock, flags: arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, @@ -526,7 +527,7 @@ export class ComponentTransformer extends AbstractVisitor { const context: InteropContext = { className: className, path: path, - arguments: args && args.length === 1 && args[0] instanceof arkts.ObjectExpression ? args[0] : undefined, + arguments: args && args.length === 1 && arkts.isObjectExpression(args[0]) ? args[0] : undefined, content: content, }; return generateInstantiateInterop(context); @@ -537,11 +538,11 @@ export class ComponentTransformer extends AbstractVisitor { visitor(node: arkts.AstNode): arkts.AstNode { this.enter(node); const newNode = this.visitEachChild(node); - if (arkts.isEtsScript(newNode)) { + if (arkts.isETSModule(newNode)) { return this.processEtsScript(newNode); } if ( - arkts.isStructDeclaration(newNode) && + arkts.isETSStructDeclaration(newNode) && this.scopeInfos.length > 0 && isComponentStruct(newNode, this.scopeInfos[this.scopeInfos.length - 1]) ) { diff --git a/arkui-plugins/ui-plugins/entry-translators/factory.ts b/arkui-plugins/ui-plugins/entry-translators/factory.ts index e4dd29d22..836384699 100644 --- a/arkui-plugins/ui-plugins/entry-translators/factory.ts +++ b/arkui-plugins/ui-plugins/entry-translators/factory.ts @@ -15,12 +15,13 @@ import * as arkts from '@koalaui/libarkts'; import * as path from 'path'; -import { annotation, createAndInsertImportDeclaration } from '../../common/arkts-utils'; +import { annotation } from '../../common/arkts-utils'; import { ENTRY_POINT_IMPORT_SOURCE_NAME, EntryWrapperNames, NavigationNames } from '../../common/predefines'; import { ProjectConfig } from '../../common/plugin-context'; import { factory as uiFactory } from '../ui-factory'; import { getRelativePagePath } from './utils'; import { addMemoAnnotation } from '../../collectors/memo-collectors/utils'; +import { NodeCache } from '../../common/node-cache'; export class factory { /** @@ -84,28 +85,27 @@ export class factory { */ static generateEntryFunction(name: string): arkts.MethodDefinition { const exp = arkts.factory.createExpressionStatement( - arkts.factory.createCallExpression(arkts.factory.createIdentifier(name), undefined, []) + arkts.factory.createCallExpression(arkts.factory.createIdentifier(name), [], undefined, false, false) ); const key: arkts.Identifier = arkts.factory.createIdentifier(EntryWrapperNames.ENTRY_FUNC); - const block = arkts.factory.createBlock([exp]); + const block = arkts.factory.createBlockStatement([exp]); const entryScript = arkts.factory .createScriptFunction( block, - arkts.FunctionSignature.createFunctionSignature( - undefined, - [], - arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), - false - ), + undefined, + [], + arkts.factory.createETSPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), + false, arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD, - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, + key, + undefined ) - .setIdent(key); const def = arkts.factory.createMethodDefinition( arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_METHOD, - key, - entryScript, + key.clone(), + arkts.factory.createFunctionExpression(key.clone(), entryScript), arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, false ); @@ -115,21 +115,22 @@ export class factory { static generateConstructor(): arkts.MethodDefinition { const key: arkts.Identifier = arkts.factory.createIdentifier('constructor'); - const block = arkts.factory.createBlock([]); + const block = arkts.factory.createBlockStatement([]); const entryScript = arkts.factory .createScriptFunction( block, - arkts.FunctionSignature.createFunctionSignature(undefined, [], undefined, false), + undefined, [], undefined, false, arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_CONSTRUCTOR | arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_IMPLICIT_SUPER_CALL_NEEDED, arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC | - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_CONSTRUCTOR - ) - .setIdent(key); + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_CONSTRUCTOR, + key, + undefined + ); const def = arkts.factory.createMethodDefinition( arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_CONSTRUCTOR, - key, - entryScript, + key.clone(), + arkts.factory.createFunctionExpression(key.clone(), entryScript), arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, false ); @@ -145,29 +146,33 @@ export class factory { */ static generateEntryProperty(name: string): arkts.ClassProperty { const exp = arkts.factory.createExpressionStatement( - arkts.factory.createCallExpression(arkts.factory.createIdentifier(name), undefined, []) + arkts.factory.createCallExpression(arkts.factory.createIdentifier(name), [], undefined, false, false) ); const key: arkts.Identifier = arkts.factory.createIdentifier(EntryWrapperNames.ENTRY_FUNC); - const block: arkts.BlockStatement = arkts.factory.createBlock([exp]); - const signature: arkts.FunctionSignature = arkts.FunctionSignature.createFunctionSignature( - undefined, - [], - arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), - false - ); + const block: arkts.BlockStatement = arkts.factory.createBlockStatement([exp]); const entryScript: arkts.ScriptFunction = arkts.factory .createScriptFunction( block, - signature, + undefined, + [], + arkts.factory.createETSPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), + false, arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC - ) - .setIdent(key); + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, + key, + undefined + ); const def = arkts.factory.createClassProperty( key, - arkts.factory.createArrowFunction(entryScript), - arkts.factory.createFunctionType(signature, arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW), + arkts.factory.createArrowFunctionExpression(entryScript), + arkts.factory.createETSFunctionType( + undefined, + [], + arkts.factory.createETSPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), + false, + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW + ), arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, false ); @@ -190,8 +195,8 @@ export class factory { undefined, [], undefined, - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( + arkts.factory.createETSTypeReference( + arkts.factory.createETSTypeReferencePart( arkts.factory.createIdentifier(EntryWrapperNames.ENTRY_POINT_CLASS_NAME) ) ), @@ -216,11 +221,11 @@ export class factory { node.definition?.body.forEach((member) => { if ( arkts.isMethodDefinition(member) && - !!member.scriptFunction.id && - member.scriptFunction.id.name === EntryWrapperNames.ENTRY_FUNC + !!member.function!.id && + member.function!.id.name === EntryWrapperNames.ENTRY_FUNC ) { - addMemoAnnotation(member.scriptFunction); - arkts.NodeCache.getInstance().collect(member); + addMemoAnnotation(member.function!); + NodeCache.getInstance().collect(member); } }); } @@ -268,19 +273,19 @@ export class factory { * to the top of script's statements. */ static createAndInsertEntryPointImport(program?: arkts.Program) { - const source: arkts.StringLiteral = arkts.factory.create1StringLiteral(ENTRY_POINT_IMPORT_SOURCE_NAME); + const source: arkts.StringLiteral = arkts.factory.createStringLiteral(ENTRY_POINT_IMPORT_SOURCE_NAME); const imported: arkts.Identifier = arkts.factory.createIdentifier(EntryWrapperNames.ENTRY_POINT_CLASS_NAME); // Insert this import at the top of the script's statements. - if (!program) { - throw Error('Failed to insert import: Transformer has no program'); - } - createAndInsertImportDeclaration( + return arkts.factory.createETSImportDeclaration( source, - imported, - imported, - arkts.Es2pandaImportKinds.IMPORT_KINDS_VALUE, - program - ); + [ + arkts.factory.createImportSpecifier( + imported, + imported.clone(), + ), + ], + arkts.Es2pandaImportKinds.IMPORT_KINDS_ALL, + ) } /** @@ -306,23 +311,25 @@ export class factory { if (useSharedStorage && useSharedStorage.value && arkts.isBooleanLiteral(useSharedStorage.value)) { sharedArg = useSharedStorage.value; } - let storageArg = arkts.factory.createUndefinedLiteral(); + let storageArg: arkts.Expression = arkts.factory.createUndefinedLiteral(); if (storage && storage.value && arkts.isStringLiteral(storage.value)) { storageArg = arkts.factory.createCallExpression( arkts.factory.createIdentifier(storage.value.str), + [], undefined, - undefined + false, + false ); } const superCall = arkts.factory.createExpressionStatement( - arkts.factory.createCallExpression(arkts.factory.createSuperExpression(), undefined, [ + arkts.factory.createCallExpression(arkts.factory.createSuperExpression(), [ sharedArg, storageArg, - ]) + ], undefined, false, false) ); - if (ctor.scriptFunction.body && arkts.isBlockStatement(ctor.scriptFunction.body)) { - ctor.scriptFunction.setBody( - arkts.factory.updateBlock(ctor.scriptFunction.body, [...ctor.scriptFunction.body.statements, superCall]) + if (ctor.function!.body && arkts.isBlockStatement(ctor.function!.body)) { + ctor.function!.setBody( + arkts.factory.updateBlockStatement(ctor.function!.body, [...ctor.function!.body.statements, superCall]) ); } } @@ -333,27 +340,19 @@ export class factory { static navInterfaceArg( projectConfig: ProjectConfig | undefined, fileAbsName: string | undefined - ): arkts.TSAsExpression { + ): arkts.Expression { const projectRoot = projectConfig?.moduleRootPath ? path.join(projectConfig.moduleRootPath, 'src', 'main', 'ets') : ''; const pageFullPath = getRelativePagePath(projectConfig?.projectPath ?? '', fileAbsName ?? ''); const pagePath = getRelativePagePath(projectRoot, fileAbsName ?? ''); - return arkts.factory.createTSAsExpression( - arkts.factory.createObjectExpression( - arkts.Es2pandaAstNodeType.AST_NODE_TYPE_OBJECT_EXPRESSION, - [ - factory.createNavProperty(NavigationNames.BUNDLE_NAME, projectConfig?.bundleName), - factory.createNavProperty(NavigationNames.MODULE_NAME, projectConfig?.moduleName), - factory.createNavProperty(NavigationNames.PAGE_PATH, pagePath), - factory.createNavProperty(NavigationNames.PAGE_FULL_PATH, pageFullPath), - factory.createNavProperty(NavigationNames.INTEGRATED_HSP, projectConfig?.integratedHsp?.toString()), - ], - false - ), - uiFactory.createTypeReferenceFromString(NavigationNames.NAVINTERFACE), - false - ); + return arkts.factory.createObjectExpression([ + factory.createNavProperty(NavigationNames.BUNDLE_NAME, projectConfig?.bundleName), + factory.createNavProperty(NavigationNames.MODULE_NAME, projectConfig?.moduleName), + factory.createNavProperty(NavigationNames.PAGE_PATH, pagePath), + factory.createNavProperty(NavigationNames.PAGE_FULL_PATH, pageFullPath), + factory.createNavProperty(NavigationNames.INTEGRATED_HSP, projectConfig?.integratedHsp?.toString()), + ]); } /** @@ -361,8 +360,11 @@ export class factory { */ static createNavProperty(key: NavigationNames, value: string | undefined): arkts.Property { return arkts.factory.createProperty( + arkts.Es2pandaPropertyKind.PROPERTY_KIND_INIT, arkts.factory.createIdentifier(key), - arkts.factory.createStringLiteral(value ?? '') + arkts.factory.createStringLiteral(value ?? ''), + false, + false ); } @@ -383,19 +385,21 @@ export class factory { false, false ), - undefined, [ arkts.factory.createStringLiteral(entryRouteName ?? ''), arkts.factory.createETSNewClassInstanceExpression( - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( + arkts.factory.createETSTypeReference( + arkts.factory.createETSTypeReferencePart( arkts.factory.createIdentifier(EntryWrapperNames.WRAPPER_CLASS_NAME) ) ), [] ), factory.navInterfaceArg(projectConfig, fileAbsName), - ] + ], + undefined, + false, + false ) ); } @@ -408,7 +412,7 @@ export class factory { [], arkts.factory.createIdentifier(NavigationNames.NAVINTERFACE), undefined, - arkts.factory.createInterfaceBody([ + arkts.factory.createTSInterfaceBody([ this.createClassProp(NavigationNames.BUNDLE_NAME), this.createClassProp(NavigationNames.MODULE_NAME), this.createClassProp(NavigationNames.PAGE_PATH), @@ -437,8 +441,9 @@ export class factory { * helper for generateRegisterNamedRouter to generate param decl, e.g: `routerName: string` */ static registerRouteParam(name: EntryWrapperNames, type: string): arkts.ETSParameterExpression { - return arkts.factory.createParameterDeclaration( + return arkts.factory.createETSParameterExpression( arkts.factory.createIdentifier(name, uiFactory.createTypeReferenceFromString(type)), + false, undefined ); } @@ -456,7 +461,7 @@ export class factory { key: arkts.factory.createIdentifier(EntryWrapperNames.REGISTER_NAMED_ROUTER), kind: arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_METHOD, function: { - body: arkts.factory.createBlock([]), + body: arkts.factory.createBlockStatement([]), params: params, flags: arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD, modifiers: arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_STATIC, diff --git a/arkui-plugins/ui-plugins/index.ts b/arkui-plugins/ui-plugins/index.ts index f34b9b1e8..87a1d0724 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 { CheckedTransformer } from './checked-transformer'; import { Plugins, PluginContext, ProjectConfig } from '../common/plugin-context'; -import { ProgramVisitor } from '../common/program-visitor'; +import { CanSkipPhasesCache, ProgramVisitor } from '../common/program-visitor'; import { EXTERNAL_SOURCE_PREFIX_NAMES } from '../common/predefines'; import { debugLog } from '../common/debug'; import { MetaDataCollector } from '../common/metadata-collector'; @@ -35,8 +35,7 @@ export function uiTransform(): Plugins { }; } -function parsedTransform(this: PluginContext): arkts.EtsScript | undefined { - let script: arkts.EtsScript | undefined; +function parsedTransform(this: PluginContext): arkts.ETSModule | undefined { console.log('[UI PLUGIN] AFTER PARSED ENTER'); arkts.Performance.getInstance().memoryTrackerPrintCurrent('ArkTS:Parse'); arkts.Performance.getInstance().memoryTrackerReset(); @@ -45,22 +44,22 @@ function parsedTransform(this: PluginContext): arkts.EtsScript | undefined { if (!!contextPtr) { let program = arkts.getOrUpdateGlobalContext(contextPtr).program; script = program.astNode; - const canSkipPhases = program.canSkipPhases(); + const canSkipPhases = CanSkipPhasesCache.check(program); arkts.Performance.getInstance().createEvent('ui-parsed'); program = parsedProgramVisit(program, this, canSkipPhases); - script = program.astNode; + script = program.ast; arkts.Performance.getInstance().stopEvent('ui-parsed', true); - this.setArkTSAst(script); + this.setArkTSAst(script as arkts.ETSModule); arkts.Performance.getInstance().memoryTrackerGetDelta('UIPlugin:AfterParse'); arkts.Performance.getInstance().memoryTrackerReset(); arkts.Performance.getInstance().stopMemRecord('Node:UIPlugin:AfterParse'); console.log('[UI PLUGIN] AFTER PARSED EXIT'); - return script; + return script as arkts.ETSModule; } console.log('[UI PLUGIN] AFTER PARSED EXIT WITH NO TRANSFORM'); - return script; + return undefined; } function parsedProgramVisit( @@ -87,8 +86,7 @@ function parsedProgramVisit( return program; } -function checkedTransform(this: PluginContext): arkts.EtsScript | undefined { - let script: arkts.EtsScript | undefined; +function checkedTransform(this: PluginContext): arkts.ETSModule | undefined { console.log('[UI PLUGIN] AFTER CHECKED ENTER'); arkts.Performance.getInstance().memoryTrackerPrintCurrent('ArkTS:Check'); arkts.Performance.getInstance().memoryTrackerGetDelta('ArkTS:Check'); @@ -98,21 +96,21 @@ function checkedTransform(this: PluginContext): arkts.EtsScript | undefined { if (!!contextPtr) { let program = arkts.getOrUpdateGlobalContext(contextPtr).program; script = program.astNode; - const canSkipPhases = program.canSkipPhases(); + const canSkipPhases = CanSkipPhasesCache.check(program); arkts.Performance.getInstance().createEvent('ui-checked'); program = checkedProgramVisit(program, this, canSkipPhases); - script = program.astNode; + script = program.ast; arkts.Performance.getInstance().stopEvent('ui-checked', true); - this.setArkTSAst(script); + this.setArkTSAst(script as arkts.ETSModule); arkts.Performance.getInstance().memoryTrackerGetDelta('UIPlugin:UI-AfterCheck'); arkts.Performance.getInstance().stopMemRecord('Node:UIPlugin:UI-AfterCheck'); console.log('[UI PLUGIN] AFTER CHECKED EXIT'); - return script; + return script as arkts.ETSModule; } console.log('[UI PLUGIN] AFTER CHECKED EXIT WITH NO TRANSFORM'); - return script; + return undefined; } function checkedProgramVisit( diff --git a/arkui-plugins/ui-plugins/interop/builder-interop.ts b/arkui-plugins/ui-plugins/interop/builder-interop.ts index f2073b52d..330d8d0f5 100644 --- a/arkui-plugins/ui-plugins/interop/builder-interop.ts +++ b/arkui-plugins/ui-plugins/interop/builder-interop.ts @@ -24,15 +24,15 @@ import { getWrapValue, setPropertyESValue } from './utils'; +import { NodeCache } from '../../common/node-cache'; interface builderParam { - args: arkts.AstNode[], + args: arkts.Expression[], paramsInfo: arkts.Statement[] } -function invokeFunctionWithParam(functionName: string, result: string, className: string, args: arkts.AstNode[]): arkts.Statement { +function invokeFunctionWithParam(functionName: string, result: string, className: string, args: arkts.Expression[]): arkts.Statement { return arkts.factory.createVariableDeclaration( - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_LET, [arkts.factory.createVariableDeclarator( arkts.Es2pandaVariableDeclaratorFlag.VARIABLE_DECLARATOR_FLAG_LET, @@ -45,12 +45,14 @@ function invokeFunctionWithParam(functionName: string, result: string, className false, false ), - undefined, [ getWrapValue(arkts.factory.createIdentifier(className)), arkts.factory.createIdentifier(InteroperAbilityNames.ELMTID), ...args - ] + ], + undefined, + false, + false ) )] ); @@ -66,8 +68,10 @@ function invokeRunPendingJobs(): arkts.Statement { false, false ), + [], undefined, - undefined + false, + false ) ); } @@ -83,17 +87,19 @@ function invokeComponent(): arkts.Statement[] { false, false ), - undefined, [ arkts.factory.createIdentifier(InteroperAbilityNames.COMPONENT) - ] + ], + undefined, + false, + false ) ); return [viewPU, create]; } function createBuilderInitializer(className: string, functionName: string, param: builderParam): arkts.ArrowFunctionExpression { - const block = arkts.factory.createBlock( + const block = arkts.factory.createBlockStatement( [ createGlobal(), ...createELMTID(), @@ -104,17 +110,17 @@ function createBuilderInitializer(className: string, functionName: string, param createInitReturn(className) ] ); - return arkts.factory.createArrowFunction( + return arkts.factory.createArrowFunctionExpression( arkts.factory.createScriptFunction( block, - arkts.factory.createFunctionSignature( undefined, [], undefined, false, - ), arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, + undefined, + undefined ) ); } @@ -125,7 +131,6 @@ function createBuilderInitializer(className: string, functionName: string, param */ function getInstanceParam(): arkts.Statement { return arkts.factory.createVariableDeclaration( - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_LET, [ arkts.factory.createVariableDeclarator( @@ -140,13 +145,15 @@ function getInstanceParam(): arkts.Statement { false, false ), - undefined, [ arkts.factory.createStringLiteral('arg1') - ] + ], + undefined, + false, + false, ), - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( + arkts.factory.createETSTypeReference( + arkts.factory.createETSTypeReferencePart( arkts.factory.createIdentifier(ESValueMethodNames.ESVALUE) ) ), @@ -175,11 +182,13 @@ function instanceParamTypeOf(): arkts.Statement { false, false ), + [], undefined, - undefined + false, + false, ), arkts.factory.createStringLiteral('object'), arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_NOT_EQUAL ), - arkts.factory.createBlock([ + arkts.factory.createBlockStatement([ arkts.factory.createReturnStatement() ]) ); @@ -192,7 +201,6 @@ function instanceParamTypeOf(): arkts.Statement { */ function getParamWrapped(argument: arkts.Identifier): arkts.Statement { return arkts.factory.createVariableDeclaration( - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_LET, [ arkts.factory.createVariableDeclarator( @@ -206,10 +214,12 @@ function getParamWrapped(argument: arkts.Identifier): arkts.Statement { false, false ), - undefined, [ argument - ] + ], + undefined, + false, + false ) ) ] @@ -222,7 +232,6 @@ function getParamWrapped(argument: arkts.Identifier): arkts.Statement { */ function getItem(): arkts.Statement { return arkts.factory.createVariableDeclaration( - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_LET, [ arkts.factory.createVariableDeclarator( @@ -236,8 +245,10 @@ function getItem(): arkts.Statement { false, false ), + [], undefined, - undefined + false, + false ) ) ] @@ -246,7 +257,6 @@ function getItem(): arkts.Statement { function getResult(): arkts.Statement { return arkts.factory.createVariableDeclaration( - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_LET, [ arkts.factory.createVariableDeclarator( @@ -260,8 +270,10 @@ function getResult(): arkts.Statement { false, false ), + [], undefined, - undefined + false, + false ) ) ] @@ -277,13 +289,13 @@ function getResultDone(): arkts.Statement { false, false ), - arkts.factory.createBlock([ - arkts.BreakStatement.createBreakStatement() + arkts.factory.createBlockStatement([ + arkts.BreakStatement.create1BreakStatement() ]) ); } -function getParamWrappedProperty(): arkts.Statement { +function getParamWrappedProperty(): arkts.Expression { return arkts.factory.createCallExpression( arkts.factory.createMemberExpression( arkts.factory.createIdentifier(BuilderParams.PARAM_WRAPPED), @@ -292,7 +304,6 @@ function getParamWrappedProperty(): arkts.Statement { false, false ), - undefined, [ arkts.factory.createTSAsExpression( arkts.factory.createMemberExpression( @@ -303,14 +314,17 @@ function getParamWrappedProperty(): arkts.Statement { false ), - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( + arkts.factory.createETSTypeReference( + arkts.factory.createETSTypeReferencePart( arkts.factory.createIdentifier(ESValueMethodNames.ESVALUE) ) ), false ), - ] + ], + undefined, + false, + false ); } @@ -324,7 +338,6 @@ function setInstanceParam(): arkts.Statement { false, false ), - undefined, [ arkts.factory.createTSAsExpression( arkts.factory.createMemberExpression( @@ -334,15 +347,18 @@ function setInstanceParam(): arkts.Statement { false, false ), - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( + arkts.factory.createETSTypeReference( + arkts.factory.createETSTypeReferencePart( arkts.factory.createIdentifier(ESValueMethodNames.ESVALUE) ) ), false ), getParamWrappedProperty() - ] + ], + undefined, + false, + false ) ); } @@ -362,7 +378,7 @@ function setInstanceParam(): arkts.Statement { function getWhile(): arkts.Statement { return arkts.WhileStatement.createWhileStatement( arkts.factory.createBooleanLiteral(true), - arkts.factory.createBlock( + arkts.factory.createBlockStatement( [ getResult(), getResultDone(), @@ -421,38 +437,39 @@ function getUpdateArgs(node: arkts.CallExpression): arkts.Statement[] { } function createBuilderUpdate(node: arkts.CallExpression): arkts.ArrowFunctionExpression { - return arkts.factory.createArrowFunction( + return arkts.factory.createArrowFunctionExpression( arkts.factory.createScriptFunction( - arkts.factory.createBlock( + arkts.factory.createBlockStatement( [ ...getUpdateArgs(node) ] ), - arkts.factory.createFunctionSignature( - undefined, - [ - arkts.factory.createParameterDeclaration( - arkts.factory.createIdentifier(InteroperAbilityNames.INSTANCE, - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier(ESValueMethodNames.ESVALUE) - ) + undefined, + [ + arkts.factory.createETSParameterExpression( + arkts.factory.createIdentifier(InteroperAbilityNames.INSTANCE, + arkts.factory.createETSTypeReference( + arkts.factory.createETSTypeReferencePart( + arkts.factory.createIdentifier(ESValueMethodNames.ESVALUE) ) - ), - undefined, + ) ), - ], - undefined, - false, - ), + false, + undefined, + ), + ], + undefined, + false, arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, + undefined, + undefined ) ); } function getInitArgs(node: arkts.CallExpression): builderParam { - const args: arkts.AstNode[] = []; + const args: arkts.Expression[] = []; let ObjectExpressionNum: number = 0; const body: arkts.Statement[] = []; node.arguments.forEach((argument) => { @@ -498,13 +515,13 @@ export function generateBuilderCompatible(node: arkts.CallExpression, moduleName const result = arkts.factory.updateCallExpression( node, arkts.factory.createIdentifier(InteroperAbilityNames.ARKUICOMPATIBLE), - undefined, [ initializer, updater, - ] + ], + undefined ); - arkts.NodeCache.getInstance().collect(result); + NodeCache.getInstance().collect(result); return result; } diff --git a/arkui-plugins/ui-plugins/interop/initstatevar.ts b/arkui-plugins/ui-plugins/interop/initstatevar.ts index 1f43c179e..5cca11059 100644 --- a/arkui-plugins/ui-plugins/interop/initstatevar.ts +++ b/arkui-plugins/ui-plugins/interop/initstatevar.ts @@ -77,9 +77,8 @@ export function initialArgs(args: arkts.ObjectExpression, varMap: Map arkts.Expression): ark proxyName, arkts.factory.createCallExpression( arkts.factory.createIdentifier(InteroperAbilityNames.GETCOMPATIBLESTATE), - undefined, [ stateVar() - ] + ], + undefined, + false, + false ) ); } @@ -205,7 +206,7 @@ export function processLink(keyName: string, value: arkts.Expression, type: arkt * @param keyName - The name of the state variable (e.g., state) * @returns generate code to process regular data interoperability */ -export function processNormal(keyName: string, value: arkts.AstNode): arkts.Statement[] { +export function processNormal(keyName: string, value: arkts.Expression): arkts.Statement[] { const result: arkts.Statement[] = []; if (arkts.isObjectExpression(value)) { processObjectLiteral(value, InteroperAbilityNames.PARAM, result, keyName); @@ -229,16 +230,18 @@ export function processNormal(keyName: string, value: arkts.AstNode): arkts.Stat * Input: {builderParam: this.builder} * Output: param.setProperty("builderParam", transferCompatibleBuilder(this.builder)); */ -export function processBuilderParam(keyName: string, value: arkts.AstNode): arkts.Statement[] { +export function processBuilderParam(keyName: string, value: arkts.Expression): arkts.Statement[] { const result: arkts.Statement[] = []; const needUpdate: boolean = checkUpdatable(value); const newValue = arkts.factory.createCallExpression( needUpdate ? arkts.factory.createIdentifier(BuilderMethodNames.TRANSFERCOMPATIBLEUPDATABLEBUILDER) : arkts.factory.createIdentifier(BuilderMethodNames.TRANSFERCOMPATIBLEBUILDER), - undefined, [ value - ] + ], + undefined, + false, + false ); const setProperty = setPropertyESValue( InteroperAbilityNames.PARAM, diff --git a/arkui-plugins/ui-plugins/interop/interop.ts b/arkui-plugins/ui-plugins/interop/interop.ts index 554444410..d27fdb705 100644 --- a/arkui-plugins/ui-plugins/interop/interop.ts +++ b/arkui-plugins/ui-plugins/interop/interop.ts @@ -30,42 +30,36 @@ import { createInitReturn } from './utils'; import { ImportCollector } from '../../common/import-collector'; -import { factory as uiFactory } from '../ui-factory'; import { DecoratorNames } from '../../common/predefines'; import { hasDecorator } from '../property-translators/utils'; - +import { NodeCache } from '../../common/node-cache'; function paramsLambdaDeclaration(name: string, args?: arkts.ObjectExpression): arkts.Statement[] { const result: arkts.Statement[] = []; 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.createArrowFunctionExpression( arkts.factory.createScriptFunction( - arkts.factory.createBlock([arkts.factory.createReturnStatement( - args ? args : arkts.ObjectExpression.createObjectExpression( - arkts.Es2pandaAstNodeType.AST_NODE_TYPE_OBJECT_EXPRESSION, - [], - false - ), + arkts.factory.createBlockStatement([arkts.factory.createReturnStatement( + args ? args : arkts.factory.createObjectExpression([]), )]), - arkts.factory.createFunctionSignature( - undefined, - [], - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier(getCustomComponentOptionsName(name)) - ) - ), - false + undefined, + [], + arkts.factory.createETSTypeReference( + arkts.factory.createETSTypeReferencePart( + arkts.factory.createIdentifier(getCustomComponentOptionsName(name)) + ) ), + false, arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, + undefined, + undefined ) ) ), @@ -77,7 +71,7 @@ function paramsLambdaDeclaration(name: string, args?: arkts.ObjectExpression): a } function createExtraInfo(properties: string[], value: string[]): arkts.Statement[] { - const body: arkts.AstNode[] = []; + const body: arkts.Statement[] = []; body.push(createEmptyESValue(InteroperAbilityNames.EXTRAINFO)); properties.forEach((prop, index) => { const val = value[index]; @@ -90,7 +84,7 @@ function createExtraInfo(properties: string[], value: string[]): arkts.Statement return body; } -function generateTSASExpression(expression: arkts.AstNode): arkts.Expression { +function generateTSASExpression(expression: arkts.Expression): arkts.Expression { return arkts.factory.createTSAsExpression( arkts.factory.createCallExpression( arkts.factory.createMemberExpression( @@ -100,11 +94,13 @@ function generateTSASExpression(expression: arkts.AstNode): arkts.Expression { false, false ), + [], undefined, - undefined + false, + false ), - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( + arkts.factory.createETSTypeReference( + arkts.factory.createETSTypeReferencePart( arkts.factory.createIdentifier('Object') ) ), @@ -124,21 +120,21 @@ function newComponent(className: string): arkts.Statement { arkts.factory.createUndefinedLiteral(), generateTSASExpression(arkts.factory.createIdentifier(InteroperAbilityNames.ELMTID)), arkts.factory.createTSAsExpression( - arkts.factory.createArrowFunction( + arkts.factory.createArrowFunctionExpression( arkts.factory.createScriptFunction( - arkts.factory.createBlock([]), - arkts.factory.createFunctionSignature( - undefined, - [], - undefined, - false - ), + arkts.factory.createBlockStatement([]), + undefined, + [], + undefined, + false, arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, + undefined, + undefined ) ), - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( + arkts.factory.createETSTypeReference( + arkts.factory.createETSTypeReferencePart( arkts.factory.createIdentifier('Object') ) ), @@ -163,10 +159,12 @@ function createComponent(className: string): arkts.Statement[] { false, false ), - undefined, [ arkts.factory.createIdentifier(InteroperAbilityNames.COMPONENT) - ] + ], + undefined, + false, + false ) ); return [component, ViewPU, create]; @@ -187,7 +185,7 @@ function createWrapperBlock(context: InteropContext, varMap: Map, updateProp: arkts.Property[]): arkts.ArrowFunctionExpression { const block = createWrapperBlock(context, varMap, updateProp); - return arkts.factory.createArrowFunction( + return arkts.factory.createArrowFunctionExpression( arkts.factory.createScriptFunction( block, - arkts.factory.createFunctionSignature( - undefined, - [], - undefined, - false, - ), + undefined, + [], + undefined, + false, arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, + undefined, + undefined ) ); } @@ -234,19 +232,23 @@ function updateStateVars(updateProp: arkts.Property[]): arkts.Statement[] { const insertProp = createUpdateProp(updateProp); return [ ...insertProp, - arkts.factory.createCallExpression( - arkts.factory.createMemberExpression( - arkts.factory.createIdentifier(InteroperAbilityNames.INSTANCE), - arkts.factory.createIdentifier(ESValueMethodNames.INVOKEMETHOD), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + arkts.factory.createExpressionStatement( + arkts.factory.createCallExpression( + arkts.factory.createMemberExpression( + arkts.factory.createIdentifier(InteroperAbilityNames.INSTANCE), + arkts.factory.createIdentifier(ESValueMethodNames.INVOKEMETHOD), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ), + [ + arkts.factory.createStringLiteral('updateStateVars'), + arkts.factory.createIdentifier('updateParam') + ], + undefined, false, false - ), - undefined, - [ - arkts.factory.createStringLiteral('updateStateVars'), - arkts.factory.createIdentifier('updateParam') - ] + ) ) ]; } @@ -259,32 +261,33 @@ function updateStateVars(updateProp: arkts.Property[]): arkts.Statement[] { */ function createUpdater(updateProp: arkts.Property[]): arkts.ArrowFunctionExpression { const updateState = (updateProp.length !== 0) ? updateStateVars(updateProp) : []; - return arkts.factory.createArrowFunction( + return arkts.factory.createArrowFunctionExpression( arkts.factory.createScriptFunction( - arkts.factory.createBlock( + arkts.factory.createBlockStatement( [ ...updateState ] ), - arkts.factory.createFunctionSignature( - undefined, - [ - arkts.factory.createParameterDeclaration( - arkts.factory.createIdentifier(InteroperAbilityNames.INSTANCE, - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier(ESValueMethodNames.ESVALUE) - ) + undefined, + [ + arkts.factory.createETSParameterExpression( + arkts.factory.createIdentifier(InteroperAbilityNames.INSTANCE, + arkts.factory.createETSTypeReference( + arkts.factory.createETSTypeReferencePart( + arkts.factory.createIdentifier(ESValueMethodNames.ESVALUE) ) - ), - undefined, + ) ), - ], - undefined, - false, - ), + false, + undefined, + ), + ], + undefined, + false, arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, + undefined, + undefined ) ); } @@ -292,41 +295,41 @@ function createUpdater(updateProp: arkts.Property[]): arkts.ArrowFunctionExpress function updateArguments(context: InteropContext, name: string): arkts.ObjectExpression { return context.arguments ? arkts.factory.updateObjectExpression( context.arguments, - arkts.Es2pandaAstNodeType.AST_NODE_TYPE_OBJECT_EXPRESSION, [ ...(context.arguments?.properties as arkts.Property[]), arkts.factory.createProperty( + arkts.Es2pandaPropertyKind.PROPERTY_KIND_INIT, arkts.factory.createIdentifier(name), arkts.factory.createTSAsExpression( context.content, - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( - arkts.factory.createIdentifier('Function') - ) - ), - false - ) - ) - ], - false - ) : arkts.factory.createObjectExpression( - arkts.Es2pandaAstNodeType.AST_NODE_TYPE_OBJECT_EXPRESSION, - [ - arkts.factory.createProperty( - arkts.factory.createIdentifier(name), - arkts.factory.createTSAsExpression( - context.content, - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( + arkts.factory.createETSTypeReference( + arkts.factory.createETSTypeReferencePart( arkts.factory.createIdentifier('Function') ) ), false - ) + ), + false, + false ) ], - false - ); + ) : arkts.factory.createObjectExpression([ + arkts.factory.createProperty( + arkts.Es2pandaPropertyKind.PROPERTY_KIND_INIT, + arkts.factory.createIdentifier(name), + arkts.factory.createTSAsExpression( + context.content, + arkts.factory.createETSTypeReference( + arkts.factory.createETSTypeReferencePart( + arkts.factory.createIdentifier('Function') + ) + ), + false + ), + false, + false, + ) + ]); } function generateVarMap(context: InteropContext, node: arkts.Identifier): Map { @@ -351,8 +354,8 @@ function generateVarMap(context: InteropContext, node: arkts.Identifier): Map.instantiate_Interop. */ 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') { + if (arkts.isCallExpression(node) && arkts.isMemberExpression(node.callee) && + arkts.isIdentifier(node.callee?.property) && + node.callee?.property.name === 'instantiate_Interop') { ImportCollector.getInstance().collectSource(InteroperAbilityNames.ARKUICOMPATIBLE, InteroperAbilityNames.INTEROP); ImportCollector.getInstance().collectImport(InteroperAbilityNames.ARKUICOMPATIBLE); ImportCollector.getInstance().collectSource(InteroperAbilityNames.GETCOMPATIBLESTATE, InteroperAbilityNames.INTEROP); @@ -416,14 +421,14 @@ export function isArkUICompatible(node: arkts.AstNode): boolean { * @returns After Checked, transform instantiate_Interop -> ArkUICompatible */ export function generateArkUICompatible(node: arkts.CallExpression): arkts.CallExpression { - const classInterop = (node.expression as arkts.MemberExpression).object as arkts.Identifier; + const classInterop = (node.callee 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 content = args[4] instanceof arkts.UndefinedLiteral ? undefined : args[4] as arkts.ArrowFunctionExpression; + const line = arkts.isUndefinedLiteral(args[1]) ? undefined : (args[1] as arkts.NumberLiteral).value(); + const col = arkts.isUndefinedLiteral(args[2]) ? undefined : (args[2] as arkts.NumberLiteral).value(); + const options = arkts.isUndefinedLiteral(args[3]) ? undefined : args[3] as arkts.ObjectExpression; + const content = arkts.isUndefinedLiteral(args[4]) ? undefined : args[4] as arkts.ArrowFunctionExpression; const context: InteropContext = { className: className, path: path, @@ -440,13 +445,13 @@ export function generateArkUICompatible(node: arkts.CallExpression): arkts.CallE const result = arkts.factory.updateCallExpression( node, arkts.factory.createIdentifier(InteroperAbilityNames.ARKUICOMPATIBLE), - undefined, [ initializer, updater, arkts.factory.createThisExpression(), - ] + ], + undefined, ); - arkts.NodeCache.getInstance().collect(result); + NodeCache.getInstance().collect(result); return result; } \ No newline at end of file diff --git a/arkui-plugins/ui-plugins/interop/legacy-transformer.ts b/arkui-plugins/ui-plugins/interop/legacy-transformer.ts index 1b831a9b0..0c45d6be0 100644 --- a/arkui-plugins/ui-plugins/interop/legacy-transformer.ts +++ b/arkui-plugins/ui-plugins/interop/legacy-transformer.ts @@ -16,9 +16,6 @@ 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 './predefines'; import { getCustomComponentOptionsName } from '../utils'; @@ -58,47 +55,44 @@ export class LegacyTransformer extends AbstractVisitor { return this.structList; } - createParam(name: string, type: string): arkts.ETSParameterExpression { - return arkts.factory.createParameterDeclaration( + createParam(name: string, type: string, isOptional = false): arkts.ETSParameterExpression { + return arkts.factory.createETSParameterExpression( arkts.factory.createIdentifier( name, - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( + arkts.factory.createETSTypeReference( + arkts.factory.createETSTypeReferencePart( arkts.factory.createIdentifier(type) ) ) ), - undefined + isOptional, + 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 trailingBlock = this.createParam('trailingBlock', 'Object'); - trailingBlock.setOptional(true); + const line = this.createParam('line', 'number', true); + const col = this.createParam('col', 'number', true); + const options = this.createParam('options', getCustomComponentOptionsName(name), true); + const trailingBlock = this.createParam('trailingBlock', 'Object', true); const script = arkts.factory.createScriptFunction( - arkts.factory.createBlock([]), - arkts.FunctionSignature.createFunctionSignature( - undefined, - [path, line, col, options, trailingBlock], - arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), - false - ), + arkts.factory.createBlockStatement([]), + undefined, + [path, line, col, options, trailingBlock], + arkts.factory.createETSPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), + false, arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD, - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC | arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_STATIC + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC | arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_STATIC, + arkts.factory.createIdentifier('instantiate_Interop'), + undefined ); return arkts.factory.createMethodDefinition( arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_METHOD, arkts.factory.createIdentifier('instantiate_Interop'), - script, + arkts.factory.createFunctionExpression(arkts.factory.createIdentifier('instantiate_Interop'), script), arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC | arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_STATIC, false ); @@ -127,8 +121,8 @@ export class LegacyTransformer extends AbstractVisitor { const interfaceNode = arkts.factory.createInterfaceDeclaration( [], arkts.factory.createIdentifier(getCustomComponentOptionsName(name)), - nullptr, - arkts.factory.createInterfaceBody([...(this.generateMember(map) || [])]), + undefined, + arkts.factory.createTSInterfaceBody([...(this.generateMember(map) || [])]), false, false ); @@ -136,7 +130,7 @@ export class LegacyTransformer extends AbstractVisitor { return interfaceNode; } - processComponent(node: arkts.StructDeclaration): arkts.StructDeclaration | arkts.ClassDeclaration { + processComponent(node: arkts.ETSStructDeclaration): arkts.ETSStructDeclaration | arkts.ClassDeclaration { const definition: arkts.ClassDefinition = node.definition!; const ident = definition.ident!; const hasExportFlag = @@ -162,7 +156,7 @@ export class LegacyTransformer extends AbstractVisitor { arkts.Es2pandaLanguage.JS ); - if (arkts.isStructDeclaration(node)) { + if (arkts.isETSStructDeclaration(node)) { const _node = arkts.factory.createClassDeclaration(newDefinition); _node.modifiers = node.modifiers; return _node; @@ -172,39 +166,46 @@ export class LegacyTransformer extends AbstractVisitor { } processConstructor(node: arkts.MethodDefinition): arkts.MethodDefinition { - const valueType = arkts.factory.createUnionType([ - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( + const valueType = arkts.factory.createETSUnionType([ + arkts.factory.createETSTypeReference( + arkts.factory.createETSTypeReferencePart( arkts.factory.createIdentifier('Object') ) ), arkts.factory.createETSUndefinedType() ]); const script = factory.createScriptFunction({ - body: arkts.factory.createBlock([]), + key: node.id?.clone(), + body: arkts.factory.createBlockStatement([]), params: [ - arkts.factory.createParameterDeclaration( + arkts.factory.createETSParameterExpression( arkts.factory.createIdentifier(InteroperAbilityNames.PARENT, valueType), + false, undefined, ), - arkts.factory.createParameterDeclaration( + arkts.factory.createETSParameterExpression( arkts.factory.createIdentifier(InteroperAbilityNames.PARAM, valueType), + false, undefined, ), - arkts.factory.createParameterDeclaration( + arkts.factory.createETSParameterExpression( arkts.factory.createIdentifier('localStorage', valueType), + false, undefined, ), - arkts.factory.createParameterDeclaration( + arkts.factory.createETSParameterExpression( arkts.factory.createIdentifier(InteroperAbilityNames.ELMTID, valueType), + false, undefined, ), - arkts.factory.createParameterDeclaration( + arkts.factory.createETSParameterExpression( arkts.factory.createIdentifier(InteroperAbilityNames.PARAMSLAMBDA, valueType), + false, undefined, ), - arkts.factory.createParameterDeclaration( + arkts.factory.createETSParameterExpression( arkts.factory.createIdentifier(InteroperAbilityNames.EXTRAINFO, valueType), + false, undefined, ) ], @@ -214,16 +215,16 @@ export class LegacyTransformer extends AbstractVisitor { return arkts.factory.updateMethodDefinition( node, node.kind, - node.name, - script, + node.id, + arkts.factory.createFunctionExpression(node.id?.clone(), script), node.modifiers, false ); } - collectComponentMembers(node: arkts.StructDeclaration, className: string): Map { + collectComponentMembers(node: arkts.ETSStructDeclaration, className: string): Map { const result: Map = new Map(); - node.definition.body.map((it) => { + node.definition?.body.map((it) => { if (arkts.isClassProperty(it)) { const name = (it.key as arkts.Identifier).name; const type = it.typeAnnotation!; @@ -233,26 +234,26 @@ export class LegacyTransformer extends AbstractVisitor { return result; } - processEtsScript(node: arkts.EtsScript): arkts.EtsScript { - let updateStatements: arkts.AstNode[] = []; + processEtsScript(node: arkts.ETSModule): arkts.ETSModule { + let updateStatements: arkts.Statement[] = []; if (this.componentInterfaceCollection.length > 0) { updateStatements.push(...this.componentInterfaceCollection); } if (updateStatements.length > 0) { - return arkts.factory.updateEtsScript(node, [...node.statements, ...updateStatements]); + return arkts.factory.updateETSModule(node, [...node.statements, ...updateStatements], node.ident, node.getNamespaceFlag(), node.program); } return node; } enter(node: arkts.AstNode): void { - if (arkts.isStructDeclaration(node) && !!node.definition.ident) { + if (arkts.isETSStructDeclaration(node) && !!node.definition?.ident) { const scopeInfo: ScopeInfo = { name: node.definition.ident.name }; this.scopeInfos.push(scopeInfo); } } exit(node: arkts.AstNode): void { - if (arkts.isStructDeclaration(node) || arkts.isClassDeclaration(node)) { + if (arkts.isETSStructDeclaration(node) || arkts.isClassDeclaration(node)) { if (!node.definition || !node.definition.ident || this.scopeInfos.length === 0) { return; } @@ -265,8 +266,8 @@ export class LegacyTransformer extends AbstractVisitor { handleWrappedBuilderNode(node: arkts.ETSTypeReference): arkts.ETSTypeReference { if (node.part && arkts.isETSTypeReferencePart(node.part) && node.part.name && arkts.isIdentifier(node.part.name) && node.part.name.name === 'WrappedBuilder') { - return arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( + return arkts.factory.createETSTypeReference( + arkts.factory.createETSTypeReferencePart( arkts.factory.createIdentifier('Any') ) ); @@ -276,8 +277,8 @@ export class LegacyTransformer extends AbstractVisitor { // handle WrappedBuilder handleWrappedBuilder(node: arkts.VariableDeclarator): arkts.VariableDeclarator { - if (arkts.isIdentifier(node.name) && node.name.typeAnnotation) { - let typeAnnotation = node.name.typeAnnotation; + if (arkts.isIdentifier(node.id) && node.id.typeAnnotation) { + let typeAnnotation = node.id.typeAnnotation; // WrappedBuilder<[aa]>[] => Any[] if (arkts.isTSArrayType(typeAnnotation) && typeAnnotation.elementType && arkts.isETSTypeReference(typeAnnotation.elementType)) { @@ -285,14 +286,14 @@ export class LegacyTransformer extends AbstractVisitor { node, node.flag, arkts.factory.updateIdentifier( - node.name, - node.name.name, + node.id, + node.id.name, arkts.TSArrayType.updateTSArrayType( typeAnnotation, this.handleWrappedBuilderNode(typeAnnotation.elementType) ) ), - node.initializer + node.init ); } // WrappedBuilder<[aa]> => Any @@ -301,11 +302,11 @@ export class LegacyTransformer extends AbstractVisitor { node, node.flag, arkts.factory.updateIdentifier( - node.name, - node.name.name, + node.id, + node.id.name, this.handleWrappedBuilderNode(typeAnnotation) ), - node.initializer + node.init ); } } @@ -315,17 +316,17 @@ export class LegacyTransformer extends AbstractVisitor { visitor(node: arkts.AstNode): arkts.AstNode { this.enter(node); const newNode = this.visitEachChild(node); - if (arkts.isEtsScript(newNode)) { + if (arkts.isETSModule(newNode)) { return this.processEtsScript(newNode); } - if (arkts.isStructDeclaration(newNode)) { + if (arkts.isETSStructDeclaration(newNode)) { const definition = newNode.definition!; const annotations = definition.annotations; if (annotations.some(annotation => annotation instanceof arkts.Identifier && annotation.name === 'Component')) { return newNode; } const className = newNode.definition?.ident?.name!; - const memberMap = this.collectComponentMembers(newNode as arkts.StructDeclaration, className); + const memberMap = this.collectComponentMembers(newNode as arkts.ETSStructDeclaration, className); this.componentInterfaceCollection.push(this.generateComponentInterface(className, node.modifiers, memberMap)); const updateNode = this.processComponent(newNode); this.exit(newNode); diff --git a/arkui-plugins/ui-plugins/interop/utils.ts b/arkui-plugins/ui-plugins/interop/utils.ts index 3dff5e7af..c16ec3ccb 100644 --- a/arkui-plugins/ui-plugins/interop/utils.ts +++ b/arkui-plugins/ui-plugins/interop/utils.ts @@ -26,7 +26,6 @@ import { ESValueMethodNames, InteroperAbilityNames } from './predefines'; */ export function createEmptyESValue(result: string): arkts.VariableDeclaration { return arkts.factory.createVariableDeclaration( - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_LET, [ arkts.factory.createVariableDeclarator( @@ -40,8 +39,10 @@ export function createEmptyESValue(result: string): arkts.VariableDeclaration { false, false ), + [], undefined, - undefined + false, + false ) ) ] @@ -53,7 +54,7 @@ export function createEmptyESValue(result: string): arkts.VariableDeclaration { * @param value * @returns ESValue.wrap(value) */ -export function getWrapValue(value: arkts.AstNode): arkts.AstNode { +export function getWrapValue(value: arkts.Expression): arkts.Expression { return arkts.factory.createCallExpression( arkts.factory.createMemberExpression( arkts.factory.createIdentifier(ESValueMethodNames.ESVALUE), @@ -62,8 +63,10 @@ export function getWrapValue(value: arkts.AstNode): arkts.AstNode { false, false ), + [value], undefined, - [value] + false, + false ); } @@ -74,7 +77,7 @@ export function getWrapValue(value: arkts.AstNode): arkts.AstNode { * @param value * @returns object.setProperty(key, value) */ -export function setPropertyESValue(object: string, key: string, value: arkts.AstNode): arkts.ExpressionStatement { +export function setPropertyESValue(object: string, key: string, value: arkts.Expression): arkts.ExpressionStatement { return arkts.factory.createExpressionStatement( arkts.factory.createCallExpression( arkts.factory.createMemberExpression( @@ -84,11 +87,13 @@ export function setPropertyESValue(object: string, key: string, value: arkts.Ast false, false ), - undefined, [ arkts.factory.createStringLiteral(key), value.clone() - ] + ], + undefined, + false, + false ) ); } @@ -102,7 +107,6 @@ export function setPropertyESValue(object: string, key: string, value: arkts.Ast */ export function getPropertyESValue(result: string, obj: string, key: string): arkts.VariableDeclaration { return arkts.factory.createVariableDeclaration( - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_LET, [ arkts.factory.createVariableDeclarator( @@ -116,8 +120,10 @@ export function getPropertyESValue(result: string, obj: string, key: string): ar false, false ), + [arkts.factory.createStringLiteral(key)], undefined, - [arkts.factory.create1StringLiteral(key)] + false, + false ) ) ] @@ -147,7 +153,6 @@ export function createELMTID(): arkts.Statement[] { 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, @@ -160,8 +165,10 @@ export function createELMTID(): arkts.Statement[] { false, false ), + [], undefined, - undefined + false, + false ) )] ); @@ -179,20 +186,22 @@ export function createELMTID(): arkts.Statement[] { */ export 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 - ), + arkts.factory.createObjectExpression([ + arkts.Property.create1Property( + arkts.Es2pandaPropertyKind.PROPERTY_KIND_INIT, + arkts.factory.createIdentifier(InteroperAbilityNames.COMPONENT), + arkts.factory.createIdentifier(InteroperAbilityNames.COMPONENT), + false, + false + ), + arkts.Property.create1Property( + arkts.Es2pandaPropertyKind.PROPERTY_KIND_INIT, + arkts.factory.createIdentifier('name'), + arkts.factory.createStringLiteral(componentName), + false, + false + ) + ]), ); } @@ -202,7 +211,6 @@ export function createInitReturn(componentName: string): arkts.ReturnStatement { */ export 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, @@ -215,8 +223,10 @@ export function createGlobal(): arkts.Statement { false, false ), + [], undefined, - undefined + false, + false ) )] ); diff --git a/arkui-plugins/ui-plugins/name-collector.ts b/arkui-plugins/ui-plugins/name-collector.ts index 60d29a3e0..2a2babf06 100644 --- a/arkui-plugins/ui-plugins/name-collector.ts +++ b/arkui-plugins/ui-plugins/name-collector.ts @@ -69,9 +69,9 @@ export class NameCollector extends AbstractVisitor { const isComponentBuilder = hasBuilderLambdaAnnotation(node); if (!isComponentBuilder) return undefined; - if (!node.scriptFunction.id) return undefined; + if (!node.function?.id) return undefined; - return node.scriptFunction; + return node.function; } visitor(node: arkts.AstNode): arkts.AstNode { diff --git a/arkui-plugins/ui-plugins/printer-transformer.ts b/arkui-plugins/ui-plugins/printer-transformer.ts index 2ccab0b0e..91d04bb14 100644 --- a/arkui-plugins/ui-plugins/printer-transformer.ts +++ b/arkui-plugins/ui-plugins/printer-transformer.ts @@ -21,7 +21,7 @@ export interface TransformerOptions { } export default function printerTransformer(userPluginOptions?: TransformerOptions) { - return (node: arkts.EtsScript) => { + return (node: arkts.ETSModule) => { return new PrintVisitor().visitor(node); }; } diff --git a/arkui-plugins/ui-plugins/property-translators/base.ts b/arkui-plugins/ui-plugins/property-translators/base.ts index e79a7e763..38faba3e2 100644 --- a/arkui-plugins/ui-plugins/property-translators/base.ts +++ b/arkui-plugins/ui-plugins/property-translators/base.ts @@ -53,8 +53,10 @@ export abstract class PropertyTranslator { ): arkts.MethodDefinition { const right: arkts.CallExpression = arkts.factory.createCallExpression( arkts.factory.createIdentifier(StateManagementTypes.OBSERVABLE_PROXY), + [arkts.factory.createIdentifier('value')], undefined, - [arkts.factory.createIdentifier('value')] + false, + false ); collectStateManagementTypeImport(StateManagementTypes.OBSERVABLE_PROXY); return createSetter(originalName, typeAnnotation, left, right); @@ -69,7 +71,7 @@ export abstract class MethodTranslator { constructor(method: arkts.MethodDefinition, classInfo: ClassInfo) { this.method = method; this.classInfo = classInfo; - this.returnType = this.method.scriptFunction.returnTypeAnnotation?.clone(); + this.returnType = this.method.function!.returnTypeAnnotation?.clone(); } abstract translateMember(): arkts.AstNode[]; diff --git a/arkui-plugins/ui-plugins/property-translators/builderParam.ts b/arkui-plugins/ui-plugins/property-translators/builderParam.ts index b7619dd0d..5abff51f9 100644 --- a/arkui-plugins/ui-plugins/property-translators/builderParam.ts +++ b/arkui-plugins/ui-plugins/property-translators/builderParam.ts @@ -23,6 +23,7 @@ import { GetterSetter, InitializerConstructor } from './types'; import { factory } from './factory'; import { addMemoAnnotation, findCanAddMemoFromTypeAnnotation } from '../../collectors/memo-collectors/utils'; import { PropertyCache } from './cache/propertyCache'; +import { NodeCache } from '../../common/node-cache'; export class BuilderParamTranslator extends PropertyTranslator implements InitializerConstructor, GetterSetter { translateMember(): arkts.AstNode[] { @@ -34,7 +35,7 @@ export class BuilderParamTranslator extends PropertyTranslator implements Initia cacheTranslatedInitializer(newName: string, originalName: string): void { const mutableThis: arkts.Expression = generateThisBacking(newName); - const initializeStruct: arkts.AstNode = this.generateInitializeStruct(mutableThis, originalName); + const initializeStruct: arkts.Statement = this.generateInitializeStruct(mutableThis, originalName); PropertyCache.getInstance().collectInitializeStruct(this.structInfo.name, [initializeStruct]); } @@ -50,7 +51,7 @@ export class BuilderParamTranslator extends PropertyTranslator implements Initia arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PRIVATE, true ); - arkts.NodeCache.getInstance().collect(field); + NodeCache.getInstance().collect(field); const thisSetValue: arkts.Expression = generateThisBacking(newName, false, false); const getter: arkts.MethodDefinition = this.translateGetter( originalName, @@ -59,9 +60,9 @@ export class BuilderParamTranslator extends PropertyTranslator implements Initia ? generateThisBacking(newName, false, false) : generateThisBacking(newName, false, true) ); - arkts.NodeCache.getInstance().collect(getter); - const setter: arkts.MethodDefinition = this.translateSetter(originalName, propertyType, thisSetValue); - arkts.NodeCache.getInstance().collect(setter); + NodeCache.getInstance().collect(getter); + const setter: arkts.MethodDefinition = this.translateSetter(originalName, propertyType?.clone(), thisSetValue); + NodeCache.getInstance().collect(setter); return [field, getter, setter]; } @@ -83,25 +84,27 @@ export class BuilderParamTranslator extends PropertyTranslator implements Initia return createSetter(originalName, typeAnnotation, left, right, true); } - generateInitializeStruct(mutableThis: arkts.Expression, originalName: string): arkts.AstNode { + generateInitializeStruct(mutableThis: arkts.Expression, originalName: string): arkts.Statement { const value = this.property.value; if (!!value && arkts.isArrowFunctionExpression(value)) { - arkts.NodeCache.getInstance().collect(value); + NodeCache.getInstance().collect(value); } - return arkts.factory.createAssignmentExpression( - mutableThis, - arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - arkts.factory.createBinaryExpression( + return arkts.factory.createExpressionStatement( + arkts.factory.createAssignmentExpression( + mutableThis, arkts.factory.createBinaryExpression( - factory.createBlockStatementForOptionalExpression( - arkts.factory.createIdentifier('initializers'), - originalName + arkts.factory.createBinaryExpression( + factory.createBlockStatementForOptionalExpression( + arkts.factory.createIdentifier('initializers'), + originalName + ), + arkts.factory.createIdentifier('content'), + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_NULLISH_COALESCING ), - arkts.factory.createIdentifier('content'), + value ?? arkts.factory.createUndefinedLiteral(), arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_NULLISH_COALESCING ), - value ?? arkts.factory.createUndefinedLiteral(), - arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_NULLISH_COALESCING + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION ) ); } @@ -135,20 +138,20 @@ export class BuilderParamInterfaceTranslator e */ private updateBuilderParamMethodInInterface(method: arkts.MethodDefinition): arkts.MethodDefinition { if (method.kind === arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_GET) { - const type: arkts.TypeNode | undefined = method.scriptFunction.returnTypeAnnotation; + const type: arkts.TypeNode | undefined = method.function!.returnTypeAnnotation; if (!!type && (arkts.isETSFunctionType(type) || arkts.isETSUnionType(type))) { addMemoAnnotation(type); } removeDecorator(method, DecoratorNames.BUILDER_PARAM); - arkts.NodeCache.getInstance().collect(method, { isGetter: true }); + NodeCache.getInstance().collect(method, { isGetter: true }); } else if (method.kind === arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_SET) { - const param = method.scriptFunction.params.at(0)! as arkts.ETSParameterExpression; - const type = param.type; + const param = method.function!.params.at(0)! as arkts.ETSParameterExpression; + const type = param.typeAnnotation; if (!!type && (arkts.isETSFunctionType(type) || arkts.isETSUnionType(type))) { addMemoAnnotation(type); } removeDecorator(method, DecoratorNames.BUILDER_PARAM); - arkts.NodeCache.getInstance().collect(method, { isSetter: true }); + NodeCache.getInstance().collect(method, { isSetter: true }); } return method; } diff --git a/arkui-plugins/ui-plugins/property-translators/cache/monitorCache.ts b/arkui-plugins/ui-plugins/property-translators/cache/monitorCache.ts index 898d2aa21..8e86653f4 100644 --- a/arkui-plugins/ui-plugins/property-translators/cache/monitorCache.ts +++ b/arkui-plugins/ui-plugins/property-translators/cache/monitorCache.ts @@ -41,7 +41,7 @@ export class MonitorCache { this._cache.clear(); } - getCachedMonitors(className: string): arkts.AstNode[] { + getCachedMonitors(className: string): arkts.Statement[] { if (!this._cache.has(className)) { return []; } diff --git a/arkui-plugins/ui-plugins/property-translators/cache/propertyCache.ts b/arkui-plugins/ui-plugins/property-translators/cache/propertyCache.ts index ed7677586..43bc7ca27 100644 --- a/arkui-plugins/ui-plugins/property-translators/cache/propertyCache.ts +++ b/arkui-plugins/ui-plugins/property-translators/cache/propertyCache.ts @@ -15,7 +15,7 @@ import * as arkts from '@koalaui/libarkts'; export interface PropertyCachedBody { - initializeBody?: arkts.AstNode[]; + initializeBody?: arkts.Statement[]; updateBody?: arkts.AstNode[]; toRecordBody?: arkts.Property[]; constructorBody?: arkts.AstNode[]; @@ -41,7 +41,7 @@ export class PropertyCache { this._cache.clear(); } - getInitializeBody(name: string): arkts.AstNode[] { + getInitializeBody(name: string): arkts.Statement[] { return this._cache.get(name)?.initializeBody ?? []; } @@ -53,7 +53,7 @@ export class PropertyCache { return this._cache.get(name)?.toRecordBody ?? []; } - collectInitializeStruct(name: string, initializeStruct: arkts.AstNode[]): void { + collectInitializeStruct(name: string, initializeStruct: arkts.Statement[]): void { const initializeBody = this._cache.get(name)?.initializeBody ?? []; const newInitializeBody = [...initializeBody, ...initializeStruct]; this._cache.set(name, { ...this._cache.get(name), initializeBody: newInitializeBody }); diff --git a/arkui-plugins/ui-plugins/property-translators/computed.ts b/arkui-plugins/ui-plugins/property-translators/computed.ts index 1777a3620..ee224a426 100644 --- a/arkui-plugins/ui-plugins/property-translators/computed.ts +++ b/arkui-plugins/ui-plugins/property-translators/computed.ts @@ -34,7 +34,7 @@ export class ComputedTranslator extends MethodTranslator implements InitializerC } translateMember(): arkts.AstNode[] { - const originalName: string = expectName(this.method.name); + const originalName: string = expectName(this.method.id); const newName: string = computedField(originalName); if (!this.returnType) { this.returnType = getGetterReturnType(this.method); @@ -50,11 +50,11 @@ export class ComputedTranslator extends MethodTranslator implements InitializerC arkts.factory.createIdentifier(newName), factory.generateStateMgmtFactoryCall( StateManagementTypes.MAKE_COMPUTED, - this.returnType, + this.returnType?.clone(), [ - arkts.factory.createArrowFunction( + arkts.factory.createArrowFunctionExpression( UIFactory.createScriptFunction({ - body: this.method.scriptFunction.body?.clone(), + body: this.method.function!.body?.clone(), modifiers: modifiers, flags: arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, }) @@ -70,8 +70,8 @@ export class ComputedTranslator extends MethodTranslator implements InitializerC const originGetter: arkts.MethodDefinition = UIFactory.updateMethodDefinition(this.method, { function: { - returnTypeAnnotation: this.returnType, - body: arkts.factory.createBlock([ + returnTypeAnnotation: this.returnType?.clone(), + body: arkts.factory.createBlockStatement([ arkts.factory.createReturnStatement(this.generateComputedGet(newName)), ]), }, diff --git a/arkui-plugins/ui-plugins/property-translators/consume.ts b/arkui-plugins/ui-plugins/property-translators/consume.ts index ab60f9846..58de163ed 100644 --- a/arkui-plugins/ui-plugins/property-translators/consume.ts +++ b/arkui-plugins/ui-plugins/property-translators/consume.ts @@ -40,7 +40,7 @@ export class ConsumeTranslator extends PropertyTranslator implements Initializer } cacheTranslatedInitializer(newName: string, originalName: string): void { - const initializeStruct: arkts.AstNode = this.generateInitializeStruct(originalName, newName); + const initializeStruct: arkts.Statement = this.generateInitializeStruct(originalName, newName); PropertyCache.getInstance().collectInitializeStruct(this.structInfo.name, [initializeStruct]); if (!!this.structInfo.annotations?.reusable) { const toRecord = generateToRecord(newName, originalName); @@ -82,18 +82,18 @@ export class ConsumeTranslator extends PropertyTranslator implements Initializer return createSetter2(originalName, typeAnnotation, statement); } - generateInitializeStruct(originalName: string, newName: string): arkts.AstNode { + generateInitializeStruct(originalName: string, newName: string): arkts.Statement { const args: arkts.Expression[] = [ - arkts.factory.create1StringLiteral(originalName), - arkts.factory.create1StringLiteral( + arkts.factory.createStringLiteral(originalName), + arkts.factory.createStringLiteral( getValueInAnnotation(this.property, DecoratorNames.CONSUME) ?? originalName ), ]; factory.judgeIfAddWatchFunc(args, this.property); const assign: arkts.AssignmentExpression = arkts.factory.createAssignmentExpression( generateThisBacking(newName), - arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - factory.generateStateMgmtFactoryCall(StateManagementTypes.MAKE_CONSUME, this.propertyType, args, true) + factory.generateStateMgmtFactoryCall(StateManagementTypes.MAKE_CONSUME, this.propertyType, args, true), + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION ); return arkts.factory.createExpressionStatement(assign); } diff --git a/arkui-plugins/ui-plugins/property-translators/consumer.ts b/arkui-plugins/ui-plugins/property-translators/consumer.ts index a645d5811..71c46c944 100644 --- a/arkui-plugins/ui-plugins/property-translators/consumer.ts +++ b/arkui-plugins/ui-plugins/property-translators/consumer.ts @@ -39,7 +39,7 @@ export class ConsumerTranslator extends PropertyTranslator implements Initialize } cacheTranslatedInitializer(newName: string, originalName: string): void { - const initializeStruct: arkts.AstNode = this.generateInitializeStruct(originalName, newName); + const initializeStruct: arkts.Statement = this.generateInitializeStruct(originalName, newName); PropertyCache.getInstance().collectInitializeStruct(this.structInfo.name, [initializeStruct]); } @@ -77,18 +77,18 @@ export class ConsumerTranslator extends PropertyTranslator implements Initialize return createSetter2(originalName, typeAnnotation, statement); } - generateInitializeStruct(originalName: string, newName: string): arkts.AstNode { + generateInitializeStruct(originalName: string, newName: string): arkts.Statement { const args: arkts.Expression[] = [ - arkts.factory.create1StringLiteral(originalName), - arkts.factory.create1StringLiteral( + arkts.factory.createStringLiteral(originalName), + arkts.factory.createStringLiteral( getValueInAnnotation(this.property, DecoratorNames.CONSUMER) ?? originalName ), this.property.value!, ]; const assign: arkts.AssignmentExpression = arkts.factory.createAssignmentExpression( generateThisBacking(newName), - arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - factory.generateStateMgmtFactoryCall(StateManagementTypes.MAKE_CONSUMER, this.propertyType, args, true) + factory.generateStateMgmtFactoryCall(StateManagementTypes.MAKE_CONSUMER, this.propertyType, args, true), + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION ); 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 5bca64afe..5b22f3fbc 100644 --- a/arkui-plugins/ui-plugins/property-translators/factory.ts +++ b/arkui-plugins/ui-plugins/property-translators/factory.ts @@ -45,7 +45,7 @@ export class factory { * @param info optional member information */ static createBlockStatementForOptionalExpression( - object: arkts.AstNode, + object: arkts.Expression, key: string, info?: OptionalMemberInfo ): arkts.Expression { @@ -63,9 +63,8 @@ export class factory { * @param left left expression. * @param right right expression. */ - static generateLetVariableDecl(left: arkts.Identifier, right: arkts.AstNode): arkts.VariableDeclaration { + static generateLetVariableDecl(left: arkts.Identifier, right: arkts.Expression): arkts.VariableDeclaration { return arkts.factory.createVariableDeclaration( - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_LET, [ arkts.factory.createVariableDeclarator( @@ -110,11 +109,11 @@ export class factory { info?.isNumeric ? '$_get' : key ); return info?.isCall - ? arkts.factory.createCallExpression(alternate, undefined, undefined) + ? arkts.factory.createCallExpression(alternate, [], undefined, false, false) : info?.isNumeric - ? arkts.factory.createCallExpression(alternate, undefined, [ - arkts.factory.createNumericLiteral(Number(key)), - ]) + ? arkts.factory.createCallExpression(alternate, [ + arkts.factory.createNumberLiteral(Number(key)), + ], undefined, false, false) : alternate; } @@ -124,7 +123,7 @@ export class factory { * @param node entry wrapper class declaration node. */ static createDoubleBlockStatementForOptionalExpression( - object: arkts.AstNode, + object: arkts.Expression, key1: string, key2: string ): arkts.Expression { @@ -169,12 +168,14 @@ export class factory { hasReceiver: boolean, bodyStatementsList: arkts.Statement[] ): arkts.ArrowFunctionExpression { - return arkts.factory.createArrowFunction( + return arkts.factory.createArrowFunctionExpression( arkts.factory.createScriptFunction( arkts.BlockStatement.createBlockStatement(bodyStatementsList), - arkts.factory.createFunctionSignature(typeParams, params ? params : [], returnType, hasReceiver), + typeParams, params ? params : [], returnType, hasReceiver, arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, + undefined, + undefined ) ); } @@ -186,18 +187,19 @@ export class factory { return factory.createArrowFunctionWithParamsAndBody( undefined, [ - arkts.factory.createParameterDeclaration( + arkts.factory.createETSParameterExpression( arkts.factory.createIdentifier('_', UIFactory.createTypeReferenceFromString('string')), + false, undefined ), ], - arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), + arkts.factory.createETSPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), false, [ arkts.factory.createExpressionStatement( - arkts.factory.createCallExpression(generateThisBacking(callbackName), undefined, [ + arkts.factory.createCallExpression(generateThisBacking(callbackName), [ arkts.factory.createIdentifier('_'), - ]) + ], undefined, false, false) ), ] ); @@ -209,7 +211,7 @@ export class factory { static createBackingGetOrSetCall( newName: string, getOrSet: string, - args: arkts.AstNode[] | undefined + args: arkts.Expression[] ): arkts.CallExpression { return arkts.factory.createCallExpression( arkts.factory.createMemberExpression( @@ -221,8 +223,10 @@ export class factory { false, false ), + args, undefined, - args + false, + false ); } @@ -235,8 +239,8 @@ export class factory { args: arkts.Expression[] | undefined ): arkts.ETSNewClassInstanceExpression { return arkts.factory.createETSNewClassInstanceExpression( - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( + arkts.factory.createETSTypeReference( + arkts.factory.createETSTypeReferencePart( arkts.factory.createIdentifier(className), arkts.factory.createTSTypeParameterInstantiation(typeAnnotation ? [typeAnnotation.clone()] : []) ) @@ -251,7 +255,7 @@ export class factory { static generateStateMgmtFactoryCall( makeType: StateManagementTypes, typeArguments: arkts.TypeNode | undefined, - args: arkts.AstNode[], + args: arkts.Expression[], argsContainsThis: boolean ): arkts.CallExpression { collectStateManagementTypeImport(StateManagementTypes.STATE_MANAGEMENT_FACTORY); @@ -260,8 +264,10 @@ export class factory { arkts.factory.createIdentifier(StateManagementTypes.STATE_MANAGEMENT_FACTORY), makeType ), - typeArguments ? [typeArguments] : undefined, - [...(argsContainsThis ? [arkts.factory.createThisExpression()] : []), ...args] + [...(argsContainsThis ? [arkts.factory.createThisExpression()] : []), ...args], + typeArguments ? arkts.factory.createTSTypeParameterInstantiation([typeArguments]) : undefined, + false, + false ); } @@ -271,7 +277,7 @@ export class factory { static createIfInUpdateStruct( originalName: string, member: arkts.Expression, - args: arkts.AstNode[] + args: arkts.Expression[] ): arkts.IfStatement { const initializers = arkts.factory.createIdentifier(CustomComponentNames.COMPONENT_INITIALIZERS_NAME); const binaryItem = factory.createBlockStatementForOptionalExpression( @@ -280,8 +286,8 @@ export class factory { ); return arkts.factory.createIfStatement( binaryItem, - arkts.factory.createBlock([ - arkts.factory.createExpressionStatement(arkts.factory.createCallExpression(member, undefined, args)), + arkts.factory.createBlockStatement([ + arkts.factory.createExpressionStatement(arkts.factory.createCallExpression(member, args, undefined, false, false)), ]) ); } @@ -340,8 +346,8 @@ export class factory { type: arkts.TypeNode | undefined ): arkts.ETSTypeReference { collectStateManagementTypeImport(stageManagementType); - return arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( + return arkts.factory.createETSTypeReference( + arkts.factory.createETSTypeReferencePart( arkts.factory.createIdentifier(stageManagementType), arkts.factory.createTSTypeParameterInstantiation([type ?? arkts.factory.createETSUndefinedType()]) ) @@ -355,8 +361,8 @@ export class factory { const subscribedWatches: arkts.ClassProperty = arkts.factory.createClassProperty( arkts.factory.createIdentifier('subscribedWatches'), factory.generateStateMgmtFactoryCall(StateManagementTypes.MAKE_SUBSCRIBED_WATCHES, undefined, [], false), - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( + arkts.factory.createETSTypeReference( + arkts.factory.createETSTypeReferencePart( arkts.factory.createIdentifier(StateManagementTypes.SUBSCRIBED_WATCHES) ) ), @@ -406,43 +412,48 @@ export class factory { return arkts.factory.createMethodDefinition( arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_METHOD, arkts.factory.createIdentifier(methodName), - arkts.factory.createScriptFunction( - arkts.factory.createBlock([ + arkts.factory.createFunctionExpression(arkts.factory.createIdentifier(methodName), arkts.factory.createScriptFunction( + arkts.factory.createBlockStatement([ isReturnStatement ? arkts.factory.createReturnStatement( arkts.factory.createCallExpression( factory.thisSubscribedWatchesMember(methodName), + [arkts.factory.createIdentifier(paramName)], undefined, - [arkts.factory.createIdentifier(paramName)] + false, + false ) ) : arkts.factory.createExpressionStatement( arkts.factory.createCallExpression( factory.thisSubscribedWatchesMember(methodName), + [arkts.factory.createIdentifier(paramName)], undefined, - [arkts.factory.createIdentifier(paramName)] + false, + false ) ), ]), - arkts.factory.createFunctionSignature( - undefined, - [ - arkts.factory.createParameterDeclaration( - arkts.factory.createIdentifier( - paramName, - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart(arkts.factory.createIdentifier(paramType)) - ) - ), - undefined + undefined, + [ + arkts.factory.createETSParameterExpression( + arkts.factory.createIdentifier( + paramName, + arkts.factory.createETSTypeReference( + arkts.factory.createETSTypeReferencePart(arkts.factory.createIdentifier(paramType)) + ) ), - ], - arkts.factory.createPrimitiveType(returnType), - false - ), + false, + undefined + ), + ], + arkts.factory.createETSPrimitiveType(returnType), + false, arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD, - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC - ), + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, + arkts.factory.createIdentifier(methodName), + undefined + )), arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, false ); @@ -473,9 +484,9 @@ export class factory { static createV1RenderIdMembers(isObservedV2: boolean): arkts.AstNode[] { const v1RenderId: arkts.ClassProperty = arkts.factory.createClassProperty( arkts.factory.createIdentifier(ObservedNames.V1_RERENDER_ID), - arkts.factory.createNumericLiteral(0), - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( + arkts.factory.createNumberLiteral(0), + arkts.factory.createETSTypeReference( + arkts.factory.createETSTypeReferencePart( arkts.factory.createIdentifier(StateManagementTypes.RENDER_ID_TYPE) ) ), @@ -495,25 +506,26 @@ export class factory { const assignRenderId: arkts.ExpressionStatement = arkts.factory.createExpressionStatement( arkts.factory.createAssignmentExpression( generateThisBacking(ObservedNames.V1_RERENDER_ID), - arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - arkts.factory.createIdentifier(ObservedNames.RERENDER_ID) + arkts.factory.createIdentifier(ObservedNames.RERENDER_ID), + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION ) ); return UIFactory.createMethodDefinition({ key: arkts.factory.createIdentifier(ObservedNames.SET_V1_RERENDER_ID), kind: arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_METHOD, function: { - body: arkts.factory.createBlock(isObservedV2 ? [] : [assignRenderId]), + body: arkts.factory.createBlockStatement(isObservedV2 ? [] : [assignRenderId]), params: [ - arkts.factory.createParameterDeclaration( + arkts.factory.createETSParameterExpression( arkts.factory.createIdentifier( ObservedNames.RERENDER_ID, UIFactory.createTypeReferenceFromString(StateManagementTypes.RENDER_ID_TYPE) ), + false, undefined ), ], - returnTypeAnnotation: arkts.factory.createPrimitiveType( + returnTypeAnnotation: arkts.factory.createETSPrimitiveType( arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID ), flags: arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD, @@ -533,8 +545,10 @@ export class factory { arkts.factory.createIdentifier(ObservedNames.META), ObservedNames.ADD_REF ), + [], undefined, - undefined + false, + false ) ); collectStateManagementTypeImport(StateManagementTypes.MUTABLE_STATE_META); @@ -542,17 +556,18 @@ export class factory { key: arkts.factory.createIdentifier(ObservedNames.CONDITIONAL_ADD_REF), kind: arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_METHOD, function: { - body: arkts.factory.createBlock(isObservedV2 ? [metaAddRef] : [factory.shouldAddRef(metaAddRef)]), + body: arkts.factory.createBlockStatement(isObservedV2 ? [metaAddRef] : [factory.shouldAddRef(metaAddRef)]), params: [ - arkts.factory.createParameterDeclaration( + arkts.factory.createETSParameterExpression( arkts.factory.createIdentifier( ObservedNames.META, UIFactory.createTypeReferenceFromString(StateManagementTypes.MUTABLE_STATE_META) ), + false, undefined ), ], - returnTypeAnnotation: arkts.factory.createPrimitiveType( + returnTypeAnnotation: arkts.factory.createETSPrimitiveType( arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID ), flags: arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD, @@ -571,11 +586,13 @@ export class factory { arkts.factory.createIdentifier(StateManagementTypes.OBSERVE), ObservedNames.SHOULD_ADD_REF ), + [generateThisBacking(ObservedNames.V1_RERENDER_ID)], undefined, - [generateThisBacking(ObservedNames.V1_RERENDER_ID)] + false, + false ); collectStateManagementTypeImport(StateManagementTypes.OBSERVE); - const consequent: arkts.BlockStatement = arkts.factory.createBlock([metaAddRef]); + const consequent: arkts.BlockStatement = arkts.factory.createBlockStatement([metaAddRef]); return arkts.factory.createIfStatement(test, consequent); } @@ -601,7 +618,7 @@ export class factory { static addMemoToBuilderClassMethod(method: arkts.MethodDefinition): arkts.MethodDefinition { if (hasDecorator(method, DecoratorNames.BUILDER)) { removeDecorator(method, DecoratorNames.BUILDER); - addMemoAnnotation(method.scriptFunction); + addMemoAnnotation(method.function!); } return method; } @@ -613,7 +630,6 @@ export class factory { return arkts.factory.createMemberExpression( arkts.factory.createCallExpression( arkts.factory.createIdentifier(StateManagementTypes.STORAGE_LINK_STATE), - property.typeAnnotation ? [property.typeAnnotation] : [], [ arkts.factory.createMemberExpression( arkts.factory.createThisExpression(), @@ -624,7 +640,10 @@ export class factory { ), arkts.factory.createStringLiteral(localStorageporpValueStr), property.value ?? arkts.factory.createUndefinedLiteral(), - ] + ], + property.typeAnnotation ? arkts.factory.createTSTypeParameterInstantiation([property.typeAnnotation]): undefined, + false, + false ), arkts.factory.createIdentifier('value'), arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, @@ -638,9 +657,9 @@ export class factory { */ static wrapInterfacePropertyType(type: arkts.TypeNode, wrapTypeName: StateManagementTypes): arkts.TypeNode { if (arkts.isETSUnionType(type)) { - return arkts.factory.updateUnionType(type, [ - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( + return arkts.factory.updateETSUnionType(type, [ + arkts.factory.createETSTypeReference( + arkts.factory.createETSTypeReferencePart( arkts.factory.createIdentifier(wrapTypeName), arkts.factory.createTSTypeParameterInstantiation([type.types[0]]) ) @@ -658,19 +677,21 @@ export class factory { param: arkts.Expression, wrapTypeName: StateManagementTypes ): arkts.Expression { - if (!arkts.isEtsParameterExpression(param)) { + if (!arkts.isETSParameterExpression(param)) { return param; } - if (!param.type || !arkts.isETSUnionType(param.type)) { + if (!param.typeAnnotation || !arkts.isETSUnionType(param.typeAnnotation)) { return param; } - return arkts.factory.updateParameterDeclaration( + return arkts.factory.updateETSParameterExpression( param, arkts.factory.createIdentifier( - param.identifier.name, - factory.wrapInterfacePropertyType(param.type, wrapTypeName) + param.ident!.name, + factory.wrapInterfacePropertyType(param.typeAnnotation!, wrapTypeName) ), - param.initializer + param.isOptional, + param.initializer, + param.annotations ); } @@ -711,7 +732,7 @@ export class factory { decorator: DecoratorNames ): arkts.MethodDefinition { if (method.kind === arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_GET) { - const func = method.scriptFunction; + const func = method.function; const newType: arkts.TypeNode | undefined = factory.wrapStateManagementTypeToType( func.returnTypeAnnotation, decorator @@ -723,9 +744,9 @@ export class factory { return method; } if (method.kind === arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_SET) { - const func = method.scriptFunction; + const func = method.function; const newParam: arkts.Expression | undefined = factory.wrapStateManagementTypeToParam( - method.scriptFunction.params.at(0), + method.function!.params.at(0), decorator ); removeDecorator(method, decorator); @@ -800,8 +821,8 @@ export class factory { return arkts.factory.createExpressionStatement( arkts.factory.createAssignmentExpression( thisValue, - arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - right + right, + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION ) ); } @@ -817,14 +838,14 @@ export class factory { } static generateLambdaArg(originalName: string): arkts.ArrowFunctionExpression { - return arkts.factory.createArrowFunction( + return arkts.factory.createArrowFunctionExpression( UIFactory.createScriptFunction({ params: [UIFactory.createParameterDeclaration(MonitorNames.M_PARAM, MonitorNames.I_MONITOR)], - body: arkts.factory.createBlock([ + body: arkts.factory.createBlockStatement([ arkts.factory.createExpressionStatement( - arkts.factory.createCallExpression(generateThisBacking(originalName), undefined, [ + arkts.factory.createCallExpression(generateThisBacking(originalName), [ arkts.factory.createIdentifier(MonitorNames.M_PARAM), - ]) + ], undefined, false, false) ), ]), flags: arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, @@ -874,25 +895,40 @@ export class factory { if (itemNameSplit.length > 0) { monitorVariable = this.generateMonitorVariable(itemNameSplit); } - return arkts.factory.createObjectExpression( - arkts.Es2pandaAstNodeType.AST_NODE_TYPE_OBJECT_EXPRESSION, - [ - arkts.factory.createProperty( - arkts.factory.createIdentifier(MonitorNames.PATH), - arkts.factory.create1StringLiteral(monitorItem) + return arkts.factory.createObjectExpression([ + arkts.factory.createProperty( + arkts.Es2pandaPropertyKind.PROPERTY_KIND_INIT, + arkts.factory.createIdentifier(MonitorNames.PATH), + arkts.factory.createStringLiteral(monitorItem), + false, + false + ), + arkts.factory.createProperty( + arkts.Es2pandaPropertyKind.PROPERTY_KIND_INIT, + arkts.factory.createIdentifier(MonitorNames.VALUE_CALL_CACK), + arkts.factory.createArrowFunctionExpression( + UIFactory.createScriptFunction({ + flags: arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, + body: arkts.factory.createBlockStatement([arkts.factory.createReturnStatement(monitorVariable)]), + returnTypeAnnotation: UIFactory.createTypeReferenceFromString(TypeNames.NULLISH_TYPE), + }) ), - arkts.factory.createProperty( - arkts.factory.createIdentifier(MonitorNames.VALUE_CALL_CACK), - arkts.factory.createArrowFunction( - UIFactory.createScriptFunction({ - flags: arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, - body: arkts.factory.createBlock([arkts.factory.createReturnStatement(monitorVariable)]), - returnTypeAnnotation: UIFactory.createTypeReferenceFromString(TypeNames.ANY), - }) - ) + false, + false + ), + arkts.factory.createProperty( + arkts.Es2pandaPropertyKind.PROPERTY_KIND_INIT, + arkts.factory.createIdentifier(MonitorNames.VALUE_CALL_CACK), + arkts.factory.createArrowFunctionExpression( + UIFactory.createScriptFunction({ + flags: arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, + body: arkts.factory.createBlockStatement([arkts.factory.createReturnStatement(monitorVariable)]), + returnTypeAnnotation: UIFactory.createTypeReferenceFromString(TypeNames.ANY), + }) ), - ], - false - ); + false, + false + ), + ]); } } diff --git a/arkui-plugins/ui-plugins/property-translators/link.ts b/arkui-plugins/ui-plugins/property-translators/link.ts index edc9b4d3c..de140d08f 100644 --- a/arkui-plugins/ui-plugins/property-translators/link.ts +++ b/arkui-plugins/ui-plugins/property-translators/link.ts @@ -42,7 +42,7 @@ export class LinkTranslator extends PropertyTranslator implements InitializerCon } cacheTranslatedInitializer(newName: string, originalName: string): void { - const initializeStruct: arkts.AstNode = this.generateInitializeStruct(newName, originalName); + const initializeStruct: arkts.Statement = this.generateInitializeStruct(newName, originalName); PropertyCache.getInstance().collectInitializeStruct(this.structInfo.name, [initializeStruct]); if (!!this.structInfo.annotations?.reusable) { const toRecord = generateToRecord(newName, originalName); @@ -57,7 +57,7 @@ export class LinkTranslator extends PropertyTranslator implements InitializerCon ); const args: arkts.Expression[] = [ - arkts.factory.create1StringLiteral(originalName), + arkts.factory.createStringLiteral(originalName), arkts.factory.createTSNonNullExpression( factory.createNonNullOrOptionalMemberExpression( CustomComponentNames.COMPONENT_INITIALIZERS_NAME, @@ -74,13 +74,13 @@ export class LinkTranslator extends PropertyTranslator implements InitializerCon arkts.factory.createExpressionStatement( arkts.factory.createAssignmentExpression( generateThisBacking(newName, false, false), - arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - factory.generateStateMgmtFactoryCall(StateManagementTypes.MAKE_LINK, this.propertyType, args, true) + factory.generateStateMgmtFactoryCall(StateManagementTypes.MAKE_LINK, this.propertyType, args, true), + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION ) ), ]); - return arkts.factory.createExpressionStatement(arkts.factory.createIfStatement(test, consequent)); + return arkts.factory.createIfStatement(test, consequent); } translateWithoutInitializer(newName: string, originalName: string): arkts.AstNode[] { diff --git a/arkui-plugins/ui-plugins/property-translators/local.ts b/arkui-plugins/ui-plugins/property-translators/local.ts index bdd9b2899..2c34c0fd6 100644 --- a/arkui-plugins/ui-plugins/property-translators/local.ts +++ b/arkui-plugins/ui-plugins/property-translators/local.ts @@ -53,7 +53,7 @@ export class LocalTranslator extends PropertyTranslator implements InitializerCo cacheTranslatedInitializer(newName: string, originalName: string): void { if (!this.isStatic) { - const initializeStruct: arkts.AstNode = this.generateInitializeStruct(newName, originalName); + const initializeStruct: arkts.Statement = this.generateInitializeStruct(newName, originalName); PropertyCache.getInstance().collectInitializeStruct(this.structInfo.name, [initializeStruct]); } } @@ -106,19 +106,19 @@ export class LocalTranslator extends PropertyTranslator implements InitializerCo return createSetter2(originalName, typeAnnotation, statement, this.isStatic); } - generateInitializeStruct(newName: string, originalName: string): arkts.AstNode { + generateInitializeStruct(newName: string, originalName: string): arkts.Statement { collectStateManagementTypeImport(StateManagementTypes.LOCAL_DECORATED); const assign: arkts.AssignmentExpression = arkts.factory.createAssignmentExpression( generateThisBacking(newName), - arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - this.generateInitializeValue(originalName) + this.generateInitializeValue(originalName), + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION ); return arkts.factory.createExpressionStatement(assign); } generateInitializeValue(originalName: string): arkts.Expression { const args: arkts.Expression[] = [ - arkts.factory.create1StringLiteral(originalName), + arkts.factory.createStringLiteral(originalName), this.property.value ?? arkts.factory.createUndefinedLiteral(), ]; collectStateManagementTypeImport(StateManagementTypes.LOCAL_DECORATED); diff --git a/arkui-plugins/ui-plugins/property-translators/localStoragePropRef.ts b/arkui-plugins/ui-plugins/property-translators/localStoragePropRef.ts index f7fe9dddc..6d176d153 100644 --- a/arkui-plugins/ui-plugins/property-translators/localStoragePropRef.ts +++ b/arkui-plugins/ui-plugins/property-translators/localStoragePropRef.ts @@ -42,7 +42,7 @@ export class LocalStoragePropRefTranslator extends PropertyTranslator implements } cacheTranslatedInitializer(newName: string, originalName: string): void { - const initializeStruct: arkts.AstNode = this.generateInitializeStruct(newName, originalName); + const initializeStruct: arkts.Statement = this.generateInitializeStruct(newName, originalName); PropertyCache.getInstance().collectInitializeStruct(this.structInfo.name, [initializeStruct]); if (!!this.structInfo.annotations?.reusable) { const toRecord = generateToRecord(newName, originalName); @@ -50,7 +50,7 @@ export class LocalStoragePropRefTranslator extends PropertyTranslator implements } } - generateInitializeStruct(newName: string, originalName: string): arkts.AstNode { + generateInitializeStruct(newName: string, originalName: string): arkts.Statement { const localStoragePropRefValueStr: string | undefined = getValueInAnnotation( this.property, DecoratorNames.LOCAL_STORAGE_PROP_REF @@ -61,19 +61,21 @@ export class LocalStoragePropRefTranslator extends PropertyTranslator implements const args: arkts.Expression[] = [ arkts.factory.createStringLiteral(localStoragePropRefValueStr), - arkts.factory.create1StringLiteral(originalName), + arkts.factory.createStringLiteral(originalName), this.property.value ?? arkts.factory.createUndefinedLiteral(), ]; factory.judgeIfAddWatchFunc(args, this.property); collectStateManagementTypeImport(StateManagementTypes.LOCAL_STORAGE_PROP_REF_DECORATED); - return arkts.factory.createAssignmentExpression( - generateThisBacking(newName), - arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - factory.generateStateMgmtFactoryCall( - StateManagementTypes.MAKE_LOCAL_STORAGE_PROP_REF, - this.propertyType, - args, - true + return arkts.factory.createExpressionStatement( + arkts.factory.createAssignmentExpression( + generateThisBacking(newName), + factory.generateStateMgmtFactoryCall( + StateManagementTypes.MAKE_LOCAL_STORAGE_PROP_REF, + this.propertyType, + args, + true + ), + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION ) ); } diff --git a/arkui-plugins/ui-plugins/property-translators/localstoragelink.ts b/arkui-plugins/ui-plugins/property-translators/localstoragelink.ts index 3b477dea0..368e1d2e1 100755 --- a/arkui-plugins/ui-plugins/property-translators/localstoragelink.ts +++ b/arkui-plugins/ui-plugins/property-translators/localstoragelink.ts @@ -42,7 +42,7 @@ export class LocalStorageLinkTranslator extends PropertyTranslator implements In } cacheTranslatedInitializer(newName: string, originalName: string): void { - const initializeStruct: arkts.AstNode = this.generateInitializeStruct(newName, originalName); + const initializeStruct: arkts.Statement = this.generateInitializeStruct(newName, originalName); PropertyCache.getInstance().collectInitializeStruct(this.structInfo.name, [initializeStruct]); if (!!this.structInfo.annotations?.reusable) { const toRecord = generateToRecord(newName, originalName); @@ -50,7 +50,7 @@ export class LocalStorageLinkTranslator extends PropertyTranslator implements In } } - generateInitializeStruct(newName: string, originalName: string): arkts.AstNode { + generateInitializeStruct(newName: string, originalName: string): arkts.Statement { const localStorageLinkValueStr: string | undefined = getValueInAnnotation( this.property, DecoratorNames.LOCAL_STORAGE_LINK @@ -61,19 +61,21 @@ export class LocalStorageLinkTranslator extends PropertyTranslator implements In const args: arkts.Expression[] = [ arkts.factory.createStringLiteral(localStorageLinkValueStr), - arkts.factory.create1StringLiteral(originalName), + arkts.factory.createStringLiteral(originalName), this.property.value ?? arkts.factory.createUndefinedLiteral(), ]; factory.judgeIfAddWatchFunc(args, this.property); collectStateManagementTypeImport(StateManagementTypes.LOCAL_STORAGE_LINK_DECORATED); - return arkts.factory.createAssignmentExpression( - generateThisBacking(newName), - arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - factory.generateStateMgmtFactoryCall( - StateManagementTypes.MAKE_LOCAL_STORAGE_LINK, - this.propertyType, - args, - true + return arkts.factory.createExpressionStatement( + arkts.factory.createAssignmentExpression( + generateThisBacking(newName), + factory.generateStateMgmtFactoryCall( + StateManagementTypes.MAKE_LOCAL_STORAGE_LINK, + this.propertyType, + args, + true + ), + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION ) ); } diff --git a/arkui-plugins/ui-plugins/property-translators/monitor.ts b/arkui-plugins/ui-plugins/property-translators/monitor.ts index 2070b4fd5..988d7b6bf 100644 --- a/arkui-plugins/ui-plugins/property-translators/monitor.ts +++ b/arkui-plugins/ui-plugins/property-translators/monitor.ts @@ -26,7 +26,7 @@ import { MonitorCache, MonitorInfo } from './cache/monitorCache'; export class MonitorTranslator extends MethodTranslator implements InitializerConstructor { translateMember(): arkts.AstNode[] { - const originalName: string = expectName(this.method.name); + const originalName: string = expectName(this.method.id); const newName: string = monitorField(originalName); this.cacheTranslatedInitializer(newName, originalName); return this.translateWithoutInitializer(newName, originalName); @@ -34,7 +34,7 @@ export class MonitorTranslator extends MethodTranslator implements InitializerCo cacheTranslatedInitializer(newName: string, originalName: string): void { const monitorItem: string[] | undefined = getValueInMonitorAnnotation( - this.method.scriptFunction.annotations + this.method.function!.annotations ); const monitorPathsStr: string = !!monitorItem ? monitorItem.join(',') : ''; const monitorInfo: MonitorInfo = { @@ -50,7 +50,7 @@ export class MonitorTranslator extends MethodTranslator implements InitializerCo const field: arkts.ClassProperty = arkts.factory.createClassProperty( arkts.factory.createIdentifier(newName), undefined, - arkts.factory.createUnionType([ + arkts.factory.createETSUnionType([ UIFactory.createTypeReferenceFromString(StateManagementTypes.MONITOR_DECORATED), arkts.factory.createETSUndefinedType(), ]), diff --git a/arkui-plugins/ui-plugins/property-translators/objectlink.ts b/arkui-plugins/ui-plugins/property-translators/objectlink.ts index 133192ee8..b23bdb388 100644 --- a/arkui-plugins/ui-plugins/property-translators/objectlink.ts +++ b/arkui-plugins/ui-plugins/property-translators/objectlink.ts @@ -33,7 +33,7 @@ export class ObjectLinkTranslator extends PropertyTranslator implements Initiali } cacheTranslatedInitializer(newName: string, originalName: string): void { - const initializeStruct: arkts.AstNode = this.generateInitializeStruct(newName, originalName); + const initializeStruct: arkts.Statement = this.generateInitializeStruct(newName, originalName); PropertyCache.getInstance().collectInitializeStruct(this.structInfo.name, [initializeStruct]); const updateStruct: arkts.AstNode = this.generateUpdateStruct(newName, originalName); PropertyCache.getInstance().collectUpdateStruct(this.structInfo.name, [updateStruct]); @@ -43,7 +43,7 @@ export class ObjectLinkTranslator extends PropertyTranslator implements Initiali } } - generateInitializeStruct(newName: string, originalName: string): arkts.AstNode { + generateInitializeStruct(newName: string, originalName: string): arkts.Statement { const initializers = arkts.factory.createTSAsExpression( factory.createBlockStatementForOptionalExpression( arkts.factory.createIdentifier(CustomComponentNames.COMPONENT_INITIALIZERS_NAME), @@ -52,13 +52,15 @@ export class ObjectLinkTranslator extends PropertyTranslator implements Initiali this.propertyType, false ); - const args: arkts.Expression[] = [arkts.factory.create1StringLiteral(originalName), initializers]; + const args: arkts.Expression[] = [arkts.factory.createStringLiteral(originalName), initializers]; factory.judgeIfAddWatchFunc(args, this.property); - return arkts.factory.createAssignmentExpression( - generateThisBacking(newName), - arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - factory.generateStateMgmtFactoryCall(StateManagementTypes.MAKE_OBJECT_LINK, this.propertyType, args, true) + return arkts.factory.createExpressionStatement( + arkts.factory.createAssignmentExpression( + generateThisBacking(newName), + factory.generateStateMgmtFactoryCall(StateManagementTypes.MAKE_OBJECT_LINK, this.propertyType, args, true), + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION + ) ); } diff --git a/arkui-plugins/ui-plugins/property-translators/observedTrack.ts b/arkui-plugins/ui-plugins/property-translators/observedTrack.ts index 84cc39257..2c8496aae 100644 --- a/arkui-plugins/ui-plugins/property-translators/observedTrack.ts +++ b/arkui-plugins/ui-plugins/property-translators/observedTrack.ts @@ -92,7 +92,7 @@ export class ObservedTrackTranslator extends ObservedPropertyTranslator { createGetter(originalName: string, newName: string): arkts.MethodDefinition { const conditionalAddRef = arkts.factory.createExpressionStatement( - arkts.factory.createCallExpression(generateThisBacking(ObservedNames.CONDITIONAL_ADD_REF), undefined, [ + arkts.factory.createCallExpression(generateThisBacking(ObservedNames.CONDITIONAL_ADD_REF), [ arkts.factory.createMemberExpression( arkts.factory.createThisExpression(), this.metaIdentifier(originalName), @@ -100,7 +100,7 @@ export class ObservedTrackTranslator extends ObservedPropertyTranslator { false, false ), - ]) + ], undefined, false, false) ); const backingMember: arkts.Expression = generateThisBacking(newName); const returnMember: arkts.ReturnStatement = arkts.factory.createReturnStatement( @@ -108,7 +108,7 @@ export class ObservedTrackTranslator extends ObservedPropertyTranslator { ? backingMember : arkts.factory.createTSAsExpression(backingMember, this.propertyType, false) ); - const body = arkts.factory.createBlock([conditionalAddRef, returnMember]); + const body = arkts.factory.createBlockStatement([conditionalAddRef, returnMember]); return uiFactory.createMethodDefinition({ kind: arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_GET, key: arkts.factory.createIdentifier(originalName), @@ -124,9 +124,10 @@ export class ObservedTrackTranslator extends ObservedPropertyTranslator { createSetter(originalName: string, newName: string): arkts.MethodDefinition { const ifEqualsNewValue: arkts.IfStatement = this.setterIfEqualsNewValue(originalName, newName); - const body = arkts.factory.createBlock([ifEqualsNewValue]); - const param = arkts.factory.createParameterDeclaration( + const body = arkts.factory.createBlockStatement([ifEqualsNewValue]); + const param = arkts.factory.createETSParameterExpression( arkts.factory.createIdentifier(ObservedNames.NEW_VALUE, this.propertyType), + false, undefined ); @@ -155,25 +156,28 @@ export class ObservedTrackTranslator extends ObservedPropertyTranslator { if (this.hasImplement) { { const idx: number = this.classScopeInfo.getters.findIndex( - (getter) => getter.name.name === originalName + (getter) => getter.id?.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), + newGetter.id?.clone(), + arkts.factory.createFunctionExpression(newGetter.id?.clone(), newGetter.function! + .addFlag(arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD) + ), originGetter.modifiers, false ); arkts.factory.updateMethodDefinition( originSetter, originSetter.kind, - newSetter.name, - newSetter.scriptFunction + newSetter.id?.clone(), + arkts.factory.createFunctionExpression(newSetter.id?.clone(), newSetter.function! .addFlag(arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_OVERLOAD) - .addFlag(arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD), + .addFlag(arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD) + ), originSetter.modifiers, false ); @@ -201,8 +205,8 @@ export class ObservedTrackTranslator extends ObservedPropertyTranslator { const setNewValue = arkts.factory.createExpressionStatement( arkts.factory.createAssignmentExpression( backingValue, - arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - arkts.factory.createIdentifier(ObservedNames.NEW_VALUE) + arkts.factory.createIdentifier(ObservedNames.NEW_VALUE), + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION ) ); @@ -221,15 +225,17 @@ export class ObservedTrackTranslator extends ObservedPropertyTranslator { false, false ), + [], undefined, - undefined + false, + false ) ); const subscribingWatches = arkts.factory.createExpressionStatement( - arkts.factory.createCallExpression(generateThisBacking(ObservedNames.EXECUATE_WATCHES), undefined, [ + arkts.factory.createCallExpression(generateThisBacking(ObservedNames.EXECUATE_WATCHES), [ arkts.factory.createStringLiteral(originalName), - ]) + ], undefined, false, false) ); return arkts.factory.createIfStatement( @@ -238,7 +244,7 @@ export class ObservedTrackTranslator extends ObservedPropertyTranslator { arkts.factory.createIdentifier(ObservedNames.NEW_VALUE), arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_NOT_STRICT_EQUAL ), - arkts.factory.createBlock([setNewValue, fireChange, subscribingWatches]) + arkts.factory.createBlockStatement([setNewValue, fireChange, subscribingWatches]) ); } } diff --git a/arkui-plugins/ui-plugins/property-translators/observedV2Trace.ts b/arkui-plugins/ui-plugins/property-translators/observedV2Trace.ts index 673184f74..f6c96736a 100644 --- a/arkui-plugins/ui-plugins/property-translators/observedV2Trace.ts +++ b/arkui-plugins/ui-plugins/property-translators/observedV2Trace.ts @@ -108,15 +108,17 @@ export class ObservedV2TraceTranslator extends ObservedPropertyTranslator { arkts.factory.createIdentifier(StateManagementTypes.UI_UTILS), StateManagementTypes.MAKE_OBSERVED ), - undefined, [ this.property.value ? observedMember - : arkts.factory.createTSAsExpression(observedMember, this.propertyType, false), - ] + : arkts.factory.createTSAsExpression(observedMember, this.propertyType?.clone(), false), + ], + undefined, + false, + false ) ); - const body = arkts.factory.createBlock([this.createAddRef(originalName, classIdent), returnMember]); + const body = arkts.factory.createBlockStatement([this.createAddRef(originalName, classIdent), returnMember]); return uiFactory.createMethodDefinition({ kind: arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_GET, key: arkts.factory.createIdentifier(originalName), @@ -136,9 +138,10 @@ export class ObservedV2TraceTranslator extends ObservedPropertyTranslator { methodModifier: arkts.Es2pandaModifierFlags ): arkts.MethodDefinition { const ifEqualsNewValue: arkts.IfStatement = this.setterIfEqualsNewValue(originalName, newName); - const body = arkts.factory.createBlock([ifEqualsNewValue]); - const param = arkts.factory.createParameterDeclaration( + const body = arkts.factory.createBlockStatement([ifEqualsNewValue]); + const param = arkts.factory.createETSParameterExpression( arkts.factory.createIdentifier(ObservedNames.NEW_VALUE, this.propertyType), + false, undefined ); @@ -164,25 +167,28 @@ export class ObservedV2TraceTranslator extends ObservedPropertyTranslator { if (this.hasImplement) { { const idx: number = this.classScopeInfo.getters.findIndex( - (getter) => getter.name.name === originalName + (getter) => getter.id?.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), + newGetter.id?.clone(), + arkts.factory.createFunctionExpression(newGetter.id?.clone(), newGetter.function! + .addFlag(arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD) + ), originGetter.modifiers, false ); arkts.factory.updateMethodDefinition( originSetter, originSetter.kind, - newSetter.name, - newSetter.scriptFunction + newSetter.id?.clone(), + arkts.factory.createFunctionExpression(newSetter.id?.clone(), newSetter.function! .addFlag(arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_OVERLOAD) - .addFlag(arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD), + .addFlag(arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD) + ), originSetter.modifiers, false ); @@ -209,9 +215,9 @@ export class ObservedV2TraceTranslator extends ObservedPropertyTranslator { createAddRef(originalName: string, classIdent: arkts.Identifier): arkts.ExpressionStatement { const metaName: string = `${StateManagementTypes.META}_${originalName}`; const conditionalAddRef = arkts.factory.createExpressionStatement( - arkts.factory.createCallExpression(generateThisBacking(ObservedNames.CONDITIONAL_ADD_REF), undefined, [ + arkts.factory.createCallExpression(generateThisBacking(ObservedNames.CONDITIONAL_ADD_REF), [ generateThisBacking(metaName), - ]) + ], undefined, false, false) ); const metaAddRef = arkts.factory.createExpressionStatement( arkts.factory.createCallExpression( @@ -219,8 +225,10 @@ export class ObservedV2TraceTranslator extends ObservedPropertyTranslator { uiFactory.generateMemberExpression(classIdent.clone(), metaName), ObservedNames.ADD_REF ), + [], undefined, - undefined + false, + false ) ); return this.isStatic ? metaAddRef : conditionalAddRef; @@ -236,8 +244,8 @@ export class ObservedV2TraceTranslator extends ObservedPropertyTranslator { const setNewValue = arkts.factory.createExpressionStatement( arkts.factory.createAssignmentExpression( this.isStatic ? staticBackingValue : backingValue, - arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - arkts.factory.createIdentifier(ObservedNames.NEW_VALUE) + arkts.factory.createIdentifier(ObservedNames.NEW_VALUE), + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION ) ); @@ -250,15 +258,17 @@ export class ObservedV2TraceTranslator extends ObservedPropertyTranslator { false, false ), + [], undefined, - undefined + false, + false ) ); const subscribingWatches = arkts.factory.createExpressionStatement( - arkts.factory.createCallExpression(generateThisBacking(ObservedNames.EXECUATE_WATCHES), undefined, [ + arkts.factory.createCallExpression(generateThisBacking(ObservedNames.EXECUATE_WATCHES), [ arkts.factory.createStringLiteral(originalName), - ]) + ], undefined, false, false) ); const consequentArr = this.isStatic ? [setNewValue, fireChange] : [setNewValue, fireChange, subscribingWatches]; @@ -268,7 +278,7 @@ export class ObservedV2TraceTranslator extends ObservedPropertyTranslator { arkts.factory.createIdentifier(ObservedNames.NEW_VALUE), arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_NOT_STRICT_EQUAL ), - arkts.factory.createBlock(consequentArr) + arkts.factory.createBlockStatement(consequentArr) ); } } diff --git a/arkui-plugins/ui-plugins/property-translators/once.ts b/arkui-plugins/ui-plugins/property-translators/once.ts index 1af0383ae..7ad5469d3 100644 --- a/arkui-plugins/ui-plugins/property-translators/once.ts +++ b/arkui-plugins/ui-plugins/property-translators/once.ts @@ -40,7 +40,7 @@ export class OnceTranslator extends PropertyTranslator implements InitializerCon } cacheTranslatedInitializer(newName: string, originalName: string): void { - const initializeStruct: arkts.AstNode = this.generateInitializeStruct(newName, originalName); + const initializeStruct: arkts.Statement = this.generateInitializeStruct(newName, originalName); PropertyCache.getInstance().collectInitializeStruct(this.structInfo.name, [initializeStruct]); } @@ -78,20 +78,20 @@ export class OnceTranslator extends PropertyTranslator implements InitializerCon return createSetter2(originalName, typeAnnotation, statement); } - generateInitializeStruct(newName: string, originalName: string): arkts.AstNode { + generateInitializeStruct(newName: string, originalName: string): arkts.Statement { const outInitialize: arkts.Expression = factory.createBlockStatementForOptionalExpression( arkts.factory.createIdentifier(CustomComponentNames.COMPONENT_INITIALIZERS_NAME), originalName ); const args: arkts.Expression[] = [ - arkts.factory.create1StringLiteral(originalName), + arkts.factory.createStringLiteral(originalName), factory.generateInitializeValue(this.property, this.propertyType, originalName), ]; collectStateManagementTypeImport(StateManagementTypes.ONCE_DECORATED); const assign: arkts.AssignmentExpression = arkts.factory.createAssignmentExpression( generateThisBacking(newName), - arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - factory.generateStateMgmtFactoryCall(StateManagementTypes.MAKE_PARAM_ONCE, this.propertyType, args, true) + factory.generateStateMgmtFactoryCall(StateManagementTypes.MAKE_PARAM_ONCE, this.propertyType, args, true), + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION ); return arkts.factory.createExpressionStatement(assign); } diff --git a/arkui-plugins/ui-plugins/property-translators/param.ts b/arkui-plugins/ui-plugins/property-translators/param.ts index e6b64bfe4..9bf18ab8a 100644 --- a/arkui-plugins/ui-plugins/property-translators/param.ts +++ b/arkui-plugins/ui-plugins/property-translators/param.ts @@ -39,7 +39,7 @@ export class ParamTranslator extends PropertyTranslator implements InitializerCo } cacheTranslatedInitializer(newName: string, originalName: string): void { - const initializeStruct: arkts.AstNode = this.generateInitializeStruct(newName, originalName); + const initializeStruct: arkts.Statement = this.generateInitializeStruct(newName, originalName); PropertyCache.getInstance().collectInitializeStruct(this.structInfo.name, [initializeStruct]); const updateStruct: arkts.AstNode = this.generateUpdateStruct(generateThisBacking(newName), originalName); PropertyCache.getInstance().collectUpdateStruct(this.structInfo.name, [updateStruct]); @@ -67,16 +67,16 @@ export class ParamTranslator extends PropertyTranslator implements InitializerCo return createGetter(originalName, typeAnnotation, returnValue); } - generateInitializeStruct(newName: string, originalName: string): arkts.AstNode { + generateInitializeStruct(newName: string, originalName: string): arkts.Statement { const args: arkts.Expression[] = [ - arkts.factory.create1StringLiteral(originalName), + arkts.factory.createStringLiteral(originalName), factory.generateInitializeValue(this.property, this.propertyType, originalName), ]; collectStateManagementTypeImport(StateManagementTypes.PARAM_DECORATED); const assign: arkts.AssignmentExpression = arkts.factory.createAssignmentExpression( generateThisBacking(newName), - arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - factory.generateStateMgmtFactoryCall(StateManagementTypes.MAKE_PARAM, this.propertyType, args, true) + factory.generateStateMgmtFactoryCall(StateManagementTypes.MAKE_PARAM, this.propertyType, args, true), + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION ); return arkts.factory.createExpressionStatement(assign); } diff --git a/arkui-plugins/ui-plugins/property-translators/propRef.ts b/arkui-plugins/ui-plugins/property-translators/propRef.ts index e8447835d..955190309 100644 --- a/arkui-plugins/ui-plugins/property-translators/propRef.ts +++ b/arkui-plugins/ui-plugins/property-translators/propRef.ts @@ -43,7 +43,7 @@ export class PropRefTranslator extends PropertyTranslator implements Initializer cacheTranslatedInitializer(newName: string, originalName: string): void { const mutableThis: arkts.Expression = generateThisBacking(newName); - const initializeStruct: arkts.AstNode = this.generateInitializeStruct(newName, originalName); + const initializeStruct: arkts.Statement = this.generateInitializeStruct(newName, originalName); PropertyCache.getInstance().collectInitializeStruct(this.structInfo.name, [initializeStruct]); const updateStruct: arkts.AstNode = this.generateUpdateStruct(mutableThis, originalName); PropertyCache.getInstance().collectUpdateStruct(this.structInfo.name, [updateStruct]); @@ -87,17 +87,17 @@ export class PropRefTranslator extends PropertyTranslator implements Initializer return createSetter2(originalName, typeAnnotation, statement); } - generateInitializeStruct(newName: string, originalName: string): arkts.AstNode { + generateInitializeStruct(newName: string, originalName: string): arkts.Statement { const args: arkts.Expression[] = [ - arkts.factory.create1StringLiteral(originalName), + arkts.factory.createStringLiteral(originalName), factory.generateInitializeValue(this.property, this.propertyType, originalName), ]; factory.judgeIfAddWatchFunc(args, this.property); collectStateManagementTypeImport(StateManagementTypes.PROP_REF_DECORATED); const assign: arkts.AssignmentExpression = arkts.factory.createAssignmentExpression( generateThisBacking(newName), - arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - factory.generateStateMgmtFactoryCall(StateManagementTypes.MAKE_PROP_REF, this.propertyType, args, true) + factory.generateStateMgmtFactoryCall(StateManagementTypes.MAKE_PROP_REF, this.propertyType, args, true), + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION ); return arkts.factory.createExpressionStatement(assign); } diff --git a/arkui-plugins/ui-plugins/property-translators/provide.ts b/arkui-plugins/ui-plugins/property-translators/provide.ts index ea50f8807..292d479d9 100644 --- a/arkui-plugins/ui-plugins/property-translators/provide.ts +++ b/arkui-plugins/ui-plugins/property-translators/provide.ts @@ -42,7 +42,7 @@ export class ProvideTranslator extends PropertyTranslator implements Initializer } cacheTranslatedInitializer(newName: string, originalName: string): void { - const initializeStruct: arkts.AstNode = this.generateInitializeStruct(originalName, newName); + const initializeStruct: arkts.Statement = this.generateInitializeStruct(originalName, newName); PropertyCache.getInstance().collectInitializeStruct(this.structInfo.name, [initializeStruct]); if (!!this.structInfo.annotations?.reusable) { const toRecord = generateToRecord(newName, originalName); @@ -84,21 +84,21 @@ export class ProvideTranslator extends PropertyTranslator implements Initializer return createSetter2(originalName, typeAnnotation, statement); } - generateInitializeStruct(originalName: string, newName: string): arkts.AstNode { + generateInitializeStruct(originalName: string, newName: string): arkts.Statement { const options: undefined | ProvideOptions = getValueInProvideAnnotation(this.property); const alias: string = options?.alias ?? originalName; const allowOverride: boolean = options?.allowOverride ?? false; const args: arkts.Expression[] = [ - arkts.factory.create1StringLiteral(originalName), - arkts.factory.create1StringLiteral(alias), + arkts.factory.createStringLiteral(originalName), + arkts.factory.createStringLiteral(alias), factory.generateInitializeValue(this.property, this.propertyType, originalName), arkts.factory.createBooleanLiteral(allowOverride), ]; factory.judgeIfAddWatchFunc(args, this.property); const assign: arkts.AssignmentExpression = arkts.factory.createAssignmentExpression( generateThisBacking(newName), - arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - factory.generateStateMgmtFactoryCall(StateManagementTypes.MAKE_PROVIDE, this.propertyType, args, true) + factory.generateStateMgmtFactoryCall(StateManagementTypes.MAKE_PROVIDE, this.propertyType, args, true), + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION ); return arkts.factory.createExpressionStatement(assign); } diff --git a/arkui-plugins/ui-plugins/property-translators/provider.ts b/arkui-plugins/ui-plugins/property-translators/provider.ts index 0a157a491..54aac9325 100644 --- a/arkui-plugins/ui-plugins/property-translators/provider.ts +++ b/arkui-plugins/ui-plugins/property-translators/provider.ts @@ -39,7 +39,7 @@ export class ProviderTranslator extends PropertyTranslator implements Initialize } cacheTranslatedInitializer(newName: string, originalName: string): void { - const initializeStruct: arkts.AstNode = this.generateInitializeStruct(originalName, newName); + const initializeStruct: arkts.Statement = this.generateInitializeStruct(originalName, newName); PropertyCache.getInstance().collectInitializeStruct(this.structInfo.name, [initializeStruct]); } @@ -77,18 +77,18 @@ export class ProviderTranslator extends PropertyTranslator implements Initialize return createSetter2(originalName, typeAnnotation, statement); } - generateInitializeStruct(originalName: string, newName: string): arkts.AstNode { + generateInitializeStruct(originalName: string, newName: string): arkts.Statement { const args: arkts.Expression[] = [ - arkts.factory.create1StringLiteral(originalName), - arkts.factory.create1StringLiteral( + arkts.factory.createStringLiteral(originalName), + arkts.factory.createStringLiteral( getValueInAnnotation(this.property, DecoratorNames.PROVIDER) ?? originalName ), this.property.value!, ]; const assign: arkts.AssignmentExpression = arkts.factory.createAssignmentExpression( generateThisBacking(newName), - arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - factory.generateStateMgmtFactoryCall(StateManagementTypes.MAKE_PROVIDER, this.propertyType, args, true) + factory.generateStateMgmtFactoryCall(StateManagementTypes.MAKE_PROVIDER, this.propertyType, args, true), + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION ); 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 9cae2857d..72033d359 100644 --- a/arkui-plugins/ui-plugins/property-translators/regularProperty.ts +++ b/arkui-plugins/ui-plugins/property-translators/regularProperty.ts @@ -33,7 +33,7 @@ export class RegularPropertyTranslator extends PropertyTranslator implements Ini cacheTranslatedInitializer(newName: string, originalName: string): void { const value = this.property.value ?? arkts.factory.createUndefinedLiteral(); - let initializeStruct: arkts.AstNode = this.generateInitializeStruct(newName, originalName, value); + let initializeStruct: arkts.Statement = this.generateInitializeStruct(newName, originalName, value); if ( !!this.propertyType && !!this.structInfo.annotations.customdialog && @@ -59,8 +59,8 @@ export class RegularPropertyTranslator extends PropertyTranslator implements Ini const thisSet: arkts.ExpressionStatement = arkts.factory.createExpressionStatement( arkts.factory.createAssignmentExpression( thisValue, - arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - arkts.factory.createIdentifier('value') + arkts.factory.createIdentifier('value'), + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION ) ); const getter: arkts.MethodDefinition = this.translateGetter( @@ -89,7 +89,7 @@ export class RegularPropertyTranslator extends PropertyTranslator implements Ini return createSetter2(originalName, typeAnnotation, statement); } - generateInitializeStruct(newName: string, originalName: string, value: arkts.Expression): arkts.AstNode { + generateInitializeStruct(newName: string, originalName: string, value: arkts.Expression): arkts.Statement { const binaryItem = arkts.factory.createBinaryExpression( factory.createBlockStatementForOptionalExpression( arkts.factory.createIdentifier(CustomComponentNames.COMPONENT_INITIALIZERS_NAME), @@ -100,19 +100,19 @@ export class RegularPropertyTranslator extends PropertyTranslator implements Ini ); const assign: arkts.AssignmentExpression = arkts.factory.createAssignmentExpression( generateThisBacking(newName), - arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - binaryItem + binaryItem, + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION ); return arkts.factory.createExpressionStatement(assign); } - generateControllerInit(originalName: string, initializeStruct: arkts.AstNode): arkts.AstNode { + generateControllerInit(originalName: string, initializeStruct: arkts.Statement): arkts.Statement { return arkts.factory.createIfStatement( factory.createBlockStatementForOptionalExpression( arkts.factory.createIdentifier(CustomComponentNames.COMPONENT_INITIALIZERS_NAME), originalName ), - arkts.factory.createBlock([initializeStruct]) + arkts.factory.createBlockStatement([initializeStruct]) ); } } diff --git a/arkui-plugins/ui-plugins/property-translators/state.ts b/arkui-plugins/ui-plugins/property-translators/state.ts index 565a02435..3f1360e8c 100644 --- a/arkui-plugins/ui-plugins/property-translators/state.ts +++ b/arkui-plugins/ui-plugins/property-translators/state.ts @@ -41,7 +41,7 @@ export class StateTranslator extends PropertyTranslator implements InitializerCo } cacheTranslatedInitializer(newName: string, originalName: string): void { - const initializeStruct: arkts.AstNode = this.generateInitializeStruct(newName, originalName); + const initializeStruct: arkts.Statement = this.generateInitializeStruct(newName, originalName); PropertyCache.getInstance().collectInitializeStruct(this.structInfo.name, [initializeStruct]); if (!!this.structInfo.annotations?.reusable) { const toRecord = generateToRecord(newName, originalName); @@ -83,17 +83,17 @@ export class StateTranslator extends PropertyTranslator implements InitializerCo return createSetter2(originalName, typeAnnotation, statement); } - generateInitializeStruct(newName: string, originalName: string): arkts.AstNode { + generateInitializeStruct(newName: string, originalName: string): arkts.Statement { const args: arkts.Expression[] = [ - arkts.factory.create1StringLiteral(originalName), + arkts.factory.createStringLiteral(originalName), factory.generateInitializeValue(this.property, this.propertyType, originalName), ]; factory.judgeIfAddWatchFunc(args, this.property); collectStateManagementTypeImport(StateManagementTypes.STATE_DECORATED); const assign: arkts.AssignmentExpression = arkts.factory.createAssignmentExpression( generateThisBacking(newName), - arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - factory.generateStateMgmtFactoryCall(StateManagementTypes.MAKE_STATE, this.propertyType, args, true) + factory.generateStateMgmtFactoryCall(StateManagementTypes.MAKE_STATE, this.propertyType, args, true), + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION ); return arkts.factory.createExpressionStatement(assign); } diff --git a/arkui-plugins/ui-plugins/property-translators/storagePropRef.ts b/arkui-plugins/ui-plugins/property-translators/storagePropRef.ts index 5203e623f..a72e7b34d 100644 --- a/arkui-plugins/ui-plugins/property-translators/storagePropRef.ts +++ b/arkui-plugins/ui-plugins/property-translators/storagePropRef.ts @@ -42,7 +42,7 @@ export class StoragePropRefTranslator extends PropertyTranslator implements Init } cacheTranslatedInitializer(newName: string, originalName: string): void { - const initializeStruct: arkts.AstNode = this.generateInitializeStruct(newName, originalName); + const initializeStruct: arkts.Statement = this.generateInitializeStruct(newName, originalName); PropertyCache.getInstance().collectInitializeStruct(this.structInfo.name, [initializeStruct]); if (!!this.structInfo.annotations?.reusable) { const toRecord = generateToRecord(newName, originalName); @@ -50,7 +50,7 @@ export class StoragePropRefTranslator extends PropertyTranslator implements Init } } - generateInitializeStruct(newName: string, originalName: string): arkts.AstNode { + generateInitializeStruct(newName: string, originalName: string): arkts.Statement { const storagePropValueStr: string | undefined = getValueInAnnotation( this.property, DecoratorNames.STORAGE_PROP_REF @@ -61,20 +61,22 @@ export class StoragePropRefTranslator extends PropertyTranslator implements Init const args: arkts.Expression[] = [ arkts.factory.createStringLiteral(storagePropValueStr), - arkts.factory.create1StringLiteral(originalName), + arkts.factory.createStringLiteral(originalName), this.property.value ?? arkts.factory.createUndefinedLiteral(), ]; factory.judgeIfAddWatchFunc(args, this.property); collectStateManagementTypeImport(StateManagementTypes.STORAGE_PROP_REF_DECORATED); - return arkts.factory.createAssignmentExpression( - generateThisBacking(newName), - arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - factory.generateStateMgmtFactoryCall( - StateManagementTypes.MAKE_STORAGE_PROP_REF, - this.propertyType, - args, - true + return arkts.factory.createExpressionStatement( + arkts.factory.createAssignmentExpression( + generateThisBacking(newName), + factory.generateStateMgmtFactoryCall( + StateManagementTypes.MAKE_STORAGE_PROP_REF, + this.propertyType, + args, + true + ), + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION ) ); } diff --git a/arkui-plugins/ui-plugins/property-translators/storagelink.ts b/arkui-plugins/ui-plugins/property-translators/storagelink.ts index bb0812c75..c6f20bd6e 100644 --- a/arkui-plugins/ui-plugins/property-translators/storagelink.ts +++ b/arkui-plugins/ui-plugins/property-translators/storagelink.ts @@ -42,7 +42,7 @@ export class StorageLinkTranslator extends PropertyTranslator implements Initial } cacheTranslatedInitializer(newName: string, originalName: string): void { - const initializeStruct: arkts.AstNode = this.generateInitializeStruct(newName, originalName); + const initializeStruct: arkts.Statement = this.generateInitializeStruct(newName, originalName); PropertyCache.getInstance().collectInitializeStruct(this.structInfo.name, [initializeStruct]); if (!!this.structInfo.annotations?.reusable) { const toRecord = generateToRecord(newName, originalName); @@ -50,7 +50,7 @@ export class StorageLinkTranslator extends PropertyTranslator implements Initial } } - generateInitializeStruct(newName: string, originalName: string): arkts.AstNode { + generateInitializeStruct(newName: string, originalName: string): arkts.Statement { const storageLinkValueStr: string | undefined = getValueInAnnotation( this.property, DecoratorNames.STORAGE_LINK @@ -61,15 +61,17 @@ export class StorageLinkTranslator extends PropertyTranslator implements Initial const args: arkts.Expression[] = [ arkts.factory.createStringLiteral(storageLinkValueStr), - arkts.factory.create1StringLiteral(originalName), + arkts.factory.createStringLiteral(originalName), this.property.value ?? arkts.factory.createUndefinedLiteral(), ]; factory.judgeIfAddWatchFunc(args, this.property); collectStateManagementTypeImport(StateManagementTypes.STORAGE_LINK_DECORATED); - return arkts.factory.createAssignmentExpression( - generateThisBacking(newName), - arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - factory.generateStateMgmtFactoryCall(StateManagementTypes.MAKE_STORAGE_LINK, this.propertyType, args, true) + return arkts.factory.createExpressionStatement( + arkts.factory.createAssignmentExpression( + generateThisBacking(newName), + factory.generateStateMgmtFactoryCall(StateManagementTypes.MAKE_STORAGE_LINK, this.propertyType, args, true), + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION + ) ); } diff --git a/arkui-plugins/ui-plugins/property-translators/types.ts b/arkui-plugins/ui-plugins/property-translators/types.ts index 0b903d0e3..4a9db3d88 100644 --- a/arkui-plugins/ui-plugins/property-translators/types.ts +++ b/arkui-plugins/ui-plugins/property-translators/types.ts @@ -24,7 +24,7 @@ export interface GetterSetter { translateSetter( originalName: string, typeAnnotation: arkts.TypeNode | undefined, - left: arkts.MemberExpression + left: arkts.MemberExpression // This argument type is totally messed up, consider either MemberExpression or Statement ): arkts.MethodDefinition; } diff --git a/arkui-plugins/ui-plugins/property-translators/utils.ts b/arkui-plugins/ui-plugins/property-translators/utils.ts index 3a298cef7..70c6cf402 100644 --- a/arkui-plugins/ui-plugins/property-translators/utils.ts +++ b/arkui-plugins/ui-plugins/property-translators/utils.ts @@ -53,8 +53,8 @@ export function removeDecorator( ignoreDecl?: boolean ): void { if (arkts.isMethodDefinition(property)) { - property.scriptFunction.setAnnotations( - property.scriptFunction.annotations.filter( + property.function!.setAnnotations( + property.function!.annotations.filter( (anno) => !isDecoratorAnnotation(anno, decoratorName, ignoreDecl) ) ); @@ -74,7 +74,7 @@ export function hasDecoratorName( decoratorName: DecoratorNames ): boolean { if (arkts.isMethodDefinition(property)) { - return property.scriptFunction.annotations.some((anno) => isDecoratorAnnotation(anno, decoratorName, true)); + return property.function!.annotations.some((anno) => isDecoratorAnnotation(anno, decoratorName, true)); } return property.annotations.some((anno) => isDecoratorAnnotation(anno, decoratorName, true)); } @@ -89,7 +89,7 @@ export function hasDecorator( decoratorName: DecoratorNames ): boolean { if (arkts.isMethodDefinition(property)) { - return property.scriptFunction.annotations.some((anno) => isDecoratorAnnotation(anno, decoratorName)); + return property.function!.annotations.some((anno) => isDecoratorAnnotation(anno, decoratorName)); } return property.annotations.some((anno) => isDecoratorAnnotation(anno, decoratorName)); } @@ -116,7 +116,7 @@ export function findDecoratorByName( decoratorName: DecoratorNames ): arkts.AnnotationUsage | undefined { if (arkts.isMethodDefinition(property)) { - return property.scriptFunction.annotations.find((anno) => isDecoratorAnnotation(anno, decoratorName, true)); + return property.function!.annotations.find((anno) => isDecoratorAnnotation(anno, decoratorName, true)); } return property.annotations.find((anno) => isDecoratorAnnotation(anno, decoratorName, true)); } @@ -126,7 +126,7 @@ export function findDecorator( decoratorName: DecoratorNames ): arkts.AnnotationUsage | undefined { if (arkts.isMethodDefinition(property)) { - return property.scriptFunction.annotations.find((anno) => isDecoratorAnnotation(anno, decoratorName)); + return property.function!.annotations.find((anno) => isDecoratorAnnotation(anno, decoratorName)); } return property.annotations.find((anno) => isDecoratorAnnotation(anno, decoratorName)); } @@ -161,20 +161,22 @@ export function createGetter( if (needMemo && findCanAddMemoFromTypeAnnotation(returnType)) { addMemoAnnotation(returnType); } - const body = arkts.factory.createBlock([arkts.factory.createReturnStatement(returns)]); + const body = arkts.factory.createBlockStatement([arkts.factory.createReturnStatement(returns)]); const modifiers = isStatic ? arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_STATIC : arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC; const scriptFunction = arkts.factory.createScriptFunction( body, - arkts.FunctionSignature.createFunctionSignature(undefined, [], returnType, false), + undefined, [], returnType, false, arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_GETTER, - modifiers + modifiers, + arkts.factory.createIdentifier(name), + undefined ); return arkts.factory.createMethodDefinition( arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_GET, arkts.factory.createIdentifier(name), - scriptFunction, + arkts.factory.createFunctionExpression(arkts.factory.createIdentifier(name), scriptFunction), modifiers, false ); @@ -184,20 +186,21 @@ export function createSetter( name: string, type: arkts.TypeNode | undefined, left: arkts.Expression, - right: arkts.AstNode, + right: arkts.Expression, needMemo: boolean = false ): arkts.MethodDefinition { - const body = arkts.factory.createBlock([ + const body = arkts.factory.createBlockStatement([ arkts.factory.createExpressionStatement( arkts.factory.createAssignmentExpression( left, - arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - right + right, + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION ) ), ]); - const param: arkts.ETSParameterExpression = arkts.factory.createParameterDeclaration( + const param: arkts.ETSParameterExpression = arkts.factory.createETSParameterExpression( arkts.factory.createIdentifier('value', type?.clone()), + false, undefined ); if (needMemo && findCanAddMemoFromParameter(param)) { @@ -205,15 +208,17 @@ export function createSetter( } const scriptFunction = arkts.factory.createScriptFunction( body, - arkts.FunctionSignature.createFunctionSignature(undefined, [param], undefined, false), + undefined, [param], undefined, false, arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_SETTER, - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, + arkts.factory.createIdentifier(name), + undefined ); return arkts.factory.createMethodDefinition( arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_SET, arkts.factory.createIdentifier(name), - scriptFunction, + arkts.factory.createFunctionExpression(arkts.factory.createIdentifier(name), scriptFunction), arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, false ); @@ -225,9 +230,10 @@ export function createSetter2( statement: arkts.AstNode, isStatic: boolean = false ): arkts.MethodDefinition { - const body = arkts.factory.createBlock([statement]); - const param: arkts.ETSParameterExpression = arkts.factory.createParameterDeclaration( + const body = arkts.factory.createBlockStatement([statement as arkts.Statement]); + const param: arkts.ETSParameterExpression = arkts.factory.createETSParameterExpression( arkts.factory.createIdentifier('value', type?.clone()), + false, undefined ); const modifiers = isStatic @@ -235,15 +241,17 @@ export function createSetter2( : arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC; const scriptFunction = arkts.factory.createScriptFunction( body, - arkts.FunctionSignature.createFunctionSignature(undefined, [param], undefined, false), + undefined, [param], undefined, false, arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_SETTER, - modifiers + modifiers, + arkts.factory.createIdentifier(name), + undefined ); return arkts.factory.createMethodDefinition( arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_SET, arkts.factory.createIdentifier(name), - scriptFunction, + arkts.factory.createFunctionExpression(arkts.factory.createIdentifier(name), scriptFunction), modifiers, false ); @@ -357,7 +365,7 @@ function getDifferentAnnoTypeValue(value: arkts.Expression): string | boolean { return value.dumpSrc(); } -export function generateGetOrSetCall(beforCall: arkts.AstNode, type: GetSetTypes) { +export function generateGetOrSetCall(beforCall: arkts.Expression, type: GetSetTypes) { return arkts.factory.createCallExpression( arkts.factory.createMemberExpression( beforCall, @@ -366,14 +374,16 @@ export function generateGetOrSetCall(beforCall: arkts.AstNode, type: GetSetTypes false, false ), + type === 'set' ? [arkts.factory.createIdentifier('value')] : [], undefined, - type === 'set' ? [arkts.factory.createIdentifier('value')] : undefined, - undefined + false, + false ); } export function generateToRecord(newName: string, originalName: string): arkts.Property { - return arkts.Property.createProperty( + return arkts.Property.create1Property( + arkts.Es2pandaPropertyKind.PROPERTY_KIND_INIT, arkts.factory.createStringLiteral(originalName), arkts.factory.createBinaryExpression( arkts.factory.createMemberExpression( @@ -384,13 +394,15 @@ export function generateToRecord(newName: string, originalName: string): arkts.P false ), arkts.ETSNewClassInstanceExpression.createETSNewClassInstanceExpression( - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart(arkts.factory.createIdentifier('Object')) + arkts.factory.createETSTypeReference( + arkts.factory.createETSTypeReferencePart(arkts.factory.createIdentifier('Object')) ), [] ), arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_NULLISH_COALESCING - ) + ), + false, + false ); } diff --git a/arkui-plugins/ui-plugins/struct-translators/factory.ts b/arkui-plugins/ui-plugins/struct-translators/factory.ts index f330329c3..2b44c70c1 100644 --- a/arkui-plugins/ui-plugins/struct-translators/factory.ts +++ b/arkui-plugins/ui-plugins/struct-translators/factory.ts @@ -107,7 +107,7 @@ export class factory { let modifiers: arkts.Es2pandaModifierFlags = arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC | arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_DECLARE; if (!scope.isDecl) { - body = arkts.factory.createBlock([ + body = arkts.factory.createBlockStatement([ ...PropertyCache.getInstance().getInitializeBody(scope.name), ...MonitorCache.getInstance().getCachedMonitors(scope.name), ]); @@ -116,21 +116,22 @@ export class factory { const scriptFunction: arkts.ScriptFunction = arkts.factory .createScriptFunction( body, - arkts.FunctionSignature.createFunctionSignature( - undefined, - [UIFactory.createInitializersOptionsParameter(optionsTypeName), UIFactory.createContentParameter()], - arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), - false - ), + // arkts.FunctionSignature.createFunctionSignature( + undefined, + [UIFactory.createInitializersOptionsParameter(optionsTypeName), UIFactory.createContentParameter()], + arkts.factory.createETSPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), + false, + // ), arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD, - modifiers - ) - .setIdent(updateKey); + modifiers, + updateKey, + undefined + ); return arkts.factory.createMethodDefinition( arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_METHOD, - updateKey, - scriptFunction, + updateKey.clone(), + arkts.factory.createFunctionExpression(updateKey.clone(), scriptFunction), modifiers, false ); @@ -173,13 +174,14 @@ export class factory { }); builderNode.setOverloads(newOverLoads); if (!!newType) { - builderNode.scriptFunction.setReturnTypeAnnotation(newType); + builderNode.function!.setReturnTypeAnnotation(newType); } } else if (builderNode.kind === arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_SET) { - const param = builderNode.scriptFunction.params[0] as arkts.ETSParameterExpression; - const newParam: arkts.Expression | undefined = arkts.factory.updateParameterDeclaration( + const param = builderNode.function!.params[0] as arkts.ETSParameterExpression; + const newParam: arkts.Expression | undefined = arkts.factory.updateETSParameterExpression( param, - arkts.factory.createIdentifier(param.identifier.name, newType), + arkts.factory.createIdentifier(param.ident!.name, newType), + false, param.initializer ); if (!!newParam) { @@ -201,28 +203,27 @@ export class factory { let modifiers: arkts.Es2pandaModifierFlags = arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC | arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_DECLARE; if (!scope.isDecl) { - body = arkts.factory.createBlock(PropertyCache.getInstance().getUpdateBody(scope.name)); + body = arkts.factory.createBlockStatement(PropertyCache.getInstance().getUpdateBody(scope.name) as arkts.Statement[]); modifiers = arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC; } const scriptFunction: arkts.ScriptFunction = arkts.factory .createScriptFunction( body, - arkts.FunctionSignature.createFunctionSignature( - undefined, - [UIFactory.createInitializersOptionsParameter(optionsTypeName)], - arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), - false - ), + undefined, + [UIFactory.createInitializersOptionsParameter(optionsTypeName)], + arkts.factory.createETSPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), + false, arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD, - modifiers - ) - .setIdent(updateKey); + modifiers, + updateKey.clone(), + undefined + ); return arkts.factory.createMethodDefinition( arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_METHOD, - updateKey, - scriptFunction, + updateKey.clone(), + arkts.factory.createFunctionExpression(updateKey.clone(), scriptFunction), modifiers, false ); @@ -234,30 +235,36 @@ export class factory { static createToRecord(optionsTypeName: string, scope: CustomComponentScopeInfo): arkts.MethodDefinition { const paramsCasted = factory.generateParamsCasted(optionsTypeName); const returnRecord = arkts.factory.createReturnStatement( - arkts.ObjectExpression.createObjectExpression( - arkts.Es2pandaAstNodeType.AST_NODE_TYPE_OBJECT_EXPRESSION, - PropertyCache.getInstance().getToRecordBody(scope.name), - false + arkts.factory.createObjectExpression( + PropertyCache.getInstance().getToRecordBody(scope.name) ) ); - const body: arkts.BlockStatement = arkts.factory.createBlock([paramsCasted, returnRecord]); + const body: arkts.BlockStatement = arkts.factory.createBlockStatement([paramsCasted, returnRecord]); - const params = arkts.ETSParameterExpression.create( + const params = arkts.factory.createETSParameterExpression( arkts.factory.createIdentifier('params', factory.generateTypeReferenceWithTypeName('Object')), + false, undefined ); + const methodId = arkts.factory.createIdentifier('__toRecord'); + const toRecordScriptFunction = arkts.factory.createScriptFunction( body, - arkts.FunctionSignature.createFunctionSignature(undefined, [params], factory.generateTypeRecord(), false), + undefined, + [params], + factory.generateTypeRecord(), + false, arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD, - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, + methodId, + undefined ); return arkts.factory.createMethodDefinition( arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_CONSTRUCTOR, - arkts.factory.createIdentifier('__toRecord'), - toRecordScriptFunction, + methodId.clone(), + arkts.factory.createFunctionExpression(methodId.clone(), toRecordScriptFunction), arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_OVERRIDE, false ); @@ -268,7 +275,6 @@ export class factory { */ static generateParamsCasted(optionsTypeName: string): arkts.VariableDeclaration { return arkts.factory.createVariableDeclaration( - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_CONST, [ arkts.factory.createVariableDeclarator( @@ -288,8 +294,8 @@ export class factory { * generate Record type. */ static generateTypeRecord(): arkts.ETSTypeReference { - return arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( + return arkts.factory.createETSTypeReference( + arkts.factory.createETSTypeReferencePart( arkts.factory.createIdentifier('Record'), arkts.factory.createTSTypeParameterInstantiation([ factory.generateTypeReferenceWithTypeName('string'), @@ -303,8 +309,8 @@ export class factory { * create type reference with type name, e.g. number. */ static generateTypeReferenceWithTypeName(typeName: string): arkts.ETSTypeReference { - return arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart(arkts.factory.createIdentifier(typeName)) + return arkts.factory.createETSTypeReference( + arkts.factory.createETSTypeReferencePart(arkts.factory.createIdentifier(typeName)) ); } @@ -366,17 +372,18 @@ export class factory { */ static createAniExtendValueParam(): arkts.ETSParameterExpression { const numberType = UIFactory.createTypeReferenceFromString('number'); - const AnimatableArithmeticType = arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( + const AnimatableArithmeticType = arkts.factory.createETSTypeReference( + arkts.factory.createETSTypeReferencePart( arkts.factory.createIdentifier(AnimationNames.ANIMATABLE_ARITHMETIC), arkts.factory.createTSTypeParameterInstantiation([UIFactory.createTypeReferenceFromString('T')]) ) ); - return arkts.factory.createParameterDeclaration( + return arkts.factory.createETSParameterExpression( arkts.factory.createIdentifier( 'value', - arkts.factory.createUnionType([numberType, AnimatableArithmeticType]) + arkts.factory.createETSUnionType([numberType, AnimatableArithmeticType]) ), + false, undefined ); } @@ -385,40 +392,51 @@ export class factory { * generate __createOrSetAnimatableProperty(...) for AnimatableExtend */ static createOrSetAniProperty(): arkts.MethodDefinition { - const funcNameParam: arkts.ETSParameterExpression = arkts.factory.createParameterDeclaration( + const funcNameParam: arkts.ETSParameterExpression = arkts.factory.createETSParameterExpression( arkts.factory.createIdentifier('functionName', UIFactory.createTypeReferenceFromString('string')), + false, undefined ); - const cbParam = arkts.factory.createParameterDeclaration( + const cbParam = arkts.factory.createETSParameterExpression( arkts.factory.createIdentifier( 'callback', - arkts.factory.createFunctionType( - arkts.factory.createFunctionSignature( - undefined, - [factory.createAniExtendValueParam()], - arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), - false - ), + arkts.factory.createETSFunctionType( + undefined, + [factory.createAniExtendValueParam()], + arkts.factory.createETSPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), + false, arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW ) ), + false, undefined ); return arkts.factory.createMethodDefinition( arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_METHOD, arkts.factory.createIdentifier(AnimationNames.CREATE_OR_SET_ANIMATABLEPROPERTY), - UIFactory.createScriptFunction({ - typeParams: arkts.factory.createTypeParameterDeclaration( - [arkts.factory.createTypeParameter(arkts.factory.createIdentifier('T'))], - 0 - ), - params: [funcNameParam, factory.createAniExtendValueParam(), cbParam], - returnTypeAnnotation: arkts.factory.createPrimitiveType( - arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID - ), - flags: arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD, - modifiers: arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, - }), + arkts.factory.createFunctionExpression( + arkts.factory.createIdentifier(AnimationNames.CREATE_OR_SET_ANIMATABLEPROPERTY), + UIFactory.createScriptFunction({ + key: arkts.factory.createIdentifier(AnimationNames.CREATE_OR_SET_ANIMATABLEPROPERTY), + typeParams: arkts.factory.createTSTypeParameterDeclaration( + [ + arkts.factory.createTypeParameter( + arkts.factory.createIdentifier('T'), + undefined, + undefined, + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE + ) + ], + 0 + ), + params: [funcNameParam, factory.createAniExtendValueParam(), cbParam], + returnTypeAnnotation: arkts.factory.createETSPrimitiveType( + arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID + ), + flags: arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD, + modifiers: arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, + }) + ), arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, false ); @@ -429,29 +447,36 @@ export class factory { */ static createAnimationMethod(key: string): arkts.MethodDefinition { const aniparams: arkts.Expression[] = [ - arkts.factory.createParameterDeclaration( + arkts.factory.createETSParameterExpression( arkts.factory.createIdentifier( 'value', - arkts.factory.createUnionType([ - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart(arkts.factory.createIdentifier('AnimateParam')) + arkts.factory.createETSUnionType([ + arkts.factory.createETSTypeReference( + arkts.factory.createETSTypeReferencePart(arkts.factory.createIdentifier('AnimateParam')) ), arkts.factory.createETSUndefinedType(), ]) ), + false, undefined ), ]; + const keyIdent = arkts.factory.createIdentifier(key); const aniFunc = arkts.factory.createScriptFunction( undefined, - arkts.factory.createFunctionSignature(undefined, aniparams, arkts.TSThisType.createTSThisType(), false), + undefined, + aniparams, + arkts.TSThisType.createTSThisType(), + false, arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD, - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, + keyIdent, + undefined ); return arkts.factory.createMethodDefinition( arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_METHOD, - arkts.factory.createIdentifier(key), - aniFunc, + keyIdent.clone(), + arkts.factory.createFunctionExpression(keyIdent.clone(), aniFunc), arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, false ); @@ -486,7 +511,7 @@ export class factory { if (arkts.isMethodDefinition(member)) { PropertyFactory.addMemoToBuilderClassMethod(member); if (isKnownMethodDefinition(member, CustomComponentNames.COMPONENT_BUILD_ORI)) { - addMemoAnnotation(member.scriptFunction); + addMemoAnnotation(member.function!); return BuilderFactory.rewriteBuilderMethod(member); } return member; @@ -575,10 +600,10 @@ export class factory { projectConfig: ProjectConfig | undefined, resourceInfo: ResourceInfo ): arkts.CallExpression { - if (!arkts.isIdentifier(resourceNode.expression) || !projectConfig) { + if (!arkts.isIdentifier(resourceNode.callee) || !projectConfig) { return resourceNode; } - const resourceKind: Dollars = resourceNode.expression.name as Dollars; + const resourceKind: Dollars = resourceNode.callee.name as Dollars; if (arkts.isStringLiteral(resourceNode.arguments[0])) { return factory.processStringLiteralResourceNode( resourceNode, @@ -646,13 +671,14 @@ export class factory { static createCustomDialogMethod(isDecl: boolean, controller?: string): arkts.MethodDefinition { let block: arkts.BlockStatement | undefined = undefined; if (!!controller) { - block = arkts.factory.createBlock(this.createSetControllerElements(controller)); + block = arkts.factory.createBlockStatement(this.createSetControllerElements(controller)); } - const param: arkts.ETSParameterExpression = arkts.factory.createParameterDeclaration( + const param: arkts.ETSParameterExpression = arkts.factory.createETSParameterExpression( arkts.factory.createIdentifier( CustomDialogNames.CONTROLLER, UIFactory.createTypeReferenceFromString(CustomDialogNames.CUSTOM_DIALOG_CONTROLLER) ), + false, undefined ); const modifiers = isDecl @@ -664,7 +690,7 @@ export class factory { function: { body: block, params: [param], - returnTypeAnnotation: arkts.factory.createPrimitiveType( + returnTypeAnnotation: arkts.factory.createETSPrimitiveType( arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID ), hasReceiver: false, @@ -678,14 +704,14 @@ export class factory { /* * create assignment expression `this.__backing = controller`. */ - static createSetControllerElements(controller: string): arkts.AstNode[] { + static createSetControllerElements(controller: string): arkts.Statement[] { return controller.length !== 0 ? [ arkts.factory.createExpressionStatement( arkts.factory.createAssignmentExpression( generateThisBacking(backingField(controller)), - arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - arkts.factory.createIdentifier(CustomDialogNames.CONTROLLER) + arkts.factory.createIdentifier(CustomDialogNames.CONTROLLER), + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION ) ), ] @@ -746,9 +772,9 @@ export class factory { : Dollars.TRANSFORM_DOLLAR_RAWFILE; ImportCollector.getInstance().collectImport(transformedKey); const isDynamicBundleOrModule: boolean = isDynamicName(projectConfig); - const args: arkts.AstNode[] = [ - arkts.factory.createNumericLiteral(resourceParams.id), - arkts.factory.createNumericLiteral(resourceParams.type), + const args: arkts.Expression[] = [ + arkts.factory.createNumberLiteral(resourceParams.id), + arkts.factory.createNumberLiteral(resourceParams.type), arkts.factory.createStringLiteral(generateResourceBundleName(projectConfig, isDynamicBundleOrModule)), arkts.factory.createStringLiteral( generateResourceModuleName(projectConfig, isDynamicBundleOrModule, resourceModuleName, fromOtherModule) @@ -758,8 +784,8 @@ export class factory { return arkts.factory.updateCallExpression( resourceNode, arkts.factory.createIdentifier(transformedKey), + args, undefined, - args ); } @@ -847,8 +873,8 @@ export class factory { member = arkts.factory.updateMethodDefinition( member, member.kind, - member.name, - factory.transformAnimatableExtend(member.scriptFunction), + member.id!, + arkts.factory.createFunctionExpression(member.id?.clone(), factory.transformAnimatableExtend(member.function!)), member.modifiers, false ); @@ -974,7 +1000,7 @@ export class factory { } static transformObservedV2Constuctor(definition: arkts.ClassDefinition, className: string): arkts.MethodDefinition { - const addConstructorNodes: arkts.AstNode[] = MonitorCache.getInstance().getCachedMonitors(className); + const addConstructorNodes: arkts.Statement[] = MonitorCache.getInstance().getCachedMonitors(className); let originConstructorMethod: arkts.MethodDefinition | undefined = definition.body.find( (it) => arkts.isMethodDefinition(it) && @@ -986,7 +1012,7 @@ export class factory { key: arkts.factory.createIdentifier(CustomComponentNames.COMPONENT_CONSTRUCTOR_ORI), function: { key: arkts.factory.createIdentifier(CustomComponentNames.COMPONENT_CONSTRUCTOR_ORI), - body: isDecl ? undefined : arkts.factory.createBlock(addConstructorNodes), + body: isDecl ? undefined : arkts.factory.createBlockStatement(addConstructorNodes), flags: arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_CONSTRUCTOR, modifiers: arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_CONSTRUCTOR, }, @@ -997,12 +1023,12 @@ export class factory { if (isDecl) { return originConstructorMethod; } - const originBody = originConstructorMethod.scriptFunction.body as arkts.BlockStatement | undefined; + const originBody = originConstructorMethod.function?.body as arkts.BlockStatement | undefined; return UIFactory.updateMethodDefinition(originConstructorMethod, { function: { body: originBody - ? arkts.factory.updateBlock(originBody, [...originBody.statements, ...addConstructorNodes]) - : arkts.factory.createBlock(addConstructorNodes), + ? arkts.factory.updateBlockStatement(originBody, [...originBody.statements, ...addConstructorNodes]) + : arkts.factory.createBlockStatement(addConstructorNodes), }, }); } @@ -1016,28 +1042,29 @@ export class factory { ): arkts.ArrowFunctionExpression { const assignmentExpr = arkts.factory.createExpressionStatement( arkts.factory.createAssignmentExpression( - param.identifier.clone(), - arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - arkts.factory.createTSAsExpression(param.identifier.clone(), param.type as arkts.TypeNode, false) + param.ident?.clone(), + arkts.factory.createTSAsExpression(param.ident?.clone(), param.typeAnnotation, false), + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION ) ); const numberType = UIFactory.createTypeReferenceFromString('number'); - const AnimatableArithmeticType = arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( + const AnimatableArithmeticType = arkts.factory.createETSTypeReference( + arkts.factory.createETSTypeReferencePart( arkts.factory.createIdentifier(AnimationNames.ANIMATABLE_ARITHMETIC), - arkts.factory.createTSTypeParameterInstantiation([param.type as arkts.TypeNode]) + arkts.factory.createTSTypeParameterInstantiation([param.typeAnnotation!]) ) ); ImportCollector.getInstance().collectImport(AnimationNames.ANIMATABLE_ARITHMETIC); - return arkts.factory.createArrowFunction( + return arkts.factory.createArrowFunctionExpression( UIFactory.createScriptFunction({ - body: arkts.factory.createBlock([assignmentExpr, ...originStatements]), + body: arkts.factory.createBlockStatement([assignmentExpr, ...originStatements]), params: [ - arkts.factory.createParameterDeclaration( + arkts.factory.createETSParameterExpression( arkts.factory.createIdentifier( - param.identifier.name, - arkts.factory.createUnionType([numberType, AnimatableArithmeticType]) + param.ident!.name, + arkts.factory.createETSUnionType([numberType, AnimatableArithmeticType]) ), + false, undefined ), ], @@ -1050,7 +1077,7 @@ export class factory { * transform @AnimatableExtend method */ static transformAnimatableExtend(node: arkts.ScriptFunction): arkts.ScriptFunction { - if (!arkts.isEtsParameterExpression(node.params[1]) || !node.body || !arkts.isBlockStatement(node.body)) { + if (!arkts.isETSParameterExpression(node.params[1]) || !node.body || !arkts.isBlockStatement(node.body)) { return node; } const funcName: arkts.StringLiteral = arkts.factory.createStringLiteral(node.id?.name!); @@ -1065,25 +1092,27 @@ export class factory { false, false ), - undefined, [ funcName, - paramValue.identifier, + paramValue.ident!, factory.createAniExtendCbArg(paramValue, originStatements.slice(0, -1)), - ] + ], + undefined, + false, + false, ) ); return arkts.factory.updateScriptFunction( node, - arkts.factory.createBlock([createOrSetStatement, originStatements[originStatements.length - 1]]), - arkts.FunctionSignature.createFunctionSignature( - node.typeParams, - node.params, - node.returnTypeAnnotation, - node.hasReceiver - ), + arkts.factory.createBlockStatement([createOrSetStatement, originStatements[originStatements.length - 1]]), + node.typeParams, + node.params, + node.returnTypeAnnotation, + node.hasReceiver, node.flags, - node.modifiers + node.modifierFlags, + node.id, + node.annotations ); } @@ -1104,10 +1133,10 @@ export class factory { static transformCustomDialogController( node: arkts.ETSNewClassInstanceExpression ): arkts.ETSNewClassInstanceExpression | arkts.Expression { - if (isInvalidDialogControllerOptions(node.getArguments)) { + if (isInvalidDialogControllerOptions(node.arguments)) { return node; } - const optionArg = node.getArguments[0]; + const optionArg = node.arguments[0]; const options: arkts.ObjectExpression = arkts.isObjectExpression(optionArg) ? optionArg : ((optionArg as arkts.TSAsExpression).expr as arkts.ObjectExpression); @@ -1119,22 +1148,22 @@ export class factory { const builder: arkts.Property = properties.at(builderIndex)!; const gensymName: string = GenSymGenerator.getInstance().id(); const newBuilderValue = this.createDialogBuilderArrow(builder.value!, gensymName); - const newProperty = arkts.factory.updateProperty(builder, builder.key, newBuilderValue); + const newProperty = arkts.factory.updateProperty( + builder, builder.kind, builder.key, newBuilderValue, builder.isMethod, builder.isComputed + ); const newObj = arkts.factory.updateObjectExpression( options, - arkts.Es2pandaAstNodeType.AST_NODE_TYPE_OBJECT_EXPRESSION, [ ...(options.properties as arkts.Property[]).slice(0, builderIndex), newProperty, ...(options.properties as arkts.Property[]).slice(builderIndex + 1), this.createBaseComponent(), - ], - false + ] ); const newOptions = arkts.isTSAsExpression(optionArg) ? arkts.factory.updateTSAsExpression(optionArg, newObj, optionArg.typeAnnotation, optionArg.isConst) : newObj; - const typeRef = node.getTypeRef as arkts.ETSTypeReference; + const typeRef = node.typeRef as arkts.ETSTypeReference; const newNode = arkts.factory.updateETSNewClassInstanceExpression(node, typeRef, [newOptions]); return factory.createBlockStatementForOptionalExpression(newNode, gensymName); } @@ -1142,14 +1171,14 @@ export class factory { static createDialogBuilderArrow(value: arkts.Expression, gensymName: string): arkts.Expression { if ( arkts.isCallExpression(value) && - arkts.isMemberExpression(value.expression) && - arkts.isIdentifier(value.expression.property) && - value.expression.property.name === BuilderLambdaNames.TRANSFORM_METHOD_NAME + arkts.isMemberExpression(value.callee) && + arkts.isIdentifier(value.callee.property) && + value.callee.property.name === BuilderLambdaNames.TRANSFORM_METHOD_NAME ) { return addMemoAnnotation( - arkts.factory.createArrowFunction( + arkts.factory.createArrowFunctionExpression( UIFactory.createScriptFunction({ - body: arkts.factory.createBlock([ + body: arkts.factory.createBlockStatement([ arkts.factory.createExpressionStatement( this.transformCustomDialogComponentCall(value, gensymName) ), @@ -1168,15 +1197,15 @@ export class factory { static transformCustomDialogComponentCall(value: arkts.CallExpression, gensymName: string): arkts.CallExpression { if (value.arguments.length >= 2 && arkts.isArrowFunctionExpression(value.arguments[1])) { - const originScript: arkts.ScriptFunction = value.arguments[1].scriptFunction; + const originScript: arkts.ScriptFunction = value.arguments[1].function!; const newScript: arkts.ScriptFunction = UIFactory.updateScriptFunction(originScript, { body: this.generateInstanceSetController(originScript.body, gensymName), }); - return arkts.factory.updateCallExpression(value, value.expression, value.typeArguments, [ + return arkts.factory.updateCallExpression(value, value.callee, [ value.arguments[0], - arkts.factory.updateArrowFunction(value.arguments[1], newScript), + arkts.factory.updateArrowFunctionExpression(value.arguments[1], newScript), ...value.arguments.slice(2), - ]); + ], value.typeParams); } return value; } @@ -1194,9 +1223,8 @@ export class factory { const instanceIdent: arkts.Identifier = arkts.factory.createIdentifier( BuilderLambdaNames.STYLE_ARROW_PARAM_NAME ); - return arkts.factory.updateBlock(body, [ + return arkts.factory.updateBlockStatement(body, [ arkts.factory.createVariableDeclaration( - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_CONST, arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_CONST, [ arkts.factory.createVariableDeclarator( @@ -1213,7 +1241,7 @@ export class factory { return body; } - static genertateControllerSetCall(instanceIdent: arkts.Identifier, gensymName: string): arkts.AstNode { + static genertateControllerSetCall(instanceIdent: arkts.Identifier, gensymName: string): arkts.Statement { return arkts.factory.createExpressionStatement( arkts.factory.createCallExpression( arkts.factory.createMemberExpression( @@ -1223,28 +1251,32 @@ export class factory { false, false ), - undefined, [ arkts.factory.createTSAsExpression( arkts.factory.createIdentifier(gensymName), UIFactory.createTypeReferenceFromString(CustomDialogNames.CUSTOM_DIALOG_CONTROLLER), false ), - ] + ], + undefined, + false, + false, ) ); } static createBaseComponent(): arkts.Property { return arkts.factory.createProperty( + arkts.Es2pandaPropertyKind.PROPERTY_KIND_INIT, arkts.factory.createIdentifier(CustomDialogNames.BASE_COMPONENT), - arkts.factory.createThisExpression() + arkts.factory.createThisExpression(), + false, + false, ); } static generateLetVariableDecl(left: arkts.Identifier): arkts.VariableDeclaration { return arkts.factory.createVariableDeclaration( - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_LET, [ arkts.factory.createVariableDeclarator( @@ -1267,8 +1299,8 @@ export class factory { arkts.factory.createExpressionStatement( arkts.factory.createAssignmentExpression( arkts.factory.createIdentifier(gensymName), - arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - newNode + newNode, + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION ) ), arkts.factory.createExpressionStatement( diff --git a/arkui-plugins/ui-plugins/struct-translators/struct-transformer.ts b/arkui-plugins/ui-plugins/struct-translators/struct-transformer.ts index 722453b7a..28c3be45d 100644 --- a/arkui-plugins/ui-plugins/struct-translators/struct-transformer.ts +++ b/arkui-plugins/ui-plugins/struct-translators/struct-transformer.ts @@ -64,7 +64,7 @@ export class StructTransformer extends AbstractVisitor { } } if (arkts.isMethodDefinition(node) && this.scope.customComponents.length > 0) { - const name = node.name.name; + const name = node.id!.name; const scopeInfo = this.scope.customComponents.pop()!; scopeInfo.hasInitializeStruct ||= name === CustomComponentNames.COMPONENT_INITIALIZE_STRUCT; scopeInfo.hasUpdateStruct ||= name === CustomComponentNames.COMPONENT_UPDATE_STRUCT; @@ -105,8 +105,9 @@ export class StructTransformer extends AbstractVisitor { } else if (arkts.isTSInterfaceDeclaration(node)) { return factory.tranformInterfaceMembers(node, this.externalSourceName); } - if (arkts.isEtsScript(node) && ImportCollector.getInstance().importInfos.length > 0) { - ImportCollector.getInstance().insertCurrentImports(this.program); + if (arkts.isETSModule(node) && ImportCollector.getInstance().importInfos.length > 0) { + let imports = ImportCollector.getInstance().getImportStatements(); + return arkts.factory.updateETSModule(node, [...imports, ...node.statements], node.ident, node.getNamespaceFlag(), node.program); } return node; } diff --git a/arkui-plugins/ui-plugins/struct-translators/utils.ts b/arkui-plugins/ui-plugins/struct-translators/utils.ts index a25c5bf5c..70cc41b6a 100644 --- a/arkui-plugins/ui-plugins/struct-translators/utils.ts +++ b/arkui-plugins/ui-plugins/struct-translators/utils.ts @@ -101,14 +101,14 @@ export function isEtsGlobalClass(node: arkts.ClassDeclaration): boolean { export function isResourceNode(node: arkts.CallExpression, ignoreDecl: boolean = false): boolean { if ( !( - arkts.isIdentifier(node.expression) && - (node.expression.name === Dollars.DOLLAR_RESOURCE || node.expression.name === Dollars.DOLLAR_RAWFILE) + arkts.isIdentifier(node.callee) && + (node.callee.name === Dollars.DOLLAR_RESOURCE || node.callee.name === Dollars.DOLLAR_RAWFILE) ) ) { return false; } if (!ignoreDecl) { - const decl = arkts.getDecl(node.expression); + const decl = arkts.getDecl(node.callee!); if (!decl) { return false; } diff --git a/arkui-plugins/ui-plugins/ui-factory.ts b/arkui-plugins/ui-plugins/ui-factory.ts index 3900f3b14..f5839ed8e 100644 --- a/arkui-plugins/ui-plugins/ui-factory.ts +++ b/arkui-plugins/ui-plugins/ui-factory.ts @@ -68,20 +68,18 @@ export class factory { * create `instance: ` as parameter */ static createInstanceParameter(typeName: string): arkts.ETSParameterExpression { - return arkts.factory.createParameterDeclaration(factory.createInstanceIdentifier(typeName), undefined); + return arkts.factory.createETSParameterExpression(factory.createInstanceIdentifier(typeName), false, undefined); } /** * create `(instance: ) => void` */ static createStyleLambdaFunctionType(typeName: string): arkts.ETSFunctionType { - return arkts.factory.createFunctionType( - arkts.FunctionSignature.createFunctionSignature( - undefined, - [factory.createInstanceParameter(typeName)], - factory.createTypeReferenceFromString(typeName), - false - ), + return arkts.factory.createETSFunctionType( + undefined, + [factory.createInstanceParameter(typeName)], + factory.createTypeReferenceFromString(typeName), + false, arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW ); } @@ -92,7 +90,7 @@ export class factory { static createStyleIdentifier(typeName: string): arkts.Identifier { return arkts.factory.createIdentifier( BuilderLambdaNames.STYLE_PARAM_NAME, - arkts.factory.createUnionType([ + arkts.factory.createETSUnionType([ factory.createStyleLambdaFunctionType(typeName), arkts.factory.createETSUndefinedType(), ]) @@ -105,7 +103,7 @@ export class factory { static createInitializerOptionsIdentifier(optionsName: string): arkts.Identifier { return arkts.factory.createIdentifier( CustomComponentNames.COMPONENT_INITIALIZERS_NAME, - arkts.factory.createUnionType([ + arkts.factory.createETSUnionType([ factory.createTypeReferenceFromString(optionsName), arkts.factory.createETSUndefinedType(), ]) @@ -116,8 +114,9 @@ export class factory { * create `initializers: | undefined` as parameter */ static createInitializersOptionsParameter(optionsName: string): arkts.ETSParameterExpression { - return arkts.factory.createParameterDeclaration( + return arkts.factory.createETSParameterExpression( factory.createInitializerOptionsIdentifier(optionsName), + false, undefined ); } @@ -128,7 +127,7 @@ export class factory { static createContentIdentifier(): arkts.Identifier { return arkts.factory.createIdentifier( BuilderLambdaNames.CONTENT_PARAM_NAME, - arkts.factory.createUnionType([factory.createLambdaFunctionType(), arkts.factory.createETSUndefinedType()]) + arkts.factory.createETSUnionType([factory.createLambdaFunctionType(), arkts.factory.createETSUndefinedType()]) ); } @@ -137,7 +136,7 @@ export class factory { */ static createContentParameter(): arkts.ETSParameterExpression { const contentParam: arkts.Identifier = factory.createContentIdentifier(); - const param: arkts.ETSParameterExpression = arkts.factory.createParameterDeclaration(contentParam, undefined); + const param: arkts.ETSParameterExpression = arkts.factory.createETSParameterExpression(contentParam, false, undefined); addMemoAnnotation(param); return param; } @@ -151,19 +150,19 @@ export class factory { ): arkts.TypeNode { let part: arkts.ETSTypeReferencePart; if (!!typeParams) { - part = arkts.factory.createTypeReferencePart(arkts.factory.createIdentifier(name), typeParams); + part = arkts.factory.createETSTypeReferencePart(arkts.factory.createIdentifier(name), typeParams); } else { - part = arkts.factory.createTypeReferencePart(arkts.factory.createIdentifier(name)); + part = arkts.factory.createETSTypeReferencePart(arkts.factory.createIdentifier(name)); } - return arkts.factory.createTypeReference(part); + return arkts.factory.createETSTypeReference(part); } /** * create complex type from string and type parameter, e.g. `Set` */ static createComplexTypeFromStringAndTypeParameter(name: string, params: readonly arkts.TypeNode[]): arkts.TypeNode { - return arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( + return arkts.factory.createETSTypeReference( + arkts.factory.createETSTypeReferencePart( arkts.factory.createIdentifier(name), arkts.factory.createTSTypeParameterInstantiation(params) ) @@ -177,13 +176,11 @@ export class factory { params?: arkts.Expression[], returnType?: arkts.TypeNode | undefined ): arkts.ETSFunctionType { - return arkts.factory.createFunctionType( - arkts.FunctionSignature.createFunctionSignature( - undefined, - params ?? [], - returnType ?? arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), - false - ), + return arkts.factory.createETSFunctionType( + undefined, + params ?? [], + returnType ?? arkts.factory.createETSPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), + false, arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW ); } @@ -208,21 +205,15 @@ export class factory { const newFunc: arkts.ScriptFunction = arkts.factory.updateScriptFunction( original, config.body ?? original.body, - arkts.factory.createFunctionSignature( - config.typeParams ?? original.typeParams, - config.params ?? original.params, - config.returnTypeAnnotation ?? original.returnTypeAnnotation, - config.hasReceiver ?? original.hasReceiver - ), + config.typeParams ?? original.typeParams, + config.params ?? original.params, + config.returnTypeAnnotation ?? original.returnTypeAnnotation, + config.hasReceiver ?? original.hasReceiver, config.flags ?? original.flags, - config.modifiers ?? original.modifiers + config.modifiers ?? original.modifiers, + config.key ?? original.id, + config.annotations ?? original.annotations ); - if (!!config.key) { - newFunc.setIdent(config.key); - } - if (!!config.annotations) { - newFunc.setAnnotations(config.annotations); - } return newFunc; } @@ -232,21 +223,15 @@ export class factory { static createScriptFunction(config: Partial): arkts.ScriptFunction { const newFunc: arkts.ScriptFunction = arkts.factory.createScriptFunction( config.body ?? undefined, - arkts.factory.createFunctionSignature( - config.typeParams ?? undefined, - config.params ?? [], - config.returnTypeAnnotation ?? undefined, - config.hasReceiver ?? false - ), + config.typeParams ?? undefined, + config.params ?? [], + config.returnTypeAnnotation ?? undefined, + config.hasReceiver ?? false, config.flags ?? arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_NONE, - config.modifiers ?? arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE + config.modifiers ?? arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, + config.key?.clone(), + config.annotations, ); - if (!!config.key) { - newFunc.setIdent(config.key); - } - if (!!config.annotations) { - newFunc.setAnnotations(config.annotations); - } return newFunc; } @@ -257,18 +242,19 @@ export class factory { original: arkts.MethodDefinition, config: PartialNested ): arkts.MethodDefinition { - const key: arkts.Identifier = config.key ?? original.name; - const newFunc: arkts.ScriptFunction = factory.updateScriptFunction(original.scriptFunction, { + const key: arkts.Identifier = config.key ?? original.id!.clone(); + const newFunc: arkts.ScriptFunction = factory.updateScriptFunction(original.function!, { ...config.function, key, }); const newMethod: arkts.MethodDefinition = arkts.factory.updateMethodDefinition( original, config.kind ?? original.kind, - key, - newFunc, + key.clone(), + arkts.factory.createFunctionExpression(key.clone(), newFunc), config.modifiers ?? original.modifiers, - config.isComputed ?? false + config.isComputed ?? false, + config.overloads ); return newMethod; } @@ -283,10 +269,11 @@ export class factory { }); const newMethod: arkts.MethodDefinition = arkts.factory.createMethodDefinition( config.kind ?? arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_NONE, - config.key!, - newFunc, + config.key?.clone(), + arkts.factory.createFunctionExpression(config.key?.clone(), newFunc), config.modifiers ?? arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, - config.isComputed ?? false + config.isComputed ?? false, + config.overloads ); return newMethod; } @@ -298,7 +285,7 @@ export class factory { config: PartialExcept ): arkts.AnnotationDeclaration { const intrinsicAnnotations: arkts.AnnotationUsage[] = [ - arkts.factory.create1AnnotationUsage(arkts.factory.createIdentifier('Retention'), [ + arkts.factory.createAnnotationUsage(arkts.factory.createIdentifier('Retention'), [ arkts.factory.createClassProperty( arkts.factory.createIdentifier('policy'), arkts.factory.createStringLiteral('SOURCE'), @@ -331,7 +318,7 @@ export class factory { property.key && arkts.isIdentifier(property.key) ) { - return arkts.factory.update1AnnotationUsage(anno, anno.expr, [ + return arkts.factory.updateAnnotationUsage(anno, anno.expr, [ ...anno.properties, factory.createAliasClassProperty(property.key), ]); @@ -348,7 +335,7 @@ export class factory { static createAliasClassProperty(value: arkts.Identifier): arkts.ClassProperty { return arkts.factory.createClassProperty( arkts.factory.createIdentifier('alias'), - arkts.factory.create1StringLiteral(value.name), + arkts.factory.createStringLiteral(value.name), undefined, arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, false @@ -377,8 +364,8 @@ export class factory { typeParameters?: arkts.TSTypeParameterInstantiation ): arkts.TSClassImplements { return arkts.factory.createTSClassImplements( - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart(arkts.factory.createIdentifier(interfaceName)) + arkts.factory.createETSTypeReference( + arkts.factory.createETSTypeReferencePart(arkts.factory.createIdentifier(interfaceName)) ), typeParameters ); @@ -429,10 +416,10 @@ export class factory { return arkts.factory.updateInterfaceDeclaration( newNode, newNode.extends, - newNode.id, + newNode.id?.clone(), newNode.typeParams, arkts.factory.updateInterfaceBody(newNode.body!, [ - ...newNode.body.body, + ...newNode.body.body.map(n => n.clone()), factory.createPropertyInInterface( CustomDialogNames.BASE_COMPONENT, factory.createTypeReferenceFromString(CustomDialogNames.EXTENDABLE_COMPONENT) @@ -448,7 +435,7 @@ export class factory { * * @param method method definition node */ - static generateMemberExpression(object: arkts.AstNode, property: string, optional = false): arkts.MemberExpression { + static generateMemberExpression(object: arkts.Expression, property: string, optional = false): arkts.MemberExpression { return arkts.factory.createMemberExpression( object, arkts.factory.createIdentifier(property), @@ -464,10 +451,11 @@ export class factory { static createParameterDeclaration( keyName: string, typeName: string, - initializers?: arkts.AstNode + initializers?: arkts.Expression ): arkts.ETSParameterExpression { - return arkts.factory.createParameterDeclaration( + return arkts.factory.createETSParameterExpression( arkts.factory.createIdentifier(keyName, this.createTypeReferenceFromString(typeName)), + false, initializers ); } diff --git a/arkui-plugins/ui-plugins/utils.ts b/arkui-plugins/ui-plugins/utils.ts index 9c2960d1b..6fc122018 100644 --- a/arkui-plugins/ui-plugins/utils.ts +++ b/arkui-plugins/ui-plugins/utils.ts @@ -209,13 +209,13 @@ export function isCustomComponentAnnotation( } export function collectCustomComponentScopeInfo( - node: arkts.ClassDeclaration | arkts.StructDeclaration + node: arkts.ClassDeclaration | arkts.ETSStructDeclaration ): CustomComponentInfo | undefined { const definition: arkts.ClassDefinition | undefined = node.definition; if (!definition || !definition?.ident?.name) { return undefined; } - const isStruct = arkts.isStructDeclaration(node); + const isStruct = arkts.isETSStructDeclaration(node); const isDecl: boolean = arkts.hasModifierFlag(node, arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_DECLARE); const isCustomComponentClassDecl = !isStruct && isDecl; const shouldIgnoreDecl = isStruct || isDecl; @@ -270,8 +270,8 @@ export function getAnnotationInfoForStruct( return { isComponent, isComponentV2, isEntry, isReusable, isReusableV2, isCustomLayout, isCustomDialog }; } -export function isComponentStruct(node: arkts.StructDeclaration, scopeInfo: CustomComponentInfo): boolean { - return scopeInfo.name === node.definition.ident?.name; +export function isComponentStruct(node: arkts.ETSStructDeclaration, scopeInfo: CustomComponentInfo): boolean { + return scopeInfo.name === node.definition!.ident?.name; } /** @@ -321,19 +321,19 @@ export function isKnownMethodDefinition(method: arkts.MethodDefinition, name: st } // For now, we only considered matched method name. - const isNameMatched: boolean = method.name?.name === name; + const isNameMatched: boolean = method.id?.name === name; return isNameMatched; } export function isSpecificNewClass(node: arkts.ETSNewClassInstanceExpression, className: string): boolean { if ( - node.getTypeRef && - arkts.isETSTypeReference(node.getTypeRef) && - node.getTypeRef.part && - arkts.isETSTypeReferencePart(node.getTypeRef.part) && - node.getTypeRef.part.name && - arkts.isIdentifier(node.getTypeRef.part.name) && - node.getTypeRef.part.name.name === className + node.typeRef && + arkts.isETSTypeReference(node.typeRef) && + node.typeRef.part && + arkts.isETSTypeReferencePart(node.typeRef.part) && + node.typeRef.part.name && + arkts.isIdentifier(node.typeRef.part.name) && + node.typeRef.part.name.name === className ) { return true; } diff --git a/arkui-plugins/ui-syntax-plugins/index.ts b/arkui-plugins/ui-syntax-plugins/index.ts index c32e154c1..9914ec845 100644 --- a/arkui-plugins/ui-syntax-plugins/index.ts +++ b/arkui-plugins/ui-syntax-plugins/index.ts @@ -43,7 +43,7 @@ function createTransformer( ): PluginHandler { const visitedPrograms: Set = new Set(); const visitedExternalSources: Set = new Set(); - return tracePerformance(`UISyntaxPlugin::${phase}`, function (this: PluginContext): arkts.EtsScript | undefined { + return tracePerformance(`UISyntaxPlugin::${phase}`, function (this: PluginContext): arkts.ETSModule | undefined { const contextPtr = this.getContextPtr() ?? arkts.arktsGlobal.compilerContext?.peer; if (!contextPtr) { return undefined; @@ -97,7 +97,7 @@ function transformExternalSources( if (visitedPrograms.has(program.peer) || isHeaderFile(program.absName)) { continue; } - const script = transformer.transform(program.astNode) as arkts.EtsScript; + const script = transformer.transform(program.astNode) as arkts.ETSModule; this.setArkTSAst(script); } visitedExternalSources.add(externalSource.peer); @@ -108,8 +108,8 @@ function transformProgram( this: PluginContext, transformer: UISyntaxLinterVisitor, program: arkts.Program -): arkts.EtsScript { - const script = transformer.transform(program.astNode) as arkts.EtsScript; +): arkts.ETSModule { + const script = transformer.transform(program.astNode) as arkts.ETSModule; this.setArkTSAst(script); return script; } diff --git a/arkui-plugins/ui-syntax-plugins/processor/index.ts b/arkui-plugins/ui-syntax-plugins/processor/index.ts index 6aa704560..babb5c992 100644 --- a/arkui-plugins/ui-syntax-plugins/processor/index.ts +++ b/arkui-plugins/ui-syntax-plugins/processor/index.ts @@ -71,7 +71,7 @@ class ConcreteUISyntaxRuleContext implements UISyntaxRuleContext { ); if (options.fix) { const diagnosticInfo: arkts.DiagnosticInfo = arkts.DiagnosticInfo.create(diagnosticKind, - arkts.getStartPosition(options.node)); + options.node.startPosition); const fixSuggestion = options.fix(options.node); const suggestionKind: arkts.DiagnosticKind = arkts.DiagnosticKind.create( message, @@ -87,7 +87,7 @@ class ConcreteUISyntaxRuleContext implements UISyntaxRuleContext { ); arkts.Diagnostic.logDiagnosticWithSuggestion(diagnosticInfo, suggestionInfo); } else { - arkts.Diagnostic.logDiagnostic(diagnosticKind, arkts.getStartPosition(options.node)); + arkts.Diagnostic.logDiagnostic(diagnosticKind, options.node.startPosition); } } diff --git a/arkui-plugins/ui-syntax-plugins/rules/build-root-node.ts b/arkui-plugins/ui-syntax-plugins/rules/build-root-node.ts index 10cb57d43..a5bdd9893 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/build-root-node.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/build-root-node.ts @@ -29,16 +29,16 @@ class BuildRootNodeRule extends AbstractUISyntaxRule { } public parsed(node: arkts.AstNode): void { - if (!arkts.isStructDeclaration(node)) { + if (!arkts.isETSStructDeclaration(node)) { return; } const entryDecoratorUsage = getAnnotationUsage(node, PresetDecorators.ENTRY); - node.definition.body.forEach((member) => { - if (!arkts.isMethodDefinition(member) || getIdentifierName(member.name) !== BUILD_NAME) { + node.definition?.body.forEach((member) => { + if (!arkts.isMethodDefinition(member) || getIdentifierName(member) !== BUILD_NAME) { return; } - const blockStatement = member.scriptFunction.body; - const buildNode = member.scriptFunction.id; + const blockStatement = member.function!.body; + const buildNode = member.function!.id; if (!blockStatement || !arkts.isBlockStatement(blockStatement) || !buildNode) { return; } diff --git a/arkui-plugins/ui-syntax-plugins/rules/builderparam-decorator-check.ts b/arkui-plugins/ui-syntax-plugins/rules/builderparam-decorator-check.ts index 2b97c5808..3add5d339 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/builderparam-decorator-check.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/builderparam-decorator-check.ts @@ -43,7 +43,7 @@ class BuilderParamDecoratorCheckRule extends AbstractUISyntaxRule { return; } node.getChildren().forEach((member) => { - if (!arkts.isStructDeclaration(member) || !member.definition.ident) { + if (!arkts.isETSStructDeclaration(member) || !member.definition?.ident) { return; } let count: number = 0; @@ -72,13 +72,13 @@ class BuilderParamDecoratorCheckRule extends AbstractUISyntaxRule { return false; } let structNode = node.parent; - while (!arkts.isMethodDefinition(structNode) || getIdentifierName(structNode.name) !== BUILD_NAME) { + while (!arkts.isMethodDefinition(structNode) || getIdentifierName(structNode) !== BUILD_NAME) { if (!structNode.parent) { return false; } structNode = structNode.parent; } - return arkts.isMethodDefinition(structNode) && getIdentifierName(structNode.name) === BUILD_NAME; + return arkts.isMethodDefinition(structNode) && getIdentifierName(structNode) === BUILD_NAME; } private hasBlockStatement(node: arkts.AstNode): boolean { @@ -118,7 +118,7 @@ class BuilderParamDecoratorCheckRule extends AbstractUISyntaxRule { return; } let structNode = node.parent; - while (!arkts.isStructDeclaration(structNode)) { + while (!arkts.isETSStructDeclaration(structNode)) { if (!structNode.parent) { return; } diff --git a/arkui-plugins/ui-syntax-plugins/rules/check-construct-private-parameter.ts b/arkui-plugins/ui-syntax-plugins/rules/check-construct-private-parameter.ts index 21cab0ab1..9b498cfba 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/check-construct-private-parameter.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/check-construct-private-parameter.ts @@ -30,11 +30,11 @@ class CheckConstructPrivateParameterRule extends AbstractUISyntaxRule { this.privatePropertyMap = new Map(); } - public parsed(node: arkts.StructDeclaration): void { + public parsed(node: arkts.ETSStructDeclaration): 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) || !member.definition.ident || !member.definition.ident.name) { + if (!arkts.isETSStructDeclaration(member) || !member.definition?.ident || !member.definition.ident.name) { return; } const structName: string = member.definition.ident.name; @@ -43,10 +43,10 @@ class CheckConstructPrivateParameterRule extends AbstractUISyntaxRule { }); }); } - if (!arkts.isCallExpression(node) || !arkts.isIdentifier(node.expression)) { + if (!arkts.isCallExpression(node) || !arkts.isIdentifier(node.callee)) { return; } - const componentName = node.expression.name; + const componentName = node.callee?.name; // If the initialization is for a component with private properties if (!this.privatePropertyMap.has(componentName)) { return; diff --git a/arkui-plugins/ui-syntax-plugins/rules/check-decorated-property-type.ts b/arkui-plugins/ui-syntax-plugins/rules/check-decorated-property-type.ts index 90c6a82ed..4f173c398 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/check-decorated-property-type.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/check-decorated-property-type.ts @@ -41,8 +41,8 @@ class CheckDecoratedPropertyTypeRule extends AbstractUISyntaxRule { }; } - public parsed(node: arkts.StructDeclaration): void { - if (!arkts.isStructDeclaration(node)) { + public parsed(node: arkts.ETSStructDeclaration): void { + if (!arkts.isETSStructDeclaration(node)) { return; } if (!node.definition) { diff --git a/arkui-plugins/ui-syntax-plugins/rules/check-property-modifiers.ts b/arkui-plugins/ui-syntax-plugins/rules/check-property-modifiers.ts index 808113783..140459ea3 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/check-property-modifiers.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/check-property-modifiers.ts @@ -45,11 +45,11 @@ class CheckPropertyModifiersRule extends AbstractUISyntaxRule { }; } - public parsed(node: arkts.StructDeclaration): void { - if (!arkts.isStructDeclaration(node)) { + public parsed(node: arkts.ETSStructDeclaration): void { + if (!arkts.isETSStructDeclaration(node)) { return; } - node.definition.body.forEach(member => { + node.definition?.body.forEach(member => { if (!arkts.isClassProperty(member)) { return; } diff --git a/arkui-plugins/ui-syntax-plugins/rules/component-componentV2-init-check.ts b/arkui-plugins/ui-syntax-plugins/rules/component-componentV2-init-check.ts index 7230b8f6d..6f9b5d25e 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/component-componentV2-init-check.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/component-componentV2-init-check.ts @@ -30,7 +30,7 @@ class ComponentComponentV2InitCheckRule extends AbstractUISyntaxRule { this.componentV1WithLinkList = []; } - public parsed(node: arkts.StructDeclaration): void { + public parsed(node: arkts.ETSStructDeclaration): void { this.initComponentV1WithLinkList(node); this.checkComponentInitLink(node); } @@ -40,7 +40,7 @@ class ComponentComponentV2InitCheckRule extends AbstractUISyntaxRule { return; } node.getChildren().forEach((member) => { - if (!arkts.isStructDeclaration(member) || !member.definition.ident || + if (!arkts.isETSStructDeclaration(member) || !member.definition.ident || !hasAnnotation(member?.definition.annotations, PresetDecorators.COMPONENT_V1)) { return; } @@ -65,7 +65,7 @@ class ComponentComponentV2InitCheckRule extends AbstractUISyntaxRule { return; } let structNode = node.parent; - while (!arkts.isStructDeclaration(structNode)) { + while (!arkts.isETSStructDeclaration(structNode)) { if (!structNode.parent) { return; } diff --git a/arkui-plugins/ui-syntax-plugins/rules/component-componentV2-mix-use-check.ts b/arkui-plugins/ui-syntax-plugins/rules/component-componentV2-mix-use-check.ts index 70714c3b3..42284724f 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/component-componentV2-mix-use-check.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/component-componentV2-mix-use-check.ts @@ -47,7 +47,7 @@ class ComponentComponentV2MixUseCheckRule extends AbstractUISyntaxRule { this.findAllTSTypeAliasDeclaration(node); } - if (arkts.isStructDeclaration(node)) { + if (arkts.isETSStructDeclaration(node)) { this.processComponentAnnotations(node); } } @@ -109,7 +109,7 @@ class ComponentComponentV2MixUseCheckRule extends AbstractUISyntaxRule { } private processComponentAnnotations( - node: arkts.StructDeclaration + node: arkts.ETSStructDeclaration ): void { node.definition.annotations.forEach((anno) => { if (!anno.expr) { diff --git a/arkui-plugins/ui-syntax-plugins/rules/componentV2-mix-check.ts b/arkui-plugins/ui-syntax-plugins/rules/componentV2-mix-check.ts index 7db394582..bdb133a97 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/componentV2-mix-check.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/componentV2-mix-check.ts @@ -25,7 +25,7 @@ class ComponentV2MixCheckRule extends AbstractUISyntaxRule { } public parsed(node: arkts.AstNode): void { - if (!arkts.isStructDeclaration(node)) { + if (!arkts.isETSStructDeclaration(node)) { return; } const definition = node.definition; diff --git a/arkui-plugins/ui-syntax-plugins/rules/componentV2-state-usage-validation.ts b/arkui-plugins/ui-syntax-plugins/rules/componentV2-state-usage-validation.ts index 47d5088ec..2ddd90e6b 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/componentV2-state-usage-validation.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/componentV2-state-usage-validation.ts @@ -51,13 +51,13 @@ class ComponentV2StateUsageValidationRule extends AbstractUISyntaxRule { // Rule 5: Local, Param, Event decorators must be used with Property this.checkuseStateDecoratorsWithProperty(node); } - if (!arkts.isStructDeclaration(node)) { + if (!arkts.isETSStructDeclaration(node)) { return; } this.validateClassPropertyDecorators(node); } - private hasComponentV2Annotation = (node: arkts.StructDeclaration): boolean => !!getAnnotationUsage(node, + private hasComponentV2Annotation = (node: arkts.ETSStructDeclaration): boolean => !!getAnnotationUsage(node, PresetDecorators.COMPONENT_V2); private checkMultipleBuiltInDecorators(member: arkts.ClassProperty, @@ -164,10 +164,12 @@ class ComponentV2StateUsageValidationRule extends AbstractUISyntaxRule { }); } - private validateClassPropertyDecorators(node: arkts.StructDeclaration): void { - this.checkuseStateDecoratorsWithProperty(node.definition); + private validateClassPropertyDecorators(node: arkts.ETSStructDeclaration): void { + if (node.definition) { + this.checkuseStateDecoratorsWithProperty(node.definition); + } const isComponentV2 = this.hasComponentV2Annotation(node); - node.definition.body.forEach(member => { + node.definition?.body.forEach(member => { if (!arkts.isClassProperty(member)) { return; } @@ -222,7 +224,7 @@ class ComponentV2StateUsageValidationRule extends AbstractUISyntaxRule { return; } node.getChildren().forEach((member) => { - if (!arkts.isStructDeclaration(member) || !member.definition.ident || + if (!arkts.isETSStructDeclaration(member) || !member.definition?.ident || !this.checkDecorator(member.definition.annotations, PresetDecorators.COMPONENT_V2)) { return; } @@ -272,14 +274,14 @@ class ComponentV2StateUsageValidationRule extends AbstractUISyntaxRule { return; } let structNode = node.parent; - while (!arkts.isStructDeclaration(structNode)) { + while (!arkts.isETSStructDeclaration(structNode)) { if (!structNode.parent) { return; } structNode = structNode.parent; } let parentPropertyMap: Map = new Map(); - structNode.definition.body.forEach((property) => { + structNode.definition?.body.forEach((property) => { if (!arkts.isClassProperty(property)) { return; } diff --git a/arkui-plugins/ui-syntax-plugins/rules/computed-decorator-check.ts b/arkui-plugins/ui-syntax-plugins/rules/computed-decorator-check.ts index fd271307d..aac96f3da 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/computed-decorator-check.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/computed-decorator-check.ts @@ -37,7 +37,7 @@ class ComputedDecoratorCheckRule extends AbstractUISyntaxRule { } public parsed(node: arkts.AstNode): void { - if (arkts.isStructDeclaration(node)) { + if (arkts.isETSStructDeclaration(node)) { this.validateComponentV2InStruct(node); this.validateStructBody(node); } @@ -47,17 +47,17 @@ class ComputedDecoratorCheckRule extends AbstractUISyntaxRule { } } - private validateStructBody(node: arkts.StructDeclaration): void { + private validateStructBody(node: arkts.ETSStructDeclaration): void { let computedDecorator: arkts.AnnotationUsage | undefined; - node.definition.body.forEach((member) => { + node.definition?.body.forEach((member) => { if (arkts.isClassProperty(member)) { this.validateComputedOnClassProperty(member); return; } if (arkts.isMethodDefinition(member)) { - const methodName = getIdentifierName(member.name); - computedDecorator = findDecorator(member.scriptFunction, PresetDecorators.COMPUTED); + const methodName = getIdentifierName(member); + computedDecorator = findDecorator(member.function!, PresetDecorators.COMPUTED); this.validateComputedMethodKind(member, computedDecorator, methodName); if (member.kind === arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_SET) { @@ -129,7 +129,7 @@ class ComputedDecoratorCheckRule extends AbstractUISyntaxRule { } private validateBuildMethod(member: arkts.MethodDefinition): void { - member.scriptFunction.body?.getChildren().forEach((childNode) => { + member.function!.body?.getChildren().forEach((childNode) => { if (!arkts.isExpressionStatement(childNode)) { return; } @@ -149,13 +149,13 @@ class ComputedDecoratorCheckRule extends AbstractUISyntaxRule { } private validateCallExpression(currentNode: arkts.CallExpression): void { - if (!arkts.isIdentifier(currentNode.expression) || getIdentifierName(currentNode.expression) !== '$$') { + if (!arkts.isIdentifier(currentNode.callee) || getIdentifierName(currentNode.callee) !== '$$') { return; } currentNode.arguments.forEach((argument) => { if (arkts.isMemberExpression(argument)) { - const getterName = getIdentifierName(argument.property); + const getterName = getIdentifierName(argument.property!); this.reportValidateCallExpression(currentNode, getterName); } }); @@ -206,18 +206,18 @@ class ComputedDecoratorCheckRule extends AbstractUISyntaxRule { if (arkts.isMethodDefinition(member)) { this.validateComputedInClass(node, member, observedV2Decorator, observedDecorator); - const computedDecorator = findDecorator(member.scriptFunction, PresetDecorators.COMPUTED); - if (!arkts.isIdentifier(member.name)) { + const computedDecorator = findDecorator(member.function!, PresetDecorators.COMPUTED); + if (!arkts.isIdentifier(member.id)) { return; } - const methodName = getIdentifierName(member.name); + const methodName = getIdentifierName(member.id); this.validateComputedMethodKind(member, computedDecorator, methodName); } }); } - private validateComponentV2InStruct(node: arkts.StructDeclaration): void { + private validateComponentV2InStruct(node: arkts.ETSStructDeclaration): void { const componentV2Decorator = getAnnotationUsage(node, PresetDecorators.COMPONENT_V2); const componentDecorator = getAnnotationUsage(node, PresetDecorators.COMPONENT_V1); @@ -229,12 +229,12 @@ class ComputedDecoratorCheckRule extends AbstractUISyntaxRule { } private checkComponentV2InStruct( - node: arkts.StructDeclaration | arkts.ClassDeclaration, + node: arkts.ETSStructDeclaration | arkts.ClassDeclaration, member: arkts.MethodDefinition, componentV2Decorator: arkts.AnnotationUsage | undefined, componentDecorator: arkts.AnnotationUsage | undefined ): void { - const computedDecorator = findDecorator(member.scriptFunction, PresetDecorators.COMPUTED); + const computedDecorator = findDecorator(member.function!, PresetDecorators.COMPUTED); if (computedDecorator && !componentV2Decorator && !componentDecorator) { this.report({ node: computedDecorator, @@ -274,7 +274,7 @@ class ComputedDecoratorCheckRule extends AbstractUISyntaxRule { observedV2Decorator: arkts.AnnotationUsage | undefined, observedDecorator: arkts.AnnotationUsage | undefined ): void { - const computedDecorator = findDecorator(member.scriptFunction, PresetDecorators.COMPUTED); + const computedDecorator = findDecorator(member.function!, PresetDecorators.COMPUTED); if (computedDecorator && !observedV2Decorator && !observedDecorator && arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_GET === member.kind) { this.report({ diff --git a/arkui-plugins/ui-syntax-plugins/rules/construct-parameter-literal.ts b/arkui-plugins/ui-syntax-plugins/rules/construct-parameter-literal.ts index 784cecad5..d049df3f0 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/construct-parameter-literal.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/construct-parameter-literal.ts @@ -32,7 +32,7 @@ class ConstructParameterLiteralRule extends AbstractUISyntaxRule { this.linkMap = new Map(); } - public parsed(node: arkts.StructDeclaration): void { + public parsed(node: arkts.ETSStructDeclaration): void { this.initMap(node); this.checkInitializeWithLiteral(node); } @@ -76,7 +76,7 @@ class ConstructParameterLiteralRule extends AbstractUISyntaxRule { return; } node.getChildren().forEach((member) => { - if (!(arkts.isStructDeclaration(member))) { + if (!(arkts.isETSStructDeclaration(member))) { return; } if (!member.definition || !member.definition.ident || !arkts.isIdentifier(member.definition.ident)) { @@ -93,10 +93,10 @@ class ConstructParameterLiteralRule extends AbstractUISyntaxRule { } private checkInitializeWithLiteral(node: arkts.AstNode): void { - if (!arkts.isCallExpression(node) || !arkts.isIdentifier(node.expression)) { + if (!arkts.isCallExpression(node) || !arkts.isIdentifier(node.callee)) { return; } - const componentName = node.expression.name; + const componentName = node.callee.name; // Only assignments to properties decorated with Link or ObjectLink trigger rule checks if (!this.linkMap.has(componentName)) { return; diff --git a/arkui-plugins/ui-syntax-plugins/rules/construct-parameter.ts b/arkui-plugins/ui-syntax-plugins/rules/construct-parameter.ts index 9a4d5695c..90494a67d 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/construct-parameter.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/construct-parameter.ts @@ -64,26 +64,26 @@ class ConstructParameterRule extends AbstractUISyntaxRule { this.builderFunctionList = []; } - public parsed(node: arkts.StructDeclaration): void { + public parsed(node: arkts.ETSStructDeclaration): void { this.initList(node); this.initPropertyMap(node); this.checkConstructParameter(node); } private getPropertyAnnotationName(node: arkts.AstNode, propertyName: string): string { - while (!arkts.isStructDeclaration(node)) { + while (!arkts.isETSStructDeclaration(node)) { if (!node.parent) { return ''; } node = node.parent; } let annotationNames: string[] = []; - node.definition.body.forEach((item) => { + node.definition?.body.forEach((item) => { if (arkts.isClassProperty(item) && getClassPropertyName(item) === propertyName) { annotationNames = getClassPropertyAnnotationNames(item); } - if (arkts.isMethodDefinition(item) && getIdentifierName(item.name) === propertyName) { - annotationNames = item.scriptFunction.annotations.map((annotation) => + if (arkts.isMethodDefinition(item) && getIdentifierName(item) === propertyName) { + annotationNames = item.function!.annotations.map((annotation) => getAnnotationName(annotation) ); } @@ -120,8 +120,8 @@ class ConstructParameterRule extends AbstractUISyntaxRule { } member.annotations.forEach(annotation => { if (annotation.expr && getIdentifierName(annotation.expr) === PresetDecorators.BUILDER && - member.scriptFunction.id) { - this.builderFunctionList.push(member.scriptFunction.id.name); + member.function!.id) { + this.builderFunctionList.push(member.function!.id.name); } }); } @@ -131,7 +131,7 @@ class ConstructParameterRule extends AbstractUISyntaxRule { return; } member.getChildren().forEach((item) => { - if (!arkts.isVariableDeclarator(item) || !item.name || + if (!arkts.isVariableDeclarator(item) || !item.id || (item.initializer && arkts.isArrowFunctionExpression(item.initializer))) { return; } @@ -181,7 +181,7 @@ class ConstructParameterRule extends AbstractUISyntaxRule { return; } node.getChildren().forEach((member) => { - if (!arkts.isStructDeclaration(member) || !member.definition.ident) { + if (!arkts.isETSStructDeclaration(member) || !member.definition?.ident) { return; } let structName: string = member.definition.ident?.name ?? ''; @@ -290,7 +290,7 @@ class ConstructParameterRule extends AbstractUISyntaxRule { if (!arkts.isMemberExpression(property.value) || !arkts.isThisExpression(property.value.object)) { return; } - const parentName = getIdentifierName(property.value.property); + const parentName = getIdentifierName(property.value.property as arkts.AstNode); const parentType: string = this.getPropertyAnnotationName(node, parentName); if (parentType === '') { return; diff --git a/arkui-plugins/ui-syntax-plugins/rules/consumer-provider-decorator-check.ts b/arkui-plugins/ui-syntax-plugins/rules/consumer-provider-decorator-check.ts index 538f7e9fc..cc57ac196 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/consumer-provider-decorator-check.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/consumer-provider-decorator-check.ts @@ -63,23 +63,23 @@ class ConsumerProviderDecoratorCheckRule extends AbstractUISyntaxRule { } private rememberStructName(node: arkts.AstNode): void { - if (arkts.isStructDeclaration(node)) { - node.definition.annotations.forEach((anno) => { + if (arkts.isETSStructDeclaration(node)) { + node.definition?.annotations.forEach((anno) => { if (!anno.expr) { return; } const annoName = getIdentifierName(anno.expr); // Second, it must be decorated with a @component v2 decorator if (annoName === PresetDecorators.COMPONENT_V2) { - const structName = node.definition.ident?.name ?? ''; + const structName = node.definition?.ident?.name ?? ''; this.processStructMembers(node, structName); } }); } } - private processStructMembers(node: arkts.StructDeclaration, structName: string): void { - node.definition.body.forEach((member) => { + private processStructMembers(node: arkts.ETSStructDeclaration, structName: string): 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 consumerDecorator = member.annotations.some(annotation => @@ -112,8 +112,8 @@ class ConsumerProviderDecoratorCheckRule extends AbstractUISyntaxRule { this.validateDecorator(node, this.messages.providerAndConsumerOnlyOnProperty, PresetDecorators.PROVIDER); } - if (arkts.isStructDeclaration(node)) { - node.definition.body.forEach(member => { + if (arkts.isETSStructDeclaration(node)) { + node.definition?.body.forEach(member => { if (arkts.isClassProperty(member)) { this.validateMemberDecorators(member); } @@ -183,9 +183,9 @@ class ConsumerProviderDecoratorCheckRule extends AbstractUISyntaxRule { } if (arkts.isMethodDefinition(member)) { this.validateDecorator( - member.scriptFunction, this.messages.providerAndConsumerOnlyInStruct, PresetDecorators.CONSUMER); + member.function!, this.messages.providerAndConsumerOnlyInStruct, PresetDecorators.CONSUMER); this.validateDecorator( - member.scriptFunction, this.messages.providerAndConsumerOnlyInStruct, PresetDecorators.PROVIDER); + member.function!, this.messages.providerAndConsumerOnlyInStruct, PresetDecorators.PROVIDER); } }); return; @@ -234,10 +234,10 @@ class ConsumerProviderDecoratorCheckRule extends AbstractUISyntaxRule { } private validateConsumerInitialization(node: arkts.CallExpression): void { - if (!arkts.isIdentifier(node.expression)) { + if (!arkts.isIdentifier(node.callee)) { return; } - const callExpName: string = node.expression.name; + const callExpName: string = node.callee.name; if (this.componentV2WithConsumer.has(callExpName)) { const queue: Array = [node]; while (queue.length > 0) { @@ -254,10 +254,10 @@ class ConsumerProviderDecoratorCheckRule extends AbstractUISyntaxRule { } private validateProviderInitialization(node: arkts.CallExpression): void { - if (!arkts.isIdentifier(node.expression)) { + if (!arkts.isIdentifier(node.callee)) { return; } - const callExpName: string = node.expression.name; + const callExpName: string = node.callee.name; if (this.componentV2WithProvider.has(callExpName)) { const queue: Array = [node]; while (queue.length > 0) { 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 index d35cf99f2..80f90eadd 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/custom-dialog-missing-controller.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/custom-dialog-missing-controller.ts @@ -27,21 +27,21 @@ class CustomDialogMissingControllerRule extends AbstractUISyntaxRule { } public parsed(node: arkts.AstNode): void { - if (!arkts.isStructDeclaration(node)) { + if (!arkts.isETSStructDeclaration(node)) { return; } this.checkMissingController(node); } // Check if the @CustomDialog-decorated struct contains a property of type CustomDialogController - private checkMissingController(node: arkts.StructDeclaration): void { + private checkMissingController(node: arkts.ETSStructDeclaration): void { const customDialogDecorator = getAnnotationUsage(node, PresetDecorators.CUSTOM_DIALOG); if (!customDialogDecorator) { return; } - const structName = node.definition.ident; + const structName = node.definition?.ident; if (!structName) { return; } diff --git a/arkui-plugins/ui-syntax-plugins/rules/entry-localstorage-check.ts b/arkui-plugins/ui-syntax-plugins/rules/entry-localstorage-check.ts index 7fb289253..d798c9314 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/entry-localstorage-check.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/entry-localstorage-check.ts @@ -25,19 +25,19 @@ class EntryLocalStorageCheckRule extends AbstractUISyntaxRule { } public parsed(node: arkts.AstNode): void { - if (!arkts.isStructDeclaration(node)) { + if (!arkts.isETSStructDeclaration(node)) { return; } this.checkLocalStorageLink(node); } - private checkLocalStorageLink(node: arkts.StructDeclaration): void { + private checkLocalStorageLink(node: arkts.ETSStructDeclaration): void { // Check if @Entry decorator exists with parameter const entryDecorator = getAnnotationUsage(node, PresetDecorators.ENTRY); const isStorageUsed = entryDecorator && entryDecorator.properties[0]; // Check if @LocalStorageLink exists let localStorageLinkUsed = false; - node.definition.body.forEach(body => { + node.definition?.body.forEach(body => { if (!arkts.isClassProperty(body)) { return; } 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 index 0bd71b7c7..0034146a4 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/entry-struct-no-export.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/entry-struct-no-export.ts @@ -26,7 +26,7 @@ class EntryStructNoExportRule extends AbstractUISyntaxRule { public parsed(node: arkts.AstNode): void { // Check if the current node is a schema declaration - if (!arkts.isStructDeclaration(node)) { + if (!arkts.isETSStructDeclaration(node)) { return; } // Get the usage of the @Entry decorator diff --git a/arkui-plugins/ui-syntax-plugins/rules/main-pages-entry-check.ts b/arkui-plugins/ui-syntax-plugins/rules/main-pages-entry-check.ts index c0b9181e4..dee25f44d 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/main-pages-entry-check.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/main-pages-entry-check.ts @@ -24,7 +24,7 @@ class MainPagesEntryCheckRule extends AbstractUISyntaxRule { }; } public parsed(node: arkts.AstNode): void { - if (!arkts.isEtsScript(node) || node.isNamespace) { + if (!arkts.isETSModule(node) || node.isNamespace) { return; } const currentFilePath = getCurrentFilePath(node); @@ -40,9 +40,9 @@ class MainPagesEntryCheckRule extends AbstractUISyntaxRule { // Traverse all child nodes of the Program for (const child of node.getChildren()) { // Check if it's of type StructDeclaration - if (arkts.isStructDeclaration(child)) { + if (arkts.isETSStructDeclaration(child)) { if (!firstStructDeclaration) { - firstStructDeclaration = child.definition.ident; + firstStructDeclaration = child.definition?.ident; } const entryDocoratorUsage = getAnnotationUsage( child, diff --git a/arkui-plugins/ui-syntax-plugins/rules/monitor-decorator-check.ts b/arkui-plugins/ui-syntax-plugins/rules/monitor-decorator-check.ts index e845cac44..12b3d7674 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/monitor-decorator-check.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/monitor-decorator-check.ts @@ -32,7 +32,7 @@ class MonitorDecoratorCheckRule extends AbstractUISyntaxRule { } public parsed(node: arkts.AstNode): void { - if (!arkts.isClassDeclaration(node) && !arkts.isStructDeclaration(node)) { + if (!arkts.isClassDeclaration(node) && !arkts.isETSStructDeclaration(node)) { return; } @@ -41,7 +41,7 @@ class MonitorDecoratorCheckRule extends AbstractUISyntaxRule { this.checkMonitorInClass(node, monitorDecorator); } - if (monitorDecorator && arkts.isStructDeclaration(node)) { + if (monitorDecorator && arkts.isETSStructDeclaration(node)) { this.checkMonitorInStruct(node, monitorDecorator); } this.checkDecorateMethod(node); @@ -88,7 +88,7 @@ class MonitorDecoratorCheckRule extends AbstractUISyntaxRule { } private checkMonitorInStruct( - node: arkts.StructDeclaration, + node: arkts.ETSStructDeclaration, monitorDecorator: arkts.AnnotationUsage | undefined, ): void { if (!monitorDecorator) { @@ -124,7 +124,7 @@ class MonitorDecoratorCheckRule extends AbstractUISyntaxRule { } } - private checkDecorator(node: arkts.ClassDeclaration | arkts.StructDeclaration, decoratorName: string): boolean { + private checkDecorator(node: arkts.ClassDeclaration | arkts.ETSStructDeclaration, decoratorName: string): boolean { return node.definition?.annotations?.some( annotation => annotation.expr && arkts.isIdentifier(annotation.expr) && annotation.expr?.name === decoratorName @@ -132,7 +132,7 @@ class MonitorDecoratorCheckRule extends AbstractUISyntaxRule { } private checkMonitorUsage( - node: arkts.ClassDeclaration | arkts.StructDeclaration + node: arkts.ClassDeclaration | arkts.ETSStructDeclaration ): arkts.AnnotationUsage | undefined { let monitorUsage: arkts.AnnotationUsage | undefined; @@ -152,7 +152,7 @@ class MonitorDecoratorCheckRule extends AbstractUISyntaxRule { } private getLocalMonitorUsed(body: arkts.MethodDefinition): arkts.AnnotationUsage | undefined { - const localMonitorUsed = body.scriptFunction.annotations?.find( + const localMonitorUsed = body.function!.annotations?.find( annotation => annotation.expr && arkts.isIdentifier(annotation.expr) && annotation.expr.name === PresetDecorators.MONITOR ); @@ -160,7 +160,7 @@ class MonitorDecoratorCheckRule extends AbstractUISyntaxRule { } private checkConflictingDecorators(body: arkts.MethodDefinition, localMonitorUsed: arkts.AnnotationUsage): boolean { - const conflictingDecorators = body.scriptFunction.annotations?.filter( + const conflictingDecorators = body.function!.annotations?.filter( annotation => annotation.expr && arkts.isIdentifier(annotation.expr) && annotation.expr.name !== PresetDecorators.MONITOR ); @@ -191,7 +191,7 @@ class MonitorDecoratorCheckRule extends AbstractUISyntaxRule { }); } - private checkDecorateMethod(node: arkts.ClassDeclaration | arkts.StructDeclaration): void { + private checkDecorateMethod(node: arkts.ClassDeclaration | arkts.ETSStructDeclaration): void { // Check if @Monitor is used on a property (which is not allowed) node.definition?.body.forEach((body) => { if (!arkts.isClassProperty(body)) { diff --git a/arkui-plugins/ui-syntax-plugins/rules/nested-relationship.ts b/arkui-plugins/ui-syntax-plugins/rules/nested-relationship.ts index 2f4ee91e0..0f570d596 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/nested-relationship.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/nested-relationship.ts @@ -34,7 +34,7 @@ class NestedRelationshipRule extends AbstractUISyntaxRule { delegateParentComponent: `The '{{componentName}}' component can only be nested in the '{{parentComponentList}}' parent component.`, }; } - public parsed(node: arkts.StructDeclaration): void { + public parsed(node: arkts.ETSStructDeclaration): void { this.checkValidParentComponent(node); this.checkValidChildComponent(node); this.checkSingleChildComponent(node); diff --git a/arkui-plugins/ui-syntax-plugins/rules/nested-reuse-component-check.ts b/arkui-plugins/ui-syntax-plugins/rules/nested-reuse-component-check.ts index c1206b1ab..edca3fcdd 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/nested-reuse-component-check.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/nested-reuse-component-check.ts @@ -35,7 +35,7 @@ class NestedReuseComponentCheckRule extends AbstractUISyntaxRule { this.reusableStructName = []; } - public parsed(node: arkts.StructDeclaration): void { + public parsed(node: arkts.ETSStructDeclaration): void { this.initStructName(node); this.checkNestedReuseComponent(node); this.checkNoReusableV1InReusableV2(node); @@ -48,7 +48,7 @@ class NestedReuseComponentCheckRule extends AbstractUISyntaxRule { //Go through all the children of Program for (const childNode of node.getChildren()) { // Check whether the type is struct - if (!arkts.isStructDeclaration(childNode)) { + if (!arkts.isETSStructDeclaration(childNode)) { continue; } // Get a list of annotations @@ -82,15 +82,15 @@ class NestedReuseComponentCheckRule extends AbstractUISyntaxRule { let hasRepeat: boolean = false; let hasTemplate: boolean = false; while (arkts.isCallExpression(node) && - node.expression && arkts.isMemberExpression(node.expression) && - node.expression.object && arkts.isCallExpression(node.expression.object)) { - if (arkts.isIdentifier(node.expression.property) && getIdentifierName(node.expression.property) === TEMPLATE) { + node.callee && arkts.isMemberExpression(node.callee) && + node.callee.object && arkts.isCallExpression(node.callee.object)) { + if (arkts.isIdentifier(node.callee.property) && getIdentifierName(node.callee.property) === TEMPLATE) { hasTemplate = true; } - node = node.expression.object; + node = node.callee.object; } - if (arkts.isCallExpression(node) && arkts.isIdentifier(node.expression)) { - hasRepeat = getIdentifierName(node.expression) === COMPONENT_REPEAT; + if (arkts.isCallExpression(node) && arkts.isIdentifier(node.callee)) { + hasRepeat = getIdentifierName(node.callee) === COMPONENT_REPEAT; } return { hasRepeat, hasTemplate }; } @@ -122,13 +122,13 @@ class NestedReuseComponentCheckRule extends AbstractUISyntaxRule { } private checkNoReusableV1InReusableV2(node: arkts.AstNode): void { - if (!arkts.isCallExpression(node) || !arkts.isIdentifier(node.expression)) { + if (!arkts.isCallExpression(node) || !arkts.isIdentifier(node.callee)) { return; } - if (this.reusableStructName.includes(node.expression.name)) { + if (this.reusableStructName.includes(node.callee.name)) { // Traverse upwards to find the custom component. let struceNode: arkts.AstNode = node; - while (!arkts.isStructDeclaration(struceNode)) { + while (!arkts.isETSStructDeclaration(struceNode)) { if (!struceNode.parent) { return; } @@ -171,14 +171,14 @@ class NestedReuseComponentCheckRule extends AbstractUISyntaxRule { } private checkNestedReuseComponent(node: arkts.AstNode): void { - if (!arkts.isCallExpression(node) || !arkts.isIdentifier(node.expression)) { + if (!arkts.isCallExpression(node) || !arkts.isIdentifier(node.callee)) { return; } - if (this.reusableV2StructName.includes(node.expression.name)) { + if (this.reusableV2StructName.includes(node.callee.name)) { // Traverse upwards to find the custom component. let struceNode: arkts.AstNode = node; let hasReportedError = false; - while (!arkts.isStructDeclaration(struceNode)) { + while (!arkts.isETSStructDeclaration(struceNode)) { if (!struceNode.parent) { return; } diff --git a/arkui-plugins/ui-syntax-plugins/rules/no-child-in-button.ts b/arkui-plugins/ui-syntax-plugins/rules/no-child-in-button.ts index 74028790c..9829a711b 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/no-child-in-button.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/no-child-in-button.ts @@ -58,7 +58,7 @@ class NoChildInButtonRule extends AbstractUISyntaxRule { let isInStruct = false; let isInBuild = false; while (arkts.nodeType(parentNode) !== arkts.Es2pandaAstNodeType.AST_NODE_TYPE_ETS_MODULE) { - if (arkts.isStructDeclaration(parentNode)) { + if (arkts.isETSStructDeclaration(parentNode)) { isInStruct = true; } if (arkts.isScriptFunction(parentNode) && parentNode.id?.name === 'build') { diff --git a/arkui-plugins/ui-syntax-plugins/rules/no-duplicate-entry.ts b/arkui-plugins/ui-syntax-plugins/rules/no-duplicate-entry.ts index 51043718d..693009713 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/no-duplicate-entry.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/no-duplicate-entry.ts @@ -32,8 +32,8 @@ class NoDuplicateEntryRule extends AbstractUISyntaxRule { this.entryDecoratorUsageIndex = 1; } - public parsed(node: arkts.StructDeclaration): void { - if (!arkts.isStructDeclaration(node)) { + public parsed(node: arkts.ETSStructDeclaration): void { + if (!arkts.isETSStructDeclaration(node)) { return; } let entryDecoratorUsage = getAnnotationUsage(node, PresetDecorators.ENTRY); diff --git a/arkui-plugins/ui-syntax-plugins/rules/no-duplicate-id.ts b/arkui-plugins/ui-syntax-plugins/rules/no-duplicate-id.ts index 32f2b369d..c4ff651ab 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/no-duplicate-id.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/no-duplicate-id.ts @@ -75,7 +75,7 @@ class NoDuplicateIdRule extends AbstractUISyntaxRule { } private getIdInfo(node: arkts.CallExpression): IdInfo | undefined { - const callee = node.expression; + const callee = node.callee; if (!arkts.isMemberExpression(callee)) { return undefined; diff --git a/arkui-plugins/ui-syntax-plugins/rules/no-duplicate-preview.ts b/arkui-plugins/ui-syntax-plugins/rules/no-duplicate-preview.ts index 35d1b31e5..e1eb2cf93 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/no-duplicate-preview.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/no-duplicate-preview.ts @@ -32,8 +32,8 @@ class NoDuplicatePreviewRule extends AbstractUISyntaxRule { this.previewDecoratorUsageIndex = 10; } - public parsed(node: arkts.StructDeclaration): void { - if (!arkts.isStructDeclaration(node)) { + public parsed(node: arkts.ETSStructDeclaration): void { + if (!arkts.isETSStructDeclaration(node)) { return; } const previewDecoratorUsage = getAnnotationUsage( diff --git a/arkui-plugins/ui-syntax-plugins/rules/no-prop-link-objectlink-in-entry.ts b/arkui-plugins/ui-syntax-plugins/rules/no-prop-link-objectlink-in-entry.ts index 7c90f0c9d..77729e317 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/no-prop-link-objectlink-in-entry.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/no-prop-link-objectlink-in-entry.ts @@ -26,16 +26,16 @@ class NoPropLinkObjectLinkInEntryRule extends AbstractUISyntaxRule { }; } public parsed(node: arkts.AstNode): void { - if (!arkts.isStructDeclaration(node)) { + if (!arkts.isETSStructDeclaration(node)) { return; } this.checkNoPropLinkOrObjectLinkInEntry(node); } - private checkNoPropLinkOrObjectLinkInEntry(node: arkts.StructDeclaration): void { + private checkNoPropLinkOrObjectLinkInEntry(node: arkts.ETSStructDeclaration): void { // Check if the struct has the @Entry decorator const isEntryComponent = !!getAnnotationUsage(node, PresetDecorators.ENTRY); - if (!node.definition.ident || !arkts.isIdentifier(node.definition.ident)) { + if (!node.definition?.ident || !arkts.isIdentifier(node.definition.ident)) { return; } const componentName = node.definition.ident.name; diff --git a/arkui-plugins/ui-syntax-plugins/rules/no-same-as-built-in-attribute.ts b/arkui-plugins/ui-syntax-plugins/rules/no-same-as-built-in-attribute.ts index 5940191f6..dd9d275fe 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/no-same-as-built-in-attribute.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/no-same-as-built-in-attribute.ts @@ -25,7 +25,7 @@ class NoSameAsBuiltInAttributeRule extends AbstractUISyntaxRule { } public parsed(node: arkts.AstNode): void { - if (!arkts.isStructDeclaration(node)) { + if (!arkts.isETSStructDeclaration(node)) { return; } if (!node.definition) { 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 index fce5a72c8..a5c758888 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/observedV2-trace-usage-validation.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/observedV2-trace-usage-validation.ts @@ -81,7 +81,7 @@ class ObservedV2TraceUsageValidationRule extends AbstractUISyntaxRule { private tracePropertyRule( currentNode: arkts.AstNode, traceDecorator: arkts.AnnotationUsage): void { - if (arkts.isStructDeclaration(currentNode)) { + if (arkts.isETSStructDeclaration(currentNode)) { this.reportTraceDecoratorError(traceDecorator); } else if (arkts.isClassDeclaration(currentNode) && currentNode.definition) { const observedDecorator = this.getObservedDecorator(currentNode); @@ -170,7 +170,7 @@ class ObservedV2TraceUsageValidationRule extends AbstractUISyntaxRule { private validateTraceDecoratorUsage(node: arkts.AstNode): void { let currentNode = node; - if (arkts.isStructDeclaration(node)) { + if (arkts.isETSStructDeclaration(node)) { // Check whether the current custom component is decorated by the @ObservedV2 decorator const observedV2Decorator = getAnnotationUsage(node, PresetDecorators.OBSERVED_V2); const traceDecorator = getAnnotationUsage(node, PresetDecorators.TRACE); @@ -197,12 +197,12 @@ class ObservedV2TraceUsageValidationRule extends AbstractUISyntaxRule { } if (arkts.isMethodDefinition(node) && this.isInClassDeclaration(currentNode)) { // Check that @Trace is in the correct location - const traceDecorator = findDecorator(node.scriptFunction, PresetDecorators.TRACE); + const traceDecorator = findDecorator(node.function!, PresetDecorators.TRACE); if (traceDecorator) { this.reportTraceMemberVariableError(traceDecorator); } } else if (arkts.isMethodDefinition(node) && !this.isInClassDeclaration(currentNode)) { - const traceDecorator = findDecorator(node.scriptFunction, PresetDecorators.TRACE); + const traceDecorator = findDecorator(node.function!, PresetDecorators.TRACE); if (traceDecorator) { this.reportTraceDecoratorError(traceDecorator); } @@ -215,7 +215,7 @@ class ObservedV2TraceUsageValidationRule extends AbstractUISyntaxRule { const traceDecorator = findDecorator(node, PresetDecorators.TRACE); if (traceDecorator) { // Iterate up the parent node to check whether it is a class or a custom component - while (!arkts.isStructDeclaration(currentNode) && !arkts.isClassDeclaration(currentNode)) { + while (!arkts.isETSStructDeclaration(currentNode) && !arkts.isClassDeclaration(currentNode)) { if (!currentNode.parent) { return; } 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 index 308daf6ff..664a5658b 100644 --- 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 @@ -48,19 +48,19 @@ class OldNewDecoratorMixUseCheckRule extends AbstractUISyntaxRule { }; } - public parsed(node: arkts.StructDeclaration | arkts.ClassDeclaration): void { - if (arkts.isStructDeclaration(node)) { + public parsed(node: arkts.ETSStructDeclaration | arkts.ClassDeclaration): void { + if (arkts.isETSStructDeclaration(node)) { this.handleStructDeclaration(node); } else if (arkts.isClassDeclaration(node)) { this.handleClassDeclaration(node); } } - private handleStructDeclaration(node: arkts.StructDeclaration): void { + private handleStructDeclaration(node: arkts.ETSStructDeclaration): void { // Gets the decorator version of a custom component const componentV2Decorator = getAnnotationUsage(node, PresetDecorators.COMPONENT_V2); const componentDecorator = getAnnotationUsage(node, PresetDecorators.COMPONENT_V1); - node.definition.body.forEach((property) => { + node.definition?.body.forEach((property) => { if (!arkts.isClassProperty(property)) { return; } @@ -135,7 +135,7 @@ class OldNewDecoratorMixUseCheckRule extends AbstractUISyntaxRule { } private reportErrorAndAddDecorator( - structNode: arkts.StructDeclaration, + structNode: arkts.ETSStructDeclaration, errorDecorator: arkts.AnnotationUsage, ): void { let propertyDecoratorName = getAnnotationName(errorDecorator); diff --git a/arkui-plugins/ui-syntax-plugins/rules/once-decorator-check.ts b/arkui-plugins/ui-syntax-plugins/rules/once-decorator-check.ts index 0c0d16f82..bb9c7e452 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/once-decorator-check.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/once-decorator-check.ts @@ -31,7 +31,7 @@ class OnceDecoratorCheckRule extends AbstractUISyntaxRule { this.validateOnlyInStruct(node); this.validateOnlyOnProperty(node); - if (arkts.isStructDeclaration(node)) { + if (arkts.isETSStructDeclaration(node)) { this.validateDecorator(node); } } @@ -44,7 +44,7 @@ class OnceDecoratorCheckRule extends AbstractUISyntaxRule { } if (arkts.isMethodDefinition(member)) { - this.validateOnceDecoratorUsage(member.scriptFunction, this.messages.invalidNOtInStruct); + this.validateOnceDecoratorUsage(member.function!, this.messages.invalidNOtInStruct); } }); return; @@ -95,7 +95,7 @@ class OnceDecoratorCheckRule extends AbstractUISyntaxRule { } private validateDecorator( - node: arkts.StructDeclaration, + node: arkts.ETSStructDeclaration ): void { node.definition?.body.forEach(body => { // Check if @Once is used on a property and if @Param is used with diff --git a/arkui-plugins/ui-syntax-plugins/rules/one-decorator-on-function-method.ts b/arkui-plugins/ui-syntax-plugins/rules/one-decorator-on-function-method.ts index 38b35cae0..27633d57f 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/one-decorator-on-function-method.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/one-decorator-on-function-method.ts @@ -30,13 +30,13 @@ class OneDecoratorOnFunctionMethodRule extends AbstractUISyntaxRule { public parsed(node: arkts.AstNode): void { // If the node is not an ETS script, it is returned directly - if (!arkts.isEtsScript(node)) { + if (!arkts.isETSModule(node)) { return; } this.validateFunctionDecorator(node); } - private validateFunctionDecorator(node: arkts.EtsScript): void { + private validateFunctionDecorator(node: arkts.ETSModule): void { node.statements.forEach((statement) => { // If the node is not a function declaration, it is returned if (!arkts.isFunctionDeclaration(statement)) { @@ -49,8 +49,8 @@ class OneDecoratorOnFunctionMethodRule extends AbstractUISyntaxRule { } // @AnimatableExtend decorators can only be used with functions with this parameter. const animatableExtendDecorator = this.findDecorator(annotations, PresetDecorators.ANIMATABLE_EXTEND); - if (arkts.isScriptFunction(statement.scriptFunction) && animatableExtendDecorator) { - const member = statement.scriptFunction; + if (arkts.isScriptFunction(statement.function!) && animatableExtendDecorator) { + const member = statement.function!; if (this.hasThisParameter(member)) { return; } @@ -60,14 +60,14 @@ class OneDecoratorOnFunctionMethodRule extends AbstractUISyntaxRule { }); } - private findDecorator(annotations: arkts.AnnotationUsage[], decorator: string): arkts.AnnotationUsage | undefined { + private findDecorator(annotations: readonly arkts.AnnotationUsage[], decorator: string): arkts.AnnotationUsage | undefined { return annotations?.find(annotation => annotation.expr && arkts.isIdentifier(annotation.expr) && annotation.expr.name === decorator ); } - private otherDecoratorFilter(annotations: arkts.AnnotationUsage[]): arkts.AnnotationUsage | undefined { + private otherDecoratorFilter(annotations: readonly arkts.AnnotationUsage[]): arkts.AnnotationUsage | undefined { return annotations?.find(annotation => annotation.expr && arkts.isIdentifier(annotation.expr) && annotation.expr.name !== PresetDecorators.BUILDER @@ -76,14 +76,14 @@ class OneDecoratorOnFunctionMethodRule extends AbstractUISyntaxRule { private hasThisParameter(member: arkts.ScriptFunction): boolean { return member.params.some((param) => { - return arkts.isEtsParameterExpression(param) && - arkts.isIdentifier(param.identifier) && - param.identifier.name === PARAM_THIS_NAME; + return arkts.isETSParameterExpression(param) && + arkts.isIdentifier(param.ident) && + param.ident.name === PARAM_THIS_NAME; }); } private validateAllowedDecorators( - annotations: arkts.AnnotationUsage[], + annotations: readonly arkts.AnnotationUsage[], otherDecorator: arkts.AnnotationUsage | undefined, ): void { annotations.forEach((annotation) => { diff --git a/arkui-plugins/ui-syntax-plugins/rules/property-type.ts b/arkui-plugins/ui-syntax-plugins/rules/property-type.ts index 3a43242f0..444afeb4e 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/property-type.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/property-type.ts @@ -136,7 +136,7 @@ class PropertyTypeRule extends AbstractUISyntaxRule { } } else if (arkts.isETSPrimitiveType(member) || arkts.nodeType(member) === arkts.Es2pandaAstNodeType.AST_NODE_TYPE_ETS_STRING_LITERAL_TYPE || - arkts.nodeType(member) === arkts.Es2pandaAstNodeType.AST_NODE_TYPE_ERROR_TYPE_NODE) { + arkts.nodeType(member) === arkts.Es2pandaAstNodeType.AST_NODE_TYPE_BROKEN_TYPE_NODE) { return false; } else if (arkts.nodeType(member) === arkts.Es2pandaAstNodeType.AST_NODE_TYPE_ETS_NULL_TYPE || arkts.isETSUndefinedType(member)) { @@ -157,7 +157,7 @@ class PropertyTypeRule extends AbstractUISyntaxRule { if (propertyTypeName === PropErrorType[0] || propertyTypeName === TypeFlags.BigInt) { return false; } - } else if (arkts.nodeType(member) === arkts.Es2pandaAstNodeType.AST_NODE_TYPE_ERROR_TYPE_NODE) { + } else if (arkts.nodeType(member) === arkts.Es2pandaAstNodeType.AST_NODE_TYPE_BROKEN_TYPE_NODE) { return false; } } @@ -202,7 +202,7 @@ class PropertyTypeRule extends AbstractUISyntaxRule { } } else if (arkts.nodeType(propertyType) === arkts.Es2pandaAstNodeType.AST_NODE_TYPE_ETS_STRING_LITERAL_TYPE || arkts.nodeType(propertyType) === arkts.Es2pandaAstNodeType.AST_NODE_TYPE_ETS_NULL_TYPE || - arkts.nodeType(propertyType) === arkts.Es2pandaAstNodeType.AST_NODE_TYPE_ERROR_TYPE_NODE || + arkts.nodeType(propertyType) === arkts.Es2pandaAstNodeType.AST_NODE_TYPE_BROKEN_TYPE_NODE || arkts.isETSPrimitiveType(propertyType) || arkts.isETSUndefinedType(propertyType) ) { @@ -296,7 +296,7 @@ class PropertyTypeRule extends AbstractUISyntaxRule { } node.getChildren().forEach((member) => { // Only the situation within the component is judged - if (!arkts.isStructDeclaration(member) || !member.definition.ident) { + if (!arkts.isETSStructDeclaration(member) || !member.definition?.ident) { return; } this.getCurrentStructBuilderMethodName(member); @@ -361,13 +361,13 @@ class PropertyTypeRule extends AbstractUISyntaxRule { return; } node.getChildren().forEach((member) => { - if (arkts.isFunctionDeclaration(member) && member.scriptFunction.id?.name) { + if (arkts.isFunctionDeclaration(member) && member.function!.id?.name) { const hasBuilderDecorator = findDecorator(member, PresetDecorators.BUILDER); if (hasBuilderDecorator) { - this.builderFunctionName.push(member.scriptFunction.id?.name); + this.builderFunctionName.push(member.function!.id?.name); } } - if (arkts.isStructDeclaration(member) && member.definition.ident) { + if (arkts.isETSStructDeclaration(member) && member.definition?.ident) { let structName = member.definition.ident.name; this.structStaticMethodsMap.set(structName, new Set()); member.definition.body.forEach((item) => { @@ -381,28 +381,28 @@ class PropertyTypeRule extends AbstractUISyntaxRule { item: arkts.AstNode, structName: string ): void { - if (!arkts.isMethodDefinition(item) || !item.scriptFunction.id || !item.isStatic) { + if (!arkts.isMethodDefinition(item) || !item.function!.id || !item.isStatic) { return; } - const hasBuilderDecorator = findDecorator(item.scriptFunction, PresetDecorators.BUILDER); + const hasBuilderDecorator = findDecorator(item.function!, PresetDecorators.BUILDER); // judgment static method - if (hasBuilderDecorator && arkts.isIdentifier(item.scriptFunction.id) && item.isStatic) { - const methodName = item.scriptFunction.id.name; + if (hasBuilderDecorator && arkts.isIdentifier(item.function!.id) && item.isStatic) { + const methodName = item.function!.id.name; this.structStaticMethodsMap.get(structName)?.add(methodName); } } private getCurrentStructBuilderMethodName( - node: arkts.StructDeclaration + node: arkts.ETSStructDeclaration ): void { node.definition?.body?.forEach((item) => { - if (!arkts.isMethodDefinition(item) || !item.scriptFunction.id) { + if (!arkts.isMethodDefinition(item) || !item.function!.id) { return; } - const builderDecorator = findDecorator(item.scriptFunction, PresetDecorators.BUILDER); + const builderDecorator = findDecorator(item.function!, PresetDecorators.BUILDER); // judgment static method - if (builderDecorator && arkts.isIdentifier(item.scriptFunction.id) && !item.isStatic) { - this.currentStructBuilderMethodName.push(item.scriptFunction.id.name); + if (builderDecorator && arkts.isIdentifier(item.function!.id) && !item.isStatic) { + this.currentStructBuilderMethodName.push(item.function!.id.name); } }); } diff --git a/arkui-plugins/ui-syntax-plugins/rules/require-decorator-regular.ts b/arkui-plugins/ui-syntax-plugins/rules/require-decorator-regular.ts index dd3abf59c..2d8a23771 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/require-decorator-regular.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/require-decorator-regular.ts @@ -25,14 +25,14 @@ class RequireDecoratorRegularRule extends AbstractUISyntaxRule { } public parsed(node: arkts.AstNode): void { - if (!arkts.isStructDeclaration(node)) { + if (!arkts.isETSStructDeclaration(node)) { return; } this.checkRequireDecorator(node); } - private checkRequireDecorator(node: arkts.StructDeclaration): void { - node.definition.body.forEach(member => { + private checkRequireDecorator(node: arkts.ETSStructDeclaration): void { + node.definition?.body.forEach(member => { if (!arkts.isClassProperty(member)) { return; } diff --git a/arkui-plugins/ui-syntax-plugins/rules/reusable-component-in-V2-check.ts b/arkui-plugins/ui-syntax-plugins/rules/reusable-component-in-V2-check.ts index 57901a88d..4597ad9ec 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/reusable-component-in-V2-check.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/reusable-component-in-V2-check.ts @@ -29,7 +29,7 @@ class ReusableComponentInV2CheckRule extends AbstractUISyntaxRule { public beforeTransform(): void { this.reusableStructName = []; } - public parsed(node: arkts.StructDeclaration): void { + public parsed(node: arkts.ETSStructDeclaration): void { this.initStructName(node); this.checkNoReusableV1InComponentV2(node); } @@ -41,7 +41,7 @@ class ReusableComponentInV2CheckRule extends AbstractUISyntaxRule { //Go through all the children of Program for (const childNode of node.getChildren()) { // Check whether the type is struct - if (!arkts.isStructDeclaration(childNode)) { + if (!arkts.isETSStructDeclaration(childNode)) { continue; } const reusableV1Decorator = getAnnotationUsage(childNode, PresetDecorators.REUSABLE_V1); @@ -53,19 +53,19 @@ class ReusableComponentInV2CheckRule extends AbstractUISyntaxRule { } private checkNoReusableV1InComponentV2(node: arkts.AstNode,): void { - if (!arkts.isCallExpression(node) || !arkts.isIdentifier(node.expression)) { + if (!arkts.isCallExpression(node) || !arkts.isIdentifier(node.callee)) { return; } - if (this.reusableStructName.includes(node.expression.name)) { + if (this.reusableStructName.includes(node.callee.name)) { // Traverse upwards to find the custom component. let structNode: arkts.AstNode = node; - while (!arkts.isStructDeclaration(structNode)) { + while (!arkts.isETSStructDeclaration(structNode)) { if (!structNode.parent) { return; } structNode = structNode.parent; } - const annotationsList = structNode.definition.annotations; + const annotationsList = structNode.definition?.annotations; // Check that the current component is decorated by the @ComponentV2 decorator if (annotationsList?.some((annotation: any) => annotation.expr.name === PresetDecorators.COMPONENT_V2)) { this.report({ diff --git a/arkui-plugins/ui-syntax-plugins/rules/reusableV2-decorator-check.ts b/arkui-plugins/ui-syntax-plugins/rules/reusableV2-decorator-check.ts index 24a7ca87c..8f75eacd6 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/reusableV2-decorator-check.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/reusableV2-decorator-check.ts @@ -26,7 +26,7 @@ class ReusableV2DecoratorCheckRule extends AbstractUISyntaxRule { } public parsed(node: arkts.AstNode): void { - if (!arkts.isStructDeclaration(node)) { + if (!arkts.isETSStructDeclaration(node)) { return; } if (!node.definition) { @@ -66,7 +66,7 @@ class ReusableV2DecoratorCheckRule extends AbstractUISyntaxRule { } private reportInvalidDecoratorUsage( - node: arkts.StructDeclaration, + node: arkts.ETSStructDeclaration, structNode: arkts.Identifier | undefined, ): void { if (!structNode || !node) { diff --git a/arkui-plugins/ui-syntax-plugins/rules/reuse-attribute-check.ts b/arkui-plugins/ui-syntax-plugins/rules/reuse-attribute-check.ts index 509a2a2fd..880e28411 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/reuse-attribute-check.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/reuse-attribute-check.ts @@ -45,14 +45,14 @@ class ReuseAttributeCheckRule extends AbstractUISyntaxRule { //Go through all the children of Program for (const childNode of node.getChildren()) { // Check whether the type is struct - if (!arkts.isStructDeclaration(childNode)) { + if (!arkts.isETSStructDeclaration(childNode)) { continue; } // Check that the current component has @ComponentV2 and @ReusableV2 decorators const reusableV2Decorator = getAnnotationUsage(childNode, PresetDecorators.REUSABLE_V2); const componentV2Decorator = getAnnotationUsage(childNode, PresetDecorators.COMPONENT_V2); if (reusableV2Decorator && componentV2Decorator) { - const struceName = childNode.definition.ident?.name ?? ''; + const struceName = childNode.definition?.ident?.name ?? ''; this.reusableV2ComponentV2Struct.push(struceName); } } @@ -65,7 +65,7 @@ class ReuseAttributeCheckRule extends AbstractUISyntaxRule { // Gets the reuse or reuseId attribute const decoratedNode = node.property; if (arkts.isCallExpression(structNode)) { - const nodeExpression = structNode.expression; + const nodeExpression = structNode.callee; if (arkts.isIdentifier(nodeExpression) && arkts.isIdentifier(decoratedNode)) { if (decoratedNode.name === ReuseConstants.REUSE && !this.reusableV2ComponentV2Struct.includes(nodeExpression.name)) { diff --git a/arkui-plugins/ui-syntax-plugins/rules/specific-component-children.ts b/arkui-plugins/ui-syntax-plugins/rules/specific-component-children.ts index aace72ff3..48b094660 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/specific-component-children.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/specific-component-children.ts @@ -32,15 +32,15 @@ class SpecificComponentChildrenRule extends AbstractUISyntaxRule { }; } - public parsed(node: arkts.StructDeclaration): void { - if (!arkts.isCallExpression(node) || !node.expression) { + public parsed(node: arkts.ETSStructDeclaration): void { + if (!arkts.isCallExpression(node) || !node.callee) { return; } // Check whether the current node is an identifier and toggle component - if (!arkts.isIdentifier(node.expression)) { + if (!arkts.isIdentifier(node.callee)) { return; } - const componentName: string = getIdentifierName(node.expression); + const componentName: string = getIdentifierName(node.callee); if (componentName !== PresetDecorators.TOGGLE) { return; } diff --git a/arkui-plugins/ui-syntax-plugins/rules/static-param-require.ts b/arkui-plugins/ui-syntax-plugins/rules/static-param-require.ts index 8f2fdb8e2..a5e7a4cc6 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/static-param-require.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/static-param-require.ts @@ -30,11 +30,11 @@ class StaticParamRequireRule extends AbstractUISyntaxRule { this.staticPropertyMap = new Map(); } - public parsed(node: arkts.StructDeclaration): void { + public parsed(node: arkts.ETSStructDeclaration): 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) || !member.definition.ident || !member.definition.ident.name) { + if (!arkts.isETSStructDeclaration(member) || !member.definition.ident || !member.definition.ident.name) { return; } const hasComponentV1 = hasAnnotation(member.definition.annotations, PresetDecorators.COMPONENT_V1); @@ -45,10 +45,10 @@ class StaticParamRequireRule extends AbstractUISyntaxRule { }); }); } - if (!arkts.isCallExpression(node) || !arkts.isIdentifier(node.expression)) { + if (!arkts.isCallExpression(node) || !arkts.isIdentifier(node.callee)) { return; } - const componentName = node.expression.name; + const componentName = node.callee.name; // If the initialization is for a component with private properties if (!this.staticPropertyMap.has(componentName)) { return; diff --git a/arkui-plugins/ui-syntax-plugins/rules/struct-missing-decorator.ts b/arkui-plugins/ui-syntax-plugins/rules/struct-missing-decorator.ts index 11b48a219..39cc9232d 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/struct-missing-decorator.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/struct-missing-decorator.ts @@ -25,7 +25,7 @@ class StructMissingDecoratorRule extends AbstractUISyntaxRule { } public parsed(node: arkts.AstNode): void { - if (!arkts.isStructDeclaration(node)) { + if (!arkts.isETSStructDeclaration(node)) { return; } if (!node.definition) { @@ -51,7 +51,7 @@ class StructMissingDecoratorRule extends AbstractUISyntaxRule { } } - private hasDecorator(node: arkts.StructDeclaration, decorator: string): boolean { + private hasDecorator(node: arkts.ETSStructDeclaration, decorator: string): boolean { return !!getAnnotationUsage(node, decorator); } } diff --git a/arkui-plugins/ui-syntax-plugins/rules/struct-no-extends.ts b/arkui-plugins/ui-syntax-plugins/rules/struct-no-extends.ts index 12945ee48..3bf74708c 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/struct-no-extends.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/struct-no-extends.ts @@ -22,8 +22,8 @@ class StructNoExtendsRule extends AbstractUISyntaxRule { structNoExtends: `Structs are not allowed to inherit from classes or implement interfaces.`, }; } - public parsed(node: arkts.StructDeclaration): void { - if (!arkts.isStructDeclaration(node) || !node.definition.ident) { + public parsed(node: arkts.ETSStructDeclaration): void { + if (!arkts.isETSStructDeclaration(node) || !node.definition?.ident) { return; } const hasSuperClass: boolean = node.definition.super !== undefined; diff --git a/arkui-plugins/ui-syntax-plugins/rules/struct-property-decorator.ts b/arkui-plugins/ui-syntax-plugins/rules/struct-property-decorator.ts index 81228846b..7f6d4deca 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/struct-property-decorator.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/struct-property-decorator.ts @@ -48,7 +48,7 @@ class StructPropertyDecoratorRule extends AbstractUISyntaxRule { } public parsed(node: arkts.AstNode): void { - if (arkts.isStructDeclaration(node)) { + if (arkts.isETSStructDeclaration(node)) { const hasComponentV1 = hasAnnotation(node.definition.annotations, PresetDecorators.COMPONENT_V1); const hasComponentV2 = hasAnnotation(node.definition.annotations, PresetDecorators.COMPONENT_V2); this.checkInvalidStaticPropertyDecorations(node, hasComponentV1, hasComponentV2); @@ -63,7 +63,7 @@ class StructPropertyDecoratorRule extends AbstractUISyntaxRule { private hasPropertyDecorator( member: arkts.ClassProperty, - decorators: String[] + decorators: string[] ): boolean { const annotationName = getClassPropertyAnnotationNames(member); return decorators.some(decorator => @@ -72,7 +72,7 @@ class StructPropertyDecoratorRule extends AbstractUISyntaxRule { } private checkInvalidStaticPropertyDecorations( - node: arkts.StructDeclaration, + node: arkts.ETSStructDeclaration, hasComponentV1: boolean, hasComponentV2: boolean ): void { @@ -92,13 +92,13 @@ class StructPropertyDecoratorRule extends AbstractUISyntaxRule { }); } - private checkInvalidStaticMethodDecorations(node: arkts.ClassDeclaration | arkts.StructDeclaration): void { + private checkInvalidStaticMethodDecorations(node: arkts.ClassDeclaration | arkts.ETSStructDeclaration): void { node.definition?.body.forEach((member) => { // Errors are reported when the node type is static Method, - if (!arkts.isMethodDefinition(member) || !member.name || !member.isStatic) { + if (!arkts.isMethodDefinition(member) || !member.id || !member.isStatic) { return; } - const hasMonitor = member.funcExpr.scriptFunction.annotations.some(annotation => { + const hasMonitor = member.function!.annotations.some(annotation => { if (!annotation.expr || !arkts.isIdentifier(annotation.expr)) { return false; } @@ -107,7 +107,7 @@ class StructPropertyDecoratorRule extends AbstractUISyntaxRule { if (!hasMonitor) { return; } - const propertyNameNode = member.name; + const propertyNameNode = member.id; this.report({ node: propertyNameNode, message: this.messages.invalidStaticUsage diff --git a/arkui-plugins/ui-syntax-plugins/rules/track-decorator-check.ts b/arkui-plugins/ui-syntax-plugins/rules/track-decorator-check.ts index a585241ec..ca5af992f 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/track-decorator-check.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/track-decorator-check.ts @@ -32,7 +32,7 @@ class TrackDecoratorCheckRule extends AbstractUISyntaxRule { arkts.isTSTypeAliasDeclaration(node)) { this.reportInvalidTrackDecoratorUsage(node); } - if (arkts.isStructDeclaration(node)) { + if (arkts.isETSStructDeclaration(node)) { this.checkInvalidTrackAnnotations(node); } // Check if the current node is a class declaration @@ -51,13 +51,13 @@ class TrackDecoratorCheckRule extends AbstractUISyntaxRule { } } - private checkInvalidTrackAnnotations(node: arkts.StructDeclaration): void { + private checkInvalidTrackAnnotations(node: arkts.ETSStructDeclaration): void { const trackAnnotation = getAnnotationUsage(node, PresetDecorators.TRACK); if (trackAnnotation) { this.reportInvalidTarget(trackAnnotation); } // Traverse all members of the struct body - node.definition.body.forEach((member) => { + node.definition?.body.forEach((member) => { // Check whether it is a member variable if (arkts.isClassProperty(member)) { const trackDecorator = findDecorator(member, PresetDecorators.TRACK); @@ -68,7 +68,7 @@ class TrackDecoratorCheckRule extends AbstractUISyntaxRule { } // Check whether this is the method if (arkts.isMethodDefinition(member)) { - const trackDecorator = findDecorator(member.scriptFunction, PresetDecorators.TRACK); + const trackDecorator = findDecorator(member.function!, PresetDecorators.TRACK); // If the method is decorated with @Track, an error is reported immediately if (trackDecorator) { this.reportInvalidTarget(trackDecorator); @@ -93,7 +93,7 @@ class TrackDecoratorCheckRule extends AbstractUISyntaxRule { } // Check whether this is the method if (arkts.isMethodDefinition(member)) { - const trackDecorator = findDecorator(member.scriptFunction, PresetDecorators.TRACK); + const trackDecorator = findDecorator(member.function!, PresetDecorators.TRACK); // If the method is decorated with @Track, an error is reported immediately if (trackDecorator) { this.reportInvalidTarget(trackDecorator); diff --git a/arkui-plugins/ui-syntax-plugins/rules/ui-consistent-check.ts b/arkui-plugins/ui-syntax-plugins/rules/ui-consistent-check.ts index 695b3579f..429ffb19b 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/ui-consistent-check.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/ui-consistent-check.ts @@ -41,7 +41,7 @@ class UiConsistentCheckRule extends AbstractUISyntaxRule { }; } - public parsed(node: arkts.StructDeclaration): void { + public parsed(node: arkts.ETSStructDeclaration): void { // Specific Attributes: Check the VP units this.checkVpUnit(node); // Specific attributes: Check the VP and PX units @@ -94,7 +94,7 @@ class UiConsistentCheckRule extends AbstractUISyntaxRule { } let curNode = node; try { - while (!arkts.isStructDeclaration(curNode)) { + while (!arkts.isETSStructDeclaration(curNode)) { if (!curNode.parent) { return false; } @@ -136,18 +136,18 @@ class UiConsistentCheckRule extends AbstractUISyntaxRule { } private checkVpUnit(node: arkts.AstNode): void { - if (!arkts.isCallExpression(node) || !node.expression || - !arkts.isMemberExpression(node.expression) || !node.expression.property) { + if (!arkts.isCallExpression(node) || !node.callee || + !arkts.isMemberExpression(node.callee) || !node.callee.property) { return; } // Verify the attribute whose unit is VP - if (!arkts.isIdentifier(node.expression.property) || - !UiConsistentCheckRule.checkVpProperties.includes(node.expression.property.name)) { + if (!arkts.isIdentifier(node.callee.property) || + !UiConsistentCheckRule.checkVpProperties.includes(node.callee.property.name)) { return; } // Only the content under the UI component and the special decorator is verified - if (!this.isInUIComponent(node.expression.property) && - !this.isInSpecificDecorators(node.expression.property)) { + if (!this.isInUIComponent(node.callee.property) && + !this.isInSpecificDecorators(node.callee.property)) { return; } // Gets the attribute value text and verifies the formatting @@ -182,18 +182,18 @@ class UiConsistentCheckRule extends AbstractUISyntaxRule { } private checkVpAndPxUnit(node: arkts.AstNode): void { - if (!arkts.isCallExpression(node) || !node.expression || - !arkts.isMemberExpression(node.expression) || !node.expression.property) { + if (!arkts.isCallExpression(node) || !node.callee || + !arkts.isMemberExpression(node.callee) || !node.callee.property) { return; } // Verify the attribute whose unit is VP or PX - if (!arkts.isIdentifier(node.expression.property) || - !UiConsistentCheckRule.checkVpAndPxProperties.includes(node.expression.property.name)) { + if (!arkts.isIdentifier(node.callee.property) || + !UiConsistentCheckRule.checkVpAndPxProperties.includes(node.callee.property.name)) { return; } // Only the content under the UI component and the special decorator is verified - if (!this.isInUIComponent(node.expression.property) && - !this.isInSpecificDecorators(node.expression.property)) { + if (!this.isInUIComponent(node.callee.property) && + !this.isInSpecificDecorators(node.callee.property)) { return; } // Gets the attribute value text and verifies the formatting @@ -228,18 +228,18 @@ class UiConsistentCheckRule extends AbstractUISyntaxRule { } private checkColorParams(node: arkts.AstNode): void { - if (!arkts.isCallExpression(node) || !node.expression || - !arkts.isMemberExpression(node.expression) || !node.expression.property) { + if (!arkts.isCallExpression(node) || !node.callee || + !arkts.isMemberExpression(node.callee) || !node.callee.property) { return; } // Verify the attribute whose type is Color - if (!arkts.isIdentifier(node.expression.property) || - !this.isColorProperty(node.expression.property.name)) { + if (!arkts.isIdentifier(node.callee.property) || + !this.isColorProperty(node.callee.property.name)) { return; } // Only the content under the UI component and the special decorator is verified - if (!this.isInUIComponent(node.expression.property) && - !this.isInSpecificDecorators(node.expression.property)) { + if (!this.isInUIComponent(node.callee.property) && + !this.isInSpecificDecorators(node.callee.property)) { return; } // Gets the attribute value text and verifies the formatting diff --git a/arkui-plugins/ui-syntax-plugins/rules/validate-build-in-struct.ts b/arkui-plugins/ui-syntax-plugins/rules/validate-build-in-struct.ts index d187edd52..cada0d959 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/validate-build-in-struct.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/validate-build-in-struct.ts @@ -31,7 +31,7 @@ class ValidateBuildInStructRule extends AbstractUISyntaxRule { } public parsed(node: arkts.AstNode): void { - if (!arkts.isStructDeclaration(node)) { + if (!arkts.isETSStructDeclaration(node)) { return; } let buildFunctionCount: number = BUILD_FUNCTION_COUNT_INI; @@ -39,12 +39,12 @@ class ValidateBuildInStructRule extends AbstractUISyntaxRule { } private validateBuild( - node: arkts.StructDeclaration, + node: arkts.ETSStructDeclaration, buildFunctionCount: number ): void { - node.definition.body.forEach((member) => { + node.definition?.body.forEach((member) => { // Check if the member is defined for the method and the method name is 'build' - if (arkts.isMethodDefinition(member) && arkts.isIdentifier(member.name) && getIdentifierName(member.name) === BUILD_NAME) { + if (arkts.isMethodDefinition(member) && arkts.isIdentifier(member.id) && getIdentifierName(member.id) === BUILD_NAME) { buildFunctionCount++; this.validateBuildFunctionParameters(member); this.validateDuplicateBuild(buildFunctionCount, member); @@ -59,10 +59,10 @@ class ValidateBuildInStructRule extends AbstractUISyntaxRule { // rule1: Check if the build function contains arguments and report an error private validateBuildFunctionParameters(buildFunction: arkts.MethodDefinition): void { - const paramsNodes = buildFunction.scriptFunction.params; + const paramsNodes = buildFunction.function!.params; if (paramsNodes.length > NOT_PARAM_LENGTH) { paramsNodes.forEach((param) => { - if (arkts.isEtsParameterExpression(param)) { + if (arkts.isETSParameterExpression(param)) { this.reportBuildParamNotAllowed(param); } }); @@ -74,7 +74,7 @@ class ValidateBuildInStructRule extends AbstractUISyntaxRule { member: arkts.MethodDefinition, ): void { if (buildFunctionCount > BUILD_FUNCTION_COUNT) { - const buildNode = member.scriptFunction.id; + const buildNode = member.function!.id; if (!buildNode) { return; } @@ -101,16 +101,16 @@ class ValidateBuildInStructRule extends AbstractUISyntaxRule { } private validateConstructorForBuildFunction( - node: arkts.StructDeclaration, + node: arkts.ETSStructDeclaration, member: arkts.MethodDefinition, buildFunctionCount: number, ): void { - const blockStatement = member.scriptFunction.body; + const blockStatement = member.function!.body; if (!blockStatement || !arkts.isBlockStatement(blockStatement)) { return; } const statements = blockStatement.statements; - const structName = node.definition.ident; + const structName = node.definition?.ident; if (buildFunctionCount === BUILD_FUNCTION_COUNT_INI && statements.length === NOT_STATEMENT_LENGTH) { this.reportMissingBuildInStruct(structName, node); @@ -138,7 +138,7 @@ class ValidateBuildInStructRule extends AbstractUISyntaxRule { private reportMissingBuildInStruct( structName: arkts.Identifier | undefined, - node: arkts.StructDeclaration, + node: arkts.ETSStructDeclaration, ): void { if (!structName) { return; diff --git a/arkui-plugins/ui-syntax-plugins/rules/validate-decorator-target.ts b/arkui-plugins/ui-syntax-plugins/rules/validate-decorator-target.ts index d48cb7dd8..4bdb2cf78 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/validate-decorator-target.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/validate-decorator-target.ts @@ -54,7 +54,7 @@ class ValidateDecoratorTargetRule extends AbstractUISyntaxRule { public parsed(node: arkts.AstNode): void { this.validateDecoratorPropertyOnly(node); - if (!arkts.isStructDeclaration(node)) { + if (!arkts.isETSStructDeclaration(node)) { this.validateDecoratorStructOnly(node); } } @@ -94,7 +94,7 @@ class ValidateDecoratorTargetRule extends AbstractUISyntaxRule { if (arkts.isMethodDefinition(node) && (node.kind === arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_GET || node.kind === arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_SET)) { - node.scriptFunction.annotations.forEach((annotation) => { + node.function!.annotations.forEach((annotation) => { this.validateDecorator(annotation, structOnlyDecorators, this.messages.decoratorOnlyWithStruct); }); } diff --git a/arkui-plugins/ui-syntax-plugins/rules/variable-initialization-via-component-constructor.ts b/arkui-plugins/ui-syntax-plugins/rules/variable-initialization-via-component-constructor.ts index 29c7209c6..64f2edf2c 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/variable-initialization-via-component-constructor.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/variable-initialization-via-component-constructor.ts @@ -49,7 +49,7 @@ class VariableInitializationViaComponentConstructorRule extends AbstractUISyntax this.cannotInitMap = new Map(); } - public parsed(node: arkts.StructDeclaration): void { + public parsed(node: arkts.ETSStructDeclaration): void { this.initMap(node); this.checkMustInitialize(node); this.checkCannotInitialize(node); @@ -100,7 +100,7 @@ class VariableInitializationViaComponentConstructorRule extends AbstractUISyntax return; } node.getChildren().forEach((member) => { - if (!arkts.isStructDeclaration(member)) { + if (!arkts.isETSStructDeclaration(member)) { return; } if (!member.definition || !member.definition.ident || !arkts.isIdentifier(member.definition.ident)) { @@ -136,13 +136,13 @@ class VariableInitializationViaComponentConstructorRule extends AbstractUISyntax } private checkMustInitialize(node: arkts.AstNode): void { - if (!arkts.isCallExpression(node) || !node.expression) { + if (!arkts.isCallExpression(node) || !node.callee) { return; } - if (!arkts.isIdentifier(node.expression)) { + if (!arkts.isIdentifier(node.callee)) { return; } - const structName: string = getIdentifierName(node.expression); + const structName: string = getIdentifierName(node.callee); if (!this.mustInitMap.has(structName)) { return; } @@ -164,13 +164,13 @@ class VariableInitializationViaComponentConstructorRule extends AbstractUISyntax } private checkCannotInitialize(node: arkts.AstNode): void { - if (!arkts.isCallExpression(node) || !node.expression) { + if (!arkts.isCallExpression(node) || !node.callee) { return; } - if (!arkts.isIdentifier(node.expression)) { + if (!arkts.isIdentifier(node.callee)) { return; } - const structName: string = getIdentifierName(node.expression); + const structName: string = getIdentifierName(node.callee); if (!this.cannotInitMap.has(structName)) { return; } diff --git a/arkui-plugins/ui-syntax-plugins/rules/watch-decorator-function.ts b/arkui-plugins/ui-syntax-plugins/rules/watch-decorator-function.ts index fe2135a6e..048aed0c6 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/watch-decorator-function.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/watch-decorator-function.ts @@ -26,7 +26,7 @@ class WatchDecoratorFunctionRule extends AbstractUISyntaxRule { } public parsed(node: arkts.AstNode): void { - if (!arkts.isStructDeclaration(node)) { + if (!arkts.isETSStructDeclaration(node)) { return; } // Get all method names @@ -57,11 +57,11 @@ class WatchDecoratorFunctionRule extends AbstractUISyntaxRule { } // Gets the names of all methods in the struct - private getMethodNames(node: arkts.StructDeclaration): string[] { + private getMethodNames(node: arkts.ETSStructDeclaration): string[] { const methodNames: string[] = []; - node.definition.body.forEach((member) => { - if (arkts.isMethodDefinition(member) && arkts.isIdentifier(member.name)) { - const methodName = getIdentifierName(member.name); + node.definition?.body.forEach((member) => { + if (arkts.isMethodDefinition(member) && arkts.isIdentifier(member.id)) { + const methodName = getIdentifierName(member.id); if (methodName) { methodNames.push(methodName); } @@ -70,9 +70,9 @@ class WatchDecoratorFunctionRule extends AbstractUISyntaxRule { return methodNames; } - private getPrivateNames(node: arkts.StructDeclaration): string[] { + private getPrivateNames(node: arkts.ETSStructDeclaration): string[] { const privateNames: string[] = []; - node.definition.body.forEach((member) => { + node.definition?.body.forEach((member) => { if (arkts.isClassProperty(member) && isPrivateClassProperty(member)) { const privateName = getClassPropertyName(member); if (privateName) { @@ -84,11 +84,11 @@ class WatchDecoratorFunctionRule extends AbstractUISyntaxRule { } private validateWatch( - node: arkts.StructDeclaration, + node: arkts.ETSStructDeclaration, methodNames: string[], privateNames: string[] ): void { - node.definition.body.forEach(member => { + node.definition?.body.forEach(member => { if (!arkts.isClassProperty(member)) { return; } diff --git a/arkui-plugins/ui-syntax-plugins/rules/watch-decorator-regular.ts b/arkui-plugins/ui-syntax-plugins/rules/watch-decorator-regular.ts index fc2c30f39..cb4237b86 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/watch-decorator-regular.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/watch-decorator-regular.ts @@ -27,14 +27,14 @@ class WatchDecoratorRegularRule extends AbstractUISyntaxRule { } public parsed(node: arkts.AstNode): void { - if (!arkts.isStructDeclaration(node)) { + if (!arkts.isETSStructDeclaration(node)) { return; } this.validateWatchDecorator(node); } - private validateWatchDecorator(node: arkts.StructDeclaration): void { - node.definition.body.forEach(member => { + private validateWatchDecorator(node: arkts.ETSStructDeclaration): void { + node.definition?.body.forEach(member => { if (!arkts.isClassProperty(member)) { return; } diff --git a/arkui-plugins/ui-syntax-plugins/rules/wrap-builder-check.ts b/arkui-plugins/ui-syntax-plugins/rules/wrap-builder-check.ts index a8f2da56f..43cae2dac 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/wrap-builder-check.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/wrap-builder-check.ts @@ -30,14 +30,14 @@ class StructNoExtendsRule extends AbstractUISyntaxRule { this.builderFunctionNames = []; } - public parsed(node: arkts.StructDeclaration): void { + public parsed(node: arkts.ETSStructDeclaration): void { this.collectBuilderFunctions(node); this.validateWrapBuilderInIdentifier(node); } // Collect all the function names that are decorated with @Builder private collectBuilderFunctions(node: arkts.AstNode): void { - if (!arkts.isEtsScript(node)) { + if (!arkts.isETSModule(node)) { return; } node.statements.forEach((statement) => { @@ -48,7 +48,7 @@ class StructNoExtendsRule extends AbstractUISyntaxRule { if (!buildDecoratorUsage) { return; } - const functionName = statement.scriptFunction.id?.name; + const functionName = statement.function!.id?.name; if (!functionName || functionName === '' || this.builderFunctionNames.includes(functionName)) { return; } @@ -57,11 +57,11 @@ class StructNoExtendsRule extends AbstractUISyntaxRule { } private validateWrapBuilderInIdentifier(node: arkts.AstNode): void { - if (!arkts.isCallExpression(node) || !node.expression) { + if (!arkts.isCallExpression(node) || !node.callee) { return; } // If the current node is not a wrap builder, return - if (!arkts.isIdentifier(node.expression) || getIdentifierName(node.expression) !== WRAP_BUILDER) { + if (!arkts.isIdentifier(node.callee) || getIdentifierName(node.callee) !== WRAP_BUILDER) { return; } let functionName: string = ''; diff --git a/arkui-plugins/ui-syntax-plugins/utils/index.ts b/arkui-plugins/ui-syntax-plugins/utils/index.ts index 0e3f34341..bb7b03d60 100644 --- a/arkui-plugins/ui-syntax-plugins/utils/index.ts +++ b/arkui-plugins/ui-syntax-plugins/utils/index.ts @@ -152,7 +152,7 @@ export function getAnnotationName(annotation: arkts.AnnotationUsage): string { } export function getAnnotationUsage( - declaration: arkts.StructDeclaration, + declaration: arkts.ETSStructDeclaration, annotationName: string ): arkts.AnnotationUsage | undefined { return declaration.definition.annotations.find( @@ -495,7 +495,7 @@ export function getAnnotationUsageByName( export function isStructClassDeclaration(node: arkts.AstNode): node is arkts.ClassDeclaration { return ( - arkts.isClassDeclaration(node) && !!node.definition && arkts.classDefinitionIsFromStructConst(node.definition) + arkts.isClassDeclaration(node) && !!node.definition && node.definition.isFromStruct ); } @@ -517,7 +517,7 @@ export function getFunctionAnnotationUsage( } export function getCallee(callExpression: arkts.CallExpression): arkts.Identifier | undefined { - const expression = callExpression.expression; + const expression = callExpression.callee; if (arkts.isIdentifier(expression)) { return expression; } @@ -553,5 +553,5 @@ export const TypeFlags = { export function getCurrentFilePath(node: arkts.AstNode): string | undefined { const program = arkts.getProgramFromAstNode(node); - return program.absName; + return program.absoluteName; } \ No newline at end of file -- Gitee From d3b642886e550ac25e89e9de8ef953916f5b32a9 Mon Sep 17 00:00:00 2001 From: Aleksandr Veselov Date: Tue, 12 Aug 2025 15:48:50 +0000 Subject: [PATCH 02/39] !3 Replace externalSources Signed-off-by: Aleksandr Veselov --- arkui-plugins/ui-syntax-plugins/index.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/arkui-plugins/ui-syntax-plugins/index.ts b/arkui-plugins/ui-syntax-plugins/index.ts index 9914ec845..69b4e90f3 100644 --- a/arkui-plugins/ui-syntax-plugins/index.ts +++ b/arkui-plugins/ui-syntax-plugins/index.ts @@ -84,7 +84,7 @@ function transformExternalSources( visitedPrograms: Set, transformer: UISyntaxLinterVisitor ): void { - const externalSources = program.externalSources; + const externalSources = program.getExternalSources(); for (const externalSource of externalSources) { if (matchPrefix(EXCLUDE_EXTERNAL_SOURCE_PREFIXES, externalSource.getName())) { continue; -- Gitee From 7d9d2f295f624620b6a7c2d8ddf016f193c6a937 Mon Sep 17 00:00:00 2001 From: Aleksandr Veselov Date: Wed, 13 Aug 2025 15:36:10 +0300 Subject: [PATCH 03/39] Fix syntax in annotations Change-Id: Ie7cb209e23557b1fed69428d0cb198b0d2959269 Signed-off-by: Aleksandr Veselov --- arkui-plugins/common/plugin-context.ts | 6 +++--- .../test/ut/common/annotation.test.ts | 8 ++++---- arkui-plugins/test/utils/compile.ts | 8 ++++---- arkui-plugins/test/utils/global.ts | 18 +++++++++--------- .../utils/plugins/before-memo-no-recheck.ts | 4 ++-- .../utils/plugins/builder-lambda-no-recheck.ts | 4 ++-- .../test/utils/plugins/memo-no-recheck.ts | 4 ++-- arkui-plugins/test/utils/plugins/recheck.ts | 2 +- .../test/utils/plugins/struct-no-recheck.ts | 4 ++-- .../test/utils/plugins/struct-to-component.ts | 4 ++-- .../test/utils/plugins/ui-no-recheck.ts | 4 ++-- 11 files changed, 33 insertions(+), 33 deletions(-) diff --git a/arkui-plugins/common/plugin-context.ts b/arkui-plugins/common/plugin-context.ts index 4ce622b51..1673c9165 100644 --- a/arkui-plugins/common/plugin-context.ts +++ b/arkui-plugins/common/plugin-context.ts @@ -21,7 +21,7 @@ export class PluginContext { private ast: arkts.ETSModule | undefined; private program: arkts.Program | undefined; private projectConfig: ProjectConfig | undefined; - private contextPtr: number | undefined; + private contextPtr: arkts.KNativePointer | undefined; private codingFilePath: string | undefined; private fileManager: FileManager | undefined; @@ -74,11 +74,11 @@ export class PluginContext { return this.projectConfig; } - public setContextPtr(ptr: number): void { + public setContextPtr(ptr: arkts.KNativePointer): void { this.contextPtr = ptr; } - public getContextPtr(): number | undefined { + public getContextPtr(): arkts.KNativePointer | undefined { return this.contextPtr; } diff --git a/arkui-plugins/test/ut/common/annotation.test.ts b/arkui-plugins/test/ut/common/annotation.test.ts index d99bae124..d1799cfe0 100644 --- a/arkui-plugins/test/ut/common/annotation.test.ts +++ b/arkui-plugins/test/ut/common/annotation.test.ts @@ -58,7 +58,7 @@ class AnnotationVisitor extends AbstractVisitor { addTestAnnotation(node: AnnotationAstNode): void { if (arkts.isETSParameterExpression(node)) { - node.annotations = [this.testAnnotation()]; + node.setAnnotations([this.testAnnotation()]); } else if (arkts.isMethodDefinition(node)) { node.scriptFunction.setAnnotations([this.testAnnotation()]); } else { @@ -68,7 +68,7 @@ class AnnotationVisitor extends AbstractVisitor { removeTestAnnotation(node: AnnotationAstNode): void { if (arkts.isETSParameterExpression(node)) { - node.annotations = []; + node.setAnnotations([]); } else if (arkts.isMethodDefinition(node)) { node.scriptFunction.setAnnotations([]); } else { @@ -116,7 +116,7 @@ function addAnnotationTransform(this: PluginContext): arkts.ETSModule | undefine pluginContext: this, }); program = programVisitor.programVisitor(program); - script = program.astNode; + script = program.ast as arkts.ETSModule; return script; } return script; @@ -136,7 +136,7 @@ function removeAnnotationTransform(this: PluginContext): arkts.ETSModule | undef pluginContext: this, }); program = programVisitor.programVisitor(program); - script = program.astNode; + script = program.ast as arkts.ETSModule; return script; } return script; diff --git a/arkui-plugins/test/utils/compile.ts b/arkui-plugins/test/utils/compile.ts index 4594b3b87..f6b1fe0c7 100644 --- a/arkui-plugins/test/utils/compile.ts +++ b/arkui-plugins/test/utils/compile.ts @@ -44,7 +44,7 @@ function insertPlugin(driver: PluginDriver, plugin: PluginExecutor | undefined): function collectPluginTextContextFromSourceProgram(program: arkts.Program, tracing: TraceOptions): PluginTestContext { const pluginTestContext: PluginTestContext = {}; - const script: arkts.ETSModule = program.astNode; + const script: arkts.ETSModule = program.ast as arkts.ETSModule; pluginTestContext.scriptSnapshot = script.dumpSrc(); return pluginTestContext; } @@ -61,7 +61,7 @@ function collectPluginTextContextFromExternalSource( const name = source.getName(); const sourceProgram: arkts.Program = source.programs[0]; const shouldCollectByName = filteredExternalSourceNames.includes(name) || matchSourceName(name); - const shouldCollectByProgram = sourceProgram && (!useCache || sourceProgram.isASTLowered()); + const shouldCollectByProgram = sourceProgram && (!useCache || sourceProgram.isASTLowered); return shouldCollectByName && shouldCollectByProgram; }); const declContexts: Record = {}; @@ -75,7 +75,7 @@ function collectPluginTextContextFromExternalSource( ); } else { const sourceTestContext: SingleProgramContext = {}; - const script: arkts.ETSModule = sourceProgram.astNode; + const script: arkts.ETSModule = sourceProgram.ast as arkts.ETSModule; const scriptSnapshot = script.dumpSrc(); sourceTestContext.scriptSnapshot = scriptSnapshot; declContexts[name] = sourceTestContext; @@ -105,7 +105,7 @@ function collectPluginTestContext( ); } if (canCollectExternal) { - const externalSources: arkts.ExternalSource[] = program.externalSources; + const externalSources: arkts.ExternalSource[] = program.getExternalSources(); pluginTestContext = concatObject( pluginTestContext, collectPluginTextContextFromExternalSource(externalSources, tracing, matchSourceName, useCache) diff --git a/arkui-plugins/test/utils/global.ts b/arkui-plugins/test/utils/global.ts index 424d4512e..b70e00964 100644 --- a/arkui-plugins/test/utils/global.ts +++ b/arkui-plugins/test/utils/global.ts @@ -41,25 +41,25 @@ function createGlobalConfig( config.push(fileInfo.filePath); if (isUseCache) { - arkts.MemInitialize(); + arkts.arktsGlobal.es2panda._MemInitialize(); } arkts.arktsGlobal.filePath = fileInfo.filePath; return resetConfig(config); } function destroyGlobalConfig(config: arkts.Config, isUseCache: boolean = true): void { - destroyConfig(config); + destroyConfig(config.peer); if (isUseCache) { - arkts.MemFinalize(); + arkts.arktsGlobal.es2panda._MemFinalize(); } } -function createGlobalContextPtr(config: arkts.Config, files: string[]): number { - return arkts.CreateGlobalContext(config.peer, files, files.length, false); +function createGlobalContextPtr(config: arkts.Config, files: string[]): arkts.KNativePointer { + return arkts.arktsGlobal.es2panda._CreateGlobalContext(config.peer, files, files.length, false); } -function destroyGlobalContextPtr(globalContextPtr: number): void { - arkts.DestroyGlobalContext(globalContextPtr); +function destroyGlobalContextPtr(globalContextPtr: arkts.KNativePointer): void { + arkts.arktsGlobal.es2panda._DestroyGlobalContext(globalContextPtr); } function createCacheContextFromFile( @@ -107,9 +107,9 @@ function destroyContext(context: arkts.Context): void { } } -function destroyConfig(config: arkts.Config): void { +function destroyConfig(config: arkts.KNativePointer): void { try { - arkts.destroyConfig(config); + arkts.arktsGlobal.es2panda._DestroyConfig(config); } catch (e) { // Do nothing } diff --git a/arkui-plugins/test/utils/plugins/before-memo-no-recheck.ts b/arkui-plugins/test/utils/plugins/before-memo-no-recheck.ts index 89db0d3b2..42ed5da55 100644 --- a/arkui-plugins/test/utils/plugins/before-memo-no-recheck.ts +++ b/arkui-plugins/test/utils/plugins/before-memo-no-recheck.ts @@ -29,7 +29,7 @@ export const beforeMemoNoRecheck: Plugins = { const contextPtr = this.getContextPtr() ?? arkts.arktsGlobal.compilerContext?.peer; if (!!contextPtr) { let program = arkts.getOrUpdateGlobalContext(contextPtr).program; - script = program.astNode; + script = program.ast as arkts.ETSModule; const builderLambdaTransformer = new MemoVisitor(); const programVisitor = new ProgramVisitor({ pluginName: beforeMemoNoRecheck.name, @@ -39,7 +39,7 @@ export const beforeMemoNoRecheck: Plugins = { pluginContext: this, }); program = programVisitor.programVisitor(program); - script = program.astNode; + script = program.ast as arkts.ETSModule; return script; } return script; diff --git a/arkui-plugins/test/utils/plugins/builder-lambda-no-recheck.ts b/arkui-plugins/test/utils/plugins/builder-lambda-no-recheck.ts index d4ab2f66c..61c7f89f0 100644 --- a/arkui-plugins/test/utils/plugins/builder-lambda-no-recheck.ts +++ b/arkui-plugins/test/utils/plugins/builder-lambda-no-recheck.ts @@ -29,7 +29,7 @@ export const builderLambdaNoRecheck: Plugins = { const contextPtr = this.getContextPtr() ?? arkts.arktsGlobal.compilerContext?.peer; if (!!contextPtr) { let program = arkts.getOrUpdateGlobalContext(contextPtr).program; - script = program.astNode; + script = program.ast as arkts.ETSModule; const builderLambdaTransformer = new BuilderLambdaTransformer(this.getProjectConfig()); const programVisitor = new ProgramVisitor({ pluginName: builderLambdaNoRecheck.name, @@ -39,7 +39,7 @@ export const builderLambdaNoRecheck: Plugins = { pluginContext: this, }); program = programVisitor.programVisitor(program); - script = program.astNode; + script = program.ast as arkts.ETSModule; return script; } return script; diff --git a/arkui-plugins/test/utils/plugins/memo-no-recheck.ts b/arkui-plugins/test/utils/plugins/memo-no-recheck.ts index 81d03479f..aa53b4d56 100644 --- a/arkui-plugins/test/utils/plugins/memo-no-recheck.ts +++ b/arkui-plugins/test/utils/plugins/memo-no-recheck.ts @@ -35,7 +35,7 @@ export const memoNoRecheck: Plugins = { if (!!contextPtr) { const isFrameworkMode = !!this.getProjectConfig()?.frameworkMode; let program = arkts.getOrUpdateGlobalContext(contextPtr).program; - let script = program.astNode; + let script = program.ast as arkts.ETSModule; const positionalIdTracker = new PositionalIdTracker(arkts.getFileName(), false); const parameterTransformer = new ParameterTransformer({ positionalIdTracker, @@ -66,7 +66,7 @@ export const memoNoRecheck: Plugins = { }); program = programVisitor.programVisitor(program); NodeCache.getInstance().clear(); - script = program.astNode; + script = program.ast as arkts.ETSModule; return script; } }, diff --git a/arkui-plugins/test/utils/plugins/recheck.ts b/arkui-plugins/test/utils/plugins/recheck.ts index be4ac8bf6..31242a3c9 100644 --- a/arkui-plugins/test/utils/plugins/recheck.ts +++ b/arkui-plugins/test/utils/plugins/recheck.ts @@ -26,7 +26,7 @@ export const recheck: Plugins = { const contextPtr = this.getContextPtr() ?? arkts.arktsGlobal.compilerContext?.peer; if (!!contextPtr) { let program = arkts.getOrUpdateGlobalContext(contextPtr).program; - script = program.astNode; + script = program.ast as arkts.ETSModule; arkts.recheckSubtree(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 index d2c139628..9b60340f8 100644 --- a/arkui-plugins/test/utils/plugins/struct-no-recheck.ts +++ b/arkui-plugins/test/utils/plugins/struct-no-recheck.ts @@ -29,7 +29,7 @@ export const structNoRecheck: Plugins = { const contextPtr = this.getContextPtr() ?? arkts.arktsGlobal.compilerContext?.peer; if (!!contextPtr) { let program = arkts.getOrUpdateGlobalContext(contextPtr).program; - script = program.astNode; + script = program.ast as arkts.ETSModule; const structTransformer = new StructTransformer(this.getProjectConfig()); const programVisitor = new ProgramVisitor({ pluginName: structNoRecheck.name, @@ -39,7 +39,7 @@ export const structNoRecheck: Plugins = { pluginContext: this, }); program = programVisitor.programVisitor(program); - script = program.astNode; + script = program.ast as arkts.ETSModule; return script; } return script; diff --git a/arkui-plugins/test/utils/plugins/struct-to-component.ts b/arkui-plugins/test/utils/plugins/struct-to-component.ts index a0998d1f4..7c66cba35 100644 --- a/arkui-plugins/test/utils/plugins/struct-to-component.ts +++ b/arkui-plugins/test/utils/plugins/struct-to-component.ts @@ -29,7 +29,7 @@ export const structToComponent: Plugins = { const contextPtr = this.getContextPtr() ?? arkts.arktsGlobal.compilerContext?.peer; if (!!contextPtr) { let program = arkts.getOrUpdateGlobalContext(contextPtr).program; - script = program.astNode; + script = program.ast as arkts.ETSModule; const componentTransformer = new ComponentTransformer({ projectConfig: this.getProjectConfig(), }); @@ -41,7 +41,7 @@ export const structToComponent: Plugins = { pluginContext: this, }); program = programVisitor.programVisitor(program); - script = program.astNode; + script = program.ast as arkts.ETSModule; 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 index 343752782..c238d78bd 100644 --- a/arkui-plugins/test/utils/plugins/ui-no-recheck.ts +++ b/arkui-plugins/test/utils/plugins/ui-no-recheck.ts @@ -29,7 +29,7 @@ export const uiNoRecheck: Plugins = { const contextPtr = this.getContextPtr() ?? arkts.arktsGlobal.compilerContext?.peer; if (!!contextPtr) { let program = arkts.getOrUpdateGlobalContext(contextPtr).program; - script = program.astNode; + script = program.ast as arkts.ETSModule; const checkedTransformer = new CheckedTransformer(this.getProjectConfig()); const programVisitor = new ProgramVisitor({ pluginName: uiNoRecheck.name, @@ -39,7 +39,7 @@ export const uiNoRecheck: Plugins = { pluginContext: this, }); program = programVisitor.programVisitor(program); - script = program.astNode; + script = program.ast as arkts.ETSModule; return script; } return script; -- Gitee From 22eff8e4364bd86be0d5311fdfe5692392cb9038 Mon Sep 17 00:00:00 2001 From: Aleksandr Veselov Date: Wed, 13 Aug 2025 15:47:50 +0300 Subject: [PATCH 04/39] Migrate some utilities from wrapper to test Change-Id: I103d9bfb8bbec4f5b52f99ec39b43a2ce4711e21 Signed-off-by: Aleksandr Veselov --- arkui-plugins/test/utils/compile.ts | 48 +++++++++++++++++++++++------ arkui-plugins/test/utils/global.ts | 1 + 2 files changed, 40 insertions(+), 9 deletions(-) diff --git a/arkui-plugins/test/utils/compile.ts b/arkui-plugins/test/utils/compile.ts index f6b1fe0c7..6ee379cfe 100644 --- a/arkui-plugins/test/utils/compile.ts +++ b/arkui-plugins/test/utils/compile.ts @@ -206,7 +206,7 @@ function compileAbcWithExternal(emitter: EventEmitter, jobInfo: Jo MockPluginDriver.getInstance().getPluginContext().setContextPtr(context.peer); const stopAfter = jobInfo.stopAfter!; let shouldStop = false; - arkts.proceedToState(arkts.Es2pandaContextState.ES2PANDA_STATE_PARSED, context.peer); + proceedToState(arkts.Es2pandaContextState.ES2PANDA_STATE_PARSED, context.peer); shouldStop = runPluginsAtState( emitter, jobInfo, @@ -221,7 +221,7 @@ function compileAbcWithExternal(emitter: EventEmitter, jobInfo: Jo emitter.emit('TASK_FINISH', { jobId: 'compile-abc-with-external' }); return; } - arkts.proceedToState(arkts.Es2pandaContextState.ES2PANDA_STATE_CHECKED, context.peer); + proceedToState(arkts.Es2pandaContextState.ES2PANDA_STATE_CHECKED, context.peer); shouldStop = runPluginsAtState( emitter, jobInfo, @@ -236,7 +236,7 @@ function compileAbcWithExternal(emitter: EventEmitter, jobInfo: Jo emitter.emit('TASK_FINISH', { jobId: 'compile-abc-with-external' }); return; } - arkts.proceedToState(arkts.Es2pandaContextState.ES2PANDA_STATE_BIN_GENERATED, context.peer); + proceedToState(arkts.Es2pandaContextState.ES2PANDA_STATE_BIN_GENERATED, context.peer); destroyContext(context); MockPluginDriver.getInstance().clear(); emitter.emit('TASK_FINISH', { jobId: 'compile-abc-with-external' }); @@ -249,7 +249,7 @@ function compileAbc(emitter: EventEmitter, jobInfo: JobInfo, traci MockPluginDriver.getInstance().getPluginContext().setContextPtr(context.peer); const stopAfter = jobInfo.stopAfter!; let shouldStop = false; - arkts.proceedToState(arkts.Es2pandaContextState.ES2PANDA_STATE_PARSED, context.peer); + proceedToState(arkts.Es2pandaContextState.ES2PANDA_STATE_PARSED, context.peer); shouldStop = runPluginsAtState( emitter, jobInfo, @@ -263,7 +263,7 @@ function compileAbc(emitter: EventEmitter, jobInfo: JobInfo, traci MockPluginDriver.getInstance().clear(); return; } - arkts.proceedToState(arkts.Es2pandaContextState.ES2PANDA_STATE_CHECKED, context.peer); + proceedToState(arkts.Es2pandaContextState.ES2PANDA_STATE_CHECKED, context.peer); shouldStop = runPluginsAtState( emitter, jobInfo, @@ -277,7 +277,7 @@ function compileAbc(emitter: EventEmitter, jobInfo: JobInfo, traci MockPluginDriver.getInstance().clear(); return; } - arkts.proceedToState(arkts.Es2pandaContextState.ES2PANDA_STATE_BIN_GENERATED, context.peer); + proceedToState(arkts.Es2pandaContextState.ES2PANDA_STATE_BIN_GENERATED, context.peer); destroyContext(context); MockPluginDriver.getInstance().clear(); } @@ -287,13 +287,43 @@ function compileExternalProgram(emitter: EventEmitter, jobInfo: Jo MockPluginDriver.getInstance().getPluginContext().setProjectConfig(jobInfo.projectConfig!); const context = createContextForExternalCompilation(jobInfo); MockPluginDriver.getInstance().getPluginContext().setContextPtr(context.peer); - arkts.proceedToState(arkts.Es2pandaContextState.ES2PANDA_STATE_PARSED, context.peer); + proceedToState(arkts.Es2pandaContextState.ES2PANDA_STATE_PARSED, context.peer); runPluginsAtState(emitter, jobInfo, arkts.Es2pandaContextState.ES2PANDA_STATE_PARSED, context, tracing); - arkts.proceedToState(arkts.Es2pandaContextState.ES2PANDA_STATE_CHECKED, context.peer); + proceedToState(arkts.Es2pandaContextState.ES2PANDA_STATE_CHECKED, context.peer); runPluginsAtState(emitter, jobInfo, arkts.Es2pandaContextState.ES2PANDA_STATE_CHECKED, context, tracing); - arkts.proceedToState(arkts.Es2pandaContextState.ES2PANDA_STATE_LOWERED, context.peer); + proceedToState(arkts.Es2pandaContextState.ES2PANDA_STATE_LOWERED, context.peer); destroyContext(context); MockPluginDriver.getInstance().clear(); } +function proceedToState(state: arkts.Es2pandaContextState, context: arkts.KNativePointer, forceDtsEmit = false): void { + console.log('[TS WRAPPER] PROCEED TO STATE: ', arkts.getEnumName(arkts.Es2pandaContextState, state)); + if (arkts.arktsGlobal.es2panda._ContextState(context) === arkts.Es2pandaContextState.ES2PANDA_STATE_ERROR) { + arkts.NodeCache.clear(); + processErrorState(state, context, forceDtsEmit); + } + if (state <= arkts.arktsGlobal.es2panda._ContextState(context)) { + console.log('[TS WRAPPER] PROCEED TO STATE: SKIPPING'); + return; + } + arkts.NodeCache.clear(); + arkts.arktsGlobal.es2panda._ProceedToState(context, state); + processErrorState(state, context, forceDtsEmit); +} + +function processErrorState(state: arkts.Es2pandaContextState, context: arkts.KNativePointer, forceDtsEmit = false): void { + try { + if (arkts.arktsGlobal.es2panda._ContextState(context) === arkts.Es2pandaContextState.ES2PANDA_STATE_ERROR && !forceDtsEmit) { + const errorMessage = arkts.unpackString(arkts.arktsGlobal.generatedEs2panda._ContextErrorMessage(context)); + if (errorMessage === undefined) { + arkts.throwError(`Could not get ContextErrorMessage`); + } + arkts.throwError([`Failed to proceed to ${arkts.Es2pandaContextState[state]}`, errorMessage].join(`\n`)); + } + } catch (e) { + arkts.arktsGlobal.es2panda._DestroyContext(context); + throw e; + } +} + export { compileAbcWithExternal, compileAbc, compileExternalProgram }; diff --git a/arkui-plugins/test/utils/global.ts b/arkui-plugins/test/utils/global.ts index b70e00964..173a44f57 100644 --- a/arkui-plugins/test/utils/global.ts +++ b/arkui-plugins/test/utils/global.ts @@ -110,6 +110,7 @@ function destroyContext(context: arkts.Context): void { function destroyConfig(config: arkts.KNativePointer): void { try { arkts.arktsGlobal.es2panda._DestroyConfig(config); + arkts.arktsGlobal.resetConfig(); } catch (e) { // Do nothing } -- Gitee From 90614b5cc9f9b045c99d61f1d6433daafd72af36 Mon Sep 17 00:00:00 2001 From: Aleksandr Veselov Date: Wed, 13 Aug 2025 16:57:48 +0300 Subject: [PATCH 05/39] Fix syntax in memo-plugins Change-Id: Ib91321ee5af735a9cb3cee3304988f73f0ecdebe Signed-off-by: Aleksandr Veselov --- .../collectors/memo-collectors/utils.ts | 4 +- arkui-plugins/interop-plugins/index.ts | 4 +- .../memo-plugins/function-transformer.ts | 84 ++++++++++--------- arkui-plugins/memo-plugins/index.ts | 4 +- .../memo-plugins/internal-transformer.ts | 8 +- .../memo-plugins/memo-cache-factory.ts | 50 +++++------ arkui-plugins/memo-plugins/memo-factory.ts | 55 ++++++------ .../memo-plugins/memo-transformer.ts | 2 +- .../memo-plugins/parameter-transformer.ts | 45 +++++----- .../memo-plugins/signature-transformer.ts | 20 ++--- arkui-plugins/memo-plugins/utils.ts | 40 ++++----- 11 files changed, 159 insertions(+), 157 deletions(-) diff --git a/arkui-plugins/collectors/memo-collectors/utils.ts b/arkui-plugins/collectors/memo-collectors/utils.ts index dbe386649..30cb361a9 100644 --- a/arkui-plugins/collectors/memo-collectors/utils.ts +++ b/arkui-plugins/collectors/memo-collectors/utils.ts @@ -276,10 +276,10 @@ export function collectMemoableInfoInVariableDeclarator(node: arkts.AstNode, inf if (!arkts.isVariableDeclarator(node)) { return currInfo; } - if (!!node.id!.asTypeNode) { + if (!!(node.id! as arkts.Identifier).typeAnnotation) { currInfo = { ...currInfo, - ...collectMemoableInfoInType(node.id!.asTypeNode), + ...collectMemoableInfoInType((node.id! as arkts.Identifier).typeAnnotation!), }; } if (!!node.init && arkts.isArrowFunctionExpression(node.init)) { diff --git a/arkui-plugins/interop-plugins/index.ts b/arkui-plugins/interop-plugins/index.ts index 3504eaaa1..88d0f9fb7 100644 --- a/arkui-plugins/interop-plugins/index.ts +++ b/arkui-plugins/interop-plugins/index.ts @@ -40,7 +40,7 @@ function parsedTransform(this: PluginContext): arkts.ETSModule | undefined { const contextPtr = arkts.arktsGlobal.compilerContext?.peer ?? this.getContextPtr(); if (!!contextPtr) { let program = arkts.getOrUpdateGlobalContext(contextPtr).program; - script = program.astNode; + script = program.ast as arkts.ETSModule; if (script) { const declTransformer = new DeclTransformer({ @@ -56,7 +56,7 @@ function parsedTransform(this: PluginContext): arkts.ETSModule | undefined { }); program = programVisitor.programVisitor(program); - script = program.astNode; + script = program.ast as arkts.ETSModule; this.setArkTSAst(script as arkts.ETSModule); debugLog('interopTransform:parsed exit'); return script; diff --git a/arkui-plugins/memo-plugins/function-transformer.ts b/arkui-plugins/memo-plugins/function-transformer.ts index 4a0f601f5..ee8641f20 100644 --- a/arkui-plugins/memo-plugins/function-transformer.ts +++ b/arkui-plugins/memo-plugins/function-transformer.ts @@ -105,7 +105,7 @@ export class FunctionTransformer extends AbstractVisitor { } private enterMethod(node: arkts.MethodDefinition): void { - const name = node.name.name; + const name = node.id!.name; const isMemo = isMemoMethodDefinition(node); this.scopes.push({ name, isMemo }); } @@ -129,9 +129,9 @@ export class FunctionTransformer extends AbstractVisitor { } private enterVariableDeclarator(node: arkts.VariableDeclarator): void { - const name = node.name.name; + const name = (node.id as arkts.Identifier).name; const isMemo = isMemoVariableDeclarator(node); - this.scopes.push({ name, isMemo, regardAsSameScope: !!node.initializer }); + this.scopes.push({ name, isMemo, regardAsSameScope: !!node.init }); } private enterTSAsExpression(node: arkts.TSAsExpression): void { @@ -213,10 +213,10 @@ export class FunctionTransformer extends AbstractVisitor { 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}`); + console.error(`Attempt to call @memo-method ${decl.id!.name} from non-@memo-method ${scope.name}`); throw 'Invalid @memo usage'; } else { - console.error(`Attempt to call @memo-method ${decl.name.name} from anonymous non-@memo-method`); + console.error(`Attempt to call @memo-method ${decl.id!.name} from anonymous non-@memo-method`); throw 'Invalid @memo usage'; } } @@ -309,21 +309,25 @@ export class FunctionTransformer extends AbstractVisitor { updateMethod = arkts.factory.updateMethodDefinition( node, node.kind, - node.name, - this.signatureTransformer.visitor( - removeMemoAnnotation(this.updateScriptFunction(node.function!, node.name.name)), - hasIntrinsic + node.key, + arkts.factory.createFunctionExpression(node.id?.clone(), + this.signatureTransformer.visitor( + removeMemoAnnotation(this.updateScriptFunction(node.function!, node.id!.name)), + hasIntrinsic + ) ), - node.modifiers, + node.modifierFlags, false ); } else { updateMethod = arkts.factory.updateMethodDefinition( node, node.kind, - node.name, - this.signatureTransformer.visitor(node.function!), - node.modifiers, + node.key, + arkts.factory.createFunctionExpression(node.id?.clone(), + this.signatureTransformer.visitor(node.function!) + ), + node.modifierFlags, false ); } @@ -336,7 +340,7 @@ export class FunctionTransformer extends AbstractVisitor { decl: arkts.MethodDefinition, ignoreSelf: boolean = false ): arkts.CallExpression { - let updatedArguments: arkts.AstNode[] = node.arguments.map((it, index) => { + let updatedArguments: arkts.Expression[] = node.arguments.map((it, index) => { const param = decl.function!.params.at(index); if (!param || !arkts.isETSParameterExpression(param)) { return it; @@ -353,7 +357,7 @@ export class FunctionTransformer extends AbstractVisitor { if (!ignoreSelf) { this.checkMemoCallInMethod(decl); updatedArguments = [ - ...factory.createHiddenArguments(this.positionalIdTracker.id(decl.name.name)), + ...factory.createHiddenArguments(this.positionalIdTracker.id(decl.id!.name)), ...updatedArguments, ]; } @@ -365,7 +369,7 @@ export class FunctionTransformer extends AbstractVisitor { updatedArguments = moveToFront(updatedArguments, 2); } this.modified = true; - return arkts.factory.updateCallExpression(node, node.expression, node.typeArguments, updatedArguments); + return arkts.factory.updateCallExpression(node, node.callee, updatedArguments, node.typeParams); } private updateDeclaredCallWithName(node: arkts.CallExpression, name: string): arkts.CallExpression { @@ -374,15 +378,15 @@ export class FunctionTransformer extends AbstractVisitor { } private updateAnonymousCallWithMemoParams(node: arkts.CallExpression): arkts.CallExpression { - let newExpression: arkts.AstNode = node.expression; - if (isStandaloneArrowFunction(node.expression)) { + let newExpression: arkts.Expression = node.callee!; + if (isStandaloneArrowFunction(node.callee!)) { newExpression = arkts.factory.updateArrowFunctionExpression( - node.expression, - this.signatureTransformer.visitor(node.expression.function!) + node.callee, + this.signatureTransformer.visitor(node.callee.function!) ); } const that = this; - const updatedArguments: arkts.AstNode[] = node.arguments.map((it) => { + const updatedArguments: arkts.Expression[] = node.arguments.map((it) => { if (arkts.isArrowFunctionExpression(it) && isMemoArrowFunction(it)) { that.enterAnonymousScope(it.function!); const res = that.updateScriptFunction(it.function!); @@ -393,7 +397,7 @@ export class FunctionTransformer extends AbstractVisitor { return it; }); this.modified ||= this.signatureTransformer.modified; - return arkts.factory.updateCallExpression(node, newExpression, node.typeArguments, updatedArguments); + return arkts.factory.updateCallExpression(node, newExpression, updatedArguments, node.typeParams); } private updateAnonymousMemoCall( @@ -420,20 +424,20 @@ export class FunctionTransformer extends AbstractVisitor { return arkts.factory.updateCallExpression( node, arkts.factory.updateArrowFunctionExpression(expression, res), - newNode.typeArguments, - [...factory.createHiddenArguments(this.positionalIdTracker.id()), ...newNode.arguments] + [...factory.createHiddenArguments(this.positionalIdTracker.id()), ...newNode.arguments], + newNode.typeParams ); } private updateCallExpressionWithNoDecl(node: arkts.CallExpression): arkts.CallExpression { - if (isStandaloneArrowFunction(node.expression)) { - return this.updateAnonymousMemoCall(node, node.expression); + if (isStandaloneArrowFunction(node.callee!)) { + return this.updateAnonymousMemoCall(node, node.callee); } return this.updateAnonymousCallWithMemoParams(node); } private updateCallExpression(node: arkts.CallExpression): arkts.CallExpression { - const expr = node.expression; + const expr = node.callee!; const decl = getDeclResolveAlias(expr); if (!decl) { return this.updateCallExpressionWithNoDecl(node); @@ -456,7 +460,7 @@ export class FunctionTransformer extends AbstractVisitor { return this.updateDeclaredCallWithName(node, decl.key.name); } if (arkts.isETSParameterExpression(decl) && isMemoETSParameterExpression(decl)) { - return this.updateDeclaredCallWithName(node, decl.identifier.name); + return this.updateDeclaredCallWithName(node, decl.ident!.name); } return this.updateCallExpressionWithNoDecl(node); } @@ -548,20 +552,20 @@ export class FunctionTransformer extends AbstractVisitor { private updateVariableDeclarator(node: arkts.VariableDeclarator): arkts.VariableDeclarator { const scope = this.scopes[this.scopes.length - 1]; - const isValidScope = !!scope && scope.name === node.name.name; + const isValidScope = !!scope && scope.name === (node.id as arkts.Identifier).name; if (!isValidScope) { return node; } this.exitAnonymousScope(); if (!scope.isMemo) { - if (!!node.initializer && arkts.isArrowFunctionExpression(node.initializer)) { + if (!!node.init && arkts.isArrowFunctionExpression(node.init)) { return arkts.factory.updateVariableDeclarator( node, node.flag, - node.name, + node.id, arkts.factory.updateArrowFunctionExpression( - node.initializer, - this.signatureTransformer.visitor(node.initializer.function!) + node.init, + this.signatureTransformer.visitor(node.init.function!) ) ); } @@ -570,14 +574,14 @@ export class FunctionTransformer extends AbstractVisitor { let typeAnnotation: arkts.TypeNode | undefined; if ( - !!node.name.typeAnnotation && - !(typeAnnotation = factory.updateMemoTypeAnnotation(node.name.typeAnnotation)) + !!(node.id as arkts.Identifier).typeAnnotation && + !(typeAnnotation = factory.updateMemoTypeAnnotation((node.id as arkts.Identifier).typeAnnotation)) ) { - console.error(`ETSFunctionType or ETSUnionType expected for @memo-variable-type ${node.name.name}`); + console.error(`ETSFunctionType or ETSUnionType expected for @memo-variable-type ${(node.id as arkts.Identifier).name}`); throw 'Invalid @memo usage'; } - let initializer: arkts.AstNode | undefined = node.initializer; + let initializer: arkts.Expression | undefined = node.init; if (!!initializer && arkts.isArrowFunctionExpression(initializer)) { this.enterAnonymousScope(initializer.function!); const res = this.updateScriptFunction(initializer.function!, initializer.function!.id?.name); @@ -589,7 +593,7 @@ export class FunctionTransformer extends AbstractVisitor { return arkts.factory.updateVariableDeclarator( node, node.flag, - arkts.factory.updateIdentifier(node.name, node.name.name, typeAnnotation), + arkts.factory.updateIdentifier((node.id as arkts.Identifier), (node.id as arkts.Identifier).name, typeAnnotation), initializer ); } @@ -679,8 +683,8 @@ export class FunctionTransformer extends AbstractVisitor { return arkts.factory.updateAssignmentExpression( node, node.left!, - node.operatorType, - arkts.factory.updateArrowFunctionExpression(right, res) + arkts.factory.updateArrowFunctionExpression(right, res), + node.operatorType ); } diff --git a/arkui-plugins/memo-plugins/index.ts b/arkui-plugins/memo-plugins/index.ts index e3546a30d..99307ea4e 100644 --- a/arkui-plugins/memo-plugins/index.ts +++ b/arkui-plugins/memo-plugins/index.ts @@ -45,13 +45,13 @@ function checkedTransform(this: PluginContext): arkts.ETSModule | undefined { const contextPtr = this.getContextPtr() ?? arkts.arktsGlobal.compilerContext?.peer; if (!!contextPtr) { let program = arkts.getOrUpdateGlobalContext(contextPtr).program; - let script = program.astNode; + let script = program.ast as arkts.ETSModule; const isFrameworkMode = !!this.getProjectConfig()?.frameworkMode; const canSkipPhases = !isFrameworkMode && CanSkipPhasesCache.check(program); arkts.Performance.getInstance().createEvent('memo-checked'); program = checkedProgramVisit(program, this, canSkipPhases, isFrameworkMode); - script = program.astNode; + script = program.ast as arkts.ETSModule; arkts.Performance.getInstance().stopEvent('memo-checked', true); diff --git a/arkui-plugins/memo-plugins/internal-transformer.ts b/arkui-plugins/memo-plugins/internal-transformer.ts index 3541fb7c3..eb2ae1af2 100644 --- a/arkui-plugins/memo-plugins/internal-transformer.ts +++ b/arkui-plugins/memo-plugins/internal-transformer.ts @@ -32,14 +32,14 @@ export class InternalsTransformer extends AbstractVisitor { 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) { + if (arkts.isIdentifier(node.callee)) { + if (node.callee.name === RuntimeNames.__CONTEXT) { return arkts.factory.createIdentifier(RuntimeNames.CONTEXT, undefined); } - if (node.expression.name === RuntimeNames.__ID) { + if (node.callee.name === RuntimeNames.__ID) { return arkts.factory.createIdentifier(RuntimeNames.ID, undefined); } - if (node.expression.name === RuntimeNames.__KEY) { + if (node.callee.name === RuntimeNames.__KEY) { return this.positionalIdTracker.id(RuntimeNames.__KEY); } } diff --git a/arkui-plugins/memo-plugins/memo-cache-factory.ts b/arkui-plugins/memo-plugins/memo-cache-factory.ts index 9d0194640..529cb48a2 100644 --- a/arkui-plugins/memo-plugins/memo-cache-factory.ts +++ b/arkui-plugins/memo-plugins/memo-cache-factory.ts @@ -78,9 +78,9 @@ export class RewriteFactory { typeParams, typeParams.params.map((t) => RewriteFactory.rewriteType(t, metadata)!) ); - return arkts.factory.updateTypeReference( + return arkts.factory.updateETSTypeReference( node, - arkts.factory.updateTypeReferencePart(part, part.name, newTypeParams, part.previous) + arkts.factory.updateETSTypeReferencePart(part, part.name, newTypeParams, part.previous) ); } @@ -106,7 +106,7 @@ export class RewriteFactory { if (!node.typeAnnotation) { return node; } - const newNodeType = RewriteFactory.rewriteType(node.typeAnnotation); + const newNodeType = RewriteFactory.rewriteType(node.typeAnnotation)!; return arkts.factory.updateTSTypeAliasDeclaration(node, node.id, node.typeParams, newNodeType); } @@ -114,11 +114,11 @@ export class RewriteFactory { node: arkts.ETSParameterExpression, metadata?: CachedMetadata ): arkts.ETSParameterExpression { - if (!node.type && !node.initializer) { + if (!node.typeAnnotation && !node.initializer) { return node; } - node.type = RewriteFactory.rewriteType(node.type as arkts.TypeNode, metadata); - return node; + node.setTypeAnnotation(RewriteFactory.rewriteType(node.typeAnnotation, metadata)); + return arkts.factory.updateETSParameterExpression(node, node.ident, node.isOptional, node.initializer); } static rewriteProperty(node: arkts.Property, metadata?: CachedMetadata): arkts.Property { @@ -147,7 +147,7 @@ export class RewriteFactory { static rewriteArrowFunction( node: arkts.ArrowFunctionExpression, - metadata?: arkts.AstNodeCacheValueMetadata, + metadata?: AstNodeCacheValueMetadata, expectReturn?: arkts.TypeNode ): arkts.ArrowFunctionExpression { return arkts.factory.updateArrowFunctionExpression( @@ -172,7 +172,7 @@ export class RewriteFactory { const parameters = getFunctionParamsBeforeUnmemoized(node.params, _hasReceiver); const declaredParams: ParamInfo[] = parameters.map((p) => { const param = p as arkts.ETSParameterExpression; - return { ident: param.identifier, param }; + return { ident: param.ident!, param }; }); const _gensymCount = fixGensymParams(declaredParams, body); if (findUnmemoizedScopeInFunctionBody(body, _gensymCount)) { @@ -262,13 +262,15 @@ export class RewriteFactory { const newNode = arkts.factory.updateMethodDefinition( node, node.kind, - node.name, - RewriteFactory.rewriteScriptFunction(node.function!, { - callName: node.name.name, - ...metadata, - isSetter, - isGetter, - }), + node.key, + arkts.factory.createFunctionExpression(node.id?.clone(), + RewriteFactory.rewriteScriptFunction(node.function!, { + callName: node.id?.name, + ...metadata, + isSetter, + isGetter, + }) + ), node.modifiers, false ); @@ -282,14 +284,14 @@ export class RewriteFactory { } const _hasReceiver = metadata?.hasReceiver; let _callName: string | undefined = metadata?.callName; - if (!!_callName && arkts.isIdentifier(node.expression)) { - _callName = node.expression.name; + if (!!_callName && arkts.isIdentifier(node.callee)) { + _callName = node.callee.name; } else if ( !!_callName && - arkts.isMemberExpression(node.expression) && - arkts.isIdentifier(node.expression.property) + arkts.isMemberExpression(node.callee) && + arkts.isIdentifier(node.callee.property) ) { - _callName = node.expression.property.name; + _callName = node.callee.property.name; } return factory.insertHiddenArgumentsToCall( node, @@ -319,9 +321,9 @@ export class RewriteFactory { node: arkts.VariableDeclarator, metadata?: CachedMetadata ): arkts.VariableDeclarator { - const expectReturnType = findLocalReturnTypeFromTypeAnnotation(node.name.typeAnnotation); - const variableType = RewriteFactory.rewriteType(node.name.typeAnnotation); - let initializer = node.initializer; + const expectReturnType = findLocalReturnTypeFromTypeAnnotation((node.id as arkts.Identifier).typeAnnotation); + const variableType = RewriteFactory.rewriteType((node.id as arkts.Identifier).typeAnnotation); + let initializer = node.init; if (!!initializer && arkts.isConditionalExpression(initializer) && !!initializer.alternate) { let alternate = initializer.alternate; if (arkts.isTSAsExpression(alternate)) { @@ -348,7 +350,7 @@ export class RewriteFactory { return arkts.factory.updateVariableDeclarator( node, node.flag, - arkts.factory.updateIdentifier(node.name, node.name.name, variableType), + arkts.factory.updateIdentifier(node.id as arkts.Identifier, (node.id as arkts.Identifier).name, variableType), initializer ); } diff --git a/arkui-plugins/memo-plugins/memo-factory.ts b/arkui-plugins/memo-plugins/memo-factory.ts index 27cdc9b9d..5c3f6489e 100644 --- a/arkui-plugins/memo-plugins/memo-factory.ts +++ b/arkui-plugins/memo-plugins/memo-factory.ts @@ -42,12 +42,10 @@ export class factory { } static createContextTypesImportDeclaration(program?: arkts.Program): void { const source: arkts.StringLiteral = arkts.factory.createStringLiteral(RuntimeNames.MEMO_IMPORT_NAME); - const importDecl: arkts.ETSImportDeclaration = arkts.factory.createImportDeclaration( + const importDecl: arkts.ETSImportDeclaration = arkts.factory.createETSImportDeclaration( source, [factory.createContextTypeImportSpecifier(), factory.createIdTypeImportSpecifier()], - arkts.Es2pandaImportKinds.IMPORT_KINDS_TYPES, - program!, - arkts.Es2pandaImportFlags.IMPORT_FLAGS_NONE + arkts.Es2pandaImportKinds.IMPORT_KINDS_TYPES ); // Insert this import at the top of the script's statements. if (!program) { @@ -59,24 +57,26 @@ export class factory { // Parameters static createContextParameter(): arkts.ETSParameterExpression { - return arkts.factory.createParameterDeclaration( + return arkts.factory.createETSParameterExpression( arkts.factory.createIdentifier( RuntimeNames.CONTEXT, arkts.factory.createETSTypeReference( arkts.factory.createETSTypeReferencePart(arkts.factory.createIdentifier(RuntimeNames.CONTEXT_TYPE)) ) ), + false, undefined ); } static createIdParameter(): arkts.ETSParameterExpression { - return arkts.factory.createParameterDeclaration( + return arkts.factory.createETSParameterExpression( arkts.factory.createIdentifier( RuntimeNames.ID, arkts.factory.createETSTypeReference( arkts.factory.createETSTypeReferencePart(arkts.factory.createIdentifier(RuntimeNames.ID_TYPE)) ) ), + false, undefined ); } @@ -102,14 +102,12 @@ export class factory { hasReceiver: boolean = false, newTypeParams?: arkts.TSTypeParameterDeclaration ): arkts.ETSFunctionType { - return arkts.factory.updateFunctionType( + return arkts.factory.updateETSFunctionType( type, - arkts.factory.createFunctionSignature( - newTypeParams, - factory.createHiddenParameterIfNotAdded(type.params, hasReceiver), - type.returnType, - false - ), + newTypeParams, + factory.createHiddenParameterIfNotAdded(type.params, hasReceiver), + type.returnType, + false, arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW ); } @@ -138,14 +136,14 @@ export class factory { static createContextArgument(): arkts.Expression { return arkts.factory.createIdentifier(RuntimeNames.CONTEXT); } - static createIdArgument(hash: arkts.NumberLiteral | arkts.StringLiteral): arkts.AstNode { + static createIdArgument(hash: arkts.NumberLiteral | arkts.StringLiteral): arkts.Expression { return arkts.factory.createBinaryExpression( arkts.factory.createIdentifier(RuntimeNames.ID), hash, arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_PLUS ); } - static createHiddenArguments(hash: arkts.NumberLiteral | arkts.StringLiteral): arkts.AstNode[] { + static createHiddenArguments(hash: arkts.NumberLiteral | arkts.StringLiteral): arkts.Expression[] { return [factory.createContextArgument(), factory.createIdArgument(hash)]; } @@ -182,7 +180,6 @@ export class factory { static createMemoParameterDeclaration(parameters: string[]): arkts.VariableDeclaration { return arkts.factory.createVariableDeclaration( - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_CONST, parameters.map((name, id) => { return factory.createMemoParameterDeclarator(id, name); @@ -224,7 +221,6 @@ export class factory { cnt: number ): arkts.VariableDeclaration { return arkts.factory.createVariableDeclaration( - 0, arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_CONST, [ arkts.factory.createVariableDeclarator( @@ -242,9 +238,10 @@ export class factory { factory.createIdArgument(hash) as arkts.Expression, arkts.factory.createNumberLiteral(cnt) as arkts.Expression ], - returnTypeAnnotation + arkts.factory.createTSTypeParameterInstantiation(returnTypeAnnotation ? [returnTypeAnnotation] - : [arkts.factory.createETSPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID)], + : [arkts.factory.createETSPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID)] + ), false, false ) @@ -286,12 +283,14 @@ export class factory { ); } return arkts.factory.createBlockStatement([ - arkts.factory.createMemberExpression( - arkts.factory.createIdentifier(RuntimeNames.SCOPE), - arkts.factory.createIdentifier(RuntimeNames.INTERNAL_VALUE), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_NONE, - false, - false + arkts.factory.createExpressionStatement( + arkts.factory.createMemberExpression( + arkts.factory.createIdentifier(RuntimeNames.SCOPE), + arkts.factory.createIdentifier(RuntimeNames.INTERNAL_VALUE), + arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_NONE, + false, + false + ), ), arkts.factory.createReturnStatement(arkts.factory.createThisExpression()), ]); @@ -418,7 +417,7 @@ export class factory { if (arkts.isETSFunctionType(typeAnnotation)) { return factory.updateFunctionTypeWithMemoParameters(typeAnnotation); } else if (arkts.isETSUnionType(typeAnnotation)) { - return arkts.factory.updateUnionType( + return arkts.factory.updateETSUnionType( typeAnnotation, typeAnnotation.types.map((it) => { if (arkts.isETSFunctionType(it)) { @@ -443,9 +442,9 @@ export class factory { const expressionArgs = updatedArguments as arkts.Expression[]; return arkts.factory.updateCallExpression( node, - node.expression, + node.callee, expressionArgs, - node.typeArguments + node.typeParams ); } } diff --git a/arkui-plugins/memo-plugins/memo-transformer.ts b/arkui-plugins/memo-plugins/memo-transformer.ts index 66f1eb797..d6240765b 100644 --- a/arkui-plugins/memo-plugins/memo-transformer.ts +++ b/arkui-plugins/memo-plugins/memo-transformer.ts @@ -45,6 +45,6 @@ export default function memoTransformer(userPluginOptions?: TransformerOptions) signatureTransformer, }); factory.createContextTypesImportDeclaration(arkts.arktsGlobal.compilerContext?.program); - return functionTransformer.visitor(arkts.factory.updateEtsScript(node, node.statements)); + return functionTransformer.visitor(arkts.factory.updateETSModule(node, node.statements, node.ident, node.getNamespaceFlag(), node.program)); }; } diff --git a/arkui-plugins/memo-plugins/parameter-transformer.ts b/arkui-plugins/memo-plugins/parameter-transformer.ts index f9d2cb043..ef7a502ba 100644 --- a/arkui-plugins/memo-plugins/parameter-transformer.ts +++ b/arkui-plugins/memo-plugins/parameter-transformer.ts @@ -74,11 +74,11 @@ export class ParameterTransformer extends AbstractVisitor { parameters .filter( (it) => - it.param.type && (arkts.isETSFunctionType(it.param.type) || arkts.isETSUnionType(it.param.type)) + it.param.ident?.typeAnnotation && (arkts.isETSFunctionType(it.param.ident.typeAnnotation) || arkts.isETSUnionType(it.param.ident.typeAnnotation)) ) .map((it) => { return [ - it.param.identifier.name.startsWith(RuntimeNames.GENSYM) + it.param.ident?.name.startsWith(RuntimeNames.GENSYM) ? it.ident.originalPeer : it.param.originalPeer, (passArgs: arkts.Expression[]): arkts.CallExpression => { @@ -90,7 +90,7 @@ export class ParameterTransformer extends AbstractVisitor { this.rewriteIdentifiers = new Map( parameters.map((it) => { return [ - it.param.identifier.name.startsWith(RuntimeNames.GENSYM) + it.param.ident?.name.startsWith(RuntimeNames.GENSYM) ? it.ident.originalPeer : it.param.originalPeer, (): arkts.MemberExpression => { @@ -102,12 +102,12 @@ export class ParameterTransformer extends AbstractVisitor { this.rewriteMemoInfos = new Map( parameters.map((it) => { return [ - it.param.identifier.name.startsWith(RuntimeNames.GENSYM) + it.param.ident!.name.startsWith(RuntimeNames.GENSYM) ? it.ident.originalPeer : it.param.originalPeer, { - name: it.param.identifier.name, - rewritePeer: it.param.identifier.originalPeer, + name: it.param.ident!.name, + rewritePeer: it.param.ident!.originalPeer, isMemo: isMemoETSParameterExpression(it.param), }, ]; @@ -206,7 +206,7 @@ export class ParameterTransformer extends AbstractVisitor { } private updateParamReDeclare(node: arkts.VariableDeclarator, memoInfo: RewriteMemoInfo): arkts.VariableDeclarator { - const shouldUpdate: boolean = node.name.name !== memoInfo.name && memoInfo.isMemo; + const shouldUpdate: boolean = (node.id as arkts.Identifier).name !== memoInfo.name && memoInfo.isMemo; if (!shouldUpdate) { return node; } @@ -217,39 +217,38 @@ export class ParameterTransformer extends AbstractVisitor { let typeAnnotation: arkts.TypeNode | undefined; if ( - !!node.name.typeAnnotation && - !(typeAnnotation = factory.updateMemoTypeAnnotation(node.name.typeAnnotation)) + !!(node.id as arkts.Identifier).typeAnnotation && + !(typeAnnotation = factory.updateMemoTypeAnnotation((node.id as arkts.Identifier).typeAnnotation)) ) { - console.error(`ETSFunctionType or ETSUnionType expected for @memo-variable-type ${node.name.name}`); + console.error(`ETSFunctionType or ETSUnionType expected for @memo-variable-type ${(node.id as arkts.Identifier).name}`); throw 'Invalid @memo usage'; } - const returnType = findReturnTypeFromTypeAnnotation(decl.type); + const returnType = findReturnTypeFromTypeAnnotation(decl.typeAnnotation); return arkts.factory.updateVariableDeclarator( node, node.flag, - arkts.factory.updateIdentifier(node.name, node.name.name, typeAnnotation), - this.updateVariableDeclareInit(node.initializer, returnType) + arkts.factory.updateIdentifier(node.id as arkts.Identifier, (node.id as arkts.Identifier).name, typeAnnotation), + this.updateVariableDeclareInit(node.init, returnType) ); } private updateVariableReDeclarationFromParam(node: arkts.VariableDeclaration): arkts.VariableDeclaration { return arkts.factory.updateVariableDeclaration( node, - node.modifiers, - node.declarationKind, + node.kind, node.declarators.map((declarator) => { - if (this.rewriteMemoInfos?.has(declarator.name.originalPeer)) { - const memoInfo = this.rewriteMemoInfos.get(declarator.name.originalPeer)!; + if (this.rewriteMemoInfos?.has(declarator.id!.originalPeer)) { + const memoInfo = this.rewriteMemoInfos.get(declarator.id!.originalPeer)!; return this.updateParamReDeclare(declarator, memoInfo); } - if (!!declarator.initializer && arkts.isIdentifier(declarator.initializer)) { - const decl = arkts.getPeerDecl(declarator.initializer.originalPeer); + if (!!declarator.init && arkts.isIdentifier(declarator.init)) { + const decl = arkts.getPeerDecl(declarator.init.originalPeer); if (decl && this.rewriteIdentifiers?.has(decl.peer)) { return arkts.factory.updateVariableDeclarator( declarator, declarator.flag, - declarator.name, + declarator.id, this.rewriteIdentifiers.get(decl.peer)!() ); } @@ -280,15 +279,15 @@ export class ParameterTransformer extends AbstractVisitor { if (arkts.isVariableDeclaration(beforeChildren)) { return this.updateVariableReDeclarationFromParam(beforeChildren); } - if (arkts.isCallExpression(beforeChildren) && arkts.isIdentifier(beforeChildren.expression)) { - const decl = arkts.getPeerDecl(beforeChildren.expression.originalPeer); + if (arkts.isCallExpression(beforeChildren) && arkts.isIdentifier(beforeChildren.callee)) { + const decl = arkts.getPeerDecl(beforeChildren.callee.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); + return this.updateCallReDeclare(updateCall, beforeChildren.callee, memoInfo); } return updateCall; } diff --git a/arkui-plugins/memo-plugins/signature-transformer.ts b/arkui-plugins/memo-plugins/signature-transformer.ts index f552fa4d8..793b9e283 100644 --- a/arkui-plugins/memo-plugins/signature-transformer.ts +++ b/arkui-plugins/memo-plugins/signature-transformer.ts @@ -87,14 +87,14 @@ export class SignatureTransformer extends AbstractVisitor { } if (arkts.isETSParameterExpression(node)) { const memo = hasMemoAnnotation(node) || hasMemoIntrinsicAnnotation(node) || applyMemo; - if (!node.type) { + if (!node.ident?.typeAnnotation) { if (memo) { - console.error(`@memo parameter ${node.identifier.name} without type annotatation`); + console.error(`@memo parameter ${node.ident!.name} without type annotatation`); throw 'Invalid @memo usage'; } return node; } - node.type = this.visitor(node.type, memo); + node.ident?.setTsTypeAnnotation(this.visitor(node.ident?.typeAnnotation, memo)); return node as any as T; } if (arkts.isETSFunctionType(node)) { @@ -103,19 +103,17 @@ export class SignatureTransformer extends AbstractVisitor { this.modified = true; } const newParams = node.params.map((it) => this.visitor(it)); - return arkts.factory.updateFunctionType( + return arkts.factory.updateETSFunctionType( node, - arkts.factory.createFunctionSignature( - undefined, - memo ? factory.createHiddenParameterIfNotAdded(newParams) : newParams, - this.visitor(node.returnType!), - false - ), + undefined, + memo ? factory.createHiddenParameterIfNotAdded(newParams) : newParams, + this.visitor(node.returnType!), + false, arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW ) as any as T; } if (arkts.isETSUnionType(node)) { - return arkts.factory.updateUnionType( + return arkts.factory.updateETSUnionType( node, node.types.map((it) => this.visitor(it, applyMemo)) ) as any as T; diff --git a/arkui-plugins/memo-plugins/utils.ts b/arkui-plugins/memo-plugins/utils.ts index 81a0628b6..2d3290729 100644 --- a/arkui-plugins/memo-plugins/utils.ts +++ b/arkui-plugins/memo-plugins/utils.ts @@ -163,7 +163,7 @@ export function removeMemoAnnotation(node: T): T { (it) => !isMemoAnnotation(it, RuntimeNames.ANNOTATION) && !isMemoAnnotation(it, RuntimeNames.ANNOTATION_STABLE) ); if (arkts.isETSParameterExpression(node)) { - node.annotations = newAnnotations; + node.setAnnotations(newAnnotations); return node; } return node.setAnnotations(newAnnotations) as T; @@ -229,7 +229,7 @@ function isSyntheticReturnInBlock(node: arkts.AstNode): boolean { export function isMemoParametersDeclaration(node: arkts.AstNode): boolean { return ( arkts.isVariableDeclaration(node) && - node.declarators.every((it) => it.name.name.startsWith(RuntimeNames.PARAMETER)) + node.declarators.every((it) => arkts.isIdentifier(it.id) && it.id.name.startsWith(RuntimeNames.PARAMETER)) ); } @@ -280,7 +280,7 @@ 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) { + if (!!node.parent && arkts.isCallExpression(node.parent) && node.parent.callee?.peer === node.peer) { return true; } @@ -288,7 +288,7 @@ export function isStandaloneArrowFunction(node: arkts.AstNode): node is arkts.Ar !!node.parent && !arkts.isVariableDeclarator(node.parent) && !arkts.isClassProperty(node.parent) && - !(arkts.isCallExpression(node.parent) && node.parent.expression) + !(arkts.isCallExpression(node.parent) && node.parent.callee) ); } @@ -371,7 +371,7 @@ export function isMemoTSTypeAliasDeclaration(node: arkts.TSTypeAliasDeclaration) } export function isMemoETSParameterExpression(param: arkts.ETSParameterExpression): boolean { - const type = param.identifier.typeAnnotation; + const type = param.ident?.typeAnnotation; if (!type) { return false; } @@ -399,11 +399,11 @@ export function isMemoVariableDeclaration(node: arkts.VariableDeclaration): bool export function isMemoVariableDeclarator(node: arkts.VariableDeclarator): boolean { let isMemo: boolean = false; - if (!!node.name.typeAnnotation) { - isMemo ||= findMemoFromTypeAnnotation(node.name.typeAnnotation); + if (!!(node.id as arkts.Identifier).typeAnnotation) { + isMemo ||= findMemoFromTypeAnnotation((node.id as arkts.Identifier).typeAnnotation); } - if (!!node.initializer && arkts.isArrowFunctionExpression(node.initializer)) { - isMemo ||= isMemoArrowFunction(node.initializer); + if (!!node.init && arkts.isArrowFunctionExpression(node.init)) { + isMemo ||= isMemoArrowFunction(node.init); } if (!!node.parent && arkts.isVariableDeclaration(node.parent)) { isMemo ||= isMemoVariableDeclaration(node.parent); @@ -523,11 +523,11 @@ export function findLocalReturnTypeFromTypeAnnotation( 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.init && arkts.isIdentifier(decl.parent.init)) { + return getDeclResolveAlias(decl.parent.init); } - if (!!decl.parent.initializer && arkts.isMemberExpression(decl.parent.initializer)) { - return getDeclResolveAlias(decl.parent.initializer.property); + if (!!decl.parent.init && arkts.isMemberExpression(decl.parent.init)) { + return getDeclResolveAlias(decl.parent.init.property!); } } return decl; @@ -558,10 +558,10 @@ export function fixGensymParams(params: ParamInfo[], body: arkts.BlockStatement) if (!arkts.isVariableDeclaration(declaration)) { throw new Error(`Expected ${params[i].ident.name} replacement to original parameter`); } - if (!arkts.isIdentifier(declaration.declarators[0].name)) { + if (!arkts.isIdentifier(declaration.declarators[0].id)) { throw new Error(`Expected ${params[i].ident.name} replacement to original parameter`); } - params[i].ident = declaration.declarators[0].name; + params[i].ident = declaration.declarators[0].id; gensymParamsCount++; } } @@ -569,11 +569,11 @@ export function fixGensymParams(params: ParamInfo[], body: arkts.BlockStatement) } export function isMemoContextParamAdded(param: arkts.Expression): boolean { - return arkts.isETSParameterExpression(param) && param.identifier.name === RuntimeNames.CONTEXT; + return arkts.isETSParameterExpression(param) && param.ident?.name === RuntimeNames.CONTEXT; } export function isMemoIdParamAdded(param: arkts.Expression): boolean { - return arkts.isETSParameterExpression(param) && param.identifier.name === RuntimeNames.ID; + return arkts.isETSParameterExpression(param) && param.ident?.name === RuntimeNames.ID; } export function isUnmemoizedInFunctionParams(params?: readonly arkts.Expression[], hasReceiver?: boolean): boolean { @@ -608,7 +608,7 @@ export function findUnmemoizedScopeInFunctionBody(body: arkts.BlockStatement, ge return false; } const declarator = statement.declarators.at(0)!; - return declarator.name.name === RuntimeNames.SCOPE; + return arkts.isIdentifier(declarator.id) && declarator.id.name === RuntimeNames.SCOPE; } export function buildReturnTypeInfo( @@ -632,7 +632,7 @@ export function buildeParamInfos(parameters: readonly arkts.ETSParameterExpressi ...parameters .filter((it) => !hasMemoSkipAnnotation(it)) .map((it) => { - return { ident: it.identifier, param: it }; + return { ident: it.ident!, param: it }; }), ]; } @@ -652,7 +652,7 @@ function isThisParam(node: arkts.Expression | undefined): boolean { if (node === undefined || !arkts.isETSParameterExpression(node)) { return false; } - return node.identifier?.isReceiver ?? false; + return node.ident?.isReceiver ?? false; } export function filterMemoSkipParams(paramInfos: ParamInfo[]): ParamInfo[] { -- Gitee From 8e411110378c666b49727650d8267ad8ef618c4b Mon Sep 17 00:00:00 2001 From: Aleksandr Veselov Date: Wed, 13 Aug 2025 17:43:41 +0300 Subject: [PATCH 06/39] Fix ui-syntax-plugins Change-Id: I9803ec671a8ce19e7b16b6f371d2519a7d0c3550 Signed-off-by: Aleksandr Veselov --- arkui-plugins/ui-syntax-plugins/index.ts | 8 ++++---- .../rules/check-property-modifiers.ts | 2 +- .../ui-syntax-plugins/rules/construct-parameter.ts | 4 ++-- .../ui-syntax-plugins/rules/nested-relationship.ts | 14 +++++++------- 4 files changed, 14 insertions(+), 14 deletions(-) diff --git a/arkui-plugins/ui-syntax-plugins/index.ts b/arkui-plugins/ui-syntax-plugins/index.ts index 69b4e90f3..fb758628f 100644 --- a/arkui-plugins/ui-syntax-plugins/index.ts +++ b/arkui-plugins/ui-syntax-plugins/index.ts @@ -63,12 +63,12 @@ function createTransformer( const isCoding = this.isCoding?.() ?? false; if (isCoding) { const codingFilePath = this.getCodingFilePath(); - if (program.absName === codingFilePath) { + if (program.absoluteName === codingFilePath) { return transformProgram.call(this, transformer, program); } } else { transformExternalSources.call(this, program, visitedExternalSources, visitedPrograms, transformer); - if (program.absName) { + if (program.absoluteName) { return transformProgram.call(this, transformer, program); } } @@ -97,7 +97,7 @@ function transformExternalSources( if (visitedPrograms.has(program.peer) || isHeaderFile(program.absName)) { continue; } - const script = transformer.transform(program.astNode) as arkts.ETSModule; + const script = transformer.transform(program.ast) as arkts.ETSModule; this.setArkTSAst(script); } visitedExternalSources.add(externalSource.peer); @@ -109,7 +109,7 @@ function transformProgram( transformer: UISyntaxLinterVisitor, program: arkts.Program ): arkts.ETSModule { - const script = transformer.transform(program.astNode) as arkts.ETSModule; + const script = transformer.transform(program.ast) as arkts.ETSModule; this.setArkTSAst(script); return script; } diff --git a/arkui-plugins/ui-syntax-plugins/rules/check-property-modifiers.ts b/arkui-plugins/ui-syntax-plugins/rules/check-property-modifiers.ts index 140459ea3..6d3105005 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/check-property-modifiers.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/check-property-modifiers.ts @@ -53,7 +53,7 @@ class CheckPropertyModifiersRule extends AbstractUISyntaxRule { if (!arkts.isClassProperty(member)) { return; } - if (arkts.isDefaultAccessModifierClassProperty(member)) { + if (member.isDefaultAccessModifier) { return; } const propertyName = getClassPropertyName(member); diff --git a/arkui-plugins/ui-syntax-plugins/rules/construct-parameter.ts b/arkui-plugins/ui-syntax-plugins/rules/construct-parameter.ts index 90494a67d..7563f48af 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/construct-parameter.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/construct-parameter.ts @@ -132,10 +132,10 @@ class ConstructParameterRule extends AbstractUISyntaxRule { } member.getChildren().forEach((item) => { if (!arkts.isVariableDeclarator(item) || !item.id || - (item.initializer && arkts.isArrowFunctionExpression(item.initializer))) { + (item.init && arkts.isArrowFunctionExpression(item.init))) { return; } - this.regularVariableList.push(item.name.name); + this.regularVariableList.push((item.id as arkts.Identifier).name); }); } diff --git a/arkui-plugins/ui-syntax-plugins/rules/nested-relationship.ts b/arkui-plugins/ui-syntax-plugins/rules/nested-relationship.ts index 0f570d596..bc758d499 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/nested-relationship.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/nested-relationship.ts @@ -51,15 +51,15 @@ class NestedRelationshipRule extends AbstractUISyntaxRule { return; } let curNode = node.parent.parent; - while (!arkts.isCallExpression(curNode) || !arkts.isIdentifier(curNode.expression) || - !isBuildInComponent(this.context, curNode.expression.name)) { + while (!arkts.isCallExpression(curNode) || !arkts.isIdentifier(curNode.callee) || + !isBuildInComponent(this.context, curNode.callee.name)) { if (!curNode.parent) { return; } curNode = curNode.parent; } // If the parent component of the current component is not within the valid range, an error is reported - const parentComponentName = curNode.expression.name; + const parentComponentName = curNode.callee.name; if (!this.context.componentsInfo.validParentComponent.get(componentName)!.includes(parentComponentName)) { const parentComponentListArray: string[] = this.context.componentsInfo.validParentComponent.get(componentName)!; this.report({ @@ -80,7 +80,7 @@ class NestedRelationshipRule extends AbstractUISyntaxRule { } const componentName: string = getIdentifierName(node); if (!this.context.componentsInfo.validChildComponent.has(componentName) || !node.parent || - !arkts.isCallExpression(node.parent) || !arkts.isIdentifier(node.parent.expression)) { + !arkts.isCallExpression(node.parent) || !arkts.isIdentifier(node.parent.callee)) { return; } let parentNode = node.parent; @@ -96,11 +96,11 @@ class NestedRelationshipRule extends AbstractUISyntaxRule { } member.statements.forEach(statement => { if (!arkts.isExpressionStatement(statement) || !statement.expression || - !arkts.isCallExpression(statement.expression) || !statement.expression.expression || - !arkts.isIdentifier(statement.expression.expression)) { + !arkts.isCallExpression(statement.expression) || !statement.expression.callee || + !arkts.isIdentifier(statement.expression.callee)) { return; } - const childComponentNode = statement.expression.expression; + const childComponentNode = statement.expression.callee; const childComponentName = getIdentifierName(childComponentNode); if (childComponentListArray.includes(childComponentName) || !isBuildInComponent(this.context, childComponentName)) { -- Gitee From d4aef72815c13bdebc19808bd5894dce6bbe78b3 Mon Sep 17 00:00:00 2001 From: Aleksandr Veselov Date: Wed, 13 Aug 2025 17:50:29 +0300 Subject: [PATCH 07/39] Fix pointer type Change-Id: I478c32e415b7749d0bf2da501c054f36b680566d Signed-off-by: Aleksandr Veselov --- arkui-plugins/test/utils/global.ts | 2 +- arkui-plugins/test/utils/processors/task-processor.ts | 3 ++- arkui-plugins/test/utils/shared-types.ts | 3 ++- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/arkui-plugins/test/utils/global.ts b/arkui-plugins/test/utils/global.ts index 173a44f57..668b83f83 100644 --- a/arkui-plugins/test/utils/global.ts +++ b/arkui-plugins/test/utils/global.ts @@ -65,7 +65,7 @@ function destroyGlobalContextPtr(globalContextPtr: arkts.KNativePointer): void { function createCacheContextFromFile( config: arkts.Config, filePath: string, - globalContextPtr: number, + globalContextPtr: arkts.KNativePointer, isExternal: boolean ): arkts.Context { return arkts.Context.createCacheContextFromFile(config.peer, filePath, globalContextPtr, isExternal); diff --git a/arkui-plugins/test/utils/processors/task-processor.ts b/arkui-plugins/test/utils/processors/task-processor.ts index a66b89eb4..7e5f78ca4 100644 --- a/arkui-plugins/test/utils/processors/task-processor.ts +++ b/arkui-plugins/test/utils/processors/task-processor.ts @@ -41,6 +41,7 @@ import { Plugins, PluginState, ProjectConfig } from '../../../common/plugin-cont import { concatObject, serializable } from '../serializable'; import { compileAbc, compileExternalProgram } from '../compile'; import { BaseProcessor } from './base-processor'; +import * as arkts from '@koalaui/libarkts'; interface Job { id: string; @@ -389,7 +390,7 @@ class TaskProcessor extends BaseProcessor { private assignTaskToIdleWorker( processingJobs: Set, - globalContextPtr: number, + globalContextPtr: arkts.KNativePointer, plugins: Plugins[], stopAfter?: PluginState ) { diff --git a/arkui-plugins/test/utils/shared-types.ts b/arkui-plugins/test/utils/shared-types.ts index 83c365d53..82ebc1514 100644 --- a/arkui-plugins/test/utils/shared-types.ts +++ b/arkui-plugins/test/utils/shared-types.ts @@ -14,6 +14,7 @@ */ import type { Plugins, PluginState, ProjectConfig } from '../../common/plugin-context'; +import * as arkts from '@koalaui/libarkts'; export type PluginTesterId = string | `${string}:${string}`; @@ -82,7 +83,7 @@ export interface JobInfo { buildConfig?: BuildConfig; projectConfig?: ProjectConfig; plugins?: Plugins[]; - globalContextPtr?: number; + globalContextPtr?: arkts.KNativePointer; stopAfter?: PluginState; filePaths?: string[]; } -- Gitee From deb4648deb89d227804bff02a6277ef99429e572 Mon Sep 17 00:00:00 2001 From: Aleksandr Veselov Date: Tue, 19 Aug 2025 15:26:56 +0300 Subject: [PATCH 08/39] Fix SourcePosition and diagnostics api usage Signed-off-by: Aleksandr Veselov Change-Id: I8e71596a4a8ac43ad36b36ead8af2702044ec038 --- arkui-plugins/common/log-collector.ts | 8 ++++---- .../ui-syntax-plugins/processor/index.ts | 20 +++++++++---------- .../componentV2-state-usage-validation.ts | 4 ++-- .../rules/computed-decorator-check.ts | 4 ++-- .../consumer-provider-decorator-check.ts | 4 ++-- .../rules/monitor-decorator-check.ts | 4 ++-- .../rules/no-duplicate-entry.ts | 6 +++--- .../rules/no-duplicate-id.ts | 4 ++-- .../rules/no-duplicate-preview.ts | 2 +- .../rules/no-prop-link-objectlink-in-entry.ts | 2 +- .../observedV2-trace-usage-validation.ts | 6 +++--- .../rules/once-decorator-check.ts | 2 +- .../rules/one-decorator-on-function-method.ts | 2 +- .../rules/track-decorator-check.ts | 4 ++-- .../rules/validate-build-in-struct.ts | 2 +- 15 files changed, 37 insertions(+), 37 deletions(-) diff --git a/arkui-plugins/common/log-collector.ts b/arkui-plugins/common/log-collector.ts index 03f66565a..3cd1d9ecd 100644 --- a/arkui-plugins/common/log-collector.ts +++ b/arkui-plugins/common/log-collector.ts @@ -24,11 +24,11 @@ interface LogInfo { } export function generateDiagnosticKind(logItem: LogInfo): arkts.DiagnosticKind { - return arkts.DiagnosticKind.create( + return arkts.createDiagnosticKind( `${logItem.code}: ${logItem.message}`, logItem.type === LogType.ERROR - ? arkts.PluginDiagnosticType.ES2PANDA_PLUGIN_ERROR - : arkts.PluginDiagnosticType.ES2PANDA_PLUGIN_WARNING + ? arkts.Es2pandaPluginDiagnosticType.ES2PANDA_PLUGIN_ERROR + : arkts.Es2pandaPluginDiagnosticType.ES2PANDA_PLUGIN_WARNING ); } @@ -63,7 +63,7 @@ export class LogCollector { return; } this.logInfos.forEach((logItem: LogInfo) => { - arkts.Diagnostic.logDiagnostic(generateDiagnosticKind(logItem), logItem.node.startPosition); + arkts.logDiagnostic(generateDiagnosticKind(logItem), logItem.node.startPosition); }); } diff --git a/arkui-plugins/ui-syntax-plugins/processor/index.ts b/arkui-plugins/ui-syntax-plugins/processor/index.ts index babb5c992..b8927faee 100644 --- a/arkui-plugins/ui-syntax-plugins/processor/index.ts +++ b/arkui-plugins/ui-syntax-plugins/processor/index.ts @@ -63,31 +63,31 @@ class ConcreteUISyntaxRuleContext implements UISyntaxRuleContext { message = this.format(options.message, options.data); } - const diagnosticKind: arkts.DiagnosticKind = arkts.DiagnosticKind.create( + const diagnosticKind: arkts.DiagnosticKind = arkts.createDiagnosticKind( message, options.level === 'error' - ? arkts.PluginDiagnosticType.ES2PANDA_PLUGIN_ERROR - : arkts.PluginDiagnosticType.ES2PANDA_PLUGIN_WARNING + ? arkts.Es2pandaPluginDiagnosticType.ES2PANDA_PLUGIN_ERROR + : arkts.Es2pandaPluginDiagnosticType.ES2PANDA_PLUGIN_WARNING ); if (options.fix) { - const diagnosticInfo: arkts.DiagnosticInfo = arkts.DiagnosticInfo.create(diagnosticKind, + const diagnosticInfo: arkts.DiagnosticInfo = arkts.createDiagnosticInfo(diagnosticKind, options.node.startPosition); const fixSuggestion = options.fix(options.node); - const suggestionKind: arkts.DiagnosticKind = arkts.DiagnosticKind.create( + const suggestionKind: arkts.DiagnosticKind = arkts.createDiagnosticKind( message, - arkts.PluginDiagnosticType.ES2PANDA_PLUGIN_SUGGESTION + arkts.Es2pandaPluginDiagnosticType.ES2PANDA_PLUGIN_SUGGESTION ); const [startPosition, endPosition] = fixSuggestion.range; - const sourceRange: arkts.SourceRange = arkts.SourceRange.create(startPosition, endPosition); - const suggestionInfo: arkts.SuggestionInfo = arkts.SuggestionInfo.create( + const sourceRange: arkts.SourceRange = arkts.createSourceRange(startPosition, endPosition); + const suggestionInfo: arkts.SuggestionInfo = arkts.createSuggestionInfo( suggestionKind, fixSuggestion.code, fixSuggestion.title ? fixSuggestion.title : '', sourceRange ); - arkts.Diagnostic.logDiagnosticWithSuggestion(diagnosticInfo, suggestionInfo); + arkts.logDiagnosticWithSuggestion(diagnosticInfo, suggestionInfo); } else { - arkts.Diagnostic.logDiagnostic(diagnosticKind, options.node.startPosition); + arkts.logDiagnostic(diagnosticKind, options.node.startPosition); } } diff --git a/arkui-plugins/ui-syntax-plugins/rules/componentV2-state-usage-validation.ts b/arkui-plugins/ui-syntax-plugins/rules/componentV2-state-usage-validation.ts index 2ddd90e6b..84d26101b 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/componentV2-state-usage-validation.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/componentV2-state-usage-validation.ts @@ -117,7 +117,7 @@ class ComponentV2StateUsageValidationRule extends AbstractUISyntaxRule { message: this.messages.requireOnlyWithParam, fix: (requireDecorator) => { let startPosition = requireDecorator.startPosition; - startPosition = arkts.SourcePosition.create(startPosition.index() - 1, startPosition.line()); + startPosition = arkts.createSourcePosition(startPosition.getIndex() - 1, startPosition.getLine()); let endPosition = requireDecorator.endPosition; return { title: 'Remove the @Require annotation', @@ -153,7 +153,7 @@ class ComponentV2StateUsageValidationRule extends AbstractUISyntaxRule { data: { annotationName }, fix: (annotation) => { let startPosition = annotation.startPosition; - startPosition = arkts.SourcePosition.create(startPosition.index() - 1, startPosition.line()); + startPosition = arkts.createSourcePosition(startPosition.getIndex() - 1, startPosition.getLine()); let endPosition = annotation.endPosition; return { title: 'Remove the annotation', diff --git a/arkui-plugins/ui-syntax-plugins/rules/computed-decorator-check.ts b/arkui-plugins/ui-syntax-plugins/rules/computed-decorator-check.ts index aac96f3da..6628ce43d 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/computed-decorator-check.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/computed-decorator-check.ts @@ -81,7 +81,7 @@ class ComputedDecoratorCheckRule extends AbstractUISyntaxRule { message: this.messages.onlyOnGetter, fix: (computedDecorator) => { let startPosition = computedDecorator.startPosition; - startPosition = arkts.SourcePosition.create(startPosition.index() - 1, startPosition.line()); + startPosition = arkts.createSourcePosition(startPosition.getIndex() - 1, startPosition.getLine()); const endPosition = computedDecorator.endPosition; return { title: 'Remove the annotation', @@ -117,7 +117,7 @@ class ComputedDecoratorCheckRule extends AbstractUISyntaxRule { message: this.messages.onlyOnGetter, fix: (computedDecorator) => { let startPosition = computedDecorator.startPosition; - startPosition = arkts.SourcePosition.create(startPosition.index() - 1, startPosition.line()); + startPosition = arkts.createSourcePosition(startPosition.getIndex() - 1, startPosition.getLine()); const endPosition = computedDecorator.endPosition; return { title: 'Remove the annotation', diff --git a/arkui-plugins/ui-syntax-plugins/rules/consumer-provider-decorator-check.ts b/arkui-plugins/ui-syntax-plugins/rules/consumer-provider-decorator-check.ts index cc57ac196..739f52c1f 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/consumer-provider-decorator-check.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/consumer-provider-decorator-check.ts @@ -145,7 +145,7 @@ class ConsumerProviderDecoratorCheckRule extends AbstractUISyntaxRule { }, fix: () => { let startPosition = otherDecorators.startPosition; - startPosition = arkts.SourcePosition.create(startPosition.index() - 1, startPosition.line()); + startPosition = arkts.createSourcePosition(startPosition.getIndex() - 1, startPosition.getLine()); const endPosition = otherDecorators.endPosition; return { title: 'Remove other annotations', @@ -222,7 +222,7 @@ class ConsumerProviderDecoratorCheckRule extends AbstractUISyntaxRule { }, fix: (decorator) => { let startPosition = decorator.startPosition; - startPosition = arkts.SourcePosition.create(startPosition.index() - 1, startPosition.line()); + startPosition = arkts.createSourcePosition(startPosition.getIndex() - 1, startPosition.getLine()); const endPosition = decorator.endPosition; return { title: 'Remove the annotation', diff --git a/arkui-plugins/ui-syntax-plugins/rules/monitor-decorator-check.ts b/arkui-plugins/ui-syntax-plugins/rules/monitor-decorator-check.ts index 12b3d7674..2e0fe7737 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/monitor-decorator-check.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/monitor-decorator-check.ts @@ -180,7 +180,7 @@ class MonitorDecoratorCheckRule extends AbstractUISyntaxRule { annotation.startPosition); const endPositions = conflictingDecorators.map(annotation => annotation.endPosition); let startPosition = startPositions[0]; - startPosition = arkts.SourcePosition.create(startPosition.index() - 1, startPosition.line()); + startPosition = arkts.createSourcePosition(startPosition.getIndex() - 1, startPosition.getLine()); const endPosition = endPositions[endPositions.length - 1]; return { title: 'Remove the annotation', @@ -213,7 +213,7 @@ class MonitorDecoratorCheckRule extends AbstractUISyntaxRule { message: this.messages.monitorDecorateMethod, fix: () => { let startPosition = monitorDecorator.startPosition; - startPosition = arkts.SourcePosition.create(startPosition.index() - 1, startPosition.line()); + startPosition = arkts.createSourcePosition(startPosition.getIndex() - 1, startPosition.getLine()); const endPosition = monitorDecorator.endPosition; return { title: 'Remove the @Monitor annotation', diff --git a/arkui-plugins/ui-syntax-plugins/rules/no-duplicate-entry.ts b/arkui-plugins/ui-syntax-plugins/rules/no-duplicate-entry.ts index 693009713..29ae33df2 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/no-duplicate-entry.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/no-duplicate-entry.ts @@ -50,7 +50,7 @@ class NoDuplicateEntryRule extends AbstractUISyntaxRule { return; } let startPosition = entryDecoratorUsage.startPosition; - startPosition = arkts.SourcePosition.create(startPosition.index() - 1, startPosition.line()); + startPosition = arkts.createSourcePosition(startPosition.getIndex() - 1, startPosition.getLine()); this.report({ node: entryDecoratorUsage, message: this.messages.duplicateEntry, @@ -68,14 +68,14 @@ class NoDuplicateEntryRule extends AbstractUISyntaxRule { return; } let startPosition = entryDecoratorUsage.startPosition; - startPosition = arkts.SourcePosition.create(startPosition.index() - 1, startPosition.line()); + startPosition = arkts.createSourcePosition(startPosition.getIndex() - 1, startPosition.getLine()); this.report({ node: entryDecoratorUsage, message: this.messages.duplicateEntry, fix: () => { return { title: 'Remove the duplicate \'Entry\' annotation', - range: [startPosition, entryDecoratorUsage.endPosition], + range: [startPosition, entryDecoratorUsage!.endPosition], code: '', }; }, diff --git a/arkui-plugins/ui-syntax-plugins/rules/no-duplicate-id.ts b/arkui-plugins/ui-syntax-plugins/rules/no-duplicate-id.ts index c4ff651ab..a4f839c8e 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/no-duplicate-id.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/no-duplicate-id.ts @@ -64,8 +64,8 @@ class NoDuplicateIdRule extends AbstractUISyntaxRule { data: { id: idInfo.value, path: getCurrentFilePath(node) ?? '', - line: idInfo.node.startPosition.line().toString(), - index: idInfo.node.startPosition.index().toString() + line: idInfo.node.startPosition.getLine().toString(), + index: idInfo.node.startPosition.getIndex().toString() } }); } else { diff --git a/arkui-plugins/ui-syntax-plugins/rules/no-duplicate-preview.ts b/arkui-plugins/ui-syntax-plugins/rules/no-duplicate-preview.ts index e1eb2cf93..953b8f19f 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/no-duplicate-preview.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/no-duplicate-preview.ts @@ -63,7 +63,7 @@ class NoDuplicatePreviewRule extends AbstractUISyntaxRule { private reportError(errorNode: arkts.AnnotationUsage): void { let startPosition = errorNode.startPosition; - startPosition = arkts.SourcePosition.create(startPosition.index() - 1, startPosition.line()); + startPosition = arkts.createSourcePosition(startPosition.getIndex() - 1, startPosition.getLine()); this.report({ node: errorNode, message: this.messages.duplicateEntry, diff --git a/arkui-plugins/ui-syntax-plugins/rules/no-prop-link-objectlink-in-entry.ts b/arkui-plugins/ui-syntax-plugins/rules/no-prop-link-objectlink-in-entry.ts index 77729e317..c1736f431 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/no-prop-link-objectlink-in-entry.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/no-prop-link-objectlink-in-entry.ts @@ -72,7 +72,7 @@ class NoPropLinkObjectLinkInEntryRule extends AbstractUISyntaxRule { }, fix: (annotation) => { let startPosition = annotation.startPosition; - startPosition = arkts.SourcePosition.create(startPosition.index() - 1, startPosition.line()); + startPosition = arkts.createSourcePosition(startPosition.getIndex() - 1, startPosition.getLine()); let endPosition = annotation.endPosition; return { title: 'Remove the annotation', 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 index a5c758888..c171146ca 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/observedV2-trace-usage-validation.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/observedV2-trace-usage-validation.ts @@ -49,7 +49,7 @@ class ObservedV2TraceUsageValidationRule extends AbstractUISyntaxRule { message: this.messages.observedV2DecoratorError, fix: (observedV2Decorator) => { let startPosition = observedV2Decorator.startPosition; - startPosition = arkts.SourcePosition.create(startPosition.index() - 1, startPosition.line()); + startPosition = arkts.createSourcePosition(startPosition.getIndex() - 1, startPosition.getLine()); let endPosition = observedV2Decorator.endPosition; return { title: 'Remove the @ObservedV2 annotation', @@ -67,7 +67,7 @@ class ObservedV2TraceUsageValidationRule extends AbstractUISyntaxRule { message: this.messages.traceMemberVariableError, fix: (traceDecorator) => { let startPosition = traceDecorator.startPosition; - startPosition = arkts.SourcePosition.create(startPosition.index() - 1, startPosition.line()); + startPosition = arkts.createSourcePosition(startPosition.getIndex() - 1, startPosition.getLine()); let endPosition = traceDecorator.endPosition; return { title: 'Remove the @Trace annotation', @@ -105,7 +105,7 @@ class ObservedV2TraceUsageValidationRule extends AbstractUISyntaxRule { message: this.messages.traceDecoratorError, fix: (traceDecorator) => { let startPosition = traceDecorator.startPosition; - startPosition = arkts.SourcePosition.create(startPosition.index() - 1, startPosition.line()); + startPosition = arkts.createSourcePosition(startPosition.getIndex() - 1, startPosition.getLine()); let endPosition = traceDecorator.endPosition; return { title: 'Remove the @Trace annotation', diff --git a/arkui-plugins/ui-syntax-plugins/rules/once-decorator-check.ts b/arkui-plugins/ui-syntax-plugins/rules/once-decorator-check.ts index bb9c7e452..a598023da 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/once-decorator-check.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/once-decorator-check.ts @@ -75,7 +75,7 @@ class OnceDecoratorCheckRule extends AbstractUISyntaxRule { message: message, fix: (decorator) => { let startPosition = decorator.startPosition; - startPosition = arkts.SourcePosition.create(startPosition.index() - 1, startPosition.line()); + startPosition = arkts.createSourcePosition(startPosition.getIndex() - 1, startPosition.getLine()); const endPosition = decorator.endPosition; return { title: 'Remove the annotation', diff --git a/arkui-plugins/ui-syntax-plugins/rules/one-decorator-on-function-method.ts b/arkui-plugins/ui-syntax-plugins/rules/one-decorator-on-function-method.ts index 27633d57f..a075c3b0b 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/one-decorator-on-function-method.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/one-decorator-on-function-method.ts @@ -108,7 +108,7 @@ class OneDecoratorOnFunctionMethodRule extends AbstractUISyntaxRule { message: this.messages.invalidDecorator, fix: () => { let startPosition = otherDecorator.startPosition; - startPosition = arkts.SourcePosition.create(startPosition.index() - 1, startPosition.line()); + startPosition = arkts.createSourcePosition(startPosition.getIndex() - 1, startPosition.getLine()); const endPosition = otherDecorator.endPosition; return { title: 'Remove the annotation', diff --git a/arkui-plugins/ui-syntax-plugins/rules/track-decorator-check.ts b/arkui-plugins/ui-syntax-plugins/rules/track-decorator-check.ts index ca5af992f..ec8760d37 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/track-decorator-check.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/track-decorator-check.ts @@ -111,7 +111,7 @@ class TrackDecoratorCheckRule extends AbstractUISyntaxRule { message: this.messages.trackMustUsedWithObserved, fix: (trackDecorator) => { let startPosition = trackDecorator.startPosition; - startPosition = arkts.SourcePosition.create(startPosition.index() - 1, startPosition.line()); + startPosition = arkts.createSourcePosition(startPosition.getIndex() - 1, startPosition.getLine()); let endPosition = trackDecorator.endPosition; return { title: 'Remove the annotation', @@ -128,7 +128,7 @@ class TrackDecoratorCheckRule extends AbstractUISyntaxRule { message: this.messages.trackOnClassMemberOnly, fix: (node) => { let startPosition = node.startPosition; - startPosition = arkts.SourcePosition.create(startPosition.index() - 1, startPosition.line()); + startPosition = arkts.createSourcePosition(startPosition.getIndex() - 1, startPosition.getLine()); let endPosition = node.endPosition; return { title: 'Remove the annotation', diff --git a/arkui-plugins/ui-syntax-plugins/rules/validate-build-in-struct.ts b/arkui-plugins/ui-syntax-plugins/rules/validate-build-in-struct.ts index cada0d959..389741871 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/validate-build-in-struct.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/validate-build-in-struct.ts @@ -151,7 +151,7 @@ class ValidateBuildInStructRule extends AbstractUISyntaxRule { }, fix: () => { let startPosition = node.endPosition; - startPosition = arkts.SourcePosition.create(startPosition.index() - 1, startPosition.line()); + startPosition = arkts.createSourcePosition(startPosition.getIndex() - 1, startPosition.getLine()); const endPosition = startPosition; return { title: 'Add a build function to the custom component', -- Gitee From 6c0205199384352d4a472e877c92305f2868092b Mon Sep 17 00:00:00 2001 From: Aleksandr Veselov Date: Wed, 20 Aug 2025 16:42:19 +0300 Subject: [PATCH 09/39] Fix after rebase Signed-off-by: Aleksandr Veselov Change-Id: I23344d63222ee608b7e4a71405cd47689e782bd4 --- .../collectors/utils/collect-types.ts | 6 +-- arkui-plugins/test/utils/compile.ts | 5 +- .../builder-lambda-translators/factory.ts | 50 ++++++++++--------- .../style-internals-visitor.ts | 13 +++-- .../builder-lambda-translators/utils.ts | 2 +- .../ui-plugins/property-translators/utils.ts | 4 +- .../ui-plugins/type-translators/factory.ts | 45 ++++++++--------- .../rules/entry-componentv2-invalid-params.ts | 2 +- 8 files changed, 66 insertions(+), 61 deletions(-) diff --git a/arkui-plugins/collectors/utils/collect-types.ts b/arkui-plugins/collectors/utils/collect-types.ts index ace7ea54a..15a1f6af9 100644 --- a/arkui-plugins/collectors/utils/collect-types.ts +++ b/arkui-plugins/collectors/utils/collect-types.ts @@ -150,10 +150,10 @@ export function collectTypeRecordFromParameter(param); - const name = _param.identifier.name; - const typeRecord = collectTypeRecordFromType(_param.type)!; + const name = _param.ident!.name; + const typeRecord = collectTypeRecordFromType(_param.typeAnnotation)!; const annotations = _param.annotations; - const isOptional = _param.optional; + const isOptional = _param.isOptional; return { name, typeRecord, annotations, isOptional }; } diff --git a/arkui-plugins/test/utils/compile.ts b/arkui-plugins/test/utils/compile.ts index 6ee379cfe..e2fedb08d 100644 --- a/arkui-plugins/test/utils/compile.ts +++ b/arkui-plugins/test/utils/compile.ts @@ -33,6 +33,7 @@ import { import { PluginDriver } from './plugin-driver'; import { PluginState, PluginContext, PluginExecutor } from '../../common/plugin-context'; import { concatObject } from './serializable'; +import { NodeCache } from '../../common/node-cache'; function insertPlugin(driver: PluginDriver, plugin: PluginExecutor | undefined): boolean { const pluginContext: PluginContext = driver.getPluginContext(); @@ -299,14 +300,14 @@ function compileExternalProgram(emitter: EventEmitter, jobInfo: Jo function proceedToState(state: arkts.Es2pandaContextState, context: arkts.KNativePointer, forceDtsEmit = false): void { console.log('[TS WRAPPER] PROCEED TO STATE: ', arkts.getEnumName(arkts.Es2pandaContextState, state)); if (arkts.arktsGlobal.es2panda._ContextState(context) === arkts.Es2pandaContextState.ES2PANDA_STATE_ERROR) { - arkts.NodeCache.clear(); + NodeCache.getInstance().clear(); processErrorState(state, context, forceDtsEmit); } if (state <= arkts.arktsGlobal.es2panda._ContextState(context)) { console.log('[TS WRAPPER] PROCEED TO STATE: SKIPPING'); return; } - arkts.NodeCache.clear(); + NodeCache.getInstance().clear(); arkts.arktsGlobal.es2panda._ProceedToState(context, state); processErrorState(state, context, forceDtsEmit); } diff --git a/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts b/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts index 282a0727b..495b30e6f 100644 --- a/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts +++ b/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts @@ -221,7 +221,7 @@ export class factory { let lambdaBody: arkts.Identifier | arkts.CallExpression = arkts.factory.createIdentifier( BuilderLambdaNames.STYLE_ARROW_PARAM_NAME ); - arkts.NodeCache.getInstance().collect(lambdaBody); + NodeCache.getInstance().collect(lambdaBody); const methodName = arkts.factory.createIdentifier(getDeclaredSetAttribtueMethodName(name)); if (!hasReceiver) { lambdaBodyInfo.lambdaBody = arkts.factory.createCallExpression( @@ -232,11 +232,13 @@ export class factory { false, false ), + [], undefined, - [] + false, + false ); } else { - lambdaBodyInfo.lambdaBody = arkts.factory.createCallExpression(methodName, undefined, [lambdaBody]); + lambdaBodyInfo.lambdaBody = arkts.factory.createCallExpression(methodName, [lambdaBody], undefined, false, false); } lambdaBodyInfo.initCallPtr = lambdaBodyInfo.lambdaBody.peer; return lambdaBodyInfo; @@ -334,24 +336,22 @@ export class factory { * create content argument in builder lambda declaration. */ static createContentArgInBuilderLambdaDecl(): arkts.ETSParameterExpression { - const funcType = arkts.factory.createFunctionType( - arkts.FunctionSignature.createFunctionSignature( - undefined, - [], - arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), - false - ), + const funcType = arkts.factory.createETSFunctionType( + undefined, + [], + arkts.factory.createETSPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID), + false, arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW ); addMemoAnnotation(funcType); const parameter: arkts.ETSParameterExpression = arkts.factory - .createParameterDeclaration( + .createETSParameterExpression( arkts.factory.createIdentifier(BuilderLambdaNames.CONTENT_PARAM_NAME, funcType), + true, undefined - ) - .setOptional(true); - arkts.NodeCache.getInstance().collect(parameter); + ); + NodeCache.getInstance().collect(parameter); return parameter; } @@ -529,7 +529,7 @@ export class factory { const modifiedArgs: (arkts.Expression | undefined)[] = []; const secondLastArgInfo = buildSecondLastArgInfo(type, isFunctionCall); const isTrailingCall = leaf.isTrailingCall; - const typeArguments = leaf.typeArguments; + const typeArguments = leaf.typeParams?.params; const hasLastTrailingLambda = checkIsTrailingLambdaInLastParam(params); forEachArgWithParam( leaf.arguments, @@ -628,7 +628,7 @@ export class factory { */ static addOptionsArgsToLambdaBodyInStyleArg( lambdaBodyInfo: BuilderLambdaStyleBodyInfo, - args: (arkts.AstNode | undefined)[], + args: (arkts.Expression | undefined)[], typeArguments: readonly arkts.TypeNode[] | undefined, shouldApplyAttribute: boolean = true ): arkts.CallExpression | arkts.Identifier | undefined { @@ -666,8 +666,10 @@ export class factory { false, false ), + [], undefined, - [] + false, + false ); } @@ -892,7 +894,7 @@ export class factory { replaceBuilderLambdaDeclMethodName(nameNode!.name), newOverloads ); - arkts.NodeCache.getInstance().collect(newNode); + NodeCache.getInstance().collect(newNode); return newNode; } @@ -1184,7 +1186,7 @@ export class factory { const kind = arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_METHOD; const modifiers = arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_DECLARE; const funcTypeParams = typeParams - ? arkts.factory.createTypeParameterDeclaration(typeParams, typeParams.length) + ? arkts.factory.createTSTypeParameterDeclaration(typeParams, typeParams.length) : undefined; const returnTypeAnnotation = arkts.factory.createTSThisType(); const flags = arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD; @@ -1212,7 +1214,7 @@ export class factory { const key = arkts.factory.createIdentifier(BuilderLambdaNames.APPLY_ATTRIBUTES_FINISH_METHOD); const kind = arkts.Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_METHOD; const modifiers = arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_DECLARE; - const returnTypeAnnotation = arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID); + const returnTypeAnnotation = arkts.factory.createETSPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID); const flags = arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD; return UIFactory.createMethodDefinition({ key, @@ -1242,7 +1244,7 @@ export class factory { arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_DECLARE | arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_STATIC | arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_EXPORT; - const returnTypeAnnotation = arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID); + const returnTypeAnnotation = arkts.factory.createETSPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID); const flags = arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD; const params = factory.createDeclaredComponentFunctionParameters( attributeName, @@ -1251,7 +1253,7 @@ export class factory { ); const typeParamItems = record.typeParams?.map((p) => TypeFactory.createTypeParameterFromRecord(p)); const typeParams = !!typeParamItems - ? arkts.factory.createTypeParameterDeclaration(typeParamItems, typeParamItems.length) + ? arkts.factory.createTSTypeParameterDeclaration(typeParamItems, typeParamItems.length) : undefined; const newMethod = UIFactory.createMethodDefinition({ key, @@ -1266,8 +1268,8 @@ export class factory { }, modifiers, }); - addMemoAnnotation(newMethod.scriptFunction); - arkts.NodeCache.getInstance().collect(newMethod); + addMemoAnnotation(newMethod.function!); + NodeCache.getInstance().collect(newMethod); return newMethod; } diff --git a/arkui-plugins/ui-plugins/builder-lambda-translators/style-internals-visitor.ts b/arkui-plugins/ui-plugins/builder-lambda-translators/style-internals-visitor.ts index fc46594bf..68c070186 100644 --- a/arkui-plugins/ui-plugins/builder-lambda-translators/style-internals-visitor.ts +++ b/arkui-plugins/ui-plugins/builder-lambda-translators/style-internals-visitor.ts @@ -19,7 +19,7 @@ import { AstNodePointer } from '../../common/safe-types'; export class StyleInternalsVisitor extends AbstractVisitor { private initCallPtr: AstNodePointer | undefined; - private initCallArgs: arkts.AstNode[] | undefined; + private initCallArgs: arkts.Expression[] | undefined; private initCallTypeArguments: readonly arkts.TypeNode[] | undefined; registerInitCall(initCallPtr: AstNodePointer): this { @@ -27,7 +27,7 @@ export class StyleInternalsVisitor extends AbstractVisitor { return this; } - registerInitCallArgs(initCallArgs: arkts.AstNode[]): this { + registerInitCallArgs(initCallArgs: arkts.Expression[]): this { this.initCallArgs = initCallArgs; return this; } @@ -39,11 +39,14 @@ export class StyleInternalsVisitor extends AbstractVisitor { visitor(node: arkts.CallExpression): arkts.AstNode { if (!!this.initCallPtr && !!this.initCallArgs && node.peer === this.initCallPtr) { + const typeParams = this.initCallTypeArguments + ? arkts.factory.createTSTypeParameterInstantiation(this.initCallTypeArguments) + : node.typeParams; return arkts.factory.updateCallExpression( node, - node.expression, - this.initCallTypeArguments ?? node.typeArguments, - this.initCallArgs + node.callee, + this.initCallArgs, + typeParams ); } return this.visitEachChild(node); diff --git a/arkui-plugins/ui-plugins/builder-lambda-translators/utils.ts b/arkui-plugins/ui-plugins/builder-lambda-translators/utils.ts index 9b0dc7bf4..2562691f3 100644 --- a/arkui-plugins/ui-plugins/builder-lambda-translators/utils.ts +++ b/arkui-plugins/ui-plugins/builder-lambda-translators/utils.ts @@ -685,7 +685,7 @@ export function checkIsTrailingLambdaInLastParam(params: readonly arkts.Expressi return false; } const lastParam = params.at(params.length - 1)! as arkts.ETSParameterExpression; - return hasMemoAnnotation(lastParam) && lastParam.identifier.name === BuilderLambdaNames.COMPONENT_PARAM_ORI; + return hasMemoAnnotation(lastParam) && lastParam.ident!.name === BuilderLambdaNames.COMPONENT_PARAM_ORI; } /** diff --git a/arkui-plugins/ui-plugins/property-translators/utils.ts b/arkui-plugins/ui-plugins/property-translators/utils.ts index 70c6cf402..338dd7fbb 100644 --- a/arkui-plugins/ui-plugins/property-translators/utils.ts +++ b/arkui-plugins/ui-plugins/property-translators/utils.ts @@ -458,11 +458,11 @@ export function getArrayFromAnnoProperty(property: arkts.AstNode): string[] | un } function getMonitorStrFromMemberExpr(node: arkts.MemberExpression): string | undefined { - const decl: arkts.AstNode | undefined = arkts.getDecl(node.property); + const decl: arkts.AstNode | undefined = arkts.getDecl(node.property!); if (!decl || !arkts.isClassProperty(decl) || !decl.value || !arkts.isETSNewClassInstanceExpression(decl.value)) { return undefined; } - const args: readonly arkts.Expression[] = decl.value.getArguments; + const args: readonly arkts.Expression[] = decl.value.arguments; if (args.length >= 2 && arkts.isStringLiteral(args[1])) { return args[1].str; } diff --git a/arkui-plugins/ui-plugins/type-translators/factory.ts b/arkui-plugins/ui-plugins/type-translators/factory.ts index 14e265042..5ce317761 100644 --- a/arkui-plugins/ui-plugins/type-translators/factory.ts +++ b/arkui-plugins/ui-plugins/type-translators/factory.ts @@ -64,23 +64,23 @@ export class factory { const typeName = record?.typeName; switch (typeName) { case 'boolean': - return arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_BOOLEAN); + return arkts.factory.createETSPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_BOOLEAN); case 'byte': - return arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_BYTE); + return arkts.factory.createETSPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_BYTE); case 'char': - return arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_CHAR); + return arkts.factory.createETSPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_CHAR); case 'double': - return arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_DOUBLE); + return arkts.factory.createETSPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_DOUBLE); case 'float': - return arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_FLOAT); + return arkts.factory.createETSPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_FLOAT); case 'int': - return arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_INT); + return arkts.factory.createETSPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_INT); case 'long': - return arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_LONG); + return arkts.factory.createETSPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_LONG); case 'short': - return arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_SHORT); + return arkts.factory.createETSPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_SHORT); case 'void': - return arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID); + return arkts.factory.createETSPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_VOID); default: throw new Error(`Cannot create primitive type because of name: ${typeName}`); } @@ -94,11 +94,12 @@ export class factory { const annotations = record.annotations.map((a) => a.clone()); const isOptional = record.isOptional; const typeAnnotation = factory.createTypeNodeFromRecord(record.typeRecord); - const parameter = arkts.factory.createParameterDeclaration( + const parameter = arkts.factory.createETSParameterExpression( arkts.factory.createIdentifier(name, typeAnnotation), - undefined + false, + undefined, + annotations ); - parameter.annotations = annotations; if (isOptional) { parameter.setOptional(true); } @@ -113,7 +114,7 @@ export class factory { const typeName = record.typeName ? arkts.factory.createIdentifier(record.typeName) : undefined; const defaultType = record.defaultType ? factory.createTypeNodeFromRecord(record.defaultType) : undefined; const constraint = record.constraint ? factory.createTypeNodeFromRecord(record.constraint) : undefined; - const typeParameter = arkts.factory.createTypeParameter(typeName, constraint, defaultType); + const typeParameter = arkts.factory.createTypeParameter(typeName, constraint, defaultType, arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE); typeParameter.setAnnotations(annotations); return typeParameter; } @@ -155,13 +156,11 @@ export class factory { const returnType = factory.createTypeNodeFromRecord(record.returnType); const params = record.params.map((p) => factory.createParameterFromRecord(p)); const typeParams = record.typeParams?.map((p) => factory.createTypeParameterFromRecord(p)); - const funcType = arkts.factory.createFunctionType( - arkts.factory.createFunctionSignature( - typeParams ? arkts.factory.createTypeParameterDeclaration(typeParams, typeParams.length) : undefined, - params, - returnType, - false - ), + const funcType = arkts.factory.createETSFunctionType( + typeParams ? arkts.factory.createTSTypeParameterDeclaration(typeParams, typeParams.length) : undefined, + params, + returnType, + false, arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW ); funcType.setAnnotations(annotations); @@ -173,7 +172,7 @@ export class factory { */ static createUnionTypeFromRecord(record: UnionTypeRecord): arkts.ETSUnionType { const types = record.types.map((t) => factory.createTypeNodeFromRecord(t)); - return arkts.factory.createUnionType(types); + return arkts.factory.createETSUnionType(types); } /** @@ -204,8 +203,8 @@ export class factory { const name = record.typeName; const annotations = record.annotations; const typeParams = record.typeParams?.map((p) => factory.createTypeNodeFromRecord(p)); - const typeRef = arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( + const typeRef = arkts.factory.createETSTypeReference( + arkts.factory.createETSTypeReferencePart( factory.createTypeNameForTypeReferencePart(name), typeParams ? arkts.factory.createTSTypeParameterInstantiation(typeParams) : undefined ) diff --git a/arkui-plugins/ui-syntax-plugins/rules/entry-componentv2-invalid-params.ts b/arkui-plugins/ui-syntax-plugins/rules/entry-componentv2-invalid-params.ts index 0aa95b242..a8315b325 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/entry-componentv2-invalid-params.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/entry-componentv2-invalid-params.ts @@ -28,7 +28,7 @@ class EntryComponentV2InvalidParamsRule extends AbstractUISyntaxRule { } public parsed(node: arkts.AstNode): void { - if (!arkts.isStructDeclaration(node)) { + if (!arkts.isETSStructDeclaration(node)) { return; } -- Gitee From d89ba093dfad9981e13f99b2791d4681efeefc15 Mon Sep 17 00:00:00 2001 From: Korobeinikov Evgeny Date: Thu, 21 Aug 2025 17:41:42 +0300 Subject: [PATCH 10/39] switch libarkts path Signed-off-by: Korobeinikov Evgeny Change-Id: I506b42755a6152c382090e0f4e7f62656fff0b18 --- arkui-plugins/package.json | 2 +- arkui-plugins/path.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/arkui-plugins/package.json b/arkui-plugins/package.json index 929c12377..3b1f29c39 100644 --- a/arkui-plugins/package.json +++ b/arkui-plugins/package.json @@ -31,6 +31,6 @@ "typescript": "^5.0.0" }, "dependencies": { - "@koalaui/libarkts": "../koala-wrapper" + "@koalaui/libarkts": "../../../foundation/arkui/ace_engine/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts" } } diff --git a/arkui-plugins/path.ts b/arkui-plugins/path.ts index a8646fcbf..7f7141da6 100644 --- a/arkui-plugins/path.ts +++ b/arkui-plugins/path.ts @@ -45,7 +45,7 @@ function findRootDir() { } export function getArktsPath() { - return path.join(findRootDir(), 'koala-wrapper', './build/lib/arkts-api/index.js'); + return path.join(findRootDir(), 'ui2abc/libarkts', './lib/libarkts.js'); } export function getInteropPath() { -- Gitee From 9272bedcae260c45f6cf731fceb309858abb8e38 Mon Sep 17 00:00:00 2001 From: Aleksandr Veselov Date: Thu, 28 Aug 2025 12:03:45 +0300 Subject: [PATCH 11/39] Rebase fixup Change-Id: I8d8e52807e157e301fff6bc462c67b617ea6b619 Signed-off-by: Aleksandr Veselov --- .../builder-lambda-translators/condition-scope-visitor.ts | 7 ++++--- arkui-plugins/ui-plugins/index.ts | 4 ++-- arkui-plugins/ui-plugins/ui-factory.ts | 5 +++-- arkui-plugins/ui-syntax-plugins/index.ts | 4 ++-- 4 files changed, 11 insertions(+), 9 deletions(-) diff --git a/arkui-plugins/ui-plugins/builder-lambda-translators/condition-scope-visitor.ts b/arkui-plugins/ui-plugins/builder-lambda-translators/condition-scope-visitor.ts index 69e6b759e..a6f96ef88 100644 --- a/arkui-plugins/ui-plugins/builder-lambda-translators/condition-scope-visitor.ts +++ b/arkui-plugins/ui-plugins/builder-lambda-translators/condition-scope-visitor.ts @@ -16,6 +16,7 @@ import * as arkts from '@koalaui/libarkts'; import { AbstractVisitor } from '../../common/abstract-visitor'; import { factory as BuilderLambdaFactory } from './factory'; +import { NodeCache } from '../../common/node-cache'; /** * `ConditionScopeVisitor` is used to visit `@Builder` function body to wrap `ConditionScope`/`ConditionBranch` @@ -55,7 +56,7 @@ export class ConditionScopeVisitor extends AbstractVisitor { } private enter(node: arkts.AstNode): void { - if (arkts.isVariableDeclarator(node) && arkts.NodeCache.getInstance().has(node)) { + if (arkts.isVariableDeclarator(node) && NodeCache.getInstance().has(node)) { this._enforceUpdateCondition = true; } } @@ -81,8 +82,8 @@ export class ConditionScopeVisitor extends AbstractVisitor { } if ( arkts.isArrowFunctionExpression(node) && - !arkts.NodeCache.getInstance().has(node) && - !arkts.NodeCache.getInstance().has(node.scriptFunction) + !NodeCache.getInstance().has(node) && + !NodeCache.getInstance().has(node.function) ) { this.shouldUpdateCondition = false; this._enforceUpdateCondition = false; diff --git a/arkui-plugins/ui-plugins/index.ts b/arkui-plugins/ui-plugins/index.ts index 87a1d0724..f5dba30ad 100644 --- a/arkui-plugins/ui-plugins/index.ts +++ b/arkui-plugins/ui-plugins/index.ts @@ -43,7 +43,7 @@ function parsedTransform(this: PluginContext): arkts.ETSModule | undefined { const contextPtr = this.getContextPtr() ?? arkts.arktsGlobal.compilerContext?.peer; if (!!contextPtr) { let program = arkts.getOrUpdateGlobalContext(contextPtr).program; - script = program.astNode; + let script = program.ast; const canSkipPhases = CanSkipPhasesCache.check(program); arkts.Performance.getInstance().createEvent('ui-parsed'); @@ -95,7 +95,7 @@ function checkedTransform(this: PluginContext): arkts.ETSModule | undefined { const contextPtr = this.getContextPtr() ?? arkts.arktsGlobal.compilerContext?.peer; if (!!contextPtr) { let program = arkts.getOrUpdateGlobalContext(contextPtr).program; - script = program.astNode; + let script = program.ast; const canSkipPhases = CanSkipPhasesCache.check(program); arkts.Performance.getInstance().createEvent('ui-checked'); diff --git a/arkui-plugins/ui-plugins/ui-factory.ts b/arkui-plugins/ui-plugins/ui-factory.ts index f5839ed8e..b4262f0f1 100644 --- a/arkui-plugins/ui-plugins/ui-factory.ts +++ b/arkui-plugins/ui-plugins/ui-factory.ts @@ -464,11 +464,12 @@ export class factory { * create class static block, e.g. `static {}`. */ static createClassStaticBlock(): arkts.ClassStaticBlock { - return arkts.factory.createClassStaticBlock( + return arkts.ClassStaticBlock.createClassStaticBlock( arkts.factory.createFunctionExpression( + arkts.factory.createIdentifier(ArkTsDefaultNames.DEFAULT_STATIC_BLOCK_NAME), factory.createScriptFunction({ key: arkts.factory.createIdentifier(ArkTsDefaultNames.DEFAULT_STATIC_BLOCK_NAME), - body: arkts.factory.createBlock([]), + body: arkts.factory.createBlockStatement([]), modifiers: arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_STATIC, flags: arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_STATIC_BLOCK | diff --git a/arkui-plugins/ui-syntax-plugins/index.ts b/arkui-plugins/ui-syntax-plugins/index.ts index fb758628f..32b7c4734 100644 --- a/arkui-plugins/ui-syntax-plugins/index.ts +++ b/arkui-plugins/ui-syntax-plugins/index.ts @@ -57,7 +57,7 @@ function createTransformer( return undefined; } const program = arkts.getOrUpdateGlobalContext(contextPtr).program; - if (visitedPrograms.has(program.peer) || isHeaderFile(program.absName)) { + if (visitedPrograms.has(program.peer) || isHeaderFile(program.absoluteName)) { return undefined; } const isCoding = this.isCoding?.() ?? false; @@ -94,7 +94,7 @@ function transformExternalSources( } const programs = externalSource.programs; for (const program of programs) { - if (visitedPrograms.has(program.peer) || isHeaderFile(program.absName)) { + if (visitedPrograms.has(program.peer) || isHeaderFile(program.absoluteName)) { continue; } const script = transformer.transform(program.ast) as arkts.ETSModule; -- Gitee From d41fb88525fe3fb714a6c122733ca57e27d3bcc9 Mon Sep 17 00:00:00 2001 From: Aleksandr Veselov Date: Thu, 28 Aug 2025 18:18:56 +0300 Subject: [PATCH 12/39] Minor fixes Signed-off-by: Aleksandr Veselov Change-Id: I8479b2f4a216d31779ca668081a829562c5d2385 --- arkui-plugins/memo-plugins/utils.ts | 4 ++-- .../ui-plugins/entry-translators/factory.ts | 18 +++++++++++------- arkui-plugins/ui-plugins/ui-factory.ts | 2 +- 3 files changed, 14 insertions(+), 10 deletions(-) diff --git a/arkui-plugins/memo-plugins/utils.ts b/arkui-plugins/memo-plugins/utils.ts index 2d3290729..d2edd0e8a 100644 --- a/arkui-plugins/memo-plugins/utils.ts +++ b/arkui-plugins/memo-plugins/utils.ts @@ -500,7 +500,7 @@ export function findReturnTypeFromTypeAnnotation( return typeAnnotation.returnType; } if (arkts.isETSUnionType(typeAnnotation)) { - return typeAnnotation.types.find((type) => arkts.isETSFunctionType(type))?.returnType; + return (typeAnnotation.types.find((type) => arkts.isETSFunctionType(type)) as arkts.ETSFunctionType | undefined)?.returnType; } return undefined; } @@ -515,7 +515,7 @@ export function findLocalReturnTypeFromTypeAnnotation( return typeAnnotation.returnType; } if (arkts.isETSUnionType(typeAnnotation)) { - return typeAnnotation.types.find((type) => arkts.isETSFunctionType(type))?.returnType; + return (typeAnnotation.types.find((type) => arkts.isETSFunctionType(type)) as arkts.ETSFunctionType | undefined)?.returnType; } return undefined; } diff --git a/arkui-plugins/ui-plugins/entry-translators/factory.ts b/arkui-plugins/ui-plugins/entry-translators/factory.ts index 836384699..f6faafb68 100644 --- a/arkui-plugins/ui-plugins/entry-translators/factory.ts +++ b/arkui-plugins/ui-plugins/entry-translators/factory.ts @@ -346,13 +346,17 @@ export class factory { : ''; const pageFullPath = getRelativePagePath(projectConfig?.projectPath ?? '', fileAbsName ?? ''); const pagePath = getRelativePagePath(projectRoot, fileAbsName ?? ''); - return arkts.factory.createObjectExpression([ - factory.createNavProperty(NavigationNames.BUNDLE_NAME, projectConfig?.bundleName), - factory.createNavProperty(NavigationNames.MODULE_NAME, projectConfig?.moduleName), - factory.createNavProperty(NavigationNames.PAGE_PATH, pagePath), - factory.createNavProperty(NavigationNames.PAGE_FULL_PATH, pageFullPath), - factory.createNavProperty(NavigationNames.INTEGRATED_HSP, projectConfig?.integratedHsp?.toString()), - ]); + return arkts.factory.createTSAsExpression( + arkts.factory.createObjectExpression([ + factory.createNavProperty(NavigationNames.BUNDLE_NAME, projectConfig?.bundleName), + factory.createNavProperty(NavigationNames.MODULE_NAME, projectConfig?.moduleName), + factory.createNavProperty(NavigationNames.PAGE_PATH, pagePath), + factory.createNavProperty(NavigationNames.PAGE_FULL_PATH, pageFullPath), + factory.createNavProperty(NavigationNames.INTEGRATED_HSP, projectConfig?.integratedHsp?.toString()), + ]), + uiFactory.createTypeReferenceFromString(NavigationNames.NAVINTERFACE), + false + ); } /** diff --git a/arkui-plugins/ui-plugins/ui-factory.ts b/arkui-plugins/ui-plugins/ui-factory.ts index b4262f0f1..611d3c233 100644 --- a/arkui-plugins/ui-plugins/ui-factory.ts +++ b/arkui-plugins/ui-plugins/ui-factory.ts @@ -464,7 +464,7 @@ export class factory { * create class static block, e.g. `static {}`. */ static createClassStaticBlock(): arkts.ClassStaticBlock { - return arkts.ClassStaticBlock.createClassStaticBlock( + return arkts.factory.createClassStaticBlock( arkts.factory.createFunctionExpression( arkts.factory.createIdentifier(ArkTsDefaultNames.DEFAULT_STATIC_BLOCK_NAME), factory.createScriptFunction({ -- Gitee From 40cec2a4d6080d8209a9e2e735f37e4f049867a1 Mon Sep 17 00:00:00 2001 From: Aleksandr Veselov Date: Fri, 29 Aug 2025 18:47:21 +0300 Subject: [PATCH 13/39] Fix rebase Signed-off-by: Aleksandr Veselov Change-Id: Iba8620e0f8a03787b861e823dc81fa4f0f5bd31d --- .../collectors/memo-collectors/utils.ts | 2 +- .../builder-factory.ts | 4 +- .../builder-lambda-translators/factory.ts | 39 ++++++++++--------- .../ui-plugins/interop/initstatevar.ts | 7 ++-- 4 files changed, 27 insertions(+), 25 deletions(-) diff --git a/arkui-plugins/collectors/memo-collectors/utils.ts b/arkui-plugins/collectors/memo-collectors/utils.ts index 30cb361a9..72ba29994 100644 --- a/arkui-plugins/collectors/memo-collectors/utils.ts +++ b/arkui-plugins/collectors/memo-collectors/utils.ts @@ -87,7 +87,7 @@ export function addMemoAnnotation(node: T, memoName: Memo annotation(memoName), ]; collectMemoAnnotationImport(memoName); - if (arkts.isEtsParameterExpression(node)) { + if (arkts.isETSParameterExpression(node)) { node.setAnnotations(newAnnotations); if (!skipNames.includes(memoName)) { NodeCache.getInstance().collect(node); diff --git a/arkui-plugins/ui-plugins/builder-lambda-translators/builder-factory.ts b/arkui-plugins/ui-plugins/builder-lambda-translators/builder-factory.ts index 3e7277def..049107fab 100644 --- a/arkui-plugins/ui-plugins/builder-lambda-translators/builder-factory.ts +++ b/arkui-plugins/ui-plugins/builder-lambda-translators/builder-factory.ts @@ -136,7 +136,7 @@ export class BuilderFactory { } const isFromClass = arkts.isClassDefinition(decl); const typeRef = BuilderLambdaFactory.createTypeRefInBuilderParameterProxyCall(arg, decl); - let newArgument: arkts.AstNode; + let newArgument: arkts.Expression; if (arkts.isTSAsExpression(arg)) { const objectExpr = arg.expr as arkts.ObjectExpression; newArgument = arkts.factory.updateTSAsExpression( @@ -148,7 +148,7 @@ export class BuilderFactory { } else { newArgument = BuilderLambdaFactory.createBuilderParameterProxyCall(arg, typeRef, isFromClass); } - return arkts.factory.updateCallExpression(_node, _node.expression, _node.typeArguments, [newArgument]); + return arkts.factory.updateCallExpression(_node, _node.callee, [newArgument], _node.typeParams); } } diff --git a/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts b/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts index 495b30e6f..182366b45 100644 --- a/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts +++ b/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts @@ -1309,7 +1309,7 @@ export class factory { ): arkts.CallExpression { const entries = flatObjectExpressionToEntries(node); const objectArg = isFromClass - ? arkts.factory.createObjectExpression(arkts.Es2pandaAstNodeType.AST_NODE_TYPE_OBJECT_EXPRESSION, [], false) + ? arkts.factory.createObjectExpression([]) : node; const newMapArg = this.createInitMapArgInBuilderParameterProxyCall(entries); const updateArg = this.createUpdateArgInBuilderParameterProxyCall(typeRef, entries, isFromClass); @@ -1320,8 +1320,10 @@ export class factory { ImportCollector.getInstance().collectImport(StateManagementTypes.MAKE_BUILDER_PARAM_PROXY); return arkts.factory.createCallExpression( arkts.factory.createIdentifier(StateManagementTypes.MAKE_BUILDER_PARAM_PROXY), - [typeRef], - [objectArg, newMapArg, updateArg] + [objectArg, newMapArg, updateArg], + arkts.factory.createTSTypeParameterInstantiation([typeRef]), + false, + false ); } @@ -1350,18 +1352,16 @@ export class factory { static createInitMapArgInBuilderParameterProxyCall( entries: [arkts.Identifier, arkts.Expression | undefined][] ): arkts.ETSNewClassInstanceExpression { - const newMapName = arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( + const newMapName = arkts.factory.createETSTypeReference( + arkts.factory.createETSTypeReferencePart( arkts.factory.createIdentifier(TypeNames.MAP), arkts.factory.createTSTypeParameterInstantiation([ UIFactory.createTypeReferenceFromString(TypeNames.STRING), - arkts.factory.createFunctionType( - arkts.factory.createFunctionSignature( - undefined, - [], - UIFactory.createTypeReferenceFromString(TypeNames.ANY), - false - ), + arkts.factory.createETSFunctionType( + undefined, + [], + UIFactory.createTypeReferenceFromString(TypeNames.ANY), + false, arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW ), ]) @@ -1372,9 +1372,9 @@ export class factory { const name = k.name; const key = arkts.factory.createStringLiteral(name); const value = this.prepareBuilderParameterPropertyValue(v); - const arrowFunc = arkts.factory.createArrowFunction( + const arrowFunc = arkts.factory.createArrowFunctionExpression( UIFactory.createScriptFunction({ - body: arkts.factory.createBlock([arkts.factory.createReturnStatement(value)]), + body: arkts.factory.createBlockStatement([arkts.factory.createReturnStatement(value)]), returnTypeAnnotation: UIFactory.createTypeReferenceFromString(TypeNames.ANY), flags: arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, }) @@ -1394,8 +1394,9 @@ export class factory { isFromClass: boolean ): arkts.ArrowFunctionExpression { const genSymName: string = GenSymGenerator.getInstance().id(); - const param = arkts.factory.createParameterDeclaration( + const param = arkts.factory.createETSParameterExpression( arkts.factory.createIdentifier(genSymName, typeRef), + false, undefined ); const statements = isFromClass @@ -1411,15 +1412,15 @@ export class factory { return arkts.factory.createExpressionStatement( arkts.factory.createAssignmentExpression( left, - arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION, - right + right, + arkts.Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_SUBSTITUTION ) ); }) : []; - const body = arkts.factory.createBlock(statements); + const body = arkts.factory.createBlockStatement(statements); const flags = arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW; - return arkts.factory.createArrowFunction(UIFactory.createScriptFunction({ params: [param], body, flags })); + return arkts.factory.createArrowFunctionExpression(UIFactory.createScriptFunction({ params: [param], body, flags })); } /** diff --git a/arkui-plugins/ui-plugins/interop/initstatevar.ts b/arkui-plugins/ui-plugins/interop/initstatevar.ts index 5cca11059..584dcf4e4 100644 --- a/arkui-plugins/ui-plugins/interop/initstatevar.ts +++ b/arkui-plugins/ui-plugins/interop/initstatevar.ts @@ -143,10 +143,11 @@ function processObjectLiteral(target: arkts.ObjectExpression, curParam: string, const createParam = createEmptyESValue(curParam); result.push(createParam); } - target.properties.forEach((property: { key: arkts.Expression; value: arkts.Expression; }) => { + target.properties.forEach((prop: arkts.Expression) => { + const property = prop as arkts.Property const paramName = curParam + keyName; - const key = property.key; - const value = property.value; + const key = property.key as arkts.Identifier; + const value = property.value!; if (arkts.isObjectExpression(value)) { processObjectLiteral(value, paramName, result, keyName); const setProperty = setPropertyESValue( -- Gitee From 85a9c11b8ccb176e18e5f4eb46bbc0047249ddf9 Mon Sep 17 00:00:00 2001 From: Aleksandr Veselov Date: Mon, 1 Sep 2025 12:13:41 +0300 Subject: [PATCH 14/39] Init libarkts for tests Signed-off-by: Aleksandr Veselov Change-Id: I2acb77fc3592b028f64104910a3690c9ea8b8b35 --- arkui-plugins/test/utils/artkts-config.ts | 4 ++-- arkui-plugins/test/utils/global.ts | 5 +++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/arkui-plugins/test/utils/artkts-config.ts b/arkui-plugins/test/utils/artkts-config.ts index d47091bd7..cf4862f35 100644 --- a/arkui-plugins/test/utils/artkts-config.ts +++ b/arkui-plugins/test/utils/artkts-config.ts @@ -40,7 +40,7 @@ import { } from './path-config'; import { ArkTSConfigContextCache } from './cache'; import { BuildConfig, CompileFileInfo, DependentModule } from './shared-types'; -import { setUpSoPath } from './global'; +import { initializeLibarkts } from './global'; import { ProjectConfig } from '../../common/plugin-context'; export interface ArkTSConfigObject { @@ -247,7 +247,7 @@ class MockArktsConfigBuilder implements ArktsConfigBuilder { this.moduleInfos = new Map(); this.mergedAbcFile = path.resolve(this.outputDir, MOCK_OUTPUT_FILE_NAME); - setUpSoPath(this.pandaSdkPath); + initializeLibarkts(this.pandaSdkPath); this.generateModuleInfos(); this.generateArkTSConfigForModules(); this.cacheArkTSConfig(); diff --git a/arkui-plugins/test/utils/global.ts b/arkui-plugins/test/utils/global.ts index 668b83f83..587809350 100644 --- a/arkui-plugins/test/utils/global.ts +++ b/arkui-plugins/test/utils/global.ts @@ -116,8 +116,9 @@ function destroyConfig(config: arkts.KNativePointer): void { } } -function setUpSoPath(pandaSdkPath: string): void { +function initializeLibarkts(pandaSdkPath: string): void { arkts.arktsGlobal.es2panda._SetUpSoPath(pandaSdkPath); + arkts.initVisitsTable(); } export { @@ -131,5 +132,5 @@ export { resetConfig, destroyContext, destroyConfig, - setUpSoPath, + initializeLibarkts, }; -- Gitee From 3b7d7750ae12f8b269bc7898f8247e2045dd4f5c Mon Sep 17 00:00:00 2001 From: Aleksandr Veselov Date: Mon, 1 Sep 2025 15:35:21 +0300 Subject: [PATCH 15/39] Fix missing annotations Signed-off-by: Aleksandr Veselov Change-Id: I92cd0b80bb15f60f3ded9f63b0e4ef6c208a9929 --- arkui-plugins/interop-plugins/decl_transformer.ts | 3 ++- arkui-plugins/interop-plugins/emit_transformer.ts | 3 ++- arkui-plugins/ui-plugins/component-transformer.ts | 3 ++- arkui-plugins/ui-plugins/entry-translators/factory.ts | 6 ++++-- .../ui-plugins/struct-translators/factory.ts | 11 +++++++---- 5 files changed, 17 insertions(+), 9 deletions(-) diff --git a/arkui-plugins/interop-plugins/decl_transformer.ts b/arkui-plugins/interop-plugins/decl_transformer.ts index 1a16a6adf..57194a598 100644 --- a/arkui-plugins/interop-plugins/decl_transformer.ts +++ b/arkui-plugins/interop-plugins/decl_transformer.ts @@ -42,7 +42,8 @@ export class DeclTransformer extends AbstractVisitor { undefined, node.definition?.body, newDec.definition?.modifiers!, - arkts.classDefinitionFlags(newDec.definition!) | arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE + arkts.classDefinitionFlags(newDec.definition!) | arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, + node.definition.annotations ); arkts.factory.updateClassDeclaration(newDec, newDefinition); diff --git a/arkui-plugins/interop-plugins/emit_transformer.ts b/arkui-plugins/interop-plugins/emit_transformer.ts index c43605263..772882fa3 100644 --- a/arkui-plugins/interop-plugins/emit_transformer.ts +++ b/arkui-plugins/interop-plugins/emit_transformer.ts @@ -40,7 +40,8 @@ export class EmitTransformer extends AbstractVisitor { undefined, node.definition?.body, node.definition?.modifiers, - arkts.classDefinitionFlags(node.definition) | arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE + arkts.classDefinitionFlags(node.definition) | arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, + node.definition.annotations ); let newDec: arkts.ClassDeclaration = arkts.factory.updateClassDeclaration(node, newDefinition); diff --git a/arkui-plugins/ui-plugins/component-transformer.ts b/arkui-plugins/ui-plugins/component-transformer.ts index 61c9f071d..11060e07f 100644 --- a/arkui-plugins/ui-plugins/component-transformer.ts +++ b/arkui-plugins/ui-plugins/component-transformer.ts @@ -280,7 +280,8 @@ export class ComponentTransformer extends AbstractVisitor { node.definition.super, [entryFactory.generateRegisterNamedRouter(), ...node.definition.body], node.definition.modifiers, - arkts.classDefinitionFlags(node.definition) + arkts.classDefinitionFlags(node.definition), + node.definition.annotations ) ); } diff --git a/arkui-plugins/ui-plugins/entry-translators/factory.ts b/arkui-plugins/ui-plugins/entry-translators/factory.ts index f6faafb68..4fad64939 100644 --- a/arkui-plugins/ui-plugins/entry-translators/factory.ts +++ b/arkui-plugins/ui-plugins/entry-translators/factory.ts @@ -45,7 +45,8 @@ export class factory { definition.super, [...definition.body, factory.generateEntryFunction(classname)], definition.modifiers, - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, + definition.annotations ); return arkts.factory.updateClassDeclaration(node, updateClassDef); } @@ -72,7 +73,8 @@ export class factory { definition.super, [...definition.body, factory.generateEntryProperty(classname)], definition.modifiers, - arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE + arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, + definition.annotations ); return arkts.factory.updateClassDeclaration(node, updateClassDef); } diff --git a/arkui-plugins/ui-plugins/struct-translators/factory.ts b/arkui-plugins/ui-plugins/struct-translators/factory.ts index 2b44c70c1..9f724e1f1 100644 --- a/arkui-plugins/ui-plugins/struct-translators/factory.ts +++ b/arkui-plugins/ui-plugins/struct-translators/factory.ts @@ -331,7 +331,8 @@ export class factory { definition.super, members, definition.modifiers, - arkts.classDefinitionFlags(definition) + arkts.classDefinitionFlags(definition), + definition.annotations ); } @@ -857,7 +858,7 @@ export class factory { arkts.factory.updateInterfaceBody(node.body!, newBody), node.isStatic, node.isFromExternal - ); + ).setAnnotations(node.annotations); } return node; @@ -902,7 +903,8 @@ export class factory { node.definition.super, updatedBody, node.definition.modifiers, - arkts.classDefinitionFlags(node.definition) + arkts.classDefinitionFlags(node.definition), + node.definition.annotations ) ); } @@ -953,7 +955,8 @@ export class factory { node.super, factory.observedTrackPropertyMembers(node, ObservedAnno), node.modifiers, - arkts.classDefinitionFlags(node) + arkts.classDefinitionFlags(node), + node.annotations ); collectStateManagementTypeImport(StateManagementTypes.OBSERVED_OBJECT); return updateClassDef; -- Gitee From b2f2729b733193c4be268811d8e50c7e5e740d20 Mon Sep 17 00:00:00 2001 From: Aleksandr Veselov Date: Mon, 1 Sep 2025 16:21:24 +0300 Subject: [PATCH 16/39] Fix typo and bad merge Signed-off-by: Aleksandr Veselov Change-Id: Ia0d4f37a3b194b35a35badc5c88ec346a8374f71 --- arkui-plugins/common/predefines.ts | 2 +- .../ui-plugins/property-translators/factory.ts | 15 +-------------- 2 files changed, 2 insertions(+), 15 deletions(-) diff --git a/arkui-plugins/common/predefines.ts b/arkui-plugins/common/predefines.ts index 642d0219a..de3acb796 100644 --- a/arkui-plugins/common/predefines.ts +++ b/arkui-plugins/common/predefines.ts @@ -106,7 +106,7 @@ export enum ObservedNames { export enum MonitorNames { PATH = 'path', - VALUE_CALL_CACK = 'valueCallback', + VALUE_CALLBACK = 'valueCallback', I_MONITOR = 'IMonitor', M_PARAM = '_m', } diff --git a/arkui-plugins/ui-plugins/property-translators/factory.ts b/arkui-plugins/ui-plugins/property-translators/factory.ts index 5b22f3fbc..7e5c8caa3 100644 --- a/arkui-plugins/ui-plugins/property-translators/factory.ts +++ b/arkui-plugins/ui-plugins/property-translators/factory.ts @@ -905,20 +905,7 @@ export class factory { ), arkts.factory.createProperty( arkts.Es2pandaPropertyKind.PROPERTY_KIND_INIT, - arkts.factory.createIdentifier(MonitorNames.VALUE_CALL_CACK), - arkts.factory.createArrowFunctionExpression( - UIFactory.createScriptFunction({ - flags: arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, - body: arkts.factory.createBlockStatement([arkts.factory.createReturnStatement(monitorVariable)]), - returnTypeAnnotation: UIFactory.createTypeReferenceFromString(TypeNames.NULLISH_TYPE), - }) - ), - false, - false - ), - arkts.factory.createProperty( - arkts.Es2pandaPropertyKind.PROPERTY_KIND_INIT, - arkts.factory.createIdentifier(MonitorNames.VALUE_CALL_CACK), + arkts.factory.createIdentifier(MonitorNames.VALUE_CALLBACK), arkts.factory.createArrowFunctionExpression( UIFactory.createScriptFunction({ flags: arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, -- Gitee From 8921b7ac39b66f97532290230073d57e10513ce3 Mon Sep 17 00:00:00 2001 From: Aleksandr Veselov Date: Mon, 1 Sep 2025 18:09:41 +0300 Subject: [PATCH 17/39] Fix annotation test Signed-off-by: Aleksandr Veselov Change-Id: I3182521e2d997c87b7f30b91797ba3ce658d6b04 --- arkui-plugins/test/ut/common/annotation.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/arkui-plugins/test/ut/common/annotation.test.ts b/arkui-plugins/test/ut/common/annotation.test.ts index d1799cfe0..9832d3e71 100644 --- a/arkui-plugins/test/ut/common/annotation.test.ts +++ b/arkui-plugins/test/ut/common/annotation.test.ts @@ -60,7 +60,7 @@ class AnnotationVisitor extends AbstractVisitor { if (arkts.isETSParameterExpression(node)) { node.setAnnotations([this.testAnnotation()]); } else if (arkts.isMethodDefinition(node)) { - node.scriptFunction.setAnnotations([this.testAnnotation()]); + node.function.setAnnotations([this.testAnnotation()]); } else { node.setAnnotations([this.testAnnotation()]); } @@ -70,7 +70,7 @@ class AnnotationVisitor extends AbstractVisitor { if (arkts.isETSParameterExpression(node)) { node.setAnnotations([]); } else if (arkts.isMethodDefinition(node)) { - node.scriptFunction.setAnnotations([]); + node.function.setAnnotations([]); } else { node.setAnnotations([]); } -- Gitee From 92821ed88383d6cfdf3114603bdc4fc3b742abda Mon Sep 17 00:00:00 2001 From: Aleksandr Veselov Date: Tue, 2 Sep 2025 14:46:25 +0300 Subject: [PATCH 18/39] Sort imports in the unit tests Signed-off-by: Aleksandr Veselov Change-Id: I72af5d5a718b8844e30faeb2f1546e502153a6a1 --- arkui-plugins/test/utils/parse-string.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/arkui-plugins/test/utils/parse-string.ts b/arkui-plugins/test/utils/parse-string.ts index 2db07c21f..bd3c42530 100644 --- a/arkui-plugins/test/utils/parse-string.ts +++ b/arkui-plugins/test/utils/parse-string.ts @@ -18,10 +18,18 @@ function parseDumpSrc(str: string): string { _str = cleanCopyRight(_str); _str = removeSpaceAndReturn(_str); _str = replaceWithRandomNumber(_str); + _str = organizeImports(_str); return _str; } +function organizeImports(str: string): string { + let imports: string[] = []; + str = str.replaceAll(/^\s*import.*from.*$/gm, (importLine) => { imports.push(importLine.trim()); return "" }); + imports.sort() + return [...imports, str].join("\n") +} + function filterSource(text: string): string { const filtered: string = text.replaceAll(/%/g, '_').replaceAll(/#/g, '_').replaceAll('', '_cctor_'); -- Gitee From e5fc82bc36f36c435046285a7cf025b38a67f484 Mon Sep 17 00:00:00 2001 From: Aleksandr Veselov Date: Tue, 2 Sep 2025 16:16:33 +0300 Subject: [PATCH 19/39] Update nodeCache in factory Signed-off-by: Aleksandr Veselov Change-Id: I28286395ba86be756de936b16f8e28a696235be8 --- arkui-plugins/ui-plugins/struct-translators/factory.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/arkui-plugins/ui-plugins/struct-translators/factory.ts b/arkui-plugins/ui-plugins/struct-translators/factory.ts index 9f724e1f1..910385d8c 100644 --- a/arkui-plugins/ui-plugins/struct-translators/factory.ts +++ b/arkui-plugins/ui-plugins/struct-translators/factory.ts @@ -82,6 +82,7 @@ import { MethodTranslator } from '../property-translators/base'; import { MonitorCache } from '../property-translators/cache/monitorCache'; import { PropertyCache } from '../property-translators/cache/propertyCache'; import { ComponentAttributeCache } from '../builder-lambda-translators/cache/componentAttributeCache'; +import { NodeCache } from '../../common/node-cache'; export class factory { /** @@ -513,7 +514,9 @@ export class factory { PropertyFactory.addMemoToBuilderClassMethod(member); if (isKnownMethodDefinition(member, CustomComponentNames.COMPONENT_BUILD_ORI)) { addMemoAnnotation(member.function!); - return BuilderFactory.rewriteBuilderMethod(member); + const transformedBuildMethod = BuilderFactory.rewriteBuilderMethod(member); + NodeCache.getInstance().refresh(member, transformedBuildMethod); + return transformedBuildMethod; } return member; } -- Gitee From 4a1ca98c9d5fec4a3ee1f7b9a1075ed8ce9f91b8 Mon Sep 17 00:00:00 2001 From: Aleksandr Veselov Date: Wed, 3 Sep 2025 17:26:31 +0300 Subject: [PATCH 20/39] Fix after rebase Signed-off-by: Aleksandr Veselov Change-Id: Ia90ddf63e59944b999aaaa004b5cb969e52dd496 --- .../ui-plugins/builder-lambda-translators/factory.ts | 10 ++++++++-- arkui-plugins/ui-plugins/ui-factory.ts | 2 +- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts b/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts index 182366b45..54bbdda1b 100644 --- a/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts +++ b/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts @@ -461,8 +461,11 @@ export class factory { ) { newProperty = arkts.factory.updateProperty( prop, + arkts.Es2pandaPropertyKind.PROPERTY_KIND_INIT, arkts.factory.createIdentifier(backingField(keyName)), - factory.updateBackingMember(value, value.property.name) + factory.updateBackingMember(value, value.property.name), + false, + false ); } return declInfo?.isFunctionCall @@ -470,8 +473,11 @@ export class factory { : [ newProperty, arkts.factory.createProperty( + arkts.Es2pandaPropertyKind.PROPERTY_KIND_INIT, arkts.factory.createIdentifier(optionsHasField(keyName)), - arkts.factory.createBooleanLiteral(true) + arkts.factory.createBooleanLiteral(true), + false, + false ), ]; } diff --git a/arkui-plugins/ui-plugins/ui-factory.ts b/arkui-plugins/ui-plugins/ui-factory.ts index 611d3c233..ad9787a04 100644 --- a/arkui-plugins/ui-plugins/ui-factory.ts +++ b/arkui-plugins/ui-plugins/ui-factory.ts @@ -486,7 +486,7 @@ export class factory { const optionsHasMember: arkts.ClassProperty = arkts.factory.createClassProperty( arkts.factory.createIdentifier(optionsHasField(name)), undefined, - arkts.factory.createPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_BOOLEAN), + arkts.factory.createETSPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_BOOLEAN), arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, false ); -- Gitee From 7495200a317441c725dec90a1ab1cc772e8e7006 Mon Sep 17 00:00:00 2001 From: Aleksandr Veselov Date: Wed, 3 Sep 2025 18:16:31 +0300 Subject: [PATCH 21/39] Add some missing semicolons to task cases Signed-off-by: Aleksandr Veselov Change-Id: I615853ac255d47c245cfa7dafd418d3a7d7bca24 --- .../condition-scope/with-builder.test.ts | 2 +- .../custom-component-call.test.ts | 2 +- .../builder-param-passing.test.ts | 4 ++-- .../init-with-local-builder.test.ts | 8 +++---- .../optional-builder-param.test.ts | 8 +++---- .../decorators/link/link-basic-type.test.ts | 10 ++++---- .../decorators/link/link-complex-type.test.ts | 24 +++++++++---------- .../link/link-to-link-propref-state.test.ts | 4 ++-- .../decorators/link/state-to-link.test.ts | 2 +- .../localstoragelink-complex-type.test.ts | 16 ++++++------- .../localstoragelink-primitive-type.test.ts | 6 ++--- .../localstorageprop-ref-complex-type.test.ts | 14 +++++------ ...ocalstorageprop-ref-primitive-type.test.ts | 10 ++++---- .../decorators/require/basic-require.test.ts | 2 +- .../storagelink-appstorage.test.ts | 4 ++-- .../storagelink-complex-type.test.ts | 14 +++++------ .../storagelink-primitive-type.test.ts | 6 ++--- .../storageprop-ref-complex-type.test.ts | 14 +++++------ .../storageprop-ref-primitive-type.test.ts | 10 ++++---- .../decorators/watch/watch-basic.test.ts | 2 +- 20 files changed, 81 insertions(+), 81 deletions(-) diff --git a/arkui-plugins/test/ut/ui-plugins/builder-lambda/condition-scope/with-builder.test.ts b/arkui-plugins/test/ut/ui-plugins/builder-lambda/condition-scope/with-builder.test.ts index b70e8a936..c4b753b66 100644 --- a/arkui-plugins/test/ut/ui-plugins/builder-lambda/condition-scope/with-builder.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/builder-lambda/condition-scope/with-builder.test.ts @@ -543,7 +543,7 @@ function main() {} __memo_scope.recache(); return; } - }))) + }))); } public __updateStruct(initializers: (__Options_Child | undefined)): void {} private __backing_myBuilderParam?: @memo() ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void); diff --git a/arkui-plugins/test/ut/ui-plugins/builder-lambda/custom-component/custom-component-call.test.ts b/arkui-plugins/test/ut/ui-plugins/builder-lambda/custom-component/custom-component-call.test.ts index 4cb07f2e4..3e62f5cfe 100644 --- a/arkui-plugins/test/ut/ui-plugins/builder-lambda/custom-component/custom-component-call.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/builder-lambda/custom-component/custom-component-call.test.ts @@ -123,7 +123,7 @@ function main() {} @Component() final struct 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)) + (((gensym___38813563) == (null)) ? undefined : gensym___38813563.closer)})) ?? (content))) ?? (this.closerBuilder)); } public __updateStruct(initializers: (__Options_CustomContainer | undefined)): void {} diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/builder-param/builder-param-passing.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/builder-param/builder-param-passing.test.ts index 1f0ce315b..cfb6b7cd4 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/builder-param/builder-param-passing.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/builder-param/builder-param-passing.test.ts @@ -58,7 +58,7 @@ function main() {} @Component() final struct 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)) + (((gensym___169376706) == (null)) ? undefined : gensym___169376706.customBuilderParam)})) ?? (content))) ?? (this.customBuilder)); } public __updateStruct(initializers: (__Options_Child | undefined)): void {} @@ -155,7 +155,7 @@ function main() {} @Component() final struct Child extends CustomComponent { public __initializeStruct(initializers: (__Options_Child | undefined), @memo() content: (((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void) | undefined)): void { this.__backing_customBuilderParam = ((((({let gensym___169376706 = initializers; - (((gensym___169376706) == (null)) ? undefined : gensym___169376706.customBuilderParam)})) ?? (content))) ?? (this.customBuilder)) + (((gensym___169376706) == (null)) ? undefined : gensym___169376706.customBuilderParam)})) ?? (content))) ?? (this.customBuilder)); } public __updateStruct(initializers: (__Options_Child | undefined)): void {} diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/builder-param/init-with-local-builder.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/builder-param/init-with-local-builder.test.ts index b35f0aceb..d7fe74791 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/builder-param/init-with-local-builder.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/builder-param/init-with-local-builder.test.ts @@ -48,9 +48,9 @@ function main() {} @Component() final struct 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)) + (((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)) + (((gensym___14041256) == (null)) ? undefined : gensym___14041256.customBuilderParam2)})) ?? (content))) ?? (this.doNothingBuilder2)); } public __updateStruct(initializers: (__Options_Child | undefined)): void {} @@ -110,9 +110,9 @@ function main() {} @Component() final struct Child extends CustomComponent { public __initializeStruct(initializers: (__Options_Child | undefined), @memo() content: (((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void) | undefined)): void { this.__backing_customBuilderParam = ((((({let gensym___169376706 = initializers; - (((gensym___169376706) == (null)) ? undefined : gensym___169376706.customBuilderParam)})) ?? (content))) ?? (this.doNothingBuilder)) + (((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)) + (((gensym___14041256) == (null)) ? undefined : gensym___14041256.customBuilderParam2)})) ?? (content))) ?? (this.doNothingBuilder2)); } public __updateStruct(initializers: (__Options_Child | undefined)): void {} diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/builder-param/optional-builder-param.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/builder-param/optional-builder-param.test.ts index 899349a1a..e9756b61d 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/builder-param/optional-builder-param.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/builder-param/optional-builder-param.test.ts @@ -63,9 +63,9 @@ function main() {} @Component() final struct Child extends CustomComponent { public __initializeStruct(initializers: (__Options_Child | undefined), @memo() content: ((()=> void) | undefined)): void { this.__backing_customBuilderParam2 = ((((({let gensym___103851375 = initializers; - (((gensym___103851375) == (null)) ? undefined : gensym___103851375.customBuilderParam2)})) ?? (content))) ?? (undefined)) + (((gensym___103851375) == (null)) ? undefined : gensym___103851375.customBuilderParam2)})) ?? (content))) ?? (undefined)); this.__backing_customBuilderParam1 = ((((({let gensym___20169645 = initializers; - (((gensym___20169645) == (null)) ? undefined : gensym___20169645.customBuilderParam1)})) ?? (content))) ?? (showTextBuilder)) + (((gensym___20169645) == (null)) ? undefined : gensym___20169645.customBuilderParam1)})) ?? (content))) ?? (showTextBuilder)); } public __updateStruct(initializers: (__Options_Child | undefined)): void {} @@ -207,9 +207,9 @@ function main() {} @Component() final struct Child extends CustomComponent { public __initializeStruct(initializers: (__Options_Child | undefined), @memo() content: (((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void) | undefined)): void { this.__backing_customBuilderParam2 = ((((({let gensym___103851375 = initializers; - (((gensym___103851375) == (null)) ? undefined : gensym___103851375.customBuilderParam2)})) ?? (content))) ?? (undefined)) + (((gensym___103851375) == (null)) ? undefined : gensym___103851375.customBuilderParam2)})) ?? (content))) ?? (undefined)); this.__backing_customBuilderParam1 = ((((({let gensym___20169645 = initializers; - (((gensym___20169645) == (null)) ? undefined : gensym___20169645.customBuilderParam1)})) ?? (content))) ?? (showTextBuilder)) + (((gensym___20169645) == (null)) ? undefined : gensym___20169645.customBuilderParam1)})) ?? (content))) ?? (showTextBuilder)); } public __updateStruct(initializers: (__Options_Child | undefined)): void {} diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/link/link-basic-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/link/link-basic-type.test.ts index 99df21b18..17937033b 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/link/link-basic-type.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/link/link-basic-type.test.ts @@ -60,23 +60,23 @@ function main() {} if (({let gensym___184416899 = initializers; (((gensym___184416899) == (null)) ? undefined : gensym___184416899.__options_has_linkVar1)})) { this.__backing_linkVar1 = STATE_MGMT_FACTORY.makeLink(this, "linkVar1", initializers!.__backing_linkVar1!); - }; + } if (({let gensym___82966591 = initializers; (((gensym___82966591) == (null)) ? undefined : gensym___82966591.__options_has_linkVar2)})) { this.__backing_linkVar2 = STATE_MGMT_FACTORY.makeLink(this, "linkVar2", initializers!.__backing_linkVar2!); - }; + } if (({let gensym___55498955 = initializers; (((gensym___55498955) == (null)) ? undefined : gensym___55498955.__options_has_linkVar3)})) { this.__backing_linkVar3 = STATE_MGMT_FACTORY.makeLink(this, "linkVar3", initializers!.__backing_linkVar3!); - }; + } if (({let gensym___231322030 = initializers; (((gensym___231322030) == (null)) ? undefined : gensym___231322030.__options_has_linkVar4)})) { this.__backing_linkVar4 = STATE_MGMT_FACTORY.makeLink(this, "linkVar4", initializers!.__backing_linkVar4!); - }; + } if (({let gensym___2576517 = initializers; (((gensym___2576517) == (null)) ? undefined : gensym___2576517.__options_has_linkVar5)})) { this.__backing_linkVar5 = STATE_MGMT_FACTORY.makeLink(this, "linkVar5", initializers!.__backing_linkVar5!); - }; + } } public __updateStruct(initializers: (__Options_LinkParent | undefined)): void {} diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/link/link-complex-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/link/link-complex-type.test.ts index 5644da5a0..80f9967c2 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/link/link-complex-type.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/link/link-complex-type.test.ts @@ -137,51 +137,51 @@ final class LinkType extends BaseEnum { if (({let gensym___184416899 = initializers; (((gensym___184416899) == (null)) ? undefined : gensym___184416899.__options_has_linkVar1)})) { this.__backing_linkVar1 = STATE_MGMT_FACTORY.makeLink(this, "linkVar1", initializers!.__backing_linkVar1!); - }; + } if (({let gensym___82966591 = initializers; (((gensym___82966591) == (null)) ? undefined : gensym___82966591.__options_has_linkVar2)})) { this.__backing_linkVar2 = STATE_MGMT_FACTORY.makeLink>(this, "linkVar2", initializers!.__backing_linkVar2!); - }; + } if (({let gensym___55498955 = initializers; (((gensym___55498955) == (null)) ? undefined : gensym___55498955.__options_has_linkVar3)})) { this.__backing_linkVar3 = STATE_MGMT_FACTORY.makeLink(this, "linkVar3", initializers!.__backing_linkVar3!); - }; + } if (({let gensym___231322030 = initializers; (((gensym___231322030) == (null)) ? undefined : gensym___231322030.__options_has_linkVar4)})) { this.__backing_linkVar4 = STATE_MGMT_FACTORY.makeLink>(this, "linkVar4", initializers!.__backing_linkVar4!); - }; + } if (({let gensym___2576517 = initializers; (((gensym___2576517) == (null)) ? undefined : gensym___2576517.__options_has_linkVar5)})) { this.__backing_linkVar5 = STATE_MGMT_FACTORY.makeLink>(this, "linkVar5", initializers!.__backing_linkVar5!); - }; + } if (({let gensym___11281112 = initializers; (((gensym___11281112) == (null)) ? undefined : gensym___11281112.__options_has_linkVar6)})) { this.__backing_linkVar6 = STATE_MGMT_FACTORY.makeLink>(this, "linkVar6", initializers!.__backing_linkVar6!); - }; + } if (({let gensym___228477447 = initializers; (((gensym___228477447) == (null)) ? undefined : gensym___228477447.__options_has_linkVar7)})) { this.__backing_linkVar7 = STATE_MGMT_FACTORY.makeLink>(this, "linkVar7", initializers!.__backing_linkVar7!); - }; + } if (({let gensym___82513833 = initializers; (((gensym___82513833) == (null)) ? undefined : gensym___82513833.__options_has_linkVar8)})) { this.__backing_linkVar8 = STATE_MGMT_FACTORY.makeLink<((sr: string)=> void)>(this, "linkVar8", initializers!.__backing_linkVar8!); - }; + } if (({let gensym___218466927 = initializers; (((gensym___218466927) == (null)) ? undefined : gensym___218466927.__options_has_linkVar9)})) { this.__backing_linkVar9 = STATE_MGMT_FACTORY.makeLink(this, "linkVar9", initializers!.__backing_linkVar9!); - }; + } if (({let gensym___190376050 = initializers; (((gensym___190376050) == (null)) ? undefined : gensym___190376050.__options_has_linkVar10)})) { this.__backing_linkVar10 = STATE_MGMT_FACTORY.makeLink>(this, "linkVar10", initializers!.__backing_linkVar10!); - }; + } if (({let gensym___64181673 = initializers; (((gensym___64181673) == (null)) ? undefined : gensym___64181673.__options_has_linkVar11)})) { this.__backing_linkVar11 = STATE_MGMT_FACTORY.makeLink<(string | number)>(this, "linkVar11", initializers!.__backing_linkVar11!); - }; + } if (({let gensym___134911804 = initializers; (((gensym___134911804) == (null)) ? undefined : gensym___134911804.__options_has_linkVar12)})) { this.__backing_linkVar12 = STATE_MGMT_FACTORY.makeLink<(Set | Per)>(this, "linkVar12", initializers!.__backing_linkVar12!); - }; + } } public __updateStruct(initializers: (__Options_Parent | undefined)): void {} diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/link/link-to-link-propref-state.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/link/link-to-link-propref-state.test.ts index 1b038ec84..65ebda6c3 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/link/link-to-link-propref-state.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/link/link-to-link-propref-state.test.ts @@ -73,7 +73,7 @@ function main() {} if (({let gensym___194626867 = initializers; (((gensym___194626867) == (null)) ? undefined : gensym___194626867.__options_has_text1)})) { this.__backing_text1 = STATE_MGMT_FACTORY.makeLink(this, "text1", initializers!.__backing_text1!); - }; + } } public __updateStruct(initializers: (__Options_Parant | undefined)): void {} @@ -123,7 +123,7 @@ function main() {} if (({let gensym___55490166 = initializers; (((gensym___55490166) == (null)) ? undefined : gensym___55490166.__options_has_childText)})) { this.__backing_childText = STATE_MGMT_FACTORY.makeLink(this, "childText", initializers!.__backing_childText!); - }; + } this.__backing_childText2 = STATE_MGMT_FACTORY.makeState(this, "childText2", ((({let gensym___95513066 = initializers; (((gensym___95513066) == (null)) ? undefined : gensym___95513066.childText2)})) ?? ("sss"))); this.__backing_childText3 = STATE_MGMT_FACTORY.makePropRef(this, "childText3", (initializers!.childText3 as string)); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/link/state-to-link.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/link/state-to-link.test.ts index cf0a30ddc..3e822be89 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/link/state-to-link.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/link/state-to-link.test.ts @@ -88,7 +88,7 @@ __EntryWrapper.RegisterNamedRouter("", new __EntryWrapper(), ({ if (({let gensym___27735436 = initializers; (((gensym___27735436) == (null)) ? undefined : gensym___27735436.__options_has_selectedDate)})) { this.__backing_selectedDate = STATE_MGMT_FACTORY.makeLink(this, "selectedDate", initializers!.__backing_selectedDate!); - }; + } } public __updateStruct(initializers: (__Options_DateComponent | undefined)): void {} diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/localstoragelink/localstoragelink-complex-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/localstoragelink/localstoragelink-complex-type.test.ts index 81b0ca190..8d244215b 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/localstoragelink/localstoragelink-complex-type.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/localstoragelink/localstoragelink-complex-type.test.ts @@ -146,14 +146,14 @@ final class Status extends BaseEnum { @Entry({useSharedStorage:false,storage:"",routeName:""}) @Component() final struct MyStateSample extends CustomComponent implements PageLifeCycle { public __initializeStruct(initializers: (__Options_MyStateSample | undefined), @memo() content: ((()=> void) | undefined)): void { - this.__backing_arrayA = STATE_MGMT_FACTORY.makeLocalStorageLink>(this, "Prop1", "arrayA", [1, 2, 3]) - this.__backing_objectA = STATE_MGMT_FACTORY.makeLocalStorageLink(this, "Prop2", "objectA", {}) - this.__backing_dateA = STATE_MGMT_FACTORY.makeLocalStorageLink(this, "Prop3", "dateA", new Date("2021-08-08")) - this.__backing_setA = STATE_MGMT_FACTORY.makeLocalStorageLink>(this, "Prop4", "setA", new Set()) - this.__backing_mapA = STATE_MGMT_FACTORY.makeLocalStorageLink>(this, "Prop5", "mapA", new Map()) - this.__backing_unionA = STATE_MGMT_FACTORY.makeLocalStorageLink<(string | undefined)>(this, "Prop6", "unionA", "") - this.__backing_classA = STATE_MGMT_FACTORY.makeLocalStorageLink(this, "Prop7", "classA", new Person("John")) - this.__backing_enumA = STATE_MGMT_FACTORY.makeLocalStorageLink(this, "Prop8", "enumA", Status.NotFound) + this.__backing_arrayA = STATE_MGMT_FACTORY.makeLocalStorageLink>(this, "Prop1", "arrayA", [1, 2, 3]); + this.__backing_objectA = STATE_MGMT_FACTORY.makeLocalStorageLink(this, "Prop2", "objectA", {}); + this.__backing_dateA = STATE_MGMT_FACTORY.makeLocalStorageLink(this, "Prop3", "dateA", new Date("2021-08-08")); + this.__backing_setA = STATE_MGMT_FACTORY.makeLocalStorageLink>(this, "Prop4", "setA", new Set()); + this.__backing_mapA = STATE_MGMT_FACTORY.makeLocalStorageLink>(this, "Prop5", "mapA", new Map()); + this.__backing_unionA = STATE_MGMT_FACTORY.makeLocalStorageLink<(string | undefined)>(this, "Prop6", "unionA", ""); + this.__backing_classA = STATE_MGMT_FACTORY.makeLocalStorageLink(this, "Prop7", "classA", new Person("John")); + this.__backing_enumA = STATE_MGMT_FACTORY.makeLocalStorageLink(this, "Prop8", "enumA", Status.NotFound); } public __updateStruct(initializers: (__Options_MyStateSample | undefined)): void {} diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/localstoragelink/localstoragelink-primitive-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/localstoragelink/localstoragelink-primitive-type.test.ts index a0d915cc8..bda4399b4 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/localstoragelink/localstoragelink-primitive-type.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/localstoragelink/localstoragelink-primitive-type.test.ts @@ -70,9 +70,9 @@ __EntryWrapper.RegisterNamedRouter("", new __EntryWrapper(), ({ @Entry({useSharedStorage:false,storage:"",routeName:""}) @Component() final struct MyStateSample extends CustomComponent implements PageLifeCycle { public __initializeStruct(initializers: (__Options_MyStateSample | undefined), @memo() content: ((()=> void) | undefined)): void { - this.__backing_numA = STATE_MGMT_FACTORY.makeLocalStorageLink(this, "Prop1", "numA", 33) - this.__backing_stringA = STATE_MGMT_FACTORY.makeLocalStorageLink(this, "Prop2", "stringA", "AA") - this.__backing_booleanA = STATE_MGMT_FACTORY.makeLocalStorageLink(this, "Prop3", "booleanA", true) + this.__backing_numA = STATE_MGMT_FACTORY.makeLocalStorageLink(this, "Prop1", "numA", 33); + this.__backing_stringA = STATE_MGMT_FACTORY.makeLocalStorageLink(this, "Prop2", "stringA", "AA"); + this.__backing_booleanA = STATE_MGMT_FACTORY.makeLocalStorageLink(this, "Prop3", "booleanA", true); } public __updateStruct(initializers: (__Options_MyStateSample | undefined)): void {} diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/localstorageprop-ref/localstorageprop-ref-complex-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/localstorageprop-ref/localstorageprop-ref-complex-type.test.ts index 5e88c5774..44581928c 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/localstorageprop-ref/localstorageprop-ref-complex-type.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/localstorageprop-ref/localstorageprop-ref-complex-type.test.ts @@ -130,13 +130,13 @@ final class Status extends BaseEnum { @Component() final struct MyStateSample extends CustomComponent { public __initializeStruct(initializers: (__Options_MyStateSample | undefined), @memo() content: ((()=> void) | undefined)): void { - this.__backing_arrayB = STATE_MGMT_FACTORY.makeLocalStoragePropRef>(this, "Prop1", "arrayB", [1, 2, 3]) - this.__backing_objectB = STATE_MGMT_FACTORY.makeLocalStoragePropRef(this, "Prop2", "objectB", {}) - this.__backing_dateB = STATE_MGMT_FACTORY.makeLocalStoragePropRef(this, "Prop3", "dateB", new Date("2021-09-09")) - this.__backing_setB = STATE_MGMT_FACTORY.makeLocalStoragePropRef>(this, "Prop4", "setB", new Set()) - this.__backing_mapB = STATE_MGMT_FACTORY.makeLocalStoragePropRef>(this, "Prop5", "mapB", new Map()) - this.__backing_classB = STATE_MGMT_FACTORY.makeLocalStoragePropRef(this, "Prop7", "classB", new Person("Kevin")) - this.__backing_enumB = STATE_MGMT_FACTORY.makeLocalStoragePropRef(this, "Prop8", "enumB", Status.NotFound) + this.__backing_arrayB = STATE_MGMT_FACTORY.makeLocalStoragePropRef>(this, "Prop1", "arrayB", [1, 2, 3]); + this.__backing_objectB = STATE_MGMT_FACTORY.makeLocalStoragePropRef(this, "Prop2", "objectB", {}); + this.__backing_dateB = STATE_MGMT_FACTORY.makeLocalStoragePropRef(this, "Prop3", "dateB", new Date("2021-09-09")); + this.__backing_setB = STATE_MGMT_FACTORY.makeLocalStoragePropRef>(this, "Prop4", "setB", new Set()); + this.__backing_mapB = STATE_MGMT_FACTORY.makeLocalStoragePropRef>(this, "Prop5", "mapB", new Map()); + this.__backing_classB = STATE_MGMT_FACTORY.makeLocalStoragePropRef(this, "Prop7", "classB", new Person("Kevin")); + this.__backing_enumB = STATE_MGMT_FACTORY.makeLocalStoragePropRef(this, "Prop8", "enumB", Status.NotFound); } public __updateStruct(initializers: (__Options_MyStateSample | undefined)): void {} diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/localstorageprop-ref/localstorageprop-ref-primitive-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/localstorageprop-ref/localstorageprop-ref-primitive-type.test.ts index dd3158507..030fbd8d6 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/localstorageprop-ref/localstorageprop-ref-primitive-type.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/localstorageprop-ref/localstorageprop-ref-primitive-type.test.ts @@ -55,11 +55,11 @@ function main() {} @Component() final struct MyStateSample extends CustomComponent { public __initializeStruct(initializers: (__Options_MyStateSample | undefined), @memo() content: ((()=> void) | undefined)): void { - this.__backing_numB = STATE_MGMT_FACTORY.makeLocalStoragePropRef(this, "Prop1", "numB", 43) - this.__backing_stringB = STATE_MGMT_FACTORY.makeLocalStoragePropRef(this, "Prop2", "stringB", "BB") - this.__backing_booleanB = STATE_MGMT_FACTORY.makeLocalStoragePropRef(this, "Prop3", "booleanB", false) - this.__backing_undefinedB = STATE_MGMT_FACTORY.makeLocalStoragePropRef(this, "Prop4", "undefinedB", undefined) - this.__backing_nullB = STATE_MGMT_FACTORY.makeLocalStoragePropRef(this, "Prop5", "nullB", null) + this.__backing_numB = STATE_MGMT_FACTORY.makeLocalStoragePropRef(this, "Prop1", "numB", 43); + this.__backing_stringB = STATE_MGMT_FACTORY.makeLocalStoragePropRef(this, "Prop2", "stringB", "BB"); + this.__backing_booleanB = STATE_MGMT_FACTORY.makeLocalStoragePropRef(this, "Prop3", "booleanB", false); + this.__backing_undefinedB = STATE_MGMT_FACTORY.makeLocalStoragePropRef(this, "Prop4", "undefinedB", undefined); + this.__backing_nullB = STATE_MGMT_FACTORY.makeLocalStoragePropRef(this, "Prop5", "nullB", null); } public __updateStruct(initializers: (__Options_MyStateSample | undefined)): void {} diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/require/basic-require.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/require/basic-require.test.ts index afb86ec4b..9c2829730 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/require/basic-require.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/require/basic-require.test.ts @@ -152,7 +152,7 @@ function main() {} this.__backing_select2 = STATE_MGMT_FACTORY.makeProvide>(this, "select2", "15", (initializers!.select2 as Array), false); this.__backing_select6 = STATE_MGMT_FACTORY.makeProvide<(Array | undefined | string)>(this, "select6", "t", (initializers!.select6 as (Array | undefined | string)), false); this.__backing_builder = ((((({let gensym___63603867 = initializers; - (((gensym___63603867) == (null)) ? undefined : gensym___63603867.builder)})) ?? (content))) ?? (undefined)) + (((gensym___63603867) == (null)) ? undefined : gensym___63603867.builder)})) ?? (content))) ?? (undefined)); } public __updateStruct(initializers: (__Options_MyStateSample | undefined)): void { diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-appstorage.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-appstorage.test.ts index 5809128c4..4269070a2 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-appstorage.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-appstorage.test.ts @@ -75,8 +75,8 @@ class Data { @Entry({useSharedStorage:false,storage:"",routeName:""}) @Component() final struct Index extends CustomComponent implements PageLifeCycle { public __initializeStruct(initializers: (__Options_Index | undefined), @memo() content: ((()=> void) | undefined)): void { - this.__backing_storageLink = STATE_MGMT_FACTORY.makeStorageLink(this, "PropA", "storageLink", 1) - this.__backing_storageLinkObject = STATE_MGMT_FACTORY.makeStorageLink(this, "PropB", "storageLinkObject", new Data(1)) + this.__backing_storageLink = STATE_MGMT_FACTORY.makeStorageLink(this, "PropA", "storageLink", 1); + this.__backing_storageLinkObject = STATE_MGMT_FACTORY.makeStorageLink(this, "PropB", "storageLinkObject", new Data(1)); } public __updateStruct(initializers: (__Options_Index | undefined)): void {} diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-complex-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-complex-type.test.ts index 265b6b03c..cdfc5bca6 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-complex-type.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-complex-type.test.ts @@ -136,13 +136,13 @@ final class Status extends BaseEnum { @Entry({useSharedStorage:false,storage:"",routeName:""}) @Component() final struct MyStateSample extends CustomComponent implements PageLifeCycle { public __initializeStruct(initializers: (__Options_MyStateSample | undefined), @memo() content: ((()=> void) | undefined)): void { - this.__backing_arrayA = STATE_MGMT_FACTORY.makeStorageLink>(this, "Prop1", "arrayA", [1, 2, 3]) - this.__backing_objectA = STATE_MGMT_FACTORY.makeStorageLink(this, "Prop2", "objectA", {}) - this.__backing_dateA = STATE_MGMT_FACTORY.makeStorageLink(this, "Prop3", "dateA", new Date("2021-08-08")) - this.__backing_setA = STATE_MGMT_FACTORY.makeStorageLink>(this, "Prop4", "setA", new Set()) - this.__backing_mapA = STATE_MGMT_FACTORY.makeStorageLink>(this, "Prop5", "mapA", new Map()) - this.__backing_classA = STATE_MGMT_FACTORY.makeStorageLink(this, "Prop7", "classA", new Person("John")) - this.__backing_enumA = STATE_MGMT_FACTORY.makeStorageLink(this, "Prop8", "enumA", Status.NotFound) + this.__backing_arrayA = STATE_MGMT_FACTORY.makeStorageLink>(this, "Prop1", "arrayA", [1, 2, 3]); + this.__backing_objectA = STATE_MGMT_FACTORY.makeStorageLink(this, "Prop2", "objectA", {}); + this.__backing_dateA = STATE_MGMT_FACTORY.makeStorageLink(this, "Prop3", "dateA", new Date("2021-08-08")); + this.__backing_setA = STATE_MGMT_FACTORY.makeStorageLink>(this, "Prop4", "setA", new Set()); + this.__backing_mapA = STATE_MGMT_FACTORY.makeStorageLink>(this, "Prop5", "mapA", new Map()); + this.__backing_classA = STATE_MGMT_FACTORY.makeStorageLink(this, "Prop7", "classA", new Person("John")); + this.__backing_enumA = STATE_MGMT_FACTORY.makeStorageLink(this, "Prop8", "enumA", Status.NotFound); } public __updateStruct(initializers: (__Options_MyStateSample | undefined)): void {} diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-primitive-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-primitive-type.test.ts index 7f3ec3c20..9b2fb6cd5 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-primitive-type.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/storagelink/storagelink-primitive-type.test.ts @@ -61,9 +61,9 @@ __EntryWrapper.RegisterNamedRouter("", new __EntryWrapper(), ({ @Entry({useSharedStorage:false,storage:"",routeName:""}) @Component() final struct MyStateSample extends CustomComponent implements PageLifeCycle { public __initializeStruct(initializers: (__Options_MyStateSample | undefined), @memo() content: ((()=> void) | undefined)): void { - this.__backing_numA = STATE_MGMT_FACTORY.makeStorageLink(this, "Prop1", "numA", 33) - this.__backing_stringA = STATE_MGMT_FACTORY.makeStorageLink(this, "Prop2", "stringA", "AA") - this.__backing_booleanA = STATE_MGMT_FACTORY.makeStorageLink(this, "Prop3", "booleanA", true) + this.__backing_numA = STATE_MGMT_FACTORY.makeStorageLink(this, "Prop1", "numA", 33); + this.__backing_stringA = STATE_MGMT_FACTORY.makeStorageLink(this, "Prop2", "stringA", "AA"); + this.__backing_booleanA = STATE_MGMT_FACTORY.makeStorageLink(this, "Prop3", "booleanA", true); } public __updateStruct(initializers: (__Options_MyStateSample | undefined)): void {} diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/storageprop-ref/storageprop-ref-complex-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/storageprop-ref/storageprop-ref-complex-type.test.ts index 6202824da..f7b381584 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/storageprop-ref/storageprop-ref-complex-type.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/storageprop-ref/storageprop-ref-complex-type.test.ts @@ -130,13 +130,13 @@ final class Status extends BaseEnum { @Component() final struct MyStateSample extends CustomComponent { public __initializeStruct(initializers: (__Options_MyStateSample | undefined), @memo() content: ((()=> void) | undefined)): void { - this.__backing_arrayB = STATE_MGMT_FACTORY.makeStoragePropRef>(this, "Prop1", "arrayB", [1, 2, 3]) - this.__backing_objectB = STATE_MGMT_FACTORY.makeStoragePropRef(this, "Prop2", "objectB", {}) - this.__backing_dateB = STATE_MGMT_FACTORY.makeStoragePropRef(this, "Prop3", "dateB", new Date("2021-09-09")) - this.__backing_setB = STATE_MGMT_FACTORY.makeStoragePropRef>(this, "Prop4", "setB", new Set()) - this.__backing_mapB = STATE_MGMT_FACTORY.makeStoragePropRef>(this, "Prop5", "mapB", new Map()) - this.__backing_classB = STATE_MGMT_FACTORY.makeStoragePropRef(this, "Prop7", "classB", new Person("Kevin")) - this.__backing_enumB = STATE_MGMT_FACTORY.makeStoragePropRef(this, "Prop8", "enumB", Status.NotFound) + this.__backing_arrayB = STATE_MGMT_FACTORY.makeStoragePropRef>(this, "Prop1", "arrayB", [1, 2, 3]); + this.__backing_objectB = STATE_MGMT_FACTORY.makeStoragePropRef(this, "Prop2", "objectB", {}); + this.__backing_dateB = STATE_MGMT_FACTORY.makeStoragePropRef(this, "Prop3", "dateB", new Date("2021-09-09")); + this.__backing_setB = STATE_MGMT_FACTORY.makeStoragePropRef>(this, "Prop4", "setB", new Set()); + this.__backing_mapB = STATE_MGMT_FACTORY.makeStoragePropRef>(this, "Prop5", "mapB", new Map()); + this.__backing_classB = STATE_MGMT_FACTORY.makeStoragePropRef(this, "Prop7", "classB", new Person("Kevin")); + this.__backing_enumB = STATE_MGMT_FACTORY.makeStoragePropRef(this, "Prop8", "enumB", Status.NotFound); } public __updateStruct(initializers: (__Options_MyStateSample | undefined)): void {} diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/storageprop-ref/storageprop-ref-primitive-type.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/storageprop-ref/storageprop-ref-primitive-type.test.ts index ad190b658..fb6d55472 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/storageprop-ref/storageprop-ref-primitive-type.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/storageprop-ref/storageprop-ref-primitive-type.test.ts @@ -55,11 +55,11 @@ function main() {} @Component() final struct MyStateSample extends CustomComponent { public __initializeStruct(initializers: (__Options_MyStateSample | undefined), @memo() content: ((()=> void) | undefined)): void { - this.__backing_numB = STATE_MGMT_FACTORY.makeStoragePropRef(this, "Prop1", "numB", 43) - this.__backing_stringB = STATE_MGMT_FACTORY.makeStoragePropRef(this, "Prop2", "stringB", "BB") - this.__backing_booleanB = STATE_MGMT_FACTORY.makeStoragePropRef(this, "Prop3", "booleanB", false) - this.__backing_undefinedB = STATE_MGMT_FACTORY.makeStoragePropRef(this, "Prop4", "undefinedB", undefined) - this.__backing_nullB = STATE_MGMT_FACTORY.makeStoragePropRef(this, "Prop5", "nullB", null) + this.__backing_numB = STATE_MGMT_FACTORY.makeStoragePropRef(this, "Prop1", "numB", 43); + this.__backing_stringB = STATE_MGMT_FACTORY.makeStoragePropRef(this, "Prop2", "stringB", "BB"); + this.__backing_booleanB = STATE_MGMT_FACTORY.makeStoragePropRef(this, "Prop3", "booleanB", false); + this.__backing_undefinedB = STATE_MGMT_FACTORY.makeStoragePropRef(this, "Prop4", "undefinedB", undefined); + this.__backing_nullB = STATE_MGMT_FACTORY.makeStoragePropRef(this, "Prop5", "nullB", null); } public __updateStruct(initializers: (__Options_MyStateSample | undefined)): void {} diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/watch/watch-basic.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/watch/watch-basic.test.ts index c4a9f9255..9411b0e0e 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/watch/watch-basic.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/watch/watch-basic.test.ts @@ -164,7 +164,7 @@ __EntryWrapper.RegisterNamedRouter("", new __EntryWrapper(), ({ this.__backing_linkvar = STATE_MGMT_FACTORY.makeLink(this, "linkvar", initializers!.__backing_linkvar!, ((_: string): void => { this.linkOnChange(_); })); - }; + } this.__backing_storagelinkvar = STATE_MGMT_FACTORY.makeStorageLink(this, "prop1", "storagelinkvar", "Hello World", ((_: string): void => { this.storageLinkOnChange(_); })) -- Gitee From 50205245d811f922f6543e3ada91f3931fa39f5f Mon Sep 17 00:00:00 2001 From: Aleksandr Veselov Date: Wed, 3 Sep 2025 18:17:28 +0300 Subject: [PATCH 22/39] Ignore blank lines between imports while comparing Signed-off-by: Aleksandr Veselov Change-Id: Ic841b37e2cc1a81860a7553b54fce32bfa906ca3 --- arkui-plugins/test/utils/parse-string.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/arkui-plugins/test/utils/parse-string.ts b/arkui-plugins/test/utils/parse-string.ts index bd3c42530..69430d5a7 100644 --- a/arkui-plugins/test/utils/parse-string.ts +++ b/arkui-plugins/test/utils/parse-string.ts @@ -27,7 +27,7 @@ function organizeImports(str: string): string { let imports: string[] = []; str = str.replaceAll(/^\s*import.*from.*$/gm, (importLine) => { imports.push(importLine.trim()); return "" }); imports.sort() - return [...imports, str].join("\n") + return [...imports, "", str.trimStart()].join("\n") } function filterSource(text: string): string { -- Gitee From bed13a91b2f96e2f0498fbe792c5d83a7320033f Mon Sep 17 00:00:00 2001 From: Aleksandr Veselov Date: Wed, 3 Sep 2025 19:05:04 +0300 Subject: [PATCH 23/39] Add some missing annotation parameters Signed-off-by: Aleksandr Veselov Change-Id: I3575c52f0ad151881200be76465b866f6ae7eca8 --- .../memo-plugins/function-transformer.ts | 27 ++++++++++--------- .../memo-plugins/memo-cache-factory.ts | 5 ++-- .../memo-plugins/parameter-transformer.ts | 2 +- .../memo-plugins/return-transformer.ts | 3 ++- .../builder-factory.ts | 2 +- .../builder-lambda-translators/factory.ts | 2 +- .../ui-plugins/struct-translators/factory.ts | 5 ++-- 7 files changed, 26 insertions(+), 20 deletions(-) diff --git a/arkui-plugins/memo-plugins/function-transformer.ts b/arkui-plugins/memo-plugins/function-transformer.ts index ee8641f20..fca35e2d3 100644 --- a/arkui-plugins/memo-plugins/function-transformer.ts +++ b/arkui-plugins/memo-plugins/function-transformer.ts @@ -350,7 +350,7 @@ export class FunctionTransformer extends AbstractVisitor { const res = this.updateScriptFunction(it.function!); this.exitAnonymousScope(); this.modified = true; - return arkts.factory.updateArrowFunctionExpression(it, res); + return arkts.factory.updateArrowFunctionExpression(it, res, it.annotations); } return it; }); @@ -382,7 +382,8 @@ export class FunctionTransformer extends AbstractVisitor { if (isStandaloneArrowFunction(node.callee!)) { newExpression = arkts.factory.updateArrowFunctionExpression( node.callee, - this.signatureTransformer.visitor(node.callee.function!) + this.signatureTransformer.visitor(node.callee.function!), + node.callee.annotations ); } const that = this; @@ -392,7 +393,7 @@ export class FunctionTransformer extends AbstractVisitor { const res = that.updateScriptFunction(it.function!); that.exitAnonymousScope(); that.modified = true; - return arkts.factory.updateArrowFunctionExpression(it, res); + return arkts.factory.updateArrowFunctionExpression(it, res, it.annotations); } return it; }); @@ -423,7 +424,7 @@ export class FunctionTransformer extends AbstractVisitor { this.modified = true; return arkts.factory.updateCallExpression( node, - arkts.factory.updateArrowFunctionExpression(expression, res), + arkts.factory.updateArrowFunctionExpression(expression, res, expression.annotations), [...factory.createHiddenArguments(this.positionalIdTracker.id()), ...newNode.arguments], newNode.typeParams ); @@ -490,10 +491,11 @@ export class FunctionTransformer extends AbstractVisitor { } this.modified = true; + const nodeArrowFunction = castArrowFunctionExpression(node.value); return arkts.factory.updateClassProperty( node, node.key, - res ? arkts.factory.updateArrowFunctionExpression(castArrowFunctionExpression(node.value), res) : undefined, + res ? arkts.factory.updateArrowFunctionExpression(nodeArrowFunction, res, nodeArrowFunction.annotations) : undefined, typeAnnotation, node.modifiers, node.isComputed @@ -539,7 +541,7 @@ export class FunctionTransformer extends AbstractVisitor { } this.exitAnonymousScope(); if (!scope.isMemo) { - return arkts.factory.updateArrowFunctionExpression(node, this.signatureTransformer.visitor(node.function!)); + return arkts.factory.updateArrowFunctionExpression(node, this.signatureTransformer.visitor(node.function!), node.annotations); } this.enterAnonymousScope(node.function!); @@ -547,7 +549,7 @@ export class FunctionTransformer extends AbstractVisitor { this.exitAnonymousScope(); this.modified = true; - return arkts.factory.updateArrowFunctionExpression(node, this.signatureTransformer.visitor(res)); + return arkts.factory.updateArrowFunctionExpression(node, this.signatureTransformer.visitor(res), node.annotations); } private updateVariableDeclarator(node: arkts.VariableDeclarator): arkts.VariableDeclarator { @@ -565,7 +567,8 @@ export class FunctionTransformer extends AbstractVisitor { node.id, arkts.factory.updateArrowFunctionExpression( node.init, - this.signatureTransformer.visitor(node.init.function!) + this.signatureTransformer.visitor(node.init.function!), + node.init.annotations ) ); } @@ -586,7 +589,7 @@ export class FunctionTransformer extends AbstractVisitor { this.enterAnonymousScope(initializer.function!); const res = this.updateScriptFunction(initializer.function!, initializer.function!.id?.name); this.exitAnonymousScope(); - initializer = arkts.factory.updateArrowFunctionExpression(initializer, res); + initializer = arkts.factory.updateArrowFunctionExpression(initializer, res, initializer.annotations); } this.modified = true; @@ -625,7 +628,7 @@ export class FunctionTransformer extends AbstractVisitor { this.modified = true; return arkts.factory.updateTSAsExpression( node, - arkts.factory.updateArrowFunctionExpression(expr, res), + arkts.factory.updateArrowFunctionExpression(expr, res, expr.annotations), typeAnnotation, node.isConst ); @@ -654,7 +657,7 @@ export class FunctionTransformer extends AbstractVisitor { node, node.kind, key, - arkts.factory.updateArrowFunctionExpression(value, res), + arkts.factory.updateArrowFunctionExpression(value, res, value.annotations), node.isMethod, node.isComputed ); @@ -683,7 +686,7 @@ export class FunctionTransformer extends AbstractVisitor { return arkts.factory.updateAssignmentExpression( node, node.left!, - arkts.factory.updateArrowFunctionExpression(right, res), + arkts.factory.updateArrowFunctionExpression(right, res, right.annotations), node.operatorType ); } diff --git a/arkui-plugins/memo-plugins/memo-cache-factory.ts b/arkui-plugins/memo-plugins/memo-cache-factory.ts index 529cb48a2..d2683bd94 100644 --- a/arkui-plugins/memo-plugins/memo-cache-factory.ts +++ b/arkui-plugins/memo-plugins/memo-cache-factory.ts @@ -118,7 +118,7 @@ export class RewriteFactory { return node; } node.setTypeAnnotation(RewriteFactory.rewriteType(node.typeAnnotation, metadata)); - return arkts.factory.updateETSParameterExpression(node, node.ident, node.isOptional, node.initializer); + return arkts.factory.updateETSParameterExpression(node, node.ident, node.isOptional, node.initializer, node.annotations); } static rewriteProperty(node: arkts.Property, metadata?: CachedMetadata): arkts.Property { @@ -152,7 +152,8 @@ export class RewriteFactory { ): arkts.ArrowFunctionExpression { return arkts.factory.updateArrowFunctionExpression( node, - RewriteFactory.rewriteScriptFunction(node.function!, metadata, expectReturn) + RewriteFactory.rewriteScriptFunction(node.function!, metadata, expectReturn), + node.annotations ); } diff --git a/arkui-plugins/memo-plugins/parameter-transformer.ts b/arkui-plugins/memo-plugins/parameter-transformer.ts index ef7a502ba..64d97566c 100644 --- a/arkui-plugins/memo-plugins/parameter-transformer.ts +++ b/arkui-plugins/memo-plugins/parameter-transformer.ts @@ -173,7 +173,7 @@ export class ParameterTransformer extends AbstractVisitor { paramaterTransformer.reset(); returnTransformer.reset(); this.track(updateScriptFunction.body); - return arkts.factory.updateArrowFunctionExpression(initializer, updateScriptFunction); + return arkts.factory.updateArrowFunctionExpression(initializer, updateScriptFunction, initializer.annotations); } private updateVariableDeclareInit( diff --git a/arkui-plugins/memo-plugins/return-transformer.ts b/arkui-plugins/memo-plugins/return-transformer.ts index f11701677..b3eda7789 100644 --- a/arkui-plugins/memo-plugins/return-transformer.ts +++ b/arkui-plugins/memo-plugins/return-transformer.ts @@ -74,7 +74,8 @@ export class ReturnTransformer extends AbstractVisitor { ) { argument = arkts.factory.updateArrowFunctionExpression( argument, - factory.updateScriptFunctionWithMemoParameters(argument.function!) + factory.updateScriptFunctionWithMemoParameters(argument.function!), + argument.annotations ); } diff --git a/arkui-plugins/ui-plugins/builder-lambda-translators/builder-factory.ts b/arkui-plugins/ui-plugins/builder-lambda-translators/builder-factory.ts index 049107fab..6afe5c14b 100644 --- a/arkui-plugins/ui-plugins/builder-lambda-translators/builder-factory.ts +++ b/arkui-plugins/ui-plugins/builder-lambda-translators/builder-factory.ts @@ -99,7 +99,7 @@ export class BuilderFactory { ): arkts.ArrowFunctionExpression { const _node = coerceToAstNode(node); const newFunc = BuilderFactory.rewriteBuilderScriptFunction(_node.function!); - return arkts.factory.updateArrowFunctionExpression(_node, newFunc); + return arkts.factory.updateArrowFunctionExpression(_node, newFunc, _node.annotations); } /** diff --git a/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts b/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts index 54bbdda1b..099a81cf1 100644 --- a/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts +++ b/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts @@ -381,7 +381,7 @@ export class factory { func.id, func.annotations ); - return arkts.factory.updateArrowFunctionExpression(arg, updateFunc); + return arkts.factory.updateArrowFunctionExpression(arg, updateFunc, arg.annotations); } /** diff --git a/arkui-plugins/ui-plugins/struct-translators/factory.ts b/arkui-plugins/ui-plugins/struct-translators/factory.ts index 910385d8c..b8486fc57 100644 --- a/arkui-plugins/ui-plugins/struct-translators/factory.ts +++ b/arkui-plugins/ui-plugins/struct-translators/factory.ts @@ -183,7 +183,8 @@ export class factory { param, arkts.factory.createIdentifier(param.ident!.name, newType), false, - param.initializer + param.initializer, + param.annotations ); if (!!newParam) { return UIFactory.updateMethodDefinition(builderNode, { function: { params: [newParam] } }); @@ -1209,7 +1210,7 @@ export class factory { }); return arkts.factory.updateCallExpression(value, value.callee, [ value.arguments[0], - arkts.factory.updateArrowFunctionExpression(value.arguments[1], newScript), + arkts.factory.updateArrowFunctionExpression(value.arguments[1], newScript, value.arguments[1].annotations), ...value.arguments.slice(2), ], value.typeParams); } -- Gitee From 76e145962e313cbe7ce9861d5faeed2d2c03d147 Mon Sep 17 00:00:00 2001 From: Aleksandr Veselov Date: Wed, 3 Sep 2025 19:39:13 +0300 Subject: [PATCH 24/39] Add missing parameters in update functions Signed-off-by: Aleksandr Veselov Change-Id: Ibdee350977b70552fd4b48cbadef5282fa6726b2 --- .../interop-plugins/decl_transformer.ts | 7 ++++--- .../memo-plugins/function-transformer.ts | 20 +++++++++++-------- .../memo-plugins/memo-cache-factory.ts | 7 ++++--- arkui-plugins/memo-plugins/memo-factory.ts | 8 ++++++-- .../memo-plugins/signature-transformer.ts | 3 ++- .../objectlink/objectlink-basic.test.ts | 8 ++++---- .../objectlink/objectlink-observed.test.ts | 2 +- .../builder-factory.ts | 5 +++-- .../builder-lambda-translators/factory.ts | 2 +- .../style-internals-visitor.ts | 5 ++++- .../ui-plugins/interop/builder-interop.ts | 5 ++++- arkui-plugins/ui-plugins/interop/interop.ts | 3 +++ .../ui-plugins/interop/legacy-transformer.ts | 3 ++- .../property-translators/observedTrack.ts | 6 ++++-- .../property-translators/observedV2Trace.ts | 6 ++++-- .../ui-plugins/struct-translators/factory.ts | 8 ++++++-- 16 files changed, 64 insertions(+), 34 deletions(-) diff --git a/arkui-plugins/interop-plugins/decl_transformer.ts b/arkui-plugins/interop-plugins/decl_transformer.ts index 57194a598..4acffd1b1 100644 --- a/arkui-plugins/interop-plugins/decl_transformer.ts +++ b/arkui-plugins/interop-plugins/decl_transformer.ts @@ -100,8 +100,8 @@ export class DeclTransformer extends AbstractVisitor { false, func?.flags, func?.modifiers, - undefined, - undefined + func.id, + func.annotations, ); return arkts.factory.updateMethodDefinition( @@ -113,7 +113,8 @@ export class DeclTransformer extends AbstractVisitor { ), arkts.factory.createFunctionExpression(func.id?.clone(), updateFunc), node.modifiers, - false + false, + node.overloads ); } diff --git a/arkui-plugins/memo-plugins/function-transformer.ts b/arkui-plugins/memo-plugins/function-transformer.ts index fca35e2d3..98be4e324 100644 --- a/arkui-plugins/memo-plugins/function-transformer.ts +++ b/arkui-plugins/memo-plugins/function-transformer.ts @@ -317,7 +317,8 @@ export class FunctionTransformer extends AbstractVisitor { ) ), node.modifierFlags, - false + false, + node.overloads ); } else { updateMethod = arkts.factory.updateMethodDefinition( @@ -328,7 +329,8 @@ export class FunctionTransformer extends AbstractVisitor { this.signatureTransformer.visitor(node.function!) ), node.modifierFlags, - false + false, + node.overloads ); } this.modified ||= this.signatureTransformer.modified; @@ -369,7 +371,7 @@ export class FunctionTransformer extends AbstractVisitor { updatedArguments = moveToFront(updatedArguments, 2); } this.modified = true; - return arkts.factory.updateCallExpression(node, node.callee, updatedArguments, node.typeParams); + return arkts.factory.updateCallExpression(node, node.callee, updatedArguments, node.typeParams, node.isOptional, node.hasTrailingComma, node.trailingBlock); } private updateDeclaredCallWithName(node: arkts.CallExpression, name: string): arkts.CallExpression { @@ -398,7 +400,7 @@ export class FunctionTransformer extends AbstractVisitor { return it; }); this.modified ||= this.signatureTransformer.modified; - return arkts.factory.updateCallExpression(node, newExpression, updatedArguments, node.typeParams); + return arkts.factory.updateCallExpression(node, newExpression, updatedArguments, node.typeParams, node.isOptional, node.hasTrailingComma, node.trailingBlock ); } private updateAnonymousMemoCall( @@ -426,7 +428,7 @@ export class FunctionTransformer extends AbstractVisitor { node, arkts.factory.updateArrowFunctionExpression(expression, res, expression.annotations), [...factory.createHiddenArguments(this.positionalIdTracker.id()), ...newNode.arguments], - newNode.typeParams + newNode.typeParams, node.isOptional, node.hasTrailingComma, node.trailingBlock ); } @@ -498,7 +500,8 @@ export class FunctionTransformer extends AbstractVisitor { res ? arkts.factory.updateArrowFunctionExpression(nodeArrowFunction, res, nodeArrowFunction.annotations) : undefined, typeAnnotation, node.modifiers, - node.isComputed + node.isComputed, + node.annotations ); } @@ -515,7 +518,8 @@ export class FunctionTransformer extends AbstractVisitor { node, node.id, node.typeParams, - this.signatureTransformer.visitor(node.typeAnnotation) + this.signatureTransformer.visitor(node.typeAnnotation), + node.annotations ); this.modified ||= this.signatureTransformer.modified; return newNode; @@ -530,7 +534,7 @@ export class FunctionTransformer extends AbstractVisitor { } this.modified = true; - return arkts.factory.updateTSTypeAliasDeclaration(node, node.id, node.typeParams, typeAnnotation); + return arkts.factory.updateTSTypeAliasDeclaration(node, node.id, node.typeParams, typeAnnotation, node.annotations); } private updateStandaloneArrowFunction(node: arkts.ArrowFunctionExpression): arkts.ArrowFunctionExpression { diff --git a/arkui-plugins/memo-plugins/memo-cache-factory.ts b/arkui-plugins/memo-plugins/memo-cache-factory.ts index d2683bd94..6344e29e9 100644 --- a/arkui-plugins/memo-plugins/memo-cache-factory.ts +++ b/arkui-plugins/memo-plugins/memo-cache-factory.ts @@ -107,7 +107,7 @@ export class RewriteFactory { return node; } const newNodeType = RewriteFactory.rewriteType(node.typeAnnotation)!; - return arkts.factory.updateTSTypeAliasDeclaration(node, node.id, node.typeParams, newNodeType); + return arkts.factory.updateTSTypeAliasDeclaration(node, node.id, node.typeParams, newNodeType, node.annotations); } static rewriteParameter( @@ -142,7 +142,7 @@ export class RewriteFactory { !!node.value && arkts.isArrowFunctionExpression(node.value) ? RewriteFactory.rewriteArrowFunction(node.value, metadata) : node.value; - return arkts.factory.updateClassProperty(node, node.key, newValue, newType, node.modifiers, node.isComputed); + return arkts.factory.updateClassProperty(node, node.key, newValue, newType, node.modifiers, node.isComputed, node.annotations); } static rewriteArrowFunction( @@ -273,7 +273,8 @@ export class RewriteFactory { }) ), node.modifiers, - false + false, + node.overloads ); return newNode; } diff --git a/arkui-plugins/memo-plugins/memo-factory.ts b/arkui-plugins/memo-plugins/memo-factory.ts index 5c3f6489e..de1d7bfa7 100644 --- a/arkui-plugins/memo-plugins/memo-factory.ts +++ b/arkui-plugins/memo-plugins/memo-factory.ts @@ -108,7 +108,8 @@ export class factory { factory.createHiddenParameterIfNotAdded(type.params, hasReceiver), type.returnType, false, - arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, + type.annotations ); } static updateScriptFunctionWithMemoParameters( @@ -444,7 +445,10 @@ export class factory { node, node.callee, expressionArgs, - node.typeParams + node.typeParams, + node.isOptional, + node.hasTrailingComma, + node.trailingBlock ); } } diff --git a/arkui-plugins/memo-plugins/signature-transformer.ts b/arkui-plugins/memo-plugins/signature-transformer.ts index 793b9e283..fcd26b8a2 100644 --- a/arkui-plugins/memo-plugins/signature-transformer.ts +++ b/arkui-plugins/memo-plugins/signature-transformer.ts @@ -109,7 +109,8 @@ export class SignatureTransformer extends AbstractVisitor { memo ? factory.createHiddenParameterIfNotAdded(newParams) : newParams, this.visitor(node.returnType!), false, - arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, + node.annotations ) as any as T; } if (arkts.isETSUnionType(node)) { diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/objectlink/objectlink-basic.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/objectlink/objectlink-basic.test.ts index 9f377e590..4ccfdba0c 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/objectlink/objectlink-basic.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/objectlink/objectlink-basic.test.ts @@ -134,7 +134,7 @@ function main() {} @Component() final struct MyStateSample extends CustomComponent { public __initializeStruct(initializers: (__Options_MyStateSample | undefined), @memo() content: ((()=> void) | undefined)): void { this.__backing_objectlinkvar = STATE_MGMT_FACTORY.makeObjectLink(this, "objectlinkvar", (({let gensym___248819442 = initializers; - (((gensym___248819442) == (null)) ? undefined : gensym___248819442.objectlinkvar)}) as A)) + (((gensym___248819442) == (null)) ? undefined : gensym___248819442.objectlinkvar)}) as A)); } public __updateStruct(initializers: (__Options_MyStateSample | undefined)): void { @@ -159,11 +159,11 @@ function main() {} @Component() final struct MyStateSample2 extends CustomComponent { public __initializeStruct(initializers: (__Options_MyStateSample2 | undefined), @memo() content: ((()=> void) | undefined)): void { this.__backing_objectlinkvar1 = STATE_MGMT_FACTORY.makeObjectLink<(A | undefined)>(this, "objectlinkvar1", (({let gensym___219806589 = initializers; - (((gensym___219806589) == (null)) ? undefined : gensym___219806589.objectlinkvar1)}) as (A | undefined))) + (((gensym___219806589) == (null)) ? undefined : gensym___219806589.objectlinkvar1)}) as (A | undefined))); this.__backing_objectlinkvar2 = STATE_MGMT_FACTORY.makeObjectLink<(A | B)>(this, "objectlinkvar2", (({let gensym___217261862 = initializers; - (((gensym___217261862) == (null)) ? undefined : gensym___217261862.objectlinkvar2)}) as (A | B))) + (((gensym___217261862) == (null)) ? undefined : gensym___217261862.objectlinkvar2)}) as (A | B))); this.__backing_objectlinkvar3 = STATE_MGMT_FACTORY.makeObjectLink<(A | B | null)>(this, "objectlinkvar3", (({let gensym___199257778 = initializers; - (((gensym___199257778) == (null)) ? undefined : gensym___199257778.objectlinkvar3)}) as (A | B | null))) + (((gensym___199257778) == (null)) ? undefined : gensym___199257778.objectlinkvar3)}) as (A | B | null))); } public __updateStruct(initializers: (__Options_MyStateSample2 | undefined)): void { diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/objectlink/objectlink-observed.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/objectlink/objectlink-observed.test.ts index 7f1cbcf13..05c26773a 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/objectlink/objectlink-observed.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/objectlink/objectlink-observed.test.ts @@ -180,7 +180,7 @@ __EntryWrapper.RegisterNamedRouter("", new __EntryWrapper(), ({ this.__backing_label = ((({let gensym___171896504 = initializers; (((gensym___171896504) == (null)) ? undefined : gensym___171896504.label)})) ?? ("date")); this.__backing_data = STATE_MGMT_FACTORY.makeObjectLink(this, "data", (({let gensym___209155591 = initializers; - (((gensym___209155591) == (null)) ? undefined : gensym___209155591.data)}) as DateClass)) + (((gensym___209155591) == (null)) ? undefined : gensym___209155591.data)}) as DateClass)); } public __updateStruct(initializers: (__Options_Child | undefined)): void { diff --git a/arkui-plugins/ui-plugins/builder-lambda-translators/builder-factory.ts b/arkui-plugins/ui-plugins/builder-lambda-translators/builder-factory.ts index 6afe5c14b..8400aabb1 100644 --- a/arkui-plugins/ui-plugins/builder-lambda-translators/builder-factory.ts +++ b/arkui-plugins/ui-plugins/builder-lambda-translators/builder-factory.ts @@ -74,7 +74,8 @@ export class BuilderFactory { newValue, _node.typeAnnotation, _node.modifiers, - false + false, + _node.annotations ); } @@ -148,7 +149,7 @@ export class BuilderFactory { } else { newArgument = BuilderLambdaFactory.createBuilderParameterProxyCall(arg, typeRef, isFromClass); } - return arkts.factory.updateCallExpression(_node, _node.callee, [newArgument], _node.typeParams); + return arkts.factory.updateCallExpression(_node, _node.callee, [newArgument], _node.typeParams, _node.isOptional, _node.hasTrailingComma, _node.trailingBlock); } } diff --git a/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts b/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts index 099a81cf1..7abd27c5b 100644 --- a/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts +++ b/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts @@ -994,7 +994,7 @@ export class factory { lambdaBodyInfo.lambdaBody = lambdaBody; const args: (arkts.Expression | undefined)[] = this.generateArgsInBuilderLambda(leaf, lambdaBodyInfo, declInfo); - const newNode = arkts.factory.updateCallExpression(node, replace, filterDefined(args), leaf.typeParams); + const newNode = arkts.factory.updateCallExpression(node, replace, filterDefined(args), leaf.typeParams, node.isOptional, node.hasTrailingComma, node.trailingBlock); NodeCache.getInstance().collect(newNode); return newNode; } diff --git a/arkui-plugins/ui-plugins/builder-lambda-translators/style-internals-visitor.ts b/arkui-plugins/ui-plugins/builder-lambda-translators/style-internals-visitor.ts index 68c070186..8afb325ac 100644 --- a/arkui-plugins/ui-plugins/builder-lambda-translators/style-internals-visitor.ts +++ b/arkui-plugins/ui-plugins/builder-lambda-translators/style-internals-visitor.ts @@ -46,7 +46,10 @@ export class StyleInternalsVisitor extends AbstractVisitor { node, node.callee, this.initCallArgs, - typeParams + typeParams, + node.isOptional, + node.hasTrailingComma, + node.trailingBlock ); } return this.visitEachChild(node); diff --git a/arkui-plugins/ui-plugins/interop/builder-interop.ts b/arkui-plugins/ui-plugins/interop/builder-interop.ts index 330d8d0f5..9e1c6b943 100644 --- a/arkui-plugins/ui-plugins/interop/builder-interop.ts +++ b/arkui-plugins/ui-plugins/interop/builder-interop.ts @@ -519,7 +519,10 @@ export function generateBuilderCompatible(node: arkts.CallExpression, moduleName initializer, updater, ], - undefined + undefined, + node.isOptional, + node.hasTrailingComma, + node.trailingBlock ); NodeCache.getInstance().collect(result); return result; diff --git a/arkui-plugins/ui-plugins/interop/interop.ts b/arkui-plugins/ui-plugins/interop/interop.ts index d27fdb705..cd4ccbf69 100644 --- a/arkui-plugins/ui-plugins/interop/interop.ts +++ b/arkui-plugins/ui-plugins/interop/interop.ts @@ -451,6 +451,9 @@ export function generateArkUICompatible(node: arkts.CallExpression): arkts.CallE arkts.factory.createThisExpression(), ], undefined, + node.isOptional, + node.hasTrailingComma, + node.trailingBlock ); NodeCache.getInstance().collect(result); return result; diff --git a/arkui-plugins/ui-plugins/interop/legacy-transformer.ts b/arkui-plugins/ui-plugins/interop/legacy-transformer.ts index 0c45d6be0..b6653b935 100644 --- a/arkui-plugins/ui-plugins/interop/legacy-transformer.ts +++ b/arkui-plugins/ui-plugins/interop/legacy-transformer.ts @@ -218,7 +218,8 @@ export class LegacyTransformer extends AbstractVisitor { node.id, arkts.factory.createFunctionExpression(node.id?.clone(), script), node.modifiers, - false + false, + node.overloads ); } diff --git a/arkui-plugins/ui-plugins/property-translators/observedTrack.ts b/arkui-plugins/ui-plugins/property-translators/observedTrack.ts index 2c8496aae..070bb3efe 100644 --- a/arkui-plugins/ui-plugins/property-translators/observedTrack.ts +++ b/arkui-plugins/ui-plugins/property-translators/observedTrack.ts @@ -168,7 +168,8 @@ export class ObservedTrackTranslator extends ObservedPropertyTranslator { .addFlag(arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD) ), originGetter.modifiers, - false + false, + originGetter.overloads ); arkts.factory.updateMethodDefinition( originSetter, @@ -179,7 +180,8 @@ export class ObservedTrackTranslator extends ObservedPropertyTranslator { .addFlag(arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD) ), originSetter.modifiers, - false + false, + originSetter.overloads ); this.classScopeInfo.getters[idx] = updateGetter; } diff --git a/arkui-plugins/ui-plugins/property-translators/observedV2Trace.ts b/arkui-plugins/ui-plugins/property-translators/observedV2Trace.ts index f6c96736a..9037b200e 100644 --- a/arkui-plugins/ui-plugins/property-translators/observedV2Trace.ts +++ b/arkui-plugins/ui-plugins/property-translators/observedV2Trace.ts @@ -179,7 +179,8 @@ export class ObservedV2TraceTranslator extends ObservedPropertyTranslator { .addFlag(arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD) ), originGetter.modifiers, - false + false, + originGetter.overloads ); arkts.factory.updateMethodDefinition( originSetter, @@ -190,7 +191,8 @@ export class ObservedV2TraceTranslator extends ObservedPropertyTranslator { .addFlag(arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD) ), originSetter.modifiers, - false + false, + originSetter.overloads ); this.classScopeInfo.getters[idx] = updateGetter; } diff --git a/arkui-plugins/ui-plugins/struct-translators/factory.ts b/arkui-plugins/ui-plugins/struct-translators/factory.ts index b8486fc57..cfdade32d 100644 --- a/arkui-plugins/ui-plugins/struct-translators/factory.ts +++ b/arkui-plugins/ui-plugins/struct-translators/factory.ts @@ -791,6 +791,9 @@ export class factory { arkts.factory.createIdentifier(transformedKey), args, undefined, + resourceNode.isOptional, + resourceNode.hasTrailingComma, + resourceNode.trailingBlock ); } @@ -881,7 +884,8 @@ export class factory { member.id!, arkts.factory.createFunctionExpression(member.id?.clone(), factory.transformAnimatableExtend(member.function!)), member.modifiers, - false + false, + member.overloads ); } return member; @@ -1212,7 +1216,7 @@ export class factory { value.arguments[0], arkts.factory.updateArrowFunctionExpression(value.arguments[1], newScript, value.arguments[1].annotations), ...value.arguments.slice(2), - ], value.typeParams); + ], value.typeParams, value.isOptional, value.hasTrailingComma, value.trailingBlock); } return value; } -- Gitee From 04f81c0179d2fa42fa7c426fdd246f381a29eff3 Mon Sep 17 00:00:00 2001 From: Aleksandr Veselov Date: Wed, 3 Sep 2025 19:52:15 +0300 Subject: [PATCH 25/39] Update test cases Signed-off-by: Aleksandr Veselov Change-Id: I69a4df3b8ab25b8e57d2cd4b5777a4f0c74a0955 --- .../builder-lambda/condition-scope/with-builder.test.ts | 2 +- .../test/ut/ui-plugins/decorators/watch/watch-basic.test.ts | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/arkui-plugins/test/ut/ui-plugins/builder-lambda/condition-scope/with-builder.test.ts b/arkui-plugins/test/ut/ui-plugins/builder-lambda/condition-scope/with-builder.test.ts index c4b753b66..aa41e543b 100644 --- a/arkui-plugins/test/ut/ui-plugins/builder-lambda/condition-scope/with-builder.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/builder-lambda/condition-scope/with-builder.test.ts @@ -146,7 +146,7 @@ function main() {} })); } })); - }))) + }))); } public __updateStruct(initializers: (__Options_Child | undefined)): void {} private __backing_myBuilderParam?: @memo() (()=> void); diff --git a/arkui-plugins/test/ut/ui-plugins/decorators/watch/watch-basic.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/watch/watch-basic.test.ts index 9411b0e0e..b926185bd 100644 --- a/arkui-plugins/test/ut/ui-plugins/decorators/watch/watch-basic.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/decorators/watch/watch-basic.test.ts @@ -167,14 +167,14 @@ __EntryWrapper.RegisterNamedRouter("", new __EntryWrapper(), ({ } this.__backing_storagelinkvar = STATE_MGMT_FACTORY.makeStorageLink(this, "prop1", "storagelinkvar", "Hello World", ((_: string): void => { this.storageLinkOnChange(_); - })) + })); this.__backing_storagepropvar = STATE_MGMT_FACTORY.makeStoragePropRef(this, "prop2", "storagepropvar", "Hello World", ((_: string): void => { this.storagePropOnChange(_); - })) + })); this.__backing_objectlinkvar = STATE_MGMT_FACTORY.makeObjectLink(this, "objectlinkvar", (({let gensym___172556967 = initializers; (((gensym___172556967) == (null)) ? undefined : gensym___172556967.objectlinkvar)}) as A), ((_: string): void => { this.objectLinkOnChange(_); - })) + })); this.__backing_providevar = STATE_MGMT_FACTORY.makeProvide(this, "providevar", "providevar", ((({let gensym___244584558 = initializers; (((gensym___244584558) == (null)) ? undefined : gensym___244584558.providevar)})) ?? ("Hello World")), false, ((_: string): void => { this.ProvideOnChange(_); -- Gitee From 5d0d6ac42b240cd41a036a86731117afbd93bab6 Mon Sep 17 00:00:00 2001 From: Aleksandr Veselov Date: Wed, 3 Sep 2025 19:52:49 +0300 Subject: [PATCH 26/39] Force NodeCache updates on some node updates Signed-off-by: Aleksandr Veselov Change-Id: Id664ac7d060a2e248a29a995e0aa708119e98d64 --- arkui-plugins/common/node-cache.ts | 32 ++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/arkui-plugins/common/node-cache.ts b/arkui-plugins/common/node-cache.ts index baba1fa82..be19cedc1 100644 --- a/arkui-plugins/common/node-cache.ts +++ b/arkui-plugins/common/node-cache.ts @@ -46,6 +46,23 @@ export class NodeCache { if (!this.instance) { this.instance = new NodeCache(); } + + // Please provide the another way to force cache update on when node updates + wrapFuncWithNodeCache(this.instance, "updateArrowFunctionExpression") + wrapFuncWithNodeCache(this.instance, "updateBreakStatement") + wrapFuncWithNodeCache(this.instance, "updateCallExpression") + wrapFuncWithNodeCache(this.instance, "updateClassProperty") + wrapFuncWithNodeCache(this.instance, "updateETSFunctionType") + wrapFuncWithNodeCache(this.instance, "updateETSParameterExpression") + wrapFuncWithNodeCache(this.instance, "updateETSUnionType") + wrapFuncWithNodeCache(this.instance, "updateIdentifier") + wrapFuncWithNodeCache(this.instance, "updateMethodDefinition") + wrapFuncWithNodeCache(this.instance, "updateProperty") + wrapFuncWithNodeCache(this.instance, "updateReturnStatement") + wrapFuncWithNodeCache(this.instance, "updateScriptFunction") + wrapFuncWithNodeCache(this.instance, "updateTSTypeAliasDeclaration") + wrapFuncWithNodeCache(this.instance, "updateVariableDeclarator") + return this.instance; } @@ -98,3 +115,18 @@ export class NodeCache { }); } } + +function wrapFuncWithNodeCache(cache: NodeCache, funcName: keyof typeof arkts.factory) { + if ((funcName+"__orig") in arkts.factory) return; + + let orig = arkts.factory[funcName] as any; + let wrapped = function (this: any, original: arkts.AstNode, ...args: any[]) { + let newNode = orig.call(this, original, ...args); + if (cache.has(original)) { + cache.refresh(original, newNode); + } + return newNode + }; + (arkts.factory as any)[funcName] = wrapped as any; + (arkts.factory as any)[funcName+"__orig"] = orig as any; +} \ No newline at end of file -- Gitee From 1e0bff66e1e604e487208953fd9b354b46872da1 Mon Sep 17 00:00:00 2001 From: Aleksandr Veselov Date: Wed, 3 Sep 2025 20:13:06 +0300 Subject: [PATCH 27/39] Fix api usage Signed-off-by: Aleksandr Veselov Change-Id: I9e6b80cdb80ee49d8f37e3aa32e7f64fdfe92c23 --- arkui-plugins/ui-plugins/component-transformer.ts | 6 +++--- arkui-plugins/ui-plugins/entry-translators/factory.ts | 5 ++--- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/arkui-plugins/ui-plugins/component-transformer.ts b/arkui-plugins/ui-plugins/component-transformer.ts index 11060e07f..cbc210b54 100644 --- a/arkui-plugins/ui-plugins/component-transformer.ts +++ b/arkui-plugins/ui-plugins/component-transformer.ts @@ -410,9 +410,9 @@ export class ComponentTransformer extends AbstractVisitor { ...staticMethodBody, ], definition.modifiers, - arkts.classDefinitionFlags(definition) | arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_FINAL - ) - .setAnnotations(definition.annotations); + arkts.classDefinitionFlags(definition) | arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_FINAL, + definition.annotations + ); } generateComponentInterface( diff --git a/arkui-plugins/ui-plugins/entry-translators/factory.ts b/arkui-plugins/ui-plugins/entry-translators/factory.ts index 4fad64939..d18762a37 100644 --- a/arkui-plugins/ui-plugins/entry-translators/factory.ts +++ b/arkui-plugins/ui-plugins/entry-translators/factory.ts @@ -196,7 +196,7 @@ export class factory { undefined, undefined, [], - undefined, + ctor, arkts.factory.createETSTypeReference( arkts.factory.createETSTypeReferencePart( arkts.factory.createIdentifier(EntryWrapperNames.ENTRY_POINT_CLASS_NAME) @@ -207,8 +207,7 @@ export class factory { arkts.Es2pandaClassDefinitionModifiers.CLASS_DEFINITION_MODIFIERS_DECLARATION | arkts.Es2pandaClassDefinitionModifiers.CLASS_DEFINITION_MODIFIERS_ID_REQUIRED, arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE - ) - .setCtor(ctor as any); + ); const newClass = arkts.factory.createClassDeclaration(definition); newClass.modifiers = arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE; return newClass; -- Gitee From c877eacde324ea08971caea3ee0a5ae214c288dd Mon Sep 17 00:00:00 2001 From: Aleksandr Veselov Date: Thu, 4 Sep 2025 12:39:48 +0300 Subject: [PATCH 28/39] Fix duplicated imports in tests Signed-off-by: Aleksandr Veselov Change-Id: I300d98a6fe92db4aedc49b810e88979c4147311f --- arkui-plugins/ui-plugins/component-transformer.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/arkui-plugins/ui-plugins/component-transformer.ts b/arkui-plugins/ui-plugins/component-transformer.ts index cbc210b54..a78f321dd 100644 --- a/arkui-plugins/ui-plugins/component-transformer.ts +++ b/arkui-plugins/ui-plugins/component-transformer.ts @@ -206,7 +206,7 @@ export class ComponentTransformer extends AbstractVisitor { if (this.isExternal && this.externalSourceName === ENTRY_POINT_IMPORT_SOURCE_NAME) { const navInterface = entryFactory.createNavInterface(); navInterface.modifiers = arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_EXPORT; - return arkts.factory.updateETSModule(node, [...this.imports, ...node.statements, navInterface], node.ident, node.getNamespaceFlag(), node.program); + return arkts.factory.updateETSModule(node, [...this.imports.splice(0), ...node.statements, navInterface], node.ident, node.getNamespaceFlag(), node.program); } if (this.isExternal && this.componentInterfaceCollection.length === 0 && this.entryNames.length === 0) { return node; @@ -235,7 +235,7 @@ export class ComponentTransformer extends AbstractVisitor { } if (updateStatements.length > 0 || this.imports.length > 0) { - return arkts.factory.updateETSModule(node, [...this.imports, ...node.statements, ...updateStatements], node.ident, node.getNamespaceFlag(), node.program); + return arkts.factory.updateETSModule(node, [...this.imports.splice(0), ...node.statements, ...updateStatements], node.ident, node.getNamespaceFlag(), node.program); } return node; } -- Gitee From 0dd0f9d282ade6bb31a9d517d64c2dcfe17ceacb Mon Sep 17 00:00:00 2001 From: Aleksandr Veselov Date: Thu, 4 Sep 2025 15:12:42 +0300 Subject: [PATCH 29/39] Fix property setter Signed-off-by: Aleksandr Veselov Change-Id: I7e8764fcddaed2d9e13d721274892ce111229483 --- .../property-translators/observedTrack.ts | 26 ++++++++++--------- 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/arkui-plugins/ui-plugins/property-translators/observedTrack.ts b/arkui-plugins/ui-plugins/property-translators/observedTrack.ts index 070bb3efe..571606137 100644 --- a/arkui-plugins/ui-plugins/property-translators/observedTrack.ts +++ b/arkui-plugins/ui-plugins/property-translators/observedTrack.ts @@ -160,18 +160,8 @@ export class ObservedTrackTranslator extends ObservedPropertyTranslator { ); 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.id?.clone(), - arkts.factory.createFunctionExpression(newGetter.id?.clone(), newGetter.function! - .addFlag(arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD) - ), - originGetter.modifiers, - false, - originGetter.overloads - ); - arkts.factory.updateMethodDefinition( + + const updatedSetter = arkts.factory.updateMethodDefinition( originSetter, originSetter.kind, newSetter.id?.clone(), @@ -183,6 +173,18 @@ export class ObservedTrackTranslator extends ObservedPropertyTranslator { false, originSetter.overloads ); + + const updateGetter: arkts.MethodDefinition = arkts.factory.updateMethodDefinition( + originGetter, + originGetter.kind, + newGetter.id?.clone(), + arkts.factory.createFunctionExpression(newGetter.id?.clone(), newGetter.function! + .addFlag(arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD) + ), + originGetter.modifiers, + false, + [updatedSetter] + ); this.classScopeInfo.getters[idx] = updateGetter; } } else { -- Gitee From af7a8450fdbb1cb36d452252cb7e70384e08c052 Mon Sep 17 00:00:00 2001 From: Aleksandr Veselov Date: Thu, 4 Sep 2025 15:44:15 +0300 Subject: [PATCH 30/39] Fix property setter V2 Signed-off-by: Aleksandr Veselov Change-Id: I18c07633a415c9344d7d4aae6ac1883957963e50 --- .../property-translators/observedV2Trace.ts | 26 ++++++++++--------- 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/arkui-plugins/ui-plugins/property-translators/observedV2Trace.ts b/arkui-plugins/ui-plugins/property-translators/observedV2Trace.ts index 9037b200e..968ad0a68 100644 --- a/arkui-plugins/ui-plugins/property-translators/observedV2Trace.ts +++ b/arkui-plugins/ui-plugins/property-translators/observedV2Trace.ts @@ -171,18 +171,8 @@ export class ObservedV2TraceTranslator extends ObservedPropertyTranslator { ); 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.id?.clone(), - arkts.factory.createFunctionExpression(newGetter.id?.clone(), newGetter.function! - .addFlag(arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD) - ), - originGetter.modifiers, - false, - originGetter.overloads - ); - arkts.factory.updateMethodDefinition( + + const updatedSetter = arkts.factory.updateMethodDefinition( originSetter, originSetter.kind, newSetter.id?.clone(), @@ -194,6 +184,18 @@ export class ObservedV2TraceTranslator extends ObservedPropertyTranslator { false, originSetter.overloads ); + + const updateGetter: arkts.MethodDefinition = arkts.factory.updateMethodDefinition( + originGetter, + originGetter.kind, + newGetter.id?.clone(), + arkts.factory.createFunctionExpression(newGetter.id?.clone(), newGetter.function! + .addFlag(arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_METHOD) + ), + originGetter.modifiers, + false, + [updatedSetter] + ); this.classScopeInfo.getters[idx] = updateGetter; } } else { -- Gitee From 3a1427e9d415827e9b997b8f43a8bf2467998551 Mon Sep 17 00:00:00 2001 From: Aleksandr Veselov Date: Thu, 4 Sep 2025 16:31:07 +0300 Subject: [PATCH 31/39] Fix some test cases Signed-off-by: Aleksandr Veselov Change-Id: If1e86e9744e111667a5edb673526b0e7271ac06a --- .../custom-component/custom-component-call.test.ts | 2 +- .../ut/ui-plugins/builder-lambda/simple-component.test.ts | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/arkui-plugins/test/ut/ui-plugins/builder-lambda/custom-component/custom-component-call.test.ts b/arkui-plugins/test/ut/ui-plugins/builder-lambda/custom-component/custom-component-call.test.ts index 3e62f5cfe..244c55784 100644 --- a/arkui-plugins/test/ut/ui-plugins/builder-lambda/custom-component/custom-component-call.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/builder-lambda/custom-component/custom-component-call.test.ts @@ -207,7 +207,7 @@ function testCustomComponentTransformer(this: PluginTestContext): void { pluginTester.run( 'test custom component call transformation', - [parsedTransform, recheck, uiNoRecheck, recheck], + [parsedTransform, uiNoRecheck, recheck], { parsed: [testParedTransformer], 'checked:ui-no-recheck': [testCustomComponentTransformer], diff --git a/arkui-plugins/test/ut/ui-plugins/builder-lambda/simple-component.test.ts b/arkui-plugins/test/ut/ui-plugins/builder-lambda/simple-component.test.ts index d660394e1..2700bb214 100644 --- a/arkui-plugins/test/ut/ui-plugins/builder-lambda/simple-component.test.ts +++ b/arkui-plugins/test/ut/ui-plugins/builder-lambda/simple-component.test.ts @@ -18,7 +18,7 @@ import { PluginTester } from '../../../utils/plugin-tester'; import { mockBuildConfig } from '../../../utils/artkts-config'; import { getRootPath, MOCK_ENTRY_DIR_PATH } from '../../../utils/path-config'; import { parseDumpSrc } from '../../../utils/parse-string'; -import { beforeMemoNoRecheck, builderLambdaNoRecheck, memoNoRecheck, recheck } from '../../../utils/plugins'; +import { memoNoRecheck, recheck, uiNoRecheck } from '../../../utils/plugins'; import { BuildConfig, PluginTestContext } from '../../../utils/shared-types'; const BUILDER_LAMBDA_DIR_PATH: string = 'builder-lambda'; @@ -103,7 +103,7 @@ class MyStateSample { pluginTester.run( 'transform simple component', - [builderLambdaNoRecheck, beforeMemoNoRecheck, memoNoRecheck, recheck], + [uiNoRecheck, memoNoRecheck, recheck], { 'checked:builder-lambda-no-recheck': [testBuilderLambdaTransformer], 'checked:memo-no-recheck': [testMemoTransformer], -- Gitee From 31d5a0e38acdeaf9695c9e8748af60638e10dc83 Mon Sep 17 00:00:00 2001 From: Aleksandr Veselov Date: Fri, 5 Sep 2025 18:04:43 +0300 Subject: [PATCH 32/39] Rebase Signed-off-by: Aleksandr Veselov Change-Id: I4673e032f241a3c5bd263558feb11fe628cec8fe --- arkui-plugins/ui-plugins/interop/initstatevar.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/arkui-plugins/ui-plugins/interop/initstatevar.ts b/arkui-plugins/ui-plugins/interop/initstatevar.ts index 584dcf4e4..2a0980c02 100644 --- a/arkui-plugins/ui-plugins/interop/initstatevar.ts +++ b/arkui-plugins/ui-plugins/interop/initstatevar.ts @@ -253,7 +253,7 @@ export function processBuilderParam(keyName: string, value: arkts.Expression): a return result; } -function getIdentifier(value: arkts.AstNode): arkts.identifier | undefined { +function getIdentifier(value: arkts.AstNode): arkts.Identifier | undefined { if (arkts.isIdentifier(value)) { return value; } else if (arkts.isMemberExpression(value) && arkts.isThisExpression(value.object) && arkts.isIdentifier(value.property)) { @@ -269,10 +269,10 @@ function checkUpdatable(value: arkts.AstNode): boolean { return false; } const decl = arkts.getDecl(ident) as arkts.MethodDefinition; - const script = decl.scriptFunction; + const script = decl.function; const params = script.params; - if (params.length === 1 && arkts.isEtsParameterExpression(params[0])) { - const type = params[0].type; + if (params.length === 1 && arkts.isETSParameterExpression(params[0])) { + const type = params[0].typeAnnotation; if (type === undefined) { return false; } -- Gitee From fb8ef27f57b17d8c287d56fa7512ba2f6e6fe738 Mon Sep 17 00:00:00 2001 From: Aleksandr Veselov Date: Mon, 8 Sep 2025 11:56:43 +0300 Subject: [PATCH 33/39] Fix types Signed-off-by: Aleksandr Veselov Change-Id: I18d9333172cf63b0fdf74b30470a3ac4d5349034 --- .../cache/componentAttributeCache.ts | 21 ++++++++++--------- .../builder-lambda-translators/factory.ts | 18 ++++++++-------- .../ui-plugins/checked-transformer.ts | 2 +- .../ui-plugins/interop/legacy-transformer.ts | 5 +++-- 4 files changed, 24 insertions(+), 22 deletions(-) diff --git a/arkui-plugins/ui-plugins/builder-lambda-translators/cache/componentAttributeCache.ts b/arkui-plugins/ui-plugins/builder-lambda-translators/cache/componentAttributeCache.ts index 1914e3070..0dd1d18f0 100644 --- a/arkui-plugins/ui-plugins/builder-lambda-translators/cache/componentAttributeCache.ts +++ b/arkui-plugins/ui-plugins/builder-lambda-translators/cache/componentAttributeCache.ts @@ -88,12 +88,13 @@ export class ComponentAttributeCache { } preprocessParam(param: arkts.ETSParameterExpression, index: number, name: string): arkts.ETSParameterExpression { - if (index === 0 && isForEach(name) && !!param.type && arkts.isTypeNode(param.type)) { - return arkts.factory.createParameterDeclaration( + if (index === 0 && isForEach(name) && arkts.isTypeNode(param.typeAnnotation)) { + return arkts.factory.createETSParameterExpression( arkts.factory.createIdentifier( - param.identifier.name, - UIFactory.createLambdaFunctionType([], param.type.clone()) + param.ident!.name, + UIFactory.createLambdaFunctionType([], param.typeAnnotation.clone()) ), + false, undefined ); } @@ -101,15 +102,15 @@ export class ComponentAttributeCache { } collect(node: arkts.MethodDefinition): void { - this.collectAttributeName(node.scriptFunction.returnTypeAnnotation); + this.collectAttributeName(node.function.returnTypeAnnotation); if (!this._attributeName) { return; } - const name: string = node.name.name; - const hasRestParameter = node.scriptFunction.hasRestParameter; - const hasReceiver = node.scriptFunction.hasReceiver; - const typeParams = collectTypeRecordFromTypeParameterDeclaration(node.scriptFunction.typeParams); - const params = node.scriptFunction.params as arkts.ETSParameterExpression[]; + const name: string = node.id!.name; + const hasRestParameter = node.function.hasRestParameter; + const hasReceiver = node.function.hasReceiver; + const typeParams = collectTypeRecordFromTypeParameterDeclaration(node.function.typeParams); + const params = node.function.params as arkts.ETSParameterExpression[]; const attributeRecords: ParameterRecord[] = []; const hasLastTrailingLambda = checkIsTrailingLambdaInLastParam(params); params.forEach((p, index) => { diff --git a/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts b/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts index 7abd27c5b..bc3af7606 100644 --- a/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts +++ b/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts @@ -575,15 +575,15 @@ export class factory { * process `@ComponentBuilder` call arguments for some specific transformation. */ static processModifiedArg( - modifiedArg: arkts.AstNode | undefined, + modifiedArg: arkts.Expression | undefined, index: number | undefined, args: readonly arkts.Expression[], moduleName: string, name: string | undefined - ): arkts.AstNode | undefined { - if (index === 0 && isForEach(name, moduleName) && !!modifiedArg && arkts.isExpression(modifiedArg)) { + ): arkts.Expression | undefined { + if (index === 0 && isForEach(name, moduleName) && arkts.isExpression(modifiedArg)) { const newFunc = UIFactory.createScriptFunction({ - body: arkts.factory.createBlock([arkts.factory.createReturnStatement(modifiedArg)]), + body: arkts.factory.createBlockStatement([arkts.factory.createReturnStatement(modifiedArg)]), flags: arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, returnTypeAnnotation: factory.getReturnTypeFromArrowParameter(args) ?? factory.getReturnTypeFromTsType(modifiedArg), @@ -591,7 +591,7 @@ export class factory { }); const returnMemoableInfo = collectMemoableInfoInFunctionReturnType(newFunc); collectScriptFunctionReturnTypeFromInfo(newFunc, returnMemoableInfo); - return arkts.factory.createArrowFunction(newFunc); + return arkts.factory.createArrowFunctionExpression(newFunc); } return modifiedArg; } @@ -603,15 +603,15 @@ export class factory { if ( args.length <= 1 || !arkts.isArrowFunctionExpression(args[1]) || - args[1].scriptFunction.params.length <= 0 + args[1].function.params.length <= 0 ) { return undefined; } - const argTypeParam: arkts.Expression = args[1].scriptFunction.params[0]; - if (!arkts.isEtsParameterExpression(argTypeParam)) { + const argTypeParam: arkts.Expression = args[1].function.params[0]; + if (!arkts.isETSParameterExpression(argTypeParam)) { return undefined; } - const type: arkts.AstNode | undefined = argTypeParam.type; + const type: arkts.AstNode | undefined = argTypeParam.typeAnnotation; if (type && arkts.isTypeNode(type)) { return UIFactory.createComplexTypeFromStringAndTypeParameter(TypeNames.ARRAY, [type.clone()]); } diff --git a/arkui-plugins/ui-plugins/checked-transformer.ts b/arkui-plugins/ui-plugins/checked-transformer.ts index 7b1b01803..6ea345a2d 100644 --- a/arkui-plugins/ui-plugins/checked-transformer.ts +++ b/arkui-plugins/ui-plugins/checked-transformer.ts @@ -85,7 +85,7 @@ export class CheckedTransformer extends AbstractVisitor { init(): void { MetaDataCollector.getInstance() .setProjectConfig(this.projectConfig) - .setAbsName(this.program?.absName) + .setAbsName(this.program?.absoluteName) .setExternalSourceName(this.externalSourceName); } diff --git a/arkui-plugins/ui-plugins/interop/legacy-transformer.ts b/arkui-plugins/ui-plugins/interop/legacy-transformer.ts index b6653b935..828830969 100644 --- a/arkui-plugins/ui-plugins/interop/legacy-transformer.ts +++ b/arkui-plugins/ui-plugins/interop/legacy-transformer.ts @@ -142,7 +142,7 @@ export class LegacyTransformer extends AbstractVisitor { const instantiate_Interop: arkts.MethodDefinition = this.createInteropMethod(ident.name); - const newDefinition = arkts.factory.updateClassDefinition( + const newDefinition = arkts.ClassDefinition.update3ClassDefinition( definition, definition.ident, definition.typeParams, @@ -153,7 +153,8 @@ export class LegacyTransformer extends AbstractVisitor { [...definition.body, instantiate_Interop], definition.modifiers, arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, - arkts.Es2pandaLanguage.JS + arkts.Es2pandaLanguage.LANGUAGE_JS, + definition.annotations ); if (arkts.isETSStructDeclaration(node)) { -- Gitee From f615371cd2b3480b92e742be2f46ad218464f11c Mon Sep 17 00:00:00 2001 From: Aleksandr Veselov Date: Mon, 8 Sep 2025 12:08:53 +0300 Subject: [PATCH 34/39] Fixup after rebase Signed-off-by: Aleksandr Veselov Change-Id: Ief119fca2931ca0375b6d083de82b8c142922d03 --- arkui-plugins/common/program-visitor.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/arkui-plugins/common/program-visitor.ts b/arkui-plugins/common/program-visitor.ts index 4516df8cf..439dd2e0e 100644 --- a/arkui-plugins/common/program-visitor.ts +++ b/arkui-plugins/common/program-visitor.ts @@ -271,7 +271,6 @@ export class ProgramVisitor extends AbstractVisitor { } this.visitTransformer(transformer, script, externalSourceName, program); arkts.setAllParents(script); - transformer.reset(); if (!transformer.isExternal) { debugDumpAstNode( script, -- Gitee From c26f43eba75d2679e7f0bc2ed77873153cdf675d Mon Sep 17 00:00:00 2001 From: Aleksandr Veselov Date: Fri, 12 Sep 2025 12:25:51 +0300 Subject: [PATCH 35/39] Rebase fixups Signed-off-by: Aleksandr Veselov Change-Id: Ic9c2d6817f19dc63d59d7dc0d38782828643a902 --- arkui-plugins/ui-plugins/property-translators/computed.ts | 4 ++-- arkui-plugins/ui-plugins/ui-factory.ts | 6 ++---- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/arkui-plugins/ui-plugins/property-translators/computed.ts b/arkui-plugins/ui-plugins/property-translators/computed.ts index ee224a426..6d9d50b9f 100644 --- a/arkui-plugins/ui-plugins/property-translators/computed.ts +++ b/arkui-plugins/ui-plugins/property-translators/computed.ts @@ -89,7 +89,7 @@ export class ComputedTranslator extends MethodTranslator implements InitializerC } function getGetterReturnType(method: arkts.MethodDefinition): arkts.TypeNode | undefined { - const body = method.scriptFunction.body; + const body = method.function.body; if (!body || !arkts.isBlockStatement(body) || body.statements.length <= 0) { return undefined; } @@ -102,7 +102,7 @@ function getGetterReturnType(method: arkts.MethodDefinition): arkts.TypeNode | u } else if (typeArray.length === 1) { returnType = typeArray.at(0); } else { - returnType = arkts.factory.createUnionType(typeArray); + returnType = arkts.factory.createETSUnionType(typeArray); } returnTransformer.reset(); return returnType?.clone(); diff --git a/arkui-plugins/ui-plugins/ui-factory.ts b/arkui-plugins/ui-plugins/ui-factory.ts index ad9787a04..e4a3c0f12 100644 --- a/arkui-plugins/ui-plugins/ui-factory.ts +++ b/arkui-plugins/ui-plugins/ui-factory.ts @@ -253,8 +253,7 @@ export class factory { key.clone(), arkts.factory.createFunctionExpression(key.clone(), newFunc), config.modifiers ?? original.modifiers, - config.isComputed ?? false, - config.overloads + config.isComputed ?? false ); return newMethod; } @@ -272,8 +271,7 @@ export class factory { config.key?.clone(), arkts.factory.createFunctionExpression(config.key?.clone(), newFunc), config.modifiers ?? arkts.Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, - config.isComputed ?? false, - config.overloads + config.isComputed ?? false ); return newMethod; } -- Gitee From f70c36d7592cfa35e727d9fd5b8a73db9da7a3e9 Mon Sep 17 00:00:00 2001 From: Aleksandr Veselov Date: Fri, 12 Sep 2025 12:39:56 +0300 Subject: [PATCH 36/39] Update paths Signed-off-by: Aleksandr Veselov Change-Id: I4a0aa48692c17606e926c84b1320b3defbd6b12a --- arkui-plugins/npm_preinstall.sh | 2 +- arkui-plugins/package.json | 4 ++-- arkui-plugins/path.ts | 8 ++++---- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/arkui-plugins/npm_preinstall.sh b/arkui-plugins/npm_preinstall.sh index 478471ab0..082dafa57 100755 --- a/arkui-plugins/npm_preinstall.sh +++ b/arkui-plugins/npm_preinstall.sh @@ -14,7 +14,7 @@ # limitations under the License. if [ "$1" == "--init" ]; then - cd ../koala-wrapper + cd ../ets1.2/libarkts/ npm install npm run compile npm link diff --git a/arkui-plugins/package.json b/arkui-plugins/package.json index 3b1f29c39..4a983b28f 100644 --- a/arkui-plugins/package.json +++ b/arkui-plugins/package.json @@ -11,7 +11,7 @@ "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/", + "prepare:test": "cp -rf $INIT_CWD/../../../out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/libarkts/build/native/ ../ets1.2/libarkts/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 --maxWorkers=50% --silent", "test:gdb": "LD_LIBRARY_PATH=$INIT_CWD/../../../out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/ets2panda/lib gdb --args node ./node_modules/.bin/jest --config ./jest-test.config.js", "compile": "npm run compile:clean && npm run compile:plugins && cp -rf ./lib $INIT_CWD/../../../../out/sdk/ohos-sdk/linux/ets/ets1.2/build-tools/ui-plugins/" @@ -31,6 +31,6 @@ "typescript": "^5.0.0" }, "dependencies": { - "@koalaui/libarkts": "../../../foundation/arkui/ace_engine/frameworks/bridge/arkts_frontend/koala_mirror/ui2abc/libarkts" + "@koalaui/libarkts": "../ets1.2/libarkts/" } } diff --git a/arkui-plugins/path.ts b/arkui-plugins/path.ts index 7f7141da6..6a255a8a8 100644 --- a/arkui-plugins/path.ts +++ b/arkui-plugins/path.ts @@ -45,17 +45,17 @@ function findRootDir() { } export function getArktsPath() { - return path.join(findRootDir(), 'ui2abc/libarkts', './lib/libarkts.js'); + return path.join(findRootDir(), 'ets1.2/libarkts', './lib/libarkts.js'); } export function getInteropPath() { - return path.join(findRootDir(), 'koala-wrapper/koalaui/interop', './dist/lib/src/interop/index.js'); + return path.join(findRootDir(), 'ets1.2/interop', './build/lib/src/interop/index.js'); } export function getCommonPath() { - return path.join(findRootDir(), 'koala-wrapper/koalaui/common', './dist/lib/src/index.js'); + return path.join(findRootDir(), 'ets1.2/common', './build/lib/src/index.js'); } export function getCompatPath() { - return path.join(findRootDir(), 'koala-wrapper/koalaui/compat', './dist/src/index.js'); + return path.join(findRootDir(), 'ets1.2/compat', './build/src/index.js'); } -- Gitee From e2f1f24c61ffbd1c40d70d96213ec654fdfbbf00 Mon Sep 17 00:00:00 2001 From: Aleksandr Veselov Date: Fri, 12 Sep 2025 17:55:05 +0300 Subject: [PATCH 37/39] Fix missing wrapper type Signed-off-by: Aleksandr Veselov Change-Id: I382aab40ecabcd50af3c95054af440a7b9ea28c0 --- arkui-plugins/ui-plugins/property-translators/factory.ts | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/arkui-plugins/ui-plugins/property-translators/factory.ts b/arkui-plugins/ui-plugins/property-translators/factory.ts index 7e5c8caa3..f1f29f403 100644 --- a/arkui-plugins/ui-plugins/property-translators/factory.ts +++ b/arkui-plugins/ui-plugins/property-translators/factory.ts @@ -657,14 +657,14 @@ export class factory { */ static wrapInterfacePropertyType(type: arkts.TypeNode, wrapTypeName: StateManagementTypes): arkts.TypeNode { if (arkts.isETSUnionType(type)) { - return arkts.factory.updateETSUnionType(type, [ + return arkts.factory.createETSUnionType([ arkts.factory.createETSTypeReference( arkts.factory.createETSTypeReferencePart( arkts.factory.createIdentifier(wrapTypeName), arkts.factory.createTSTypeParameterInstantiation([type.types[0]]) ) ), - type.types[1], + ...type.types.slice(1), ]); } return type; @@ -683,8 +683,7 @@ export class factory { if (!param.typeAnnotation || !arkts.isETSUnionType(param.typeAnnotation)) { return param; } - return arkts.factory.updateETSParameterExpression( - param, + return arkts.factory.createETSParameterExpression( arkts.factory.createIdentifier( param.ident!.name, factory.wrapInterfacePropertyType(param.typeAnnotation!, wrapTypeName) -- Gitee From 111509d5a4d7ade247bd6012221ddc8404d0c9bf Mon Sep 17 00:00:00 2001 From: Aleksandr Veselov Date: Fri, 12 Sep 2025 18:01:01 +0300 Subject: [PATCH 38/39] Minor refactoring Signed-off-by: Aleksandr Veselov Change-Id: I9a58909b1910238152432c1e01b8b49d5322a41a --- .../collectors/memo-collectors/memo-visitor.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/arkui-plugins/collectors/memo-collectors/memo-visitor.ts b/arkui-plugins/collectors/memo-collectors/memo-visitor.ts index 233288748..ce8d45b65 100644 --- a/arkui-plugins/collectors/memo-collectors/memo-visitor.ts +++ b/arkui-plugins/collectors/memo-collectors/memo-visitor.ts @@ -16,11 +16,21 @@ import * as arkts from '@koalaui/libarkts'; import { AbstractVisitor } from '../../common/abstract-visitor'; import { findAndCollectMemoableNode } from './factory'; +import { ImportCollector } from '../../common/import-collector'; export class MemoVisitor extends AbstractVisitor { + reset(): void { + super.reset() + ImportCollector.getInstance().reset(); + } + visitor(node: arkts.AstNode): arkts.AstNode { const newNode = this.visitEachChild(node); findAndCollectMemoableNode(newNode); + if (arkts.isETSModule(node) && ImportCollector.getInstance().importInfos.length > 0) { + let imports = ImportCollector.getInstance().getImportStatements(); + return arkts.factory.updateETSModule(node, [...imports, ...node.statements], node.ident, node.getNamespaceFlag(), node.program); + } return newNode; } } -- Gitee From 2998a23d42fc40ccdc7cd254e88b4c8de50b48c4 Mon Sep 17 00:00:00 2001 From: Aleksandr Veselov Date: Fri, 12 Sep 2025 18:16:50 +0300 Subject: [PATCH 39/39] Add types for global Signed-off-by: Aleksandr Veselov Change-Id: Ifba54b3f5f2c4b514a9561060c84be7681c1895e --- arkui-plugins/test/utils/artkts-config.ts | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/arkui-plugins/test/utils/artkts-config.ts b/arkui-plugins/test/utils/artkts-config.ts index cf4862f35..1bd1fabfe 100644 --- a/arkui-plugins/test/utils/artkts-config.ts +++ b/arkui-plugins/test/utils/artkts-config.ts @@ -156,16 +156,22 @@ function traverseSDK(currentDir: string, pathSection: Record, } } +type TestGlobal = typeof globalThis & { + PANDA_SDK_PATH: string; + API_PATH: string; + KIT_PATH: string; +} + 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, - apiPath: global.API_PATH, - kitsPath: global.KIT_PATH, - depAnalyzerPath: path.resolve(global.PANDA_SDK_PATH, MOCK_DEP_ANALYZER_PATH), + pandaSdkPath: (global as TestGlobal).PANDA_SDK_PATH, + apiPath: (global as TestGlobal).API_PATH, + kitsPath: (global as TestGlobal).KIT_PATH, + depAnalyzerPath: path.resolve((global as TestGlobal).PANDA_SDK_PATH, MOCK_DEP_ANALYZER_PATH), sourceRoots: [getRootPath()], moduleRootPath: path.resolve(getRootPath(), MOCK_ENTRY_DIR_PATH), dependentModuleList: [], -- Gitee