diff --git a/arkui-plugins/collectors/memo-collectors/factory.ts b/arkui-plugins/collectors/memo-collectors/factory.ts index 71546a6ff296c18ad51436f6e6ec0c2d4334a012..475911bd988b4516550ae8c3cd6a94a153c5e384 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 2f9d07b8ce41349e4bfa04de26dee4904c038fad..5cffd61861608438f371524ea06a09883f164b4d 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/memo-visitor.ts b/arkui-plugins/collectors/memo-collectors/memo-visitor.ts index 233288748cbc9a087514119c0bedda40679fb7d3..ce8d45b652e951b9aa3a1a8693c6013450733ca1 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; } } diff --git a/arkui-plugins/collectors/memo-collectors/utils.ts b/arkui-plugins/collectors/memo-collectors/utils.ts index c8cf3fa23989361dfa3ad793ee39abcb7f12a7a7..72ba299945fd3bed3e1ce1c4c3a859618d8989cf 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)) { @@ -86,16 +87,16 @@ export function addMemoAnnotation(node: T, memoName: Memo annotation(memoName), ]; collectMemoAnnotationImport(memoName); - if (arkts.isEtsParameterExpression(node)) { - node.annotations = newAnnotations; + if (arkts.isETSParameterExpression(node)) { + 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! as arkts.Identifier).typeAnnotation) { currInfo = { ...currInfo, - ...collectMemoableInfoInType(node.name.typeAnnotation), + ...collectMemoableInfoInType((node.id! as arkts.Identifier).typeAnnotation!), }; } - 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/collectors/utils/collect-types.ts b/arkui-plugins/collectors/utils/collect-types.ts index ace7ea54afa4cde791977f4dab98282b10c0515b..15a1f6af9aa99832f7cde26907475b5dcdcd0da9 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/common/arkts-utils.ts b/arkui-plugins/common/arkts-utils.ts index aae9ddc4380c9aa441e4cd262570a7e0c0688a98..670eed2e69466d1a30d13df17281a24c78e39571 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 d65f0d40da094bc237037b592d7b699e322c77bd..0ac8cb543a8e8b1e7a7503606089c0cf6efe319d 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 3d9711799c01b776e626fea84429fae186a05e3b..cf70bd3ad695077d893a63d29b31bcc58dc55dfb 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 935b339af29f87951a69cc85508b64f1fa83e810..6705ee925afd9d23a91403ae6b7418843fc08a9c 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 5fa9ed7af815dca0e10d9c5bc469f3477762227d..3cd1d9ecd5699db618a12d99b7fc35b07172483f 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), arkts.getStartPosition(logItem.node)); + arkts.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 0000000000000000000000000000000000000000..be19cedc1fb0ba7fea3d824c12c52336c0af591a --- /dev/null +++ b/arkui-plugins/common/node-cache.ts @@ -0,0 +1,132 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as 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(); + } + + // 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; + } + + 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) + ); + }); + } +} + +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 diff --git a/arkui-plugins/common/plugin-context.ts b/arkui-plugins/common/plugin-context.ts index ffe81012d31f04e3cc89c486351cd17f15a323dd..1673c9165459e13830c3e334687ba918d76167f3 100644 --- a/arkui-plugins/common/plugin-context.ts +++ b/arkui-plugins/common/plugin-context.ts @@ -18,10 +18,10 @@ 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; + private contextPtr: arkts.KNativePointer | undefined; private codingFilePath: string | undefined; private fileManager: FileManager | 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; } @@ -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/common/predefines.ts b/arkui-plugins/common/predefines.ts index 642d0219a8693c3b6e6ab4fad069871cdb3595ab..de3acb79602d0732e2de6907c4ad3e9c6fbd4ff7 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/common/program-skipper.ts b/arkui-plugins/common/program-skipper.ts index dc77fc5a2ff2c5137ed2d016cb9c624a7b76e178..60557e4cfc25a104d6e5db520f7f58a1eb90ce32 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 9327b9075aadf6c5ecde84d8f41361d1f7ae06de..439dd2e0e6b453b3c62d177e02585b54a1e34f23 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; @@ -300,16 +300,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 32d6a610ed38b6c00179a12eb7fe035cec5f6988..4acffd1b1aea5eab995b8da036d7aeab69e4383e 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'; @@ -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); @@ -52,64 +53,68 @@ 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, + func.id, + func.annotations, ); 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 + false, + node.overloads ); } @@ -127,7 +132,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 d68dfbc2fb39522b05e6c352a0bc55af8d30e35c..772882fa3a9fb38365589bb7fe8352745a87a71f 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); @@ -52,7 +53,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 dc69677c950a3dfd7cb75baca0361a07692407b1..88d0f9fb722d8dc80eb7a1d14fd9846bc553e46b 100644 --- a/arkui-plugins/interop-plugins/index.ts +++ b/arkui-plugins/interop-plugins/index.ts @@ -34,13 +34,13 @@ 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) { let program = arkts.getOrUpdateGlobalContext(contextPtr).program; - script = program.astNode; + script = program.ast as arkts.ETSModule; if (script) { const declTransformer = new DeclTransformer({ @@ -56,8 +56,8 @@ function parsedTransform(this: PluginContext): arkts.EtsScript | undefined { }); program = programVisitor.programVisitor(program); - script = program.astNode; - this.setArkTSAst(script); + script = program.ast as arkts.ETSModule; + 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 49b257dc5d1cfa4d3a57fa45ea9813487c11c525..4da0eff9b84418d212cc9a5b5e3f221c00d9df03 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 f8e0561615d63e73c81f3f16e6c62822f06dd2d7..98be4e324b24b99d5ad353708b161c31c2da9691 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; @@ -104,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 }); } @@ -128,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 { @@ -212,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'; } } @@ -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,30 +301,36 @@ 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)), - hasIntrinsic + node.key, + arkts.factory.createFunctionExpression(node.id?.clone(), + this.signatureTransformer.visitor( + removeMemoAnnotation(this.updateScriptFunction(node.function!, node.id!.name)), + hasIntrinsic + ) ), - node.modifiers, - false + node.modifierFlags, + false, + node.overloads ); } else { updateMethod = arkts.factory.updateMethodDefinition( node, node.kind, - node.name, - this.signatureTransformer.visitor(node.scriptFunction), - node.modifiers, - false + node.key, + arkts.factory.createFunctionExpression(node.id?.clone(), + this.signatureTransformer.visitor(node.function!) + ), + node.modifierFlags, + false, + node.overloads ); } this.modified ||= this.signatureTransformer.modified; @@ -333,36 +342,36 @@ export class FunctionTransformer extends AbstractVisitor { decl: arkts.MethodDefinition, ignoreSelf: boolean = false ): arkts.CallExpression { - let updatedArguments: arkts.AstNode[] = node.arguments.map((it, index) => { - const param = decl.scriptFunction.params.at(index); - if (!param || !arkts.isEtsParameterExpression(param)) { + let updatedArguments: arkts.Expression[] = node.arguments.map((it, index) => { + 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, it.annotations); } return it; }); if (!ignoreSelf) { this.checkMemoCallInMethod(decl); updatedArguments = [ - ...factory.createHiddenArguments(this.positionalIdTracker.id(decl.name.name)), + ...factory.createHiddenArguments(this.positionalIdTracker.id(decl.id!.name)), ...updatedArguments, ]; } 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; - return arkts.factory.updateCallExpression(node, node.expression, node.typeArguments, updatedArguments); + 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 { @@ -371,26 +380,27 @@ 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( - node.expression, - this.signatureTransformer.visitor(node.expression.scriptFunction) + let newExpression: arkts.Expression = node.callee!; + if (isStandaloneArrowFunction(node.callee!)) { + newExpression = arkts.factory.updateArrowFunctionExpression( + node.callee, + this.signatureTransformer.visitor(node.callee.function!), + node.callee.annotations ); } 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.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, it.annotations); } 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, node.isOptional, node.hasTrailingComma, node.trailingBlock ); } private updateAnonymousMemoCall( @@ -398,7 +408,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,29 +418,29 @@ 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), - newNode.typeArguments, - [...factory.createHiddenArguments(this.positionalIdTracker.id()), ...newNode.arguments] + arkts.factory.updateArrowFunctionExpression(expression, res, expression.annotations), + [...factory.createHiddenArguments(this.positionalIdTracker.id()), ...newNode.arguments], + newNode.typeParams, node.isOptional, node.hasTrailingComma, node.trailingBlock ); } 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); @@ -452,8 +462,8 @@ 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); + if (arkts.isETSParameterExpression(decl) && isMemoETSParameterExpression(decl)) { + return this.updateDeclaredCallWithName(node, decl.ident!.name); } return this.updateCallExpressionWithNoDecl(node); } @@ -471,8 +481,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(); } @@ -483,13 +493,15 @@ export class FunctionTransformer extends AbstractVisitor { } this.modified = true; + const nodeArrowFunction = castArrowFunctionExpression(node.value); return arkts.factory.updateClassProperty( node, node.key, - res ? arkts.factory.updateArrowFunction(castArrowFunctionExpression(node.value), res) : undefined, + res ? arkts.factory.updateArrowFunctionExpression(nodeArrowFunction, res, nodeArrowFunction.annotations) : undefined, typeAnnotation, node.modifiers, - node.isComputed + node.isComputed, + node.annotations ); } @@ -506,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; @@ -521,44 +534,45 @@ 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 { 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!), node.annotations); } - 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), node.annotations); } 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, - arkts.factory.updateArrowFunction( - node.initializer, - this.signatureTransformer.visitor(node.initializer.scriptFunction) + node.id, + arkts.factory.updateArrowFunctionExpression( + node.init, + this.signatureTransformer.visitor(node.init.function!), + node.init.annotations ) ); } @@ -567,26 +581,26 @@ 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.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, initializer.annotations); } this.modified = true; 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 ); } @@ -605,8 +619,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 +632,7 @@ export class FunctionTransformer extends AbstractVisitor { this.modified = true; return arkts.factory.updateTSAsExpression( node, - arkts.factory.updateArrowFunction(expr, res), + arkts.factory.updateArrowFunctionExpression(expr, res, expr.annotations), typeAnnotation, node.isConst ); @@ -638,14 +652,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, value.annotations), + node.isMethod, + node.isComputed + ); + } private updateThisAttributeAssignment( node: arkts.AssignmentExpression, @@ -662,30 +682,30 @@ 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; return arkts.factory.updateAssignmentExpression( node, node.left!, - node.operatorType, - arkts.factory.updateArrowFunction(right, res) + arkts.factory.updateArrowFunctionExpression(right, res, right.annotations), + node.operatorType ); } 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 +746,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 ac8adfaf0c7966288dbb5a8e5f86d63980a6fdd5..6b28f707a5de6a3ea81e1cd5f035d95da22c2491 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 ca4c52e15885416980842f37b2454707e96ea1de..99307ea4ea9fedfff35347236900eb15648dfff0 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,20 +38,20 @@ 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'); 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 && program.canSkipPhases(); + 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); @@ -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/internal-transformer.ts b/arkui-plugins/memo-plugins/internal-transformer.ts index 3541fb7c37fb8db20c34eb7171c37ed3cad20044..eb2ae1af2961fed18750fd8007897a38d8249107 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 1152c365be5657adf92613504992bd01e452ddba..6344e29e94aa665b5b05e70863b0c6f4d8b6e970 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)) { @@ -77,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) ); } @@ -105,27 +106,35 @@ export class RewriteFactory { if (!node.typeAnnotation) { return node; } - const newNodeType = RewriteFactory.rewriteType(node.typeAnnotation); - return arkts.factory.updateTSTypeAliasDeclaration(node, node.id, node.typeParams, newNodeType); + const newNodeType = RewriteFactory.rewriteType(node.typeAnnotation)!; + return arkts.factory.updateTSTypeAliasDeclaration(node, node.id, node.typeParams, newNodeType, node.annotations); } static rewriteParameter( 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, node.annotations); } static rewriteProperty(node: arkts.Property, metadata?: CachedMetadata): arkts.Property { 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; @@ -133,17 +142,18 @@ 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( node: arkts.ArrowFunctionExpression, - metadata?: arkts.AstNodeCacheValueMetadata, + metadata?: 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), + node.annotations ); } @@ -163,7 +173,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)) { @@ -173,7 +183,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 +201,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] : []), @@ -253,15 +263,18 @@ export class RewriteFactory { const newNode = arkts.factory.updateMethodDefinition( node, node.kind, - node.name, - RewriteFactory.rewriteScriptFunction(node.scriptFunction, { - 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 + false, + node.overloads ); return newNode; } @@ -273,14 +286,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, @@ -310,9 +323,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)) { @@ -339,7 +352,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 948fb082ebea21ea33a76a2652465c111505dada..de1d7bfa73ee394ded0dd8e7e6eacb20f208fe16 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_TYPE, - 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.createTypeReference( - arkts.factory.createTypeReferencePart(arkts.factory.createIdentifier(RuntimeNames.CONTEXT_TYPE)) + 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.createTypeReference( - arkts.factory.createTypeReferencePart(arkts.factory.createIdentifier(RuntimeNames.ID_TYPE)) + arkts.factory.createETSTypeReference( + arkts.factory.createETSTypeReferencePart(arkts.factory.createIdentifier(RuntimeNames.ID_TYPE)) ) ), + false, undefined ); } @@ -102,48 +102,49 @@ 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 - ), - arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW + newTypeParams, + factory.createHiddenParameterIfNotAdded(type.params, hasReceiver), + type.returnType, + false, + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, + type.annotations ); } static updateScriptFunctionWithMemoParameters( 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 { + 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)]; } @@ -170,14 +171,16 @@ 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, arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_CONST, parameters.map((name, id) => { return factory.createMemoParameterDeclarator(id, name); @@ -193,8 +196,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 +208,13 @@ export class factory { false, false ), - undefined, - [...updatedArgs] + updatedArgs, + undefined, // typeParams + false, // optional_arg + false // trailingComma ); - } - + } + // Recache static createScopeDeclaration( returnTypeAnnotation: arkts.TypeNode | undefined, @@ -215,7 +222,6 @@ export class factory { cnt: number ): arkts.VariableDeclaration { return arkts.factory.createVariableDeclaration( - 0, arkts.Es2pandaVariableDeclarationKind.VARIABLE_DECLARATION_KIND_CONST, [ arkts.factory.createVariableDeclarator( @@ -229,15 +235,21 @@ export class factory { false, false ), - returnTypeAnnotation + [ + factory.createIdArgument(hash) as arkts.Expression, + arkts.factory.createNumberLiteral(cnt) as arkts.Expression + ], + arkts.factory.createTSTypeParameterInstantiation(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 +259,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,13 +283,15 @@ export class factory { ) ); } - return arkts.factory.createBlock([ - arkts.factory.createMemberExpression( - arkts.factory.createIdentifier(RuntimeNames.SCOPE), - arkts.factory.createIdentifier(RuntimeNames.INTERNAL_VALUE), - arkts.Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_NONE, - false, - false + return arkts.factory.createBlockStatement([ + 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()), ]); @@ -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] : []), @@ -390,7 +418,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)) { @@ -412,6 +440,15 @@ 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.callee, + expressionArgs, + node.typeParams, + node.isOptional, + node.hasTrailingComma, + node.trailingBlock + ); } } diff --git a/arkui-plugins/memo-plugins/memo-transformer.ts b/arkui-plugins/memo-plugins/memo-transformer.ts index 430148fc230277aa308876ed0f3b0ad16e67a63f..d6240765b02631edc451f392db575bdd992af8d4 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, @@ -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 1947b60d1a5032d00084f336dbd9a38c4590979e..64d97566ce1c017308552b02f45089ce9b45e055 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; @@ -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), }, ]; @@ -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, initializer.annotations); } private updateVariableDeclareInit( @@ -206,50 +206,49 @@ 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; } const decl = arkts.getPeerDecl(memoInfo.rewritePeer); - if (!decl || !arkts.isEtsParameterExpression(decl)) { + if (!decl || !arkts.isETSParameterExpression(decl)) { return node; } 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/return-transformer.ts b/arkui-plugins/memo-plugins/return-transformer.ts index c2c0fac2e6033aca90d5fce9060020b0286a4ebb..b3eda7789266d449066fa66eb4f42072651a33bc 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,10 @@ 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!), + argument.annotations ); } diff --git a/arkui-plugins/memo-plugins/signature-transformer.ts b/arkui-plugins/memo-plugins/signature-transformer.ts index 6c15cce2ddbb03b30833c632b4b4edeaa8229772..fcd26b8a224d2f7c7e58acdf8a659d164f211279 100644 --- a/arkui-plugins/memo-plugins/signature-transformer.ts +++ b/arkui-plugins/memo-plugins/signature-transformer.ts @@ -67,32 +67,34 @@ 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 (!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)) { @@ -101,19 +103,18 @@ 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 - ), - arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW + undefined, + memo ? factory.createHiddenParameterIfNotAdded(newParams) : newParams, + this.visitor(node.returnType!), + false, + arkts.Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, + node.annotations ) 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 3a6823daab7bab769dc689ae5cdb58120128adb4..d2edd0e8aa1f7519ef605c4a4aaef92fc64a27ad 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,8 +162,8 @@ 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)) { - node.annotations = newAnnotations; + if (arkts.isETSParameterExpression(node)) { + 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) ); } @@ -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!) ); } @@ -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); @@ -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); }); } @@ -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; } @@ -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( @@ -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, @@ -632,13 +632,13 @@ 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 }; }), ]; } 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,10 +649,10 @@ 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; } export function filterMemoSkipParams(paramInfos: ParamInfo[]): ParamInfo[] { diff --git a/arkui-plugins/npm_preinstall.sh b/arkui-plugins/npm_preinstall.sh index 478471ab0ddcfcec949a6753fc1dfd15dda9394b..082dafa576b338b64dbbc1b18ee0f5d2f5299746 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 929c12377e1d5259d15b24c986a6e41ff93b5e70..4a983b28fb3a8e8bebf53cb6b60aee1c1e473f59 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": "../koala-wrapper" + "@koalaui/libarkts": "../ets1.2/libarkts/" } } diff --git a/arkui-plugins/path.ts b/arkui-plugins/path.ts index a8646fcbf9f1a0b882082eca9843bd5441c171d9..6a255a8a8f5c1f3e3ddf55473d94bdb0f873a4ea 100644 --- a/arkui-plugins/path.ts +++ b/arkui-plugins/path.ts @@ -45,17 +45,17 @@ function findRootDir() { } export function getArktsPath() { - return path.join(findRootDir(), 'koala-wrapper', './build/lib/arkts-api/index.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'); } diff --git a/arkui-plugins/test/ut/common/annotation.test.ts b/arkui-plugins/test/ut/common/annotation.test.ts index 538c961d68790b7d5f0ee34a99064875f40f8255..9832d3e71010beed1eb9acdbf4efe84f53f27685 100644 --- a/arkui-plugins/test/ut/common/annotation.test.ts +++ b/arkui-plugins/test/ut/common/annotation.test.ts @@ -57,20 +57,20 @@ class AnnotationVisitor extends AbstractVisitor { } addTestAnnotation(node: AnnotationAstNode): void { - if (arkts.isEtsParameterExpression(node)) { - node.annotations = [this.testAnnotation()]; + 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()]); } } removeTestAnnotation(node: AnnotationAstNode): void { - if (arkts.isEtsParameterExpression(node)) { - node.annotations = []; + if (arkts.isETSParameterExpression(node)) { + node.setAnnotations([]); } else if (arkts.isMethodDefinition(node)) { - node.scriptFunction.setAnnotations([]); + node.function.setAnnotations([]); } else { node.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; @@ -116,14 +116,14 @@ function addAnnotationTransform(this: PluginContext): arkts.EtsScript | undefine pluginContext: this, }); program = programVisitor.programVisitor(program); - script = program.astNode; + script = program.ast as arkts.ETSModule; return script; } 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; @@ -136,7 +136,7 @@ function removeAnnotationTransform(this: PluginContext): arkts.EtsScript | 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/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 b70e8a936298f620592847b6ed742fa2c485fe74..aa41e543b00b0c8f9a6a399e77ea90b37c434449 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); @@ -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 4cb07f2e4167a9ee519038b8c6b68ec039f7eea2..244c55784e8122a26ef0678750380472c16bf33b 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 {} @@ -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 d660394e195e4441cbc95fe5c6c7239ac10662bd..2700bb214253128483ff661deba1f4543be12a15 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], 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 1f0ce315b1ba8ecee1272072536e32c187293436..cfb6b7cd45f6b26420cd5b02e956a550e65dc818 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 b35f0aceba9ee8d7eb2e471400aab29ae5a3519b..d7fe74791a1dd31ae657b6055f531ebaa21db4c2 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 899349a1a7b1fd53aa56f458c71548b903aa4a95..e9756b61df8fb37d025ea7e5c10770a747ddfcb7 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 99df21b189c1c85e9bc6297762f4c95003aa0834..17937033b02d03718b6e5235c8623a190258848a 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 5644da5a05a4254fd6a2c537b0f0226bb64181aa..80f9967c219e5cc1e534d5c36d0eeb3fc6a2067c 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 1b038ec84e08fee22df220ce5eac828768fc49d3..65ebda6c3c7d0df6401b30c202bca0973a6449a2 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 cf0a30ddc2959465a637a6b23c5e9d6742d6e754..3e822be8977a8743a9b34f5c678f471cb9a29702 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 81b0ca1908e47207645861610b3da481d938f399..8d244215b7240d4f2777a801f1b1be4be7f8ae8b 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 a0d915cc8063e7cd0171b56ee5d6cff654d47700..bda4399b41b9c277c8d39aa2ac17cd7e31b7bd7d 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 5e88c5774c174364617355823e63ed2589dec271..44581928cb1377daa813ecee51cddd3ef77cad20 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 dd3158507966a576dd82fb357fddf661c55d03c6..030fbd8d6e373618506f82078753c7b184368fa6 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/objectlink/objectlink-basic.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/objectlink/objectlink-basic.test.ts index 9f377e590a4d916970804e420fbbc7517f8f7eb2..4ccfdba0c93fcb827a404c7158564fbe5ca4d27d 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 7f1cbcf13740cdade27208a6bd8adcfb6b09c8e1..05c26773ac97b0d46d28bf0cb4debc26d56f0290 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/test/ut/ui-plugins/decorators/require/basic-require.test.ts b/arkui-plugins/test/ut/ui-plugins/decorators/require/basic-require.test.ts index afb86ec4bc8a2119afc998d0ea8669bf886cea6e..9c28297301454ba701e4286c0c5dab8eb94152db 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 5809128c41c22e8e888f4eda08d995054978723c..4269070a2b13c3ebc8e877ac44f0dbeccd336a11 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 265b6b03c8a4665fae2495b18053cad667bc3648..cdfc5bca622cfae15bdb50cff50c0d58343c170e 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 7f3ec3c205e09ab1bdfb00d624c95b8999f161d5..9b2fb6cd54fdf29c8363e03c0127711f8d927077 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 6202824da2cde6a8f98c44e8ee5afc0b833db0c1..f7b381584eab9530d5839e792102c5e4237044da 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 ad190b6585f191bea45146e323114f688cc3aa92..fb6d5547254b1efb9543520b3418391e980686fa 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 c4a9f9255dc528fe80fa44ca594683c3b76ae88f..b926185bdb1c6c129a42edcba478b7a90dae3c1e 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,17 +164,17 @@ __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(_); - })) + })); 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(_); diff --git a/arkui-plugins/test/utils/artkts-config.ts b/arkui-plugins/test/utils/artkts-config.ts index d47091bd71dcb491d82c04c6a2e48e7e4f282869..1bd1fabfeb188b3d9e6c447b41ba7e4e3d08cea3 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 { @@ -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: [], @@ -247,7 +253,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/compile.ts b/arkui-plugins/test/utils/compile.ts index afa55219ab9435046acb914644789ece536583c9..e2fedb08d01c368024639a055cf1cc6fb1a17c34 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(); @@ -44,7 +45,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.ast as arkts.ETSModule; pluginTestContext.scriptSnapshot = script.dumpSrc(); return pluginTestContext; } @@ -61,7 +62,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 +76,7 @@ function collectPluginTextContextFromExternalSource( ); } else { const sourceTestContext: SingleProgramContext = {}; - const script: arkts.EtsScript = sourceProgram.astNode; + const script: arkts.ETSModule = sourceProgram.ast as arkts.ETSModule; const scriptSnapshot = script.dumpSrc(); sourceTestContext.scriptSnapshot = scriptSnapshot; declContexts[name] = sourceTestContext; @@ -105,7 +106,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) @@ -206,7 +207,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 +222,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 +237,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 +250,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 +264,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 +278,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 +288,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) { + NodeCache.getInstance().clear(); + processErrorState(state, context, forceDtsEmit); + } + if (state <= arkts.arktsGlobal.es2panda._ContextState(context)) { + console.log('[TS WRAPPER] PROCEED TO STATE: SKIPPING'); + return; + } + NodeCache.getInstance().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 424d4512edbc6ec0b3f3cdef7ce8ab215b795b65..58780935045e8110a472ac2a111d15c043419033 100644 --- a/arkui-plugins/test/utils/global.ts +++ b/arkui-plugins/test/utils/global.ts @@ -41,31 +41,31 @@ 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( config: arkts.Config, filePath: string, - globalContextPtr: number, + globalContextPtr: arkts.KNativePointer, isExternal: boolean ): arkts.Context { return arkts.Context.createCacheContextFromFile(config.peer, filePath, globalContextPtr, isExternal); @@ -107,16 +107,18 @@ 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); + arkts.arktsGlobal.resetConfig(); } catch (e) { // Do nothing } } -function setUpSoPath(pandaSdkPath: string): void { +function initializeLibarkts(pandaSdkPath: string): void { arkts.arktsGlobal.es2panda._SetUpSoPath(pandaSdkPath); + arkts.initVisitsTable(); } export { @@ -130,5 +132,5 @@ export { resetConfig, destroyContext, destroyConfig, - setUpSoPath, + initializeLibarkts, }; diff --git a/arkui-plugins/test/utils/parse-string.ts b/arkui-plugins/test/utils/parse-string.ts index 2db07c21f9936ba5433116b35f96eae12ba6cbce..69430d5a74605e0e1361ee40c49b84df1ee9761d 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.trimStart()].join("\n") +} + function filterSource(text: string): string { const filtered: string = text.replaceAll(/%/g, '_').replaceAll(/#/g, '_').replaceAll('', '_cctor_'); 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 f6a2c0c13dd998eaa4fdb841a11a92f14291124e..42ed5da55cffb1a1e22fe2b8c828db7ffe3ff7c6 100644 --- a/arkui-plugins/test/utils/plugins/before-memo-no-recheck.ts +++ b/arkui-plugins/test/utils/plugins/before-memo-no-recheck.ts @@ -24,12 +24,12 @@ 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; - 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 a770c96b00574186901146a05d6ba5eed9b019f7..61c7f89f09d1961bcfb30cdc2a2cf5525f69eef3 100644 --- a/arkui-plugins/test/utils/plugins/builder-lambda-no-recheck.ts +++ b/arkui-plugins/test/utils/plugins/builder-lambda-no-recheck.ts @@ -24,12 +24,12 @@ 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; - 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 9396b34e5778d0fe20653018da0e6d8076ccb594..aa53b4d56c358f5e9744b2dc4d2b64bfbcd87dd0 100644 --- a/arkui-plugins/test/utils/plugins/memo-no-recheck.ts +++ b/arkui-plugins/test/utils/plugins/memo-no-recheck.ts @@ -23,18 +23,19 @@ 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; 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, @@ -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,8 +65,8 @@ export const memoNoRecheck: Plugins = { pluginContext: this, }); program = programVisitor.programVisitor(program); - arkts.NodeCache.getInstance().clear(); - script = program.astNode; + NodeCache.getInstance().clear(); + 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 2c3559df4107be301827c816f81442bba90b9abf..31242a3c94e39bc4eefbd542b49d95aca3e311d7 100644 --- a/arkui-plugins/test/utils/plugins/recheck.ts +++ b/arkui-plugins/test/utils/plugins/recheck.ts @@ -21,12 +21,12 @@ 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; - 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 87a7bdbd0cdec0fc276dacafed76f02403536644..9b60340f8cd6ab07f93828eb180dc8cc44666bdd 100644 --- a/arkui-plugins/test/utils/plugins/struct-no-recheck.ts +++ b/arkui-plugins/test/utils/plugins/struct-no-recheck.ts @@ -24,12 +24,12 @@ 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; - 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 ddb0281d2428a01a5939dcf29281100ab5650a04..7c66cba350db5dc736ecbb17879f498dec033491 100644 --- a/arkui-plugins/test/utils/plugins/struct-to-component.ts +++ b/arkui-plugins/test/utils/plugins/struct-to-component.ts @@ -24,12 +24,12 @@ 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; - 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 5fbc6c3fb4d7f04c8f2452611b3fb42abb0e07c5..c238d78bd02c746ee252fdb4d5f1d9857e42e853 100644 --- a/arkui-plugins/test/utils/plugins/ui-no-recheck.ts +++ b/arkui-plugins/test/utils/plugins/ui-no-recheck.ts @@ -24,12 +24,12 @@ 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; - 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; diff --git a/arkui-plugins/test/utils/processors/task-processor.ts b/arkui-plugins/test/utils/processors/task-processor.ts index a66b89eb4b8008351d27efd2b6e547c5d646035c..7e5f78ca40522ac5477cc5b35990b1fe4a4a9dff 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 83c365d53308bdf262bb294402a004f6de62d555..82ebc151435af065bf91224ed3125d9b9882ca56 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[]; } 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 081001428712868be4fe825f76a79ed102f8709b..8400aabb1f3d0a3f8f82854cbc66759f52e04728 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); } /** @@ -73,7 +74,8 @@ export class BuilderFactory { newValue, _node.typeAnnotation, _node.modifiers, - false + false, + _node.annotations ); } @@ -87,7 +89,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 +99,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, _node.annotations); } /** @@ -113,7 +115,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); } /** @@ -135,7 +137,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( @@ -147,7 +149,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, _node.isOptional, _node.hasTrailingComma, _node.trailingBlock); } } 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 aba68967cd55f7aa67be5962fa72a91821f137ad..c623bc5001c50892e17b3644c2e611132620cd5d 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/cache/componentAttributeCache.ts b/arkui-plugins/ui-plugins/builder-lambda-translators/cache/componentAttributeCache.ts index 1914e30706611d20f2555f97f564f8b80e581e3c..0dd1d18f0608a899c6443f3121a5a9aaf10163ca 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/condition-scope-visitor.ts b/arkui-plugins/ui-plugins/builder-lambda-translators/condition-scope-visitor.ts index 86ec83025b010cc0f9112fb8adadfd67b0c51b02..a6f96ef882e226e84ef802345cbdd6cb88729707 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; } } @@ -77,12 +78,12 @@ 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) && - !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/builder-lambda-translators/factory.ts b/arkui-plugins/ui-plugins/builder-lambda-translators/factory.ts index fb5650213c02566e2501d21639e63c31ef2fb1eb..bc3af7606307f9dfff160d3e95cefb50549e1f81 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); } } @@ -215,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( @@ -226,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; @@ -264,31 +272,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 +307,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; } @@ -327,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; } @@ -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, arg.annotations); } /** @@ -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); }); @@ -454,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 @@ -463,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 ), ]; } @@ -474,11 +487,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 +511,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,20 +528,20 @@ 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; + const typeArguments = leaf.typeParams?.params; const hasLastTrailingLambda = checkIsTrailingLambdaInLastParam(params); forEachArgWithParam( 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); } @@ -562,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), @@ -578,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; } @@ -590,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()]); } @@ -621,7 +634,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 { @@ -659,8 +672,10 @@ export class factory { false, false ), + [], undefined, - [] + false, + false ); } @@ -668,16 +683,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 +715,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 +755,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 +788,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 +837,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 +856,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 +872,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 +883,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,9 +897,10 @@ export class factory { node, [this.createStyleArgInBuilderLambdaDecl(typeNode, isFunctionCall)], removeAnnotationByName(func.annotations, BuilderLambdaNames.ANNOTATION_NAME), - replaceBuilderLambdaDeclMethodName(nameNode.name) - ).setOverloads(newOverloads); - arkts.NodeCache.getInstance().collect(newNode); + replaceBuilderLambdaDeclMethodName(nameNode!.name), + newOverloads + ); + NodeCache.getInstance().collect(newNode); return newNode; } @@ -900,17 +916,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 +945,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 +953,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 +992,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, node.isOptional, node.hasTrailingComma, node.trailingBlock); + NodeCache.getInstance().collect(newNode); return newNode; } @@ -998,22 +1021,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 +1046,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 +1063,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 +1080,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 +1100,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 +1129,7 @@ export class factory { }, modifiers, }); - arkts.NodeCache.getInstance().collect(method); + NodeCache.getInstance().collect(method); return method; } @@ -1113,11 +1141,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]; } @@ -1164,7 +1192,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; @@ -1192,7 +1220,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, @@ -1222,7 +1250,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, @@ -1231,7 +1259,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, @@ -1246,8 +1274,8 @@ export class factory { }, modifiers, }); - addMemoAnnotation(newMethod.scriptFunction); - arkts.NodeCache.getInstance().collect(newMethod); + addMemoAnnotation(newMethod.function!); + NodeCache.getInstance().collect(newMethod); return newMethod; } @@ -1287,7 +1315,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); @@ -1298,8 +1326,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 ); } @@ -1328,18 +1358,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 ), ]) @@ -1350,9 +1378,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, }) @@ -1372,8 +1400,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 @@ -1389,15 +1418,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/builder-lambda-translators/style-internals-visitor.ts b/arkui-plugins/ui-plugins/builder-lambda-translators/style-internals-visitor.ts index fc46594bfc1fc5671f84bfa1bf6559dfc0c4e659..8afb325ac989433dadd1132fdcf174e308fbc6d5 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,17 @@ 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, + node.isOptional, + node.hasTrailingComma, + node.trailingBlock ); } 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 9c4a7531a4476202982d16b8cf0eca804e5583f9..2562691f3036471e549ad4c0596817d62b4c56d9 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; } @@ -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/checked-transformer.ts b/arkui-plugins/ui-plugins/checked-transformer.ts index 6ad6317975430e3b1394666130bf7808f57e28cd..6ea345a2dfe410a6cedf1cc589afe554059ff9d3 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); } @@ -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 ae383cc166a70560623afcb07714d182192f6777..a78f321ddbf6e52b55118524fd91bcdcc438b265 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.splice(0), ...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.splice(0), ...node.statements, ...updateStatements], node.ident, node.getNamespaceFlag(), node.program); } return node; } @@ -279,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 ) ); } @@ -290,21 +292,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 +321,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 +354,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 +367,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 +391,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), @@ -408,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( @@ -422,8 +424,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 +434,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 +507,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 +528,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 +539,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 e4dd29d224a73bb929913285ac9d5fb2cb602a91..d18762a3713bd41294c913d990ecc88e1fbda160 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 { /** @@ -44,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); } @@ -71,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); } @@ -84,28 +87,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 +117,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 +148,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 ); @@ -189,9 +196,9 @@ export class factory { undefined, undefined, [], - undefined, - arkts.factory.createTypeReference( - arkts.factory.createTypeReferencePart( + ctor, + arkts.factory.createETSTypeReference( + arkts.factory.createETSTypeReferencePart( arkts.factory.createIdentifier(EntryWrapperNames.ENTRY_POINT_CLASS_NAME) ) ), @@ -200,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; @@ -216,11 +222,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 +274,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 +312,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,24 +341,20 @@ 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 - ), + 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 ); @@ -361,8 +365,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 +390,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 +417,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 +446,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 +466,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 f34b9b1e8fff8aaeeb9cd546ebd4ae32068b2e6c..f5dba30adeeb6955daf61495bd337169d99c8523 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(); @@ -44,23 +43,23 @@ function parsedTransform(this: PluginContext): arkts.EtsScript | undefined { const contextPtr = this.getContextPtr() ?? arkts.arktsGlobal.compilerContext?.peer; if (!!contextPtr) { let program = arkts.getOrUpdateGlobalContext(contextPtr).program; - script = program.astNode; - const canSkipPhases = program.canSkipPhases(); + let script = program.ast; + 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'); @@ -97,22 +95,22 @@ function checkedTransform(this: PluginContext): arkts.EtsScript | undefined { const contextPtr = this.getContextPtr() ?? arkts.arktsGlobal.compilerContext?.peer; if (!!contextPtr) { let program = arkts.getOrUpdateGlobalContext(contextPtr).program; - script = program.astNode; - const canSkipPhases = program.canSkipPhases(); + let script = program.ast; + 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 f2073b52d206698b503f71095287983f1f87a4df..9e1c6b943c4f3d421ed667c1c9d9fa8746a39e3f 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,16 @@ export function generateBuilderCompatible(node: arkts.CallExpression, moduleName const result = arkts.factory.updateCallExpression( node, arkts.factory.createIdentifier(InteroperAbilityNames.ARKUICOMPATIBLE), - undefined, [ initializer, updater, - ] + ], + undefined, + node.isOptional, + node.hasTrailingComma, + node.trailingBlock ); - 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 1f43c179e015d9c039e977070a2f1c661c4c057b..2a0980c0238d5094d5b7df96bdeaa9f75317a046 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 ) ); } @@ -142,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( @@ -205,7 +207,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 +231,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, @@ -249,7 +253,7 @@ export function processBuilderParam(keyName: string, value: arkts.AstNode): arkt 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)) { @@ -265,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; } diff --git a/arkui-plugins/ui-plugins/interop/interop.ts b/arkui-plugins/ui-plugins/interop/interop.ts index 5544444107e055b8b6186686a3fb034159bef282..cd4ccbf69c85dee312bba1428b4714371dfb1181 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,16 @@ 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, + node.isOptional, + node.hasTrailingComma, + node.trailingBlock ); - 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 1b831a9b00f81120621115d64aa85b81b2f64145..8288309693d8ed7d1079801edc6e0809ad05ee2e 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 = @@ -148,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, @@ -159,10 +153,11 @@ 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.isStructDeclaration(node)) { + if (arkts.isETSStructDeclaration(node)) { const _node = arkts.factory.createClassDeclaration(newDefinition); _node.modifiers = node.modifiers; return _node; @@ -172,39 +167,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 +216,17 @@ 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 + false, + node.overloads ); } - 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 +236,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 +268,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 +279,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 +288,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 +304,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 +318,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 3dff5e7af5ae4b2ff609aef34db2154918b0f9fe..c16ec3ccb9a1a38469571618714113910ec6718e 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 60d29a3e06e15f48b93298d1aa4b34dde0bc902a..2a2babf0626a6ecf295de2c19767b066942500fe 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 2ccab0b0ee73c012f40da268ffb6e7398c58b7b8..91d04bb142882b299b28d9769d74398b0b12b2e2 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 e79a7e7637cbcd5789860bdcf49e268291b3f602..38faba3e29955ee7f01672c60ccb3e1a9d9e0570 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 b7619dd0de4032b1009e92a3cee25a34dc6a60c2..5abff51f9703362780bb711f9537974922125f5d 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 898d2aa21e2add45a3b7ab88d0032b4e637460ab..8e86653f4f7615d50b5bd83d7475bf0de8025bd0 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 ed76775865f04320b32bcf785d054bbec1d1c52c..43bc7ca27dc787fb1cbd718811a57233c83616cf 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 1777a36208896bbb2389a1cead345b74c01e2d59..6d9d50b9fd6a4d447dc276062bced3aa6d867ed6 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)), ]), }, @@ -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/property-translators/consume.ts b/arkui-plugins/ui-plugins/property-translators/consume.ts index ab60f984620175dae9acf17a214b719892a09011..58de163ed6a4ea6153cbc8b239c881ac2f0f9543 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 a645d581188f9796e4fd3ed3f67a28febb53fc67..71c46c9446e37128a6d9ca9eefb47698821dfabf 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 5bca64afe1fbef7451c7aad43aeec25128f86f13..f1f29f4032c8a68525a1b3bfba6ab182897e5c27 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,14 +657,14 @@ 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.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; @@ -658,19 +677,20 @@ 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( - param, + return arkts.factory.createETSParameterExpression( 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 +731,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 +743,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 +820,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 +837,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 +894,27 @@ 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) - ), - 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), - }) - ) + 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_CALLBACK), + 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 edc9b4d3cc549b571da08c80259b6bc775fa68b8..de140d08f2d4300172dc6888bd99a93bb98750c4 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 bdd9b2899cea60ce7f587330ab8a8cc9eebbad0c..2c34c0fd66c87ba46874bfec0c39947a51855d82 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 f7fe9dddc3771136de1c3115ba487b9e0af9674b..6d176d1535cdb8004a7a4261ec2fa75bb7462cfe 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 3b477dea02e220fc31e0adc6cf9a3d8a5d9bea0d..368e1d2e1f95ddd7d04193fad0024e542e46dc22 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 2070b4fd5f068b66d3ff3531e628fe548ce7c1f7..988d7b6bf97e8c337a5b1f322984516287dc1678 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 133192ee8fd3a6e6203897e457f31b1280be77d4..b23bdb3884318bf59b7f6462488e5dc0fb899524 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 84cc3925701d68a52cc7fb698ff3f0c6fde5549d..57160613705f7c4eed23ad7f675ffc3458eea63c 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,27 +156,34 @@ 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), - originGetter.modifiers, - false - ); - arkts.factory.updateMethodDefinition( + + const updatedSetter = 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 + 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; } @@ -201,8 +209,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 +229,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 +248,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 673184f74318ddd20eef530decf912b092bef47b..968ad0a68ce6433b50dc1972b9b5040fa875a5b1 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,27 +167,34 @@ 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), - originGetter.modifiers, - false - ); - arkts.factory.updateMethodDefinition( + + const updatedSetter = 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 + 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; } @@ -209,9 +219,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 +229,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 +248,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 +262,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 +282,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 1af0383aebacc7a94b1695faa987ec8b57a9e286..7ad5469d3daefbc0baad212a6ae8efd307275080 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 e6b64bfe401a480b792b26786a1e3ee3462214bb..9bf18ab8a467b6239df6e452b7f07f0a502ca0ec 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 e8447835d71be94b9ce5a87691c0a1043faed4db..955190309c781f24fe138c45e7913ababf3a409e 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 ea50f8807c6a225bf93155d9ca543e8cb5e8a98f..292d479d9068da9250a4740fe36e1490cb3bb125 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 0a157a4913e8dffa71336b4b29d3466021e76574..54aac93253526118675ec13fc2ad1aeff7f451cb 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 9cae2857dabee1cf4823c2c1bc143eaa6e1cc497..72033d359ecd5bee3a08092383ca317fd60ec6cc 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 565a024359592c70fc4d5b508f8b2551e5168181..3f1360e8cc4ba60d87ecc3907fbdd5e07f82a110 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 5203e623f017ccb22066fc4f242c360ba09e3c17..a72e7b34dd8b74c200d092c4d14c4bd1b95141d7 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 bb0812c757cc8fb8273ce83814e00a184547394a..c6f20bd6eb2ed7ab3f3e119b55d3ca292357813e 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 0b903d0e3586521e9f2796c7439633a2b6231949..4a9db3d885046c85d262a78e9743c164ad43bb39 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 3a298cef7fdcbbd1bb20ea4c7fc271914488a892..338dd7fbbe70c09ae93c41756d37cb21013ff064 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 ); } @@ -446,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/struct-translators/factory.ts b/arkui-plugins/ui-plugins/struct-translators/factory.ts index f330329c3d6f3cde02b836c54eb0e7a8258d6947..cfdade32debf05d3703db54ce304bb54d5bdae2f 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 { /** @@ -107,7 +108,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 +117,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,14 +175,16 @@ 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), - param.initializer + arkts.factory.createIdentifier(param.ident!.name, newType), + false, + param.initializer, + param.annotations ); if (!!newParam) { return UIFactory.updateMethodDefinition(builderNode, { function: { params: [newParam] } }); @@ -201,28 +205,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 +237,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 +277,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 +296,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 +311,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)) ); } @@ -325,7 +333,8 @@ export class factory { definition.super, members, definition.modifiers, - arkts.classDefinitionFlags(definition) + arkts.classDefinitionFlags(definition), + definition.annotations ); } @@ -366,17 +375,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 +395,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 +450,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,8 +514,10 @@ export class factory { if (arkts.isMethodDefinition(member)) { PropertyFactory.addMemoToBuilderClassMethod(member); if (isKnownMethodDefinition(member, CustomComponentNames.COMPONENT_BUILD_ORI)) { - addMemoAnnotation(member.scriptFunction); - return BuilderFactory.rewriteBuilderMethod(member); + addMemoAnnotation(member.function!); + const transformedBuildMethod = BuilderFactory.rewriteBuilderMethod(member); + NodeCache.getInstance().refresh(member, transformedBuildMethod); + return transformedBuildMethod; } return member; } @@ -575,10 +605,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 +676,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 +695,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 +709,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 +777,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 +789,11 @@ export class factory { return arkts.factory.updateCallExpression( resourceNode, arkts.factory.createIdentifier(transformedKey), + args, undefined, - args + resourceNode.isOptional, + resourceNode.hasTrailingComma, + resourceNode.trailingBlock ); } @@ -831,7 +865,7 @@ export class factory { arkts.factory.updateInterfaceBody(node.body!, newBody), node.isStatic, node.isFromExternal - ); + ).setAnnotations(node.annotations); } return node; @@ -847,10 +881,11 @@ 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 + false, + member.overloads ); } return member; @@ -876,7 +911,8 @@ export class factory { node.definition.super, updatedBody, node.definition.modifiers, - arkts.classDefinitionFlags(node.definition) + arkts.classDefinitionFlags(node.definition), + node.definition.annotations ) ); } @@ -927,7 +963,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; @@ -974,7 +1011,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 +1023,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 +1034,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 +1053,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 +1088,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 +1103,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 +1144,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 +1159,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 +1182,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 +1208,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[1].annotations), ...value.arguments.slice(2), - ]); + ], value.typeParams, value.isOptional, value.hasTrailingComma, value.trailingBlock); } return value; } @@ -1194,9 +1234,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 +1252,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 +1262,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 +1310,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 722453b7a966f09e1018ec4a2d89d0d09ede4e16..28c3be45d4bc3ef1b30a9f458c5d1bafdfdfca64 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 a25c5bf5cb682c69ace9925d3c9e2bb053a27619..70cc41b6abb1bbe6c2ffcdf2570f07472ff7867e 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/type-translators/factory.ts b/arkui-plugins/ui-plugins/type-translators/factory.ts index 14e2650429732fef51864d6ddd6d0565b35ea1ae..5ce3177618a80b5f98a82cb0af53e26ec670f99e 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-plugins/ui-factory.ts b/arkui-plugins/ui-plugins/ui-factory.ts index 3900f3b1473fa2dfb771c7e85460c4b93ce73566..e4a3c0f12157a3e7c8cb9c1c4d395a470bd71f97 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,16 +242,16 @@ 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 ); @@ -283,8 +268,8 @@ 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 ); @@ -298,7 +283,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 +316,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 +333,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 +362,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 +414,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 +433,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 +449,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 ); } @@ -478,9 +464,10 @@ export class factory { static createClassStaticBlock(): arkts.ClassStaticBlock { return arkts.factory.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 | @@ -497,7 +484,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 ); diff --git a/arkui-plugins/ui-plugins/utils.ts b/arkui-plugins/ui-plugins/utils.ts index 9c2960d1b9d9ef9808404b7c747df6f0451dbdeb..6fc1220187b236b7960891bf279a94e14585856a 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 c32e154c1e5da7f423b942ba8166335e654d25ee..32b7c4734e968d6981555ea35deff3c770656c4e 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; @@ -57,18 +57,18 @@ 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; 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); } } @@ -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; @@ -94,10 +94,10 @@ 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.astNode) as arkts.EtsScript; + const script = transformer.transform(program.ast) 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.ast) 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 6aa704560719765f9d2cd932ad038a099640a266..b8927faee6983702ac7aa5eda7b46a1f3b796666 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, - arkts.getStartPosition(options.node)); + 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, arkts.getStartPosition(options.node)); + arkts.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 10cb57d438516f4e72e710fe6d7d43340b689404..a5bdd98939288edf0cc1bca2b48d1da69a063672 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 2b97c5808d27b57214db3474174e2cc301dd112c..3add5d339a321b37b852cd2357a7f51a9c4b00c0 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 21cab0ab1a3c1015fd439f407dc13579f51e2121..9b498cfba5b7f1cc45a172e05abb5b1b320d833c 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 90c6a82eda041ef9e6a4a36cd1651ab4c8f68e70..4f173c39843efbba078cc58771a26fd8fe2e37e7 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 8081137833a846d3299563d85c484241fceca8ce..6d3105005841584d3cb60ad1bc199a03f59e7acc 100644 --- a/arkui-plugins/ui-syntax-plugins/rules/check-property-modifiers.ts +++ b/arkui-plugins/ui-syntax-plugins/rules/check-property-modifiers.ts @@ -45,15 +45,15 @@ 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; } - if (arkts.isDefaultAccessModifierClassProperty(member)) { + if (member.isDefaultAccessModifier) { return; } const propertyName = getClassPropertyName(member); 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 7230b8f6d1878913a70a81b8b744fbda50252cfa..6f9b5d25e4b251139568fedec53996e6eaf40a75 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 70714c3b382345f43e170d7754cb75833dae0bbf..42284724f1e831f658ed8cbe7043b89cbae6f840 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 7db39458228955d4c9ae1a445ab357ba01ce48a7..bdb133a97ccb179e192521158e3765533cfdda59 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 47d5088ec97e6e2df8055d203173b8a9bbe8b613..84d26101b6155cdbe2d74980f330de7ae00124cb 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, @@ -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', @@ -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 fd271307d169280f104a1155e215ebe1c8854a76..6628ce43de4fdc96fd37f1f3cb682820ccf61d0b 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) { @@ -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', @@ -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 784cecad5d7f20b648e56ea33384bff7d6718ee6..d049df3f0bb098664c541c6af2eaed7ae3036304 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 9a4d5695c7fa398390b6991e3c00273a671646b3..7563f48af9c250fba66c5240639f6c9f3ea548da 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,11 +131,11 @@ class ConstructParameterRule extends AbstractUISyntaxRule { return; } member.getChildren().forEach((item) => { - if (!arkts.isVariableDeclarator(item) || !item.name || - (item.initializer && arkts.isArrowFunctionExpression(item.initializer))) { + if (!arkts.isVariableDeclarator(item) || !item.id || + (item.init && arkts.isArrowFunctionExpression(item.init))) { return; } - this.regularVariableList.push(item.name.name); + this.regularVariableList.push((item.id as arkts.Identifier).name); }); } @@ -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 538f7e9fcef5a83726f9f0c5ffb0ab0aa520490b..739f52c1fb7c32c13de588e08090576d96d19990 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); } @@ -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', @@ -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; @@ -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', @@ -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 d35cf99f296b9971af47bdca044a45079d0b72c7..80f90eadd6c69673e4e70f561c0c6b6706d89472 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-componentv2-invalid-params.ts b/arkui-plugins/ui-syntax-plugins/rules/entry-componentv2-invalid-params.ts index 0aa95b24229f21e84e35fcdaa64416df06e021f0..a8315b32554c1997c2c94796fc139c28a3cf04e7 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; } 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 7fb2892535ddafccfbf5fbb8d8cbc08c187d4586..d798c9314a1e6a8e97dd2ec046ee77f10422b5bf 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 0bd71b7c732f221a3c47bda827c3165e3d20080d..0034146a4262068f93708d74728d365af366724e 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 c0b9181e4a4de46ff022adfd40d0b7db2bfb62e6..dee25f44d49dc5a0a7750f0b52f981c25294155a 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 e845cac4430e3780f6f039edf407cdbe276b9f32..2e0fe77371f35db35e643fb9751b18d21d75b68b 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 ); @@ -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', @@ -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)) { @@ -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/nested-relationship.ts b/arkui-plugins/ui-syntax-plugins/rules/nested-relationship.ts index 2f4ee91e01762d81c4c699c03f828bd941691d48..bc758d499080447963c7273939a68ec3da2d4877 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); @@ -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)) { 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 c1206b1ab177f28fd07423ceefa91c85446508fb..edca3fcdd3344814247e68b683127c908eedd14e 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 74028790cd61832575de5c4885eea3c67109bc6b..9829a711b0d20005d3b238daeb499ca07c7c1d6f 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 51043718df9ce2cc9fd2a877cdcf4484faec4057..29ae33df2e4a249369a2769d88a7fa3f87847d1c 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); @@ -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 32f2b369d6b65d7ba729d0a9b9cfdc9d5945d6df..a4f839c8ec832755367bc65a6c842683cb3ac92b 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 { @@ -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 35d1b31e534cf0edd929a64fa20d69e4216513a6..953b8f19fcd6b6288f50a8b9abdaac27ae7659db 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( @@ -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 7c90f0c9da8d1141a918a76f32d1c67f5f103927..c1736f431ae1e980a50179bf024d35d047bff4e5 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; @@ -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/no-same-as-built-in-attribute.ts b/arkui-plugins/ui-syntax-plugins/rules/no-same-as-built-in-attribute.ts index 5940191f68b5f240a1b74058874dd0a235291b64..dd9d275febacbe670e2e6068bf44f80c23530ed3 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 fce5a72c87ace28a055f5e63ab268a9d4603f9eb..c171146cacef8923767c1299a3263d3a65bc4d53 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', @@ -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); @@ -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', @@ -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 308daf6ff731ef4a9b7307e791fe49b3925e1fe1..664a5658b10dbb05b551f66d08ebcc3c0dc85830 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 0c0d16f8209d8216c83551262df98a3261a333ad..a598023da21d5993bd0c91297df01d1df0fe5054 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; @@ -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', @@ -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 38b35cae0d139936f75a095d48a07d3a6e69cc5a..a075c3b0b5046973b8bb4976cba8ef10c627c78c 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) => { @@ -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/property-type.ts b/arkui-plugins/ui-syntax-plugins/rules/property-type.ts index 3a43242f045fe1d615d23666dd5a27f1d3f3a4f4..444afeb4eb2dd30069b5b2dadf353ba38f69260d 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 dd3abf59c2bf2f2f77c28ff6fc4521a3603f6bdf..2d8a2377199eb8c25e01771273b1d669ed1ab0c3 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 57901a88dfde794231e4ce14ecf7e125cfe9935c..4597ad9ec4267352e85fe50d81d08e36295c3280 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 24a7ca87ced670eeea904ec783d851b98cdb357d..8f75eacd6c00039f244f26f914a91be8a161401f 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 509a2a2fd79163578377eb4f433b10a1d59d3f06..880e2841113f86b2fa1cf5f104a4e21246fbfdad 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 aace72ff3493ab6e4a8d4b765f64dc0282270519..48b09466046a1fa9db236a1170e13cd10255d80e 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 8f2fdb8e2653c2e9e6376394afd5b1e5d863dba7..a5e7a4cc6645597e64e9d5d70edeb7f082d74994 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 11b48a21938957acdad946cfc2bf4c112ea0236a..39cc9232d06e70a6835a238fdc97e7ae4476d426 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 12945ee48719f9628d9f606b52d2483e71268369..3bf74708c9c460cb50a942e2ffdc5652ce27f0b0 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 81228846b8fd8c0f49abb19b890c95ffe39529c6..7f6d4deca5b06d247855a29dad7749cade451702 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 a585241ece44e81b987776a2e9a59610114226a7..ec8760d37322c8dde4bf7b977225c4b302b04804 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); @@ -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/ui-consistent-check.ts b/arkui-plugins/ui-syntax-plugins/rules/ui-consistent-check.ts index 695b3579f2d12f0340882ca4a70cd17e71ca2989..429ffb19b652a619bd61e10200589aba078d4e21 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 d187edd5257846eacf9b930e6d8a729fe78ec784..38974187136cf9653f4449fa137f63e891fe4eed 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; @@ -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', 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 d48cb7dd8122e6c012e0f5663f35ffc53e0eaf1b..4bdb2cf784f9b104650c7ad68297a99a2f543490 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 29c7209c60e4cd87849d9c913e9831d1361e375e..64f2edf2c50246f0276a5a81bbe6defe77dd72f0 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 fe2135a6e9a5c4ec74509f4270a6cb382897bb0b..048aed0c616053513b0d4664fbbeaa7bfb8ed572 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 fc2c30f3999f355d761f7a7d37193249fad67eab..cb4237b861888f91d925265d81136393054b6547 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 a8f2da56f9eebd4c64c0842de3d10a14da6bc8a5..43cae2dace65ac5141c763f6c2117e90ee2df874 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 0e3f34341be809724e5b4355f51a60b3c9707c88..bb7b03d60b4d2321e1613de487c1d218f4f836f0 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