From 3aa3bf62a0d7dccb05e7856d72899f4c5824d896 Mon Sep 17 00:00:00 2001 From: chernishevvictor Date: Tue, 24 Sep 2024 19:49:00 +0300 Subject: [PATCH] add create-function-declaration test add update-function-declaration test context brought out + review fix native types refactoring add golden for tests + review fix add test-util and some refactoring adding memo params in function signature and some refactoring add new tests with body changing updateBlock and updateFunctionDeclaration rewrite function declaration body updates context creation bug fixed + added type checking at the end for tests function delcaration full memo rewrite add some native functions moving impl details from lib to api add builder-lambda first step test adding signature and body to builder-lambda param add builder-lambda-transformer fix arktsconfig + some refactoring some changes for running and testing abc files review fixes some changes in tests fixed creation of type annotation found problem in update (added test) add equal to source file asserts in tests + deleted 1 old test update print-visitor add lambda-param-memoization test (full memo rewrite) fix updates (set parent node) fix updates (correcting function declaration update) some refactoring (ts and arkts nodes separated, api -> arkts) some refactoring + trying to fix updateFunctionDeclaration fix updateFunctionDeclaration (returns void) fix modifierFlags updates + add methods to utilites + change builder-lambda-transformer (any -> string) add some nodes + failing test fix webpack add memo-transformer add memo-transformer body rewrite refactoring memo-transformer add function-transformer fixed builder-lambda plugin removed getPeer() and enums file added some refactoring fix paths + review fix rewiev fix some refactoring refactoring (makeView renamed) some refactoring refactoring (nodeFactory type removed) add util updateChildren(peer) refactoring (add util createScriptFunction and begin of great nodeFactory rewrite) nodeFactory and util refactoring refactoring (as casts removed in tests) add util alignText for tests refactoring (createParameterDeclaration compatible with tsc now) add Token compatible type and createFunctionDeclaration return type support add modifiers support (only in createFunctionDeclaration) refactoring (new tests) deleted golden files add basic method modifiers support add assertion on modifiers equality in tests improved modifierFlags support add assertEqualsAfter --- arkoala-arkts/libarkts/arktsconfig.json | 2 +- .../compatible/src/AbstractVisitor.ts | 1 - .../src/builder-lambda-transformer.ts | 70 +- .../compatible/src/function-transformer.ts | 8 +- .../compatible/src/memo-transformer.ts | 24 +- .../libarkts/compatible/src/print-visitor.ts | 12 +- .../libarkts/native/src/es2panda_lib.cc | 162 +++- arkoala-arkts/libarkts/package.json | 2 +- arkoala-arkts/libarkts/src/NativeModule.ts | 11 +- arkoala-arkts/libarkts/src/arkts/enums.ts | 55 ++ .../libarkts/src/arkts/factory/nodeFactory.ts | 774 ++++++++++-------- .../libarkts/src/arkts/factory/nodeTests.ts | 26 +- .../libarkts/src/arkts/factory/utilities.ts | 199 +++++ arkoala-arkts/libarkts/src/arkts/index.ts | 2 + .../libarkts/src/arkts/nodeByPeer.ts | 57 ++ arkoala-arkts/libarkts/src/arkts/types.ts | 252 +++--- arkoala-arkts/libarkts/src/arkts/utilities.ts | 146 +--- .../libarkts/src/arkts/utilitiesPublic.ts | 69 ++ arkoala-arkts/libarkts/src/arkts/visitor.ts | 43 +- arkoala-arkts/libarkts/src/es2panda.ts | 3 +- .../libarkts/test/es2panda/abc-gen.test.ts | 27 +- .../es2panda/builder-lambda-rewrite.test.ts | 155 ++-- .../create-function-declaration.test.ts | 196 ++++- .../test/es2panda/function-rewrite.test.ts | 23 +- .../es2panda/lambda-param-memoization.test.ts | 51 +- .../test/es2panda/print-visitor.test.ts | 106 +-- .../update-function-declaration.test.ts | 257 ++++-- ...e_adding-body-to-lambda-param.test.ts_dump | 93 --- ...ing-lambda-param-to-signature.test.ts_dump | 50 -- ...r-lambda-transformer-sample-1.test.ts_dump | 67 -- ...r-lambda-transformer-sample-2.test.ts_dump | 101 --- ...r-lambda-transformer-sample-3.test.ts_dump | 221 ----- ...ion_empty-function-with-param.test.ts_dump | 36 - ...ty-function-with-string-param.test.ts_dump | 44 - ...on-declaration_empty-function.test.ts_dump | 19 - ...nction-with-lambda-memo-param.test.ts_dump | 205 ----- ...d-identifier-to-function-body.test.ts_dump | 28 - ...if-statement-to-function-body.test.ts_dump | 57 -- ...n_add-params-to-memo-function.test.ts_dump | 77 -- ...s-expression-to-function-body.test.ts_dump | 38 - ...rn-statement-to-function-body.test.ts_dump | 43 - ...tion-declaration-memo-rewrite.test.ts_dump | 151 ---- ...ame-and-add-param-to-function.test.ts_dump | 58 -- arkoala-arkts/libarkts/test/test-util.ts | 89 +- arkoala/framework/native/src/callbacks.h | 32 - 45 files changed, 1882 insertions(+), 2260 deletions(-) create mode 100644 arkoala-arkts/libarkts/src/arkts/factory/utilities.ts create mode 100644 arkoala-arkts/libarkts/src/arkts/nodeByPeer.ts create mode 100644 arkoala-arkts/libarkts/src/arkts/utilitiesPublic.ts delete mode 100644 arkoala-arkts/libarkts/test/golden/builder-lambda-rewrite_adding-body-to-lambda-param.test.ts_dump delete mode 100644 arkoala-arkts/libarkts/test/golden/builder-lambda-rewrite_adding-lambda-param-to-signature.test.ts_dump delete mode 100644 arkoala-arkts/libarkts/test/golden/builder-lambda-rewrite_builder-lambda-transformer-sample-1.test.ts_dump delete mode 100644 arkoala-arkts/libarkts/test/golden/builder-lambda-rewrite_builder-lambda-transformer-sample-2.test.ts_dump delete mode 100644 arkoala-arkts/libarkts/test/golden/builder-lambda-rewrite_builder-lambda-transformer-sample-3.test.ts_dump delete mode 100644 arkoala-arkts/libarkts/test/golden/create-function-declaration_empty-function-with-param.test.ts_dump delete mode 100644 arkoala-arkts/libarkts/test/golden/create-function-declaration_empty-function-with-string-param.test.ts_dump delete mode 100644 arkoala-arkts/libarkts/test/golden/create-function-declaration_empty-function.test.ts_dump delete mode 100644 arkoala-arkts/libarkts/test/golden/lambda-param-memoization_memo-function-with-lambda-memo-param.test.ts_dump delete mode 100644 arkoala-arkts/libarkts/test/golden/update-function-declaration_add-identifier-to-function-body.test.ts_dump delete mode 100644 arkoala-arkts/libarkts/test/golden/update-function-declaration_add-if-statement-to-function-body.test.ts_dump delete mode 100644 arkoala-arkts/libarkts/test/golden/update-function-declaration_add-params-to-memo-function.test.ts_dump delete mode 100644 arkoala-arkts/libarkts/test/golden/update-function-declaration_add-property-access-expression-to-function-body.test.ts_dump delete mode 100644 arkoala-arkts/libarkts/test/golden/update-function-declaration_add-return-statement-to-function-body.test.ts_dump delete mode 100644 arkoala-arkts/libarkts/test/golden/update-function-declaration_function-declaration-memo-rewrite.test.ts_dump delete mode 100644 arkoala-arkts/libarkts/test/golden/update-function-declaration_update-name-and-add-param-to-function.test.ts_dump delete mode 100644 arkoala/framework/native/src/callbacks.h diff --git a/arkoala-arkts/libarkts/arktsconfig.json b/arkoala-arkts/libarkts/arktsconfig.json index 45fa27795..f37ee3a50 100644 --- a/arkoala-arkts/libarkts/arktsconfig.json +++ b/arkoala-arkts/libarkts/arktsconfig.json @@ -1,6 +1,6 @@ { "compilerOptions": { - "baseUrl": "./node_modules/@koalaui/plugin-api-panda-sdk/@panda/sdk", + "baseUrl": "../../incremental/tools/panda/node_modules/@panda/sdk", "paths": { "std": [ "./ets/stdlib/std" diff --git a/arkoala-arkts/libarkts/compatible/src/AbstractVisitor.ts b/arkoala-arkts/libarkts/compatible/src/AbstractVisitor.ts index 3fd6bba01..31bc01cac 100644 --- a/arkoala-arkts/libarkts/compatible/src/AbstractVisitor.ts +++ b/arkoala-arkts/libarkts/compatible/src/AbstractVisitor.ts @@ -41,4 +41,3 @@ export abstract class AbstractVisitor { ) } } - diff --git a/arkoala-arkts/libarkts/compatible/src/builder-lambda-transformer.ts b/arkoala-arkts/libarkts/compatible/src/builder-lambda-transformer.ts index 2ee362056..64eed608f 100644 --- a/arkoala-arkts/libarkts/compatible/src/builder-lambda-transformer.ts +++ b/arkoala-arkts/libarkts/compatible/src/builder-lambda-transformer.ts @@ -53,72 +53,78 @@ export class BuilderLambdaTransformer extends AbstractVisitor { } let instanceCalls = [] - let node1 = node + let leaf: arkts.CallExpression = node + while (true - && arkts.isPropertyAccessExpression(node1.expression) - && arkts.isIdentifier(node1.expression.name) - && arkts.isCallExpression(node1.expression.expression) + && arkts.isPropertyAccessExpression(leaf.expression) + && arkts.isIdentifier(leaf.expression.name) + && arkts.isCallExpression(leaf.expression.expression) ) { instanceCalls.push( arkts.factory.createCallExpression( - node1.expression.name, + leaf.expression.name, undefined, - node1.arguments + leaf.arguments ) ) - node1 = node1.expression.expression + leaf = leaf.expression.expression } - if (!this.isBuilderLambdaCall(node1)) { + if (!this.isBuilderLambdaCall(leaf) || !arkts.isIdentifier(leaf.expression)) { return node } + // foo((instance: string) => { + // return instance.<...instanceCalls>; + // }, ...leaf.arguments); + instanceCalls = instanceCalls.reverse() - let instanceLambdaBodyStatement: arkts.Identifier | arkts.CallExpression = arkts.factory.createIdentifier(BuilderLambdaTransformer.builderLambdaInstanceName) + let lambdaBody: arkts.Identifier | arkts.CallExpression = arkts.factory.createIdentifier(BuilderLambdaTransformer.builderLambdaInstanceName) instanceCalls.forEach(function (call: arkts.CallExpression) { - instanceLambdaBodyStatement = arkts.factory.createCallExpression( + if (!arkts.isIdentifier(call.expression)) { + throw new Error('unreachable (call expression should be identifier)') + } + lambdaBody = arkts.factory.createCallExpression( arkts.factory.createPropertyAccessExpression( - instanceLambdaBodyStatement, - call.expression as arkts.Identifier + lambdaBody, + call.expression ), undefined, call.arguments ) }) - const instanceLambdaBody = arkts.factory.createBlock([ - arkts.factory.createReturnStatement( - instanceLambdaBodyStatement - ) - ]) - const instanceLambdaParams = [ - arkts.factory.createParameterDeclaration( - undefined, - undefined, - arkts.factory.createIdentifier( - BuilderLambdaTransformer.builderLambdaInstanceName, - arkts.factory.createKeywordTypeNode(arkts.SyntaxKind.StringKeyword) - ) - ) - ] const lambdaArg = arkts.factory.createArrowFunction( undefined, undefined, - instanceLambdaParams, + [ + arkts.factory.createParameterDeclaration( + undefined, + undefined, + arkts.factory.createIdentifier(BuilderLambdaTransformer.builderLambdaInstanceName), + undefined, + arkts.factory.createKeywordTypeNode(arkts.SyntaxKind.StringKeyword), + undefined + ) + ], undefined, undefined, - instanceLambdaBody + arkts.factory.createBlock([ + arkts.factory.createReturnStatement( + lambdaBody + ) + ]) ) - let funcName = (node1.expression as arkts.Identifier).text + let funcName = leaf.expression.text funcName = funcName.slice(BuilderLambdaTransformer.builderLambdaPrefix.length) return arkts.factory.updateCallExpression( node, - arkts.factory.updateIdentifier(node1.expression as arkts.Identifier, funcName), + arkts.factory.updateIdentifier(leaf.expression, funcName), undefined, [ lambdaArg, - ...node1.arguments + ...leaf.arguments ] ) } diff --git a/arkoala-arkts/libarkts/compatible/src/function-transformer.ts b/arkoala-arkts/libarkts/compatible/src/function-transformer.ts index ae7e21d97..5b6de9af2 100644 --- a/arkoala-arkts/libarkts/compatible/src/function-transformer.ts +++ b/arkoala-arkts/libarkts/compatible/src/function-transformer.ts @@ -54,10 +54,10 @@ function transformMethodDeclaration(node: arkts.MethodDeclaration): arkts.Node { arkts.factory.createParameterDeclaration( undefined, undefined, - arkts.factory.createIdentifier( - "x", - arkts.factory.createKeywordTypeNode(arkts.SyntaxKind.StringKeyword) - ) + arkts.factory.createIdentifier("x"), + undefined, + arkts.factory.createKeywordTypeNode(arkts.SyntaxKind.StringKeyword), + undefined ) return arkts.factory.updateMethodDeclaration( node, diff --git a/arkoala-arkts/libarkts/compatible/src/memo-transformer.ts b/arkoala-arkts/libarkts/compatible/src/memo-transformer.ts index 5276438c2..3d68b09ec 100644 --- a/arkoala-arkts/libarkts/compatible/src/memo-transformer.ts +++ b/arkoala-arkts/libarkts/compatible/src/memo-transformer.ts @@ -55,23 +55,23 @@ function transformMethodDeclaration(node: arkts.MethodDeclaration): arkts.Node { arkts.factory.createParameterDeclaration( undefined, undefined, - arkts.factory.createIdentifier( - "__memo_context", - arkts.factory.createTypeReferenceNode( - arkts.factory.createIdentifier("__memo_context_type") - ) - ) + arkts.factory.createIdentifier("__memo_context"), + undefined, + arkts.factory.createTypeReferenceNode( + arkts.factory.createIdentifier("__memo_context_type") + ), + undefined ) const memoIdParam = arkts.factory.createParameterDeclaration( undefined, undefined, - arkts.factory.createIdentifier( - "__memo_id", - arkts.factory.createTypeReferenceNode( - arkts.factory.createIdentifier("__memo_id_type") - ) - ) + arkts.factory.createIdentifier("__memo_id"), + undefined, + arkts.factory.createTypeReferenceNode( + arkts.factory.createIdentifier("__memo_id_type") + ), + undefined ) const bodyStatements = [ arkts.factory.createIfStatement( diff --git a/arkoala-arkts/libarkts/compatible/src/print-visitor.ts b/arkoala-arkts/libarkts/compatible/src/print-visitor.ts index caee5aa08..37e663d01 100644 --- a/arkoala-arkts/libarkts/compatible/src/print-visitor.ts +++ b/arkoala-arkts/libarkts/compatible/src/print-visitor.ts @@ -2,6 +2,16 @@ import * as arkts from "../../src/arkts" import { AbstractVisitor } from "./AbstractVisitor"; export class PrintVisitor extends AbstractVisitor { + constructor( + // public tracer: Tracer, + // public sourceFile: api.SourceFile, + // public functionTable: FunctionTable, + // ctx: api.TransformationContext + ) { + // super(ctx) + super() + } + private result = "" private print(s: string) { @@ -9,7 +19,7 @@ export class PrintVisitor extends AbstractVisitor { } visitor(beforeChildren: arkts.Node): arkts.Node { - this.print(beforeChildren.constructor.name) + this.print(beforeChildren.constructor.name + " (mod: " + beforeChildren.modifier + ")") const node = this.visitEachChild(beforeChildren) return node diff --git a/arkoala-arkts/libarkts/native/src/es2panda_lib.cc b/arkoala-arkts/libarkts/native/src/es2panda_lib.cc index d9c9feea2..9357e8333 100644 --- a/arkoala-arkts/libarkts/native/src/es2panda_lib.cc +++ b/arkoala-arkts/libarkts/native/src/es2panda_lib.cc @@ -204,6 +204,25 @@ KNativePointer impl_StringLiteralString(KNativePointer contextPtr, KNativePointe } KOALA_INTEROP_2(StringLiteralString, KNativePointer, KNativePointer, KNativePointer) +KNativePointer impl_CreateMethodDefinition( + KNativePointer contextPtr, + KInt kindT, + KNativePointer keyPtr, + KNativePointer valuePtr, + KInt modifiersT, + KBoolean isComputedT +) { + auto context = reinterpret_cast(contextPtr); + auto kind = static_cast(kindT); + auto key = reinterpret_cast(keyPtr); + auto value = reinterpret_cast(valuePtr); + auto modifiers = static_cast(modifiersT); + auto isComputed = static_cast(isComputedT); + + return GetImpl()->CreateMethodDefinition(context, kind, key, value, modifiers, isComputed); +} +KOALA_INTEROP_6(CreateMethodDefinition, KNativePointer, KNativePointer, KInt, KNativePointer, KNativePointer, KInt, KBoolean) + KNativePointer impl_AstNodeDumpJsonConst(KNativePointer contextPtr, KNativePointer nodePtr) { auto context = reinterpret_cast(contextPtr); auto node = reinterpret_cast(nodePtr); @@ -218,6 +237,18 @@ KNativePointer impl_AstNodeDumpEtsSrcConst(KNativePointer contextPtr, KNativePoi } KOALA_INTEROP_2(AstNodeDumpEtsSrcConst, KNativePointer, KNativePointer, KNativePointer) +KNativePointer impl_ETSParserCreateExpression(KNativePointer contextPtr, KStringPtr sourceCodePtr, KInt flagsT) { + auto context = reinterpret_cast(contextPtr); + auto flags = static_cast(flagsT); + + cout << "<" << getStringCopy(sourceCodePtr) << ">" << endl; + + return GetImpl()->ETSParserCreateExpression(context, getStringCopy(sourceCodePtr), flags); + // return GetImpl()->ETSParserCreateExpression(context, getStringCopy(sourceCodePtr), static_cast(1U << 1U)); +} +KOALA_INTEROP_3(ETSParserCreateExpression, KNativePointer, KNativePointer, KStringPtr, KInt) + + /* TODO: AstNodeKind should be provided by es2panda */ @@ -240,11 +271,16 @@ enum AstNodeKind { NumberLiteral = 16, VariableDeclaration = 17, ClassStaticBlock = 18, + Program = 19, + BinaryExpression = 20, + FunctionExpression = 21, + ScriptFunction = 22, }; -KInt impl_GetKind(KNativePointer nodePtr) { - auto node = reinterpret_cast(nodePtr); - +static KInt GetKind(es2panda_Context* context, es2panda_AstNode* node) { + if (GetImpl()->AstNodeIsProgramConst(context, node)) { + return AstNodeKind::Program; + } if (GetImpl()->IsIdentifier(node)) { return AstNodeKind::Identifier; } @@ -299,10 +335,26 @@ KInt impl_GetKind(KNativePointer nodePtr) { if (GetImpl()->IsClassStaticBlock(node)) { return AstNodeKind::ClassStaticBlock; } + if (GetImpl()->IsBinaryExpression(node)) { + return AstNodeKind::BinaryExpression; + } + if (GetImpl()->IsFunctionExpression(node)) { + return AstNodeKind::FunctionExpression; + } + if (GetImpl()->IsScriptFunction(node)) { + return AstNodeKind::ScriptFunction; + } + + return 0; +} + +KInt impl_GetKind(KNativePointer contextPtr, KNativePointer nodePtr) { + auto context = reinterpret_cast(contextPtr); + auto node = reinterpret_cast(nodePtr); - return -1; + return GetKind(context, node); } -KOALA_INTEROP_1(GetKind, KInt, KNativePointer) +KOALA_INTEROP_2(GetKind, KInt, KNativePointer, KNativePointer) KBoolean impl_IsProgram(KNativePointer contextPtr, KNativePointer nodePtr) { auto context = reinterpret_cast(contextPtr); @@ -708,6 +760,10 @@ KNativePointer impl_CreateBlockStatement( KOALA_INTEROP_3(CreateBlockStatement, KNativePointer, KNativePointer, KNativePointerArray, KInt) // TODO: rewrite everything here +/* +----------------------------------------------------------------------------------------------------------------------------- +*/ + es2panda_AstNode * __parentNode; es2panda_Context * __context; @@ -724,7 +780,7 @@ static void SetRightParent(es2panda_AstNode *node, void *arg) GetImpl()->AstNodeIterateConst(ctx, node, changeParent); } -KNativePointer impl_UpdateAllChilds(KNativePointer contextPtr, KNativePointer programPtr) { +KNativePointer impl_AstNodeUpdateAll(KNativePointer contextPtr, KNativePointer programPtr) { auto context = reinterpret_cast(contextPtr); auto program = reinterpret_cast(programPtr); @@ -732,7 +788,7 @@ KNativePointer impl_UpdateAllChilds(KNativePointer contextPtr, KNativePointer pr return program; } -KOALA_INTEROP_2(UpdateAllChilds, KNativePointer, KNativePointer, KNativePointer) +KOALA_INTEROP_2(AstNodeUpdateAll, KNativePointer, KNativePointer, KNativePointer) KNativePointer impl_AstNodeUpdateChildren(KNativePointer contextPtr, KNativePointer nodePtr) { auto context = reinterpret_cast(contextPtr); @@ -751,6 +807,69 @@ KNativePointer impl_AstNodeUpdateChildren(KNativePointer contextPtr, KNativePoin } KOALA_INTEROP_2(AstNodeUpdateChildren, KNativePointer, KNativePointer, KNativePointer) + +std::string __result; +std::size_t __depth; + +static void appendModifiers(es2panda_AstNode *node) { + __depth += 2; + std::size_t kind = GetKind(__context, node); + __result += std::string(__depth, '_'); + __result += "kind: " + std::to_string(kind); + __result += ", mod: " + std::to_string(static_cast(GetImpl()->AstNodeModifiers(__context, node))); + // if (kind == 22) { + // __result += ", script_function_flags: " + std::to_string(GetImpl()->ScriptFunctionFlagsConst(__context, node)); + // } + __result += "\n"; + GetImpl()->AstNodeIterateConst(__context, node, appendModifiers); + __depth -= 2; +} + +KNativePointer impl_AstNodeDumpModifiers( + KNativePointer contextPtr, + KNativePointer nodePtr +) { + auto context = reinterpret_cast(contextPtr); + auto node = reinterpret_cast(nodePtr); + + __context = context; + __result = ""; + __depth = 0; + GetImpl()->AstNodeIterateConst(context, node, appendModifiers); + + return new std::string(__result); +} +KOALA_INTEROP_2(AstNodeDumpModifiers, KNativePointer, KNativePointer, KNativePointer) +/* +----------------------------------------------------------------------------------------------------------------------------- +*/ + + +KNativePointer impl_CreateAstDumper( + KNativePointer contextPtr, + KNativePointer nodePtr, + KStringPtr sourcePtr +) { + auto context = reinterpret_cast(contextPtr); + auto node = reinterpret_cast(nodePtr); + + return GetImpl()->CreateAstDumper(context, node, getStringCopy(sourcePtr)); +} +KOALA_INTEROP_3(CreateAstDumper, KNativePointer, KNativePointer, KNativePointer, KStringPtr) + +KNativePointer impl_AstDumperModifierToString( + KNativePointer contextPtr, + KNativePointer dumperPtr, + KInt flagsT +) { + auto context = reinterpret_cast(contextPtr); + auto dumper = reinterpret_cast(dumperPtr); + auto flags = static_cast(flagsT); + + return new std::string(GetImpl()->AstDumperModifierToString(context, dumper, flags)); +} +KOALA_INTEROP_3(AstDumperModifierToString, KNativePointer, KNativePointer, KNativePointer, KInt) + KNativePointer impl_MethodDefinitionFunction( KNativePointer contextPtr, KNativePointer nodePtr @@ -762,6 +881,18 @@ KNativePointer impl_MethodDefinitionFunction( } KOALA_INTEROP_2(MethodDefinitionFunction, KNativePointer, KNativePointer, KNativePointer) +KInt impl_MethodDefinitionKindConst( + KNativePointer contextPtr, + KNativePointer nodePtr +) { + auto context = reinterpret_cast(contextPtr); + auto node = reinterpret_cast(nodePtr); + + return GetImpl()->MethodDefinitionKindConst(context, node); +} +KOALA_INTEROP_2(MethodDefinitionKindConst, KInt, KNativePointer, KNativePointer) + + KNativePointer impl_AstNodeSetParent( KNativePointer contextPtr, KNativePointer astPtr, @@ -971,6 +1102,15 @@ KNativePointer impl_CreateFunctionExpression(KNativePointer contextPtr, KNativeP } KOALA_INTEROP_2(CreateFunctionExpression, KNativePointer, KNativePointer, KNativePointer) +KNativePointer impl_UpdateFunctionExpression(KNativePointer contextPtr, KNativePointer nodePtr, KNativePointer funcPtr) { + auto context = reinterpret_cast(contextPtr); + auto node = reinterpret_cast(nodePtr); + auto func = reinterpret_cast(funcPtr); + + return GetImpl()->UpdateFunctionExpression(context, node, func); +} +KOALA_INTEROP_3(UpdateFunctionExpression, KNativePointer, KNativePointer, KNativePointer, KNativePointer) + KNativePointer impl_CreateArrowFunctionExpression(KNativePointer contextPtr, KNativePointer nodePtr) { auto context = reinterpret_cast(contextPtr); auto node = reinterpret_cast(nodePtr); @@ -995,6 +1135,14 @@ KNativePointer impl_ArrowFunctionExpressionCreateTypeAnnotation(KNativePointer c } KOALA_INTEROP_2(ArrowFunctionExpressionCreateTypeAnnotation, KNativePointer, KNativePointer, KNativePointer) +KNativePointer impl_FunctionExpressionFunction(KNativePointer contextPtr, KNativePointer nodePtr) { + auto context = reinterpret_cast(contextPtr); + auto node = reinterpret_cast(nodePtr); + + return GetImpl()->FunctionExpressionFunction(context, node); +} +KOALA_INTEROP_2(FunctionExpressionFunction, KNativePointer, KNativePointer, KNativePointer) + KNativePointer impl_ExpressionStatementGetExpression(KNativePointer contextPtr, KNativePointer nodePtr) { auto context = reinterpret_cast(contextPtr); auto node = reinterpret_cast(nodePtr); diff --git a/arkoala-arkts/libarkts/package.json b/arkoala-arkts/libarkts/package.json index 2736366f3..15ea4044a 100644 --- a/arkoala-arkts/libarkts/package.json +++ b/arkoala-arkts/libarkts/package.json @@ -23,7 +23,7 @@ "compile:koala:interop": "cd ../../interop && npm run compile", "compile:native": "cd native && meson setup build_es2panda && cd build_es2panda && meson compile", "compile": "npm run compile:koala:interop && npm run compile:native", - "test": "npm run compile && backend=es2panda TS_NODE_PROJECT=./test/tsconfig.json mocha -r tsconfig-paths/register --config .mocha.json", + "test": "npm run compile && backend=es2panda TS_NODE_PROJECT=./test/tsconfig.json mocha -r tsconfig-paths/register --config .mocha.json --reporter-option maxDiffSize=262144", "compatible": "cd compatible && npx webpack --config arkts.webpack.config.js", "webpack": "npm run compile && npm run compatible && npx webpack --config es2panda.webpack.config.js", "run:dev": "npm run run && backend=es2panda node build/api/es2panda.js", diff --git a/arkoala-arkts/libarkts/src/NativeModule.ts b/arkoala-arkts/libarkts/src/NativeModule.ts index 2f27eb160..d527d2681 100644 --- a/arkoala-arkts/libarkts/src/NativeModule.ts +++ b/arkoala-arkts/libarkts/src/NativeModule.ts @@ -21,6 +21,10 @@ export type KNativePointerArray = BigUint64Array export interface NativeModule { _ContextState(context: KNativePointer): KInt _ContextErrorMessage(context: KNativePointer): KNativePointer + _ETSParserCreateExpression(context: KNativePointer, sourceCode: String, flags: KInt): KNativePointer + _AstNodeDumpModifiers(context: KNativePointer, node: KNativePointer): KNativePointer + _CreateAstDumper(context: KNativePointer, node: KNativePointer, source: String): KNativePointer + _AstDumperModifierToString(context: KNativePointer, dumper: KNativePointer, flags: KInt): KNativePointer _CreateConfig(argc: number, argv: string[]): KNativePointer _CreateContextFromString(config: KNativePointer, source: String, filename: String): KNativePointer @@ -74,6 +78,7 @@ export interface NativeModule { _ReturnStatementArgument(context: KNativePointer, node: KNativePointer): KNativePointer _CreateIfStatement(context: KNativePointer, test: KNativePointer, consequent: KNativePointer, alternate: KNativePointer): KNativePointer _CreateBinaryExpression(context: KNativePointer, left: KNativePointer, right: KNativePointer, operatorType: KInt): KNativePointer + _CreateMethodDefinition(context: KNativePointer, kind: KInt, key: KNativePointer, value: KNativePointer, modifiers: KInt, isComputed: KBoolean): KNativePointer _CreateFunctionSignature(context: KNativePointer, typeParams: KNativePointer, params: KNativePointerArray, paramsLen: KInt, returnTypeAnnotation: KNativePointer): KNativePointer _CreateScriptFunction(context: KNativePointer, databody: KNativePointer, datasignature: KNativePointer, datafuncFlags: KInt, dataflags: KInt, datadeclare: KBoolean): KNativePointer @@ -93,6 +98,7 @@ export interface NativeModule { _UpdateIdentifier2(context: KNativePointer, ast: KNativePointer, name: string, typeAnnotation: KNativePointer): KNativePointer _UpdateMethodDefinition(context: KNativePointer, node: KNativePointer, kind: KInt, key: KNativePointer, value: KNativePointer, modifiers: KInt, isComputed: KBoolean): KNativePointer _MethodDefinitionFunction(context: KNativePointer, node: KNativePointer): KNativePointer + _MethodDefinitionKindConst(context: KNativePointer, node: KNativePointer): KInt _CreateMemberExpression(context: KNativePointer, object: KNativePointer, property: KNativePointer, kind: KInt, computed: KBoolean, optional: KBoolean): KNativePointer _UpdateMemberExpression(context: KNativePointer, node: KNativePointer, object: KNativePointer, property: KNativePointer, kind: KInt, computed: KBoolean, optional: KBoolean): KNativePointer @@ -101,9 +107,11 @@ export interface NativeModule { _CreateCallExpression(context: KNativePointer, callee: KNativePointer, args: KNativePointerArray, argsLen: KInt, typeParams: KNativePointer, optional: KBoolean, trailingComma: KBoolean): KNativePointer _UpdateCallExpression(node: KNativePointer, context: KNativePointer, callee: KNativePointer, args: KNativePointerArray, argsLen: KInt, typeParams: KNativePointer, optional: KBoolean, trailingComma: KBoolean): KNativePointer _CreateArrowFunctionExpression(context: KNativePointer, node: KNativePointer): KNativePointer + _FunctionExpressionFunction(context: KNativePointer, node: KNativePointer): KNativePointer _ArrowFunctionExpressionFunction(context: KNativePointer, node: KNativePointer): KNativePointer _ArrowFunctionExpressionCreateTypeAnnotation(context: KNativePointer, node: KNativePointer): KNativePointer _CreateFunctionExpression(context: KNativePointer, node: KNativePointer): KNativePointer + _UpdateFunctionExpression(context: KNativePointer, original: KNativePointer, node: KNativePointer): KNativePointer _CreateExpressionStatement(context: KNativePointer, expr: KNativePointer): KNativePointer _UpdateExpressionStatement(context: KNativePointer, node: KNativePointer, expr: KNativePointer): KNativePointer @@ -119,7 +127,7 @@ export interface NativeModule { _CreateStringLiteral(context: KNativePointer, string: string): KNativePointer _StringLiteralString(context: KNativePointer, node: KNativePointer): KNativePointer - _GetKind(node: KNativePointer): KInt + _GetKind(context: KNativePointer, node: KNativePointer): KInt _BlockStatementStatements(context: KNativePointer, node: KNativePointer): KNativePointer _BlockStatementSetStatements(context: KNativePointer, node: KNativePointer, statements: KNativePointerArray, statementsLen: KInt): void @@ -136,6 +144,7 @@ export interface NativeModule { _AstNodeDumpJsonConst(context: KNativePointer, node: KNativePointer): KNativePointer _AstNodeDumpEtsSrcConst(context: KNativePointer, node: KNativePointer): KNativePointer _AstNodeUpdateChildren(context: KNativePointer, node: KNativePointer): void + _AstNodeUpdateAll(context: KNativePointer, node: KNativePointer): void _VarBinderSetProgram(context: KNativePointer): void _VarBinderSetContext(context: KNativePointer): void diff --git a/arkoala-arkts/libarkts/src/arkts/enums.ts b/arkoala-arkts/libarkts/src/arkts/enums.ts index dcdac229d..719dd4d9e 100644 --- a/arkoala-arkts/libarkts/src/arkts/enums.ts +++ b/arkoala-arkts/libarkts/src/arkts/enums.ts @@ -15,6 +15,8 @@ export { SyntaxKind } from "@koalaui/ets-tsc" +export { TokenSyntaxKind } from "@koalaui/ets-tsc" + export enum ContextState { ES2PANDA_STATE_NEW = 0, ES2PANDA_STATE_PARSED = 1, @@ -48,6 +50,7 @@ export enum es2pandaKind { NumberLiteral = 16, VariableDeclaration = 17, ClassStaticBlock = 18, + Program = 19, }; export enum Es2pandaTokenType { @@ -296,3 +299,55 @@ export enum Es2pandaModifierFlags { MODIFIER_FLAGS_GETTER_SETTER = MODIFIER_FLAGS_GETTER | MODIFIER_FLAGS_SETTER, MODIFIER_FLAGS_EXPORTED = MODIFIER_FLAGS_EXPORT | MODIFIER_FLAGS_DEFAULT_EXPORT | MODIFIER_FLAGS_EXPORT_TYPE, }; + +export enum Es2pandaScriptFunctionFlags { + SCRIPT_FUNCTION_FLAGS_NONE = 0, + SCRIPT_FUNCTION_FLAGS_GENERATOR = 1 << 0, + SCRIPT_FUNCTION_FLAGS_ASYNC = 1 << 1, + SCRIPT_FUNCTION_FLAGS_ARROW = 1 << 2, + SCRIPT_FUNCTION_FLAGS_EXPRESSION = 1 << 3, + SCRIPT_FUNCTION_FLAGS_OVERLOAD = 1 << 4, + SCRIPT_FUNCTION_FLAGS_CONSTRUCTOR = 1 << 5, + SCRIPT_FUNCTION_FLAGS_METHOD = 1 << 6, + SCRIPT_FUNCTION_FLAGS_STATIC_BLOCK = 1 << 7, + SCRIPT_FUNCTION_FLAGS_HIDDEN = 1 << 8, + SCRIPT_FUNCTION_FLAGS_IMPLICIT_SUPER_CALL_NEEDED = 1 << 9, + SCRIPT_FUNCTION_FLAGS_ENUM = 1 << 10, + SCRIPT_FUNCTION_FLAGS_EXTERNAL = 1 << 11, + SCRIPT_FUNCTION_FLAGS_PROXY = 1 << 12, + SCRIPT_FUNCTION_FLAGS_THROWS = 1 << 13, + SCRIPT_FUNCTION_FLAGS_RETHROWS = 1 << 14, + SCRIPT_FUNCTION_FLAGS_GETTER = 1 << 15, + SCRIPT_FUNCTION_FLAGS_SETTER = 1 << 16, + SCRIPT_FUNCTION_FLAGS_ENTRY_POINT = 1 << 17, + SCRIPT_FUNCTION_FLAGS_INSTANCE_EXTENSION_METHOD = 1 << 18, + SCRIPT_FUNCTION_FLAGS_HAS_RETURN = 1 << 19, + SCRIPT_FUNCTION_FLAGS_ASYNC_IMPL = 1 << 20, + SCRIPT_FUNCTION_FLAGS_EXTERNAL_OVERLOAD = 1 << 21, +}; + +export enum Es2pandaMemberExpressionKind { + MEMBER_EXPRESSION_KIND_NONE = 0, + MEMBER_EXPRESSION_KIND_ELEMENT_ACCESS = 1 << 0, + MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS = 1 << 1, + MEMBER_EXPRESSION_KIND_GETTER = 1 << 2, + MEMBER_EXPRESSION_KIND_SETTER = 1 << 3, +}; + +export enum Es2pandaClassDefinitionModifiers { + CLASS_DEFINITION_MODIFIERS_NONE = 0, + CLASS_DEFINITION_MODIFIERS_DECLARATION = 1 << 0, + CLASS_DEFINITION_MODIFIERS_ID_REQUIRED = 1 << 1, + CLASS_DEFINITION_MODIFIERS_GLOBAL = 1 << 2, + CLASS_DEFINITION_MODIFIERS_HAS_SUPER = 1 << 3, + CLASS_DEFINITION_MODIFIERS_SET_CTOR_ID = 1 << 4, + CLASS_DEFINITION_MODIFIERS_EXTERN = 1 << 5, + CLASS_DEFINITION_MODIFIERS_ANONYMOUS = 1 << 6, + CLASS_DEFINITION_MODIFIERS_GLOBAL_INITIALIZED = 1 << 7, + CLASS_DEFINITION_MODIFIERS_CLASS_DECL = 1 << 8, + CLASS_DEFINITION_MODIFIERS_INNER = 1 << 9, + CLASS_DEFINITION_MODIFIERS_FROM_EXTERNAL = 1 << 10, + CLASS_DEFINITION_MODIFIERS_LOCAL = 1 << 11, + CLASS_DEFINITION_MODIFIERS_CLASSDEFINITION_CHECKED = 1 << 12, + CLASS_DEFINITION_MODIFIERS_DECLARATION_ID_REQUIRED = CLASS_DEFINITION_MODIFIERS_DECLARATION | CLASS_DEFINITION_MODIFIERS_ID_REQUIRED, +}; diff --git a/arkoala-arkts/libarkts/src/arkts/factory/nodeFactory.ts b/arkoala-arkts/libarkts/src/arkts/factory/nodeFactory.ts index 5dfd08c9c..0f0ec9915 100644 --- a/arkoala-arkts/libarkts/src/arkts/factory/nodeFactory.ts +++ b/arkoala-arkts/libarkts/src/arkts/factory/nodeFactory.ts @@ -1,11 +1,28 @@ import * as ts from "@koalaui/ets-tsc" import { nativeModule } from "../../NativeModule" -import { Access, KNativePointer, withPtrArray, withString } from "@koalaui/interop" -import * as util from "../utilities" +import { + throwError, + createScriptFunction, + updateScriptFunction, + updateChildren, + updateNode, + withString, + withNodeArray, + passToken, + passScriptFuncModifier, + passScriptFuncModifiers, + passModifier, + passModifiers, + setModifierFlags, + getModifierFlags, +} from "./utilities" import { Es2pandaPrimitiveType, Es2pandaMethodDefinitionKind, Es2pandaModifierFlags, + Es2pandaScriptFunctionFlags, + Es2pandaMemberExpressionKind, + Es2pandaClassDefinitionModifiers, } from "../enums" import { // util types: @@ -14,7 +31,11 @@ import { NULLPTR_ARRAY, // ts types: + ModifierLike, + BinaryOperatorToken, + Node, + Token, Identifier, StringLiteral, FunctionDeclaration, @@ -29,7 +50,6 @@ import { ArrowFunction, TypeReferenceNode, BinaryExpression, - BinaryOperatorToken, ClassDeclaration, FunctionTypeNode, TypeNode, @@ -38,105 +58,18 @@ import { SourceFile, ClassElement, MethodDeclaration, + ConstructorDeclaration, // ets types: ETSPrimitiveType, } from "../types" +import { dumpModifiers } from "../utilities" -export interface NodeFactory { - createIdentifier(name: string, typeAnnotation?: Node): Identifier; - updateIdentifier(node: Identifier, name: string, typeAnnotation?: TypeNode): Identifier; - createStringLiteral(text: string, isSingleQuote?: boolean): StringLiteral; - createFunctionDeclaration( - modifiers: undefined, - asteriskToken: undefined, - name: Identifier, - typeParameters: undefined, - parameters: readonly ParameterDeclaration[], - type: undefined, - body: Block | undefined - ): FunctionDeclaration; - updateFunctionDeclaration( - node: FunctionDeclaration, - modifiers: undefined, - asteriskToken: undefined, - name: Identifier, - typeParameters: undefined, - parameters: readonly ParameterDeclaration[], - type: undefined, - body: Block | undefined - ): FunctionDeclaration; - createParameterDeclaration( - modifiers: undefined, - dotDotDotToken: undefined, - name: Identifier, - questionToken?: undefined, - type?: TypeNode, - initializer?: undefined - ): ParameterDeclaration; - createEtsPrimitiveType(type: Es2pandaPrimitiveType): ETSPrimitiveType; - createTypeReferenceNode(identifier: Identifier, typeArguments?: undefined): TypeReferenceNode; - createKeywordTypeNode(TKind: ts.KeywordTypeSyntaxKind): KeywordTypeNode; - createBlock(statements: Statement[], multiline?: boolean): Block; - updateBlock(node: Block, statements: Statement[], multiline?: boolean): Block; - createExpressionStatement(expression: Expression): ExpressionStatement; - updateExpressionStatement(node: ExpressionStatement, expression: Expression): ExpressionStatement; - createReturnStatement(expression: Expression): ReturnStatement; - createPropertyAccessExpression(expression: Expression, name: Identifier): PropertyAccessExpression; - updatePropertyAccessExpression(node: PropertyAccessExpression, expression: Expression, name: Identifier): PropertyAccessExpression; - createCallExpression( - expression: Expression, - typeArguments?: undefined, - argumentsArray?: readonly Expression[] | undefined - ): CallExpression; - updateCallExpression( - node: CallExpression, - expression: Expression, - typeArguments?: undefined, - argumentsArray?: readonly Expression[] | undefined - ): CallExpression; - createIfStatement(expression: Expression, thenStatement: Statement, elseStatement?: undefined): IfStatement; - createToken(token: ts.TokenSyntaxKind): BinaryOperatorToken; - createBinaryExpression(left: Expression, operator: BinaryOperatorToken, right: Expression): BinaryExpression; - createArrowFunction( - modifiers: undefined, - typeParameters: undefined, - parameters: ParameterDeclaration[], - type: undefined, - equalsGreaterThanToken: undefined, - body: Block - ): ArrowFunction; - updateSourceFile(node: SourceFile, statements: readonly Statement[]): SourceFile; - updateClassDeclaration( - node: ClassDeclaration, - modifiers: undefined, - name: Identifier | undefined, - typeParameters: undefined, - heritageClauses: undefined, - members: readonly ClassElement[] - ): ClassDeclaration; - createFunctionTypeNode( - typeParameters: undefined, - parameters: readonly ParameterDeclaration[], - type: TypeNode - ): FunctionTypeNode; - updateMethodDeclaration( - node: MethodDeclaration, - modifiers: undefined, // TODO: support (now default public, static) - asteriskToken: undefined, - name: Identifier, - questionToken: undefined, - typeParameters: undefined, - parameters: readonly ParameterDeclaration[], - type: undefined, - body: Block - ): MethodDeclaration; -} - -// TODO: add flags and base in the future -export function createNodeFactory(): NodeFactory { - const factory: NodeFactory = { +// TODO: add flags and base +export function createNodeFactory() { + return { createIdentifier, + createIdentifierWithAnnotation, updateIdentifier, createStringLiteral, createFunctionDeclaration, @@ -161,98 +94,105 @@ export function createNodeFactory(): NodeFactory { updateSourceFile, updateClassDeclaration, createFunctionTypeNode, + createMethodDeclaration, updateMethodDeclaration, + createConstructorDeclaration, } - return factory + // @api + // createIdentifier( + // text: string + // ): Identifier; + function createIdentifier(name: string): Identifier { + const peer = withString(name, (_name: string) => { + return nativeModule._CreateIdentifier1(Global.context, _name) + }) + updateChildren(peer) + + return new Identifier(peer) + } // @api - function createIdentifier(name: string, typeAnnotation?: Node): Identifier { - const peer = withString(name, (name: string) => { - if (typeAnnotation !== undefined) { - return nativeModule._CreateIdentifier2(Global.context, name, typeAnnotation.peer) - } - return nativeModule._CreateIdentifier1(Global.context, name) + // NOT PROVIDED + function createIdentifierWithAnnotation(name: string, typeAnnotation: Node): Identifier { + const peer = withString(name, (_name: string) => { + return nativeModule._CreateIdentifier2(Global.context, _name, typeAnnotation.peer) }) - if (typeAnnotation !== undefined) { - util.setParent(typeAnnotation.peer, peer) - } - util.updateChildren(peer) + updateChildren(peer) return new Identifier(peer) } + // TODO: remove this method maybe // @api + // NOT PROVIDED function updateIdentifier(node: Identifier, name: string, typeAnnotation?: TypeNode): Identifier { - const peer = - (typeAnnotation === undefined) - ? - nativeModule._UpdateIdentifier1(Global.context, node.peer, name) - : - nativeModule._UpdateIdentifier2(Global.context, node.peer, name, typeAnnotation.peer) - - if (typeAnnotation !== undefined) { - util.setParent(typeAnnotation.peer, peer) - } - util.setModifierFlags(peer, util.getModifierFlags(node.peer)) - util.updateChildren(peer) + const peer = withString(name, (_name: string) => { + return (typeAnnotation === undefined) ? + nativeModule._UpdateIdentifier1(Global.context, node.peer, _name) : + nativeModule._UpdateIdentifier2(Global.context, node.peer, _name, typeAnnotation.peer) + }) + updateNode(peer, node.peer) + updateChildren(peer) return new Identifier(peer) } // @api + // createStringLiteral( + // text: string, + // isSingleQuote?: boolean + // ): StringLiteral; function createStringLiteral(s: string): StringLiteral { - const peer = withString(s, (s: string) => { - return nativeModule._CreateStringLiteral(Global.context, s) + const peer = withString(s, (_s: string) => { + return nativeModule._CreateStringLiteral(Global.context, _s) }) + updateChildren(peer) return new StringLiteral(peer) } - // tsc: createFunctionDeclaration(modifiers: readonly ModifierLike[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; // @api + // createFunctionDeclaration( + // modifiers: readonly ModifierLike[] | undefined, + // asteriskToken: AsteriskToken | undefined, + // name: string | Identifier | undefined, + // typeParameters: readonly TypeParameterDeclaration[] | undefined, + // parameters: readonly ParameterDeclaration[], + // type: TypeNode | undefined, + // body: Block | undefined + // ): FunctionDeclaration; function createFunctionDeclaration( - modifiers: undefined, + modifiers: readonly ModifierLike[] | undefined, asteriskToken: undefined, - name: Identifier, + name: string | Identifier, typeParameters: undefined, parameters: readonly ParameterDeclaration[], - type: undefined, + type: TypeNode | undefined, body: Block | undefined ): FunctionDeclaration { - const params = new BigUint64Array(parameters.map(node => BigInt(node.peer))) - - const peer = withString(name.text, (_name: string) => { - return withPtrArray(params, Access.READWRITE, (_params: BigUint64Array) => { - const _paramsLen = params.length + const peer = withString((name instanceof Identifier) ? name.text : name, (_name: string) => { + return withNodeArray(parameters, (_parameters: BigUint64Array) => { const _context = Global.context - const _body = body ? body.peer : NULLPTR const _signature = nativeModule._CreateFunctionSignature( _context, NULLPTR, - _params, - _paramsLen, - NULLPTR + _parameters, + _parameters.length, + (type !== undefined) ? type.peer : NULLPTR ) - const _scriptFunc = nativeModule._CreateScriptFunction( - _context, - _body, + // TODO: support decl param + const _scriptFunc = createScriptFunction( + (body !== undefined) ? body.peer : NULLPTR, _signature, - // TODO: fix flag params - 0, - 0, - false + (modifiers !== undefined) ? passScriptFuncModifiers(modifiers) : Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_NONE, + Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC | Es2pandaModifierFlags.MODIFIER_FLAGS_STATIC | + ((modifiers !== undefined) ? passModifiers(modifiers) : Es2pandaModifierFlags.MODIFIER_FLAGS_NONE), + false, + nativeModule._CreateIdentifier1(_context, _name) ) - if (_body !== NULLPTR) { - nativeModule._AstNodeSetParent(_context, _body, _scriptFunc) - } - - const _ident = nativeModule._CreateIdentifier1(_context, _name) - nativeModule._ScriptFunctionSetIdent(_context, _scriptFunc, _ident) - nativeModule._AstNodeSetParent(Global.context, _ident, _scriptFunc) - util.updateChildren(_scriptFunc) const _newFuncDecl = nativeModule._CreateFunctionDeclaration( @@ -260,8 +200,8 @@ export function createNodeFactory(): NodeFactory { _scriptFunc, false ) - nativeModule._AstNodeSetParent(Global.context, _scriptFunc, _newFuncDecl) - util.updateChildren(_newFuncDecl) + setModifierFlags(_newFuncDecl, getModifierFlags(_scriptFunc)) + updateChildren(_newFuncDecl) return _newFuncDecl }) @@ -271,6 +211,16 @@ export function createNodeFactory(): NodeFactory { } // @api + // updateFunctionDeclaration( + // node: FunctionDeclaration, + // modifiers: readonly ModifierLike[] | undefined, + // asteriskToken: AsteriskToken | undefined, + // name: Identifier | undefined, + // typeParameters: readonly TypeParameterDeclaration[] | undefined, + // parameters: readonly ParameterDeclaration[], + // type: TypeNode | undefined, + // body: Block | undefined + // ): FunctionDeclaration; function updateFunctionDeclaration( node: FunctionDeclaration, modifiers: undefined, @@ -282,10 +232,7 @@ export function createNodeFactory(): NodeFactory { body: Block | undefined ): FunctionDeclaration { const peer = withString(name.text, (_name: string) => { - return withPtrArray( - new BigUint64Array(parameters.map(node => BigInt(node.peer))), - Access.READWRITE, - (_parameters: BigUint64Array) => { + return withNodeArray(parameters, (_parameters: BigUint64Array) => { const _context = Global.context const _oldFuncDecl = node.peer @@ -297,8 +244,6 @@ export function createNodeFactory(): NodeFactory { _context, _oldScriptFunc ) - // TODO: use this flags - // const _oldFlags = nativeModule._ScriptFunctionFlagsConst(_context, _newScriptFunc) const _body = body ? body.peer : NULLPTR const _signature = nativeModule._CreateFunctionSignature( @@ -308,52 +253,44 @@ export function createNodeFactory(): NodeFactory { _parameters.length, nativeModule._FunctionSignatureReturnType(_context, _oldSignature) ) - const _scriptFunc = nativeModule._UpdateScriptFunction( - _context, + const _scriptFunc = updateScriptFunction( _oldScriptFunc, _body, _signature, - 0, - 0, - false - ) - parameters.forEach(function (parameter: ParameterDeclaration) { - util.setParent(parameter.peer, _scriptFunc) - }) - if (_body !== NULLPTR) { - util.setParent(_body, _scriptFunc) - } - - const _ident = nativeModule._UpdateIdentifier1( - _context, - nativeModule._ScriptFunctionId(_context, _oldScriptFunc), - _name + nativeModule._ScriptFunctionFlagsConst(_context, _oldScriptFunc), + nativeModule._AstNodeModifiers(_context, _oldScriptFunc), + false, + nativeModule._UpdateIdentifier1( + _context, + nativeModule._ScriptFunctionId(_context, _oldScriptFunc), + _name + ) ) - nativeModule._ScriptFunctionSetIdent(Global.context, _scriptFunc, _ident) - util.updateChildren(_scriptFunc) + updateNode(_scriptFunc, _oldScriptFunc) - const _funcDecl = - nativeModule._UpdateFunctionDeclaration( + return nativeModule._UpdateFunctionDeclaration( _context, _oldFuncDecl, _scriptFunc, false ) - util.setParent(_scriptFunc, _funcDecl) - - util.setModifierFlags(_scriptFunc, util.getModifierFlags(_oldScriptFunc)) - util.setModifierFlags(_funcDecl, util.getModifierFlags(_oldFuncDecl)) - util.updateChildren(_funcDecl) - - return _funcDecl }) }) + updateNode(peer, node.peer) + updateChildren(peer) return new FunctionDeclaration(peer) } - // tsc: createParameterDeclaration(modifiers: readonly ModifierLike[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken?: QuestionToken, type?: TypeNode, initializer?: Expression): ParameterDeclaration; // @api + // createParameterDeclaration( + // modifiers: readonly ModifierLike[] | undefined, + // dotDotDotToken: DotDotDotToken | undefined, + // name: string | BindingName, + // questionToken?: QuestionToken, + // type?: TypeNode, + // initializer?: Expression + // ): ParameterDeclaration; function createParameterDeclaration( modifiers: undefined, dotDotDotToken: undefined, @@ -364,60 +301,63 @@ export function createNodeFactory(): NodeFactory { ): ParameterDeclaration { const peer = nativeModule._CreateETSParameterExpression( Global.context, - (type === undefined) - ? - name.peer - : + (type === undefined) ? + name.peer : updateIdentifier( name, name.text, type ).peer ) - nativeModule._AstNodeSetParent(Global.context, name.peer, peer) - if (type !== undefined) { - nativeModule._AstNodeSetParent(Global.context, type.peer, peer) - } + updateChildren(peer) return new ParameterDeclaration(peer) } // TODO: maybe remove from api // @api - function createEtsPrimitiveType(type: Es2pandaPrimitiveType) { + // NOT PROVIDED + function createEtsPrimitiveType(type: Es2pandaPrimitiveType): TypeNode { const peer = nativeModule._CreateETSPrimitiveType(Global.context, type) return new ETSPrimitiveType(peer) } - // tsc: createTypeReferenceNode(typeName: string | EntityName, typeArguments?: readonly TypeNode[]): TypeReferenceNode; // @api + // createTypeReferenceNode( + // typeName: string | EntityName, + // typeArguments?: readonly TypeNode[] + // ): TypeReferenceNode; function createTypeReferenceNode(identifier: Identifier, typeArguments?: undefined): TypeReferenceNode { const typeRefPart = nativeModule._CreateETSTypeReferencePart(Global.context, identifier.peer, NULLPTR, NULLPTR) + updateChildren(typeRefPart) const peer = nativeModule._CreateETSTypeReference(Global.context, typeRefPart) - nativeModule._AstNodeSetParent(Global.context, typeRefPart, peer) + updateChildren(peer) return new TypeReferenceNode(peer) } + // @internal function createKeywordTypeNodeFromString(keyword: string): KeywordTypeNode { - const identifier: KNativePointer = withString(keyword, (name: string) => { + const ident = withString(keyword, (name: string) => { return nativeModule._CreateIdentifier1(Global.context, name) }) - nativeModule._IdentifierSetReference(Global.context, identifier, true) - const typeRefPart = nativeModule._CreateETSTypeReferencePart1(Global.context, identifier) - nativeModule._AstNodeSetParent(Global.context, identifier, typeRefPart) + nativeModule._IdentifierSetReference(Global.context, ident, true) + const typeRefPart = nativeModule._CreateETSTypeReferencePart1(Global.context, ident) + nativeModule._AstNodeSetParent(Global.context, ident, typeRefPart) const peer = nativeModule._CreateETSTypeReference(Global.context, typeRefPart) nativeModule._AstNodeSetParent(Global.context, typeRefPart, peer); return new KeywordTypeNode(peer) } + // @internal function createKeywordTypeNodeFromKind(kind: number): KeywordTypeNode { return new KeywordTypeNode(nativeModule._CreateETSPrimitiveType(Global.context, kind)) } // @api + // createKeywordTypeNode(kind: TKind): KeywordTypeNode; function createKeywordTypeNode(TKind: ts.KeywordTypeSyntaxKind): KeywordTypeNode { const keywords = new Map([ [ts.SyntaxKind.NumberKeyword, createKeywordTypeNodeFromString("number")], @@ -426,174 +366,200 @@ export function createNodeFactory(): NodeFactory { [ts.SyntaxKind.VoidKeyword, createKeywordTypeNodeFromKind(8)], ]) - return keywords.get(TKind) ?? util.throwError('unsupported keyword') + return keywords.get(TKind) ?? throwError('unsupported keyword') } // @api + // createBlock( + // statements: readonly Statement[], + // multiLine?: boolean + // ): Block; function createBlock(statements: Statement[], multiline?: boolean): Block { - const statementList = new BigUint64Array(statements.map(node => BigInt(node.peer))) - - const peer = withPtrArray(statementList, Access.READWRITE, (statementList: BigUint64Array) => { - return nativeModule._CreateBlockStatement(Global.context, statementList, statementList.length) - }) - statements.forEach(function (statement: Statement) { - nativeModule._AstNodeSetParent(Global.context, statement.peer, peer) + const peer = withNodeArray(statements, (_statements: BigUint64Array) => { + return nativeModule._CreateBlockStatement(Global.context, _statements, _statements.length) }) + updateChildren(peer) return new Block(peer) } // @api + // updateBlock( + // node: Block, + // statements: readonly Statement[] + // ): Block; function updateBlock(node: Block, statements: Statement[], multiline?: boolean): Block { - const statementList = new BigUint64Array(statements.map(node => BigInt(node.peer))) - - const peer = withPtrArray(statementList, Access.READWRITE, (statementList: BigUint64Array) => { - return nativeModule._UpdateBlockStatement(Global.context, node.peer, statementList, statementList.length) - }) - statements.forEach(function (statement: Statement) { - nativeModule._AstNodeSetParent(Global.context, statement.peer, peer) + const peer = withNodeArray(statements, (_statements: BigUint64Array) => { + return nativeModule._UpdateBlockStatement(Global.context, node.peer, _statements, _statements.length) }) + updateNode(peer, node.peer) + updateChildren(peer) return new Block(peer) } // @api + // createExpressionStatement(expression: Expression): ExpressionStatement; function createExpressionStatement(expression: Expression): ExpressionStatement { const peer = nativeModule._CreateExpressionStatement(Global.context, expression.peer) - nativeModule._AstNodeSetParent(Global.context, expression.peer, peer) + updateChildren(peer) return new ExpressionStatement(peer) } // @api + // updateExpressionStatement(node: ExpressionStatement, expression: Expression): ExpressionStatement; function updateExpressionStatement(node: ExpressionStatement, expression: Expression): ExpressionStatement { const peer = nativeModule._UpdateExpressionStatement(Global.context, node.peer, expression.peer) - nativeModule._AstNodeSetParent(Global.context, expression.peer, peer) + updateNode(peer, node.peer) + updateChildren(peer) return new ExpressionStatement(peer) } // @api + // createReturnStatement(expression?: Expression): ReturnStatement; function createReturnStatement(expression: Expression): ReturnStatement { const peer = nativeModule._CreateReturnStatement1(Global.context, expression.peer) - nativeModule._AstNodeSetParent(Global.context, expression.peer, peer) + updateChildren(peer) return new ReturnStatement(peer) } - // tsc: createPropertyAccessExpression(expression: Expression, name: string | MemberName): PropertyAccessExpression; // @api + // createPropertyAccessExpression(expression: Expression, name: string | MemberName): PropertyAccessExpression; function createPropertyAccessExpression(expression: Expression, name: Identifier): PropertyAccessExpression { - const peer = nativeModule._CreateMemberExpression(Global.context, expression.peer, name.peer, 2, false, false) - nativeModule._AstNodeSetParent(Global.context, expression.peer, peer) - nativeModule._AstNodeSetParent(Global.context, name.peer, peer) + const peer = nativeModule._CreateMemberExpression( + Global.context, + expression.peer, + name.peer, + Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ) + updateChildren(peer) return new PropertyAccessExpression(peer) } // @api + // updatePropertyAccessExpression(node: PropertyAccessExpression, expression: Expression, name: MemberName): PropertyAccessExpression; function updatePropertyAccessExpression(node: PropertyAccessExpression, expression: Expression, name: Identifier): PropertyAccessExpression { - const peer = nativeModule._UpdateMemberExpression(Global.context, node.peer, expression.peer, name.peer, 2, false, false) - nativeModule._AstNodeSetParent(Global.context, expression.peer, peer) - nativeModule._AstNodeSetParent(Global.context, name.peer, peer) + const peer = nativeModule._UpdateMemberExpression( + Global.context, + node.peer, + expression.peer, + name.peer, + Es2pandaMemberExpressionKind.MEMBER_EXPRESSION_KIND_PROPERTY_ACCESS, + false, + false + ) + updateNode(peer, node.peer) + updateChildren(peer) return new PropertyAccessExpression(peer) } - // tsc: createCallExpression(expression: Expression, typeArguments: readonly TypeNode[] | undefined, argumentsArray: readonly Expression[] | undefined): CallExpression; // @api + // createCallExpression( + // expression: Expression, + // typeArguments: readonly TypeNode[] | undefined, + // argumentsArray: readonly Expression[] | undefined + // ): CallExpression; function createCallExpression( expression: Expression, typeArguments?: undefined, argumentsArray?: readonly Expression[] | undefined ): CallExpression { - const _arguments: readonly Expression[] = argumentsArray ? argumentsArray : [] - - const peer = withPtrArray( - new BigUint64Array(_arguments.map(node => BigInt(node.peer))), - Access.READWRITE, - (args: BigUint64Array) => { + const peer = withNodeArray(argumentsArray, (_arguments: BigUint64Array) => { return nativeModule._CreateCallExpression( Global.context, expression.peer, - args, - args.length, + _arguments, + _arguments.length, NULLPTR, false, false ) }) - nativeModule._AstNodeSetParent(Global.context, expression.peer, peer) - _arguments.forEach(function (argument: Expression) { - nativeModule._AstNodeSetParent(Global.context, argument.peer, peer) - }) + updateChildren(peer) return new CallExpression(peer) } - // tsc: updateCallExpression(node: CallExpression, expression: Expression, typeArguments: readonly TypeNode[] | undefined, argumentsArray: readonly Expression[]): CallExpression; // @api + // updateCallExpression( + // node: CallExpression, + // expression: Expression, + // typeArguments: readonly TypeNode[] | undefined, + // argumentsArray: readonly Expression[] + // ): CallExpression; function updateCallExpression( node: CallExpression, expression: Expression, typeArguments?: undefined, argumentsArray?: readonly Expression[] | undefined ): CallExpression { - const _arguments: readonly Expression[] = argumentsArray ? argumentsArray : [] - - const peer = withPtrArray( - new BigUint64Array(_arguments.map(node => BigInt(node.peer))), - Access.READWRITE, - (args: BigUint64Array) => { + const peer = withNodeArray(argumentsArray, (_arguments: BigUint64Array) => { return nativeModule._UpdateCallExpression( Global.context, node.peer, expression.peer, - args, - args.length, + _arguments, + _arguments.length, NULLPTR, false, false ) }) - util.setParent(expression.peer, peer) - _arguments.forEach(function (argument: Expression) { - util.setParent(argument.peer, peer) - }) - util.setModifierFlags(peer, util.getModifierFlags(node.peer)) + updateNode(peer, node.peer) + updateChildren(peer) return new CallExpression(peer) } - // tsc: createIfStatement(expression: Expression, thenStatement: Statement, elseStatement?: Statement): IfStatement; // @api + // createIfStatement( + // expression: Expression, + // thenStatement: Statement, + // elseStatement?: Statement + // ): IfStatement; function createIfStatement(expression: Expression, thenStatement: Statement, elseStatement?: undefined): IfStatement { const peer = nativeModule._CreateIfStatement(Global.context, expression.peer, thenStatement.peer, NULLPTR) - nativeModule._AstNodeSetParent(Global.context, expression.peer, peer) - nativeModule._AstNodeSetParent(Global.context, thenStatement.peer, peer) + updateChildren(peer) return new IfStatement(peer) } - // returns only BinaryOperatorToken temporary - // tsc: createToken(token: SyntaxKind._): _; + // TODO: fix maybe (temporary solution) // @api - function createToken(token: ts.TokenSyntaxKind): BinaryOperatorToken { - return new BinaryOperatorToken(token) + // createToken(token: SyntaxKind._): _; + function createToken(token: TKind) { + return new Token(token) } - // tsc: createBinaryExpression(left: Expression, operator: BinaryOperator | BinaryOperatorToken, right: Expression): BinaryExpression; // @api + // createBinaryExpression( + // left: Expression, + // operator: BinaryOperator | BinaryOperatorToken, + // right: Expression + // ): BinaryExpression; function createBinaryExpression(left: Expression, operator: BinaryOperatorToken, right: Expression): BinaryExpression { - const peer = nativeModule._CreateBinaryExpression(Global.context, left.peer, right.peer, (operator as BinaryOperatorToken).token) - nativeModule._AstNodeSetParent(Global.context, left.peer, peer) - nativeModule._AstNodeSetParent(Global.context, right.peer, peer) + const peer = nativeModule._CreateBinaryExpression(Global.context, left.peer, right.peer, passToken(operator)) + updateChildren(peer) return new BinaryExpression(peer) } - // tsc: createArrowFunction(modifiers: readonly Modifier[] | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, equalsGreaterThanToken: EqualsGreaterThanToken | undefined, body: ConciseBody): ArrowFunction; // @api + // createArrowFunction( + // modifiers: readonly Modifier[] | undefined, + // typeParameters: readonly TypeParameterDeclaration[] | undefined, + // parameters: readonly ParameterDeclaration[], + // type: TypeNode | undefined, + // equalsGreaterThanToken: EqualsGreaterThanToken | undefined, + // body: ConciseBody + // ): ArrowFunction; function createArrowFunction( modifiers: undefined, typeParameters: undefined, @@ -602,63 +568,61 @@ export function createNodeFactory(): NodeFactory { equalsGreaterThanToken: undefined, body: Block ) { - const params = new BigUint64Array(parameters.map(node => BigInt(node.peer))) - - const peer = withPtrArray(params, Access.READWRITE, (_params: BigUint64Array) => { + const peer = withNodeArray(parameters, (_parameters: BigUint64Array) => { const _context = Global.context const _body = body.peer const _signature = nativeModule._CreateFunctionSignature( _context, NULLPTR, - _params, - _params.length, + _parameters, + _parameters.length, NULLPTR ) - const _scriptFunc = nativeModule._CreateScriptFunction( - _context, + const _scriptFunc = createScriptFunction( _body, _signature, - // TODO: fix flag params - 4, - 0, - false + Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ARROW, + Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, + false, + undefined ) - if (_body !== NULLPTR) { - util.setParent(_body, _scriptFunc) - } - parameters.forEach(function (parameter: ParameterDeclaration) { - util.setParent(parameter.peer, _scriptFunc) - }) - const _newArrowFunc = nativeModule._CreateArrowFunctionExpression( + const _arrowFunc = nativeModule._CreateArrowFunctionExpression( _context, _scriptFunc ) - util.setParent(_scriptFunc, _newArrowFunc) + updateChildren(_arrowFunc) - return _newArrowFunc + return _arrowFunc }) return new ArrowFunction(peer) } + // TODO: fix (now doesn't create a new node) // @api + // updateSourceFile( + // node: SourceFile, + // statements: readonly Statement[], + // isDeclarationFile?: boolean, + // referencedFiles?: readonly FileReference[], + // typeReferences?: readonly FileReference[], + // hasNoDefaultLib?: boolean, + // libReferences?: readonly FileReference[] + // ): SourceFile; function updateSourceFile(node: SourceFile, statements: readonly Statement[]): SourceFile { - const statementList = new BigUint64Array(statements.map(node => BigInt(node.peer))) - - withPtrArray(statementList, Access.READWRITE, (statementList: BigUint64Array) => { - nativeModule._BlockStatementSetStatements(Global.context, node.peer, statementList, statementList.length) - }) - statements.forEach(function (statement: Statement) { - nativeModule._AstNodeSetParent(Global.context, statement.peer, node.peer) + withNodeArray(statements, (_statements: BigUint64Array) => { + nativeModule._BlockStatementSetStatements(Global.context, node.peer, _statements, _statements.length) }) + updateChildren(node.peer) return node } - // tsc: updateClassDeclaration( + // @api + // updateClassDeclaration( // node: ClassDeclaration, // modifiers: readonly ModifierLike[] | undefined, // name: Identifier | undefined, @@ -666,7 +630,6 @@ export function createNodeFactory(): NodeFactory { // heritageClauses: readonly HeritageClause[] | undefined, // members: readonly ClassElement[] // ): ClassDeclaration; - // @api function updateClassDeclaration( node: ClassDeclaration, modifiers: undefined, @@ -675,10 +638,7 @@ export function createNodeFactory(): NodeFactory { heritageClauses: undefined, members: readonly ClassElement[] ) { - // TODO: support undefined name and other params - const _members = new BigUint64Array(members.map(node => BigInt(node.peer))) - - const peer = withPtrArray(_members, Access.READWRITE, (_members: BigUint64Array) => { + const peer = withNodeArray(members, (_members: BigUint64Array) => { const _context = Global.context const _classDefinition = nativeModule._ClassDeclarationDefinition( @@ -694,17 +654,16 @@ export function createNodeFactory(): NodeFactory { const _newClassDefinition = nativeModule._UpdateClassDefinition1( _context, _classDefinition, - name!.peer, + // TODO: maybe this is wrong + (name === undefined) ? NULLPTR : name.peer, _members, _members.length, - 0, - 0, + Es2pandaClassDefinitionModifiers.CLASS_DEFINITION_MODIFIERS_NONE, + Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, _lang ) - nativeModule._AstNodeSetParent(Global.context, name!.peer, _newClassDefinition) - members.forEach(function (member: ClassElement) { - nativeModule._AstNodeSetParent(Global.context, member.peer, _newClassDefinition) - }) + updateNode(_newClassDefinition, _classDefinition) + updateChildren(_newClassDefinition) return nativeModule._UpdateClassDeclaration( _context, @@ -712,24 +671,24 @@ export function createNodeFactory(): NodeFactory { _newClassDefinition ) }) + updateNode(peer, node.peer) + updateChildren(peer) return new ClassDeclaration(peer) } + // @api // tsc: createFunctionTypeNode( // typeParameters: readonly TypeParameterDeclaration[] | undefined, // parameters: readonly ParameterDeclaration[], // type: TypeNode // ): FunctionTypeNode; - // @api function createFunctionTypeNode( typeParameters: undefined, parameters: readonly ParameterDeclaration[], type: TypeNode ): FunctionTypeNode { - const _parameters = new BigUint64Array(parameters.map(node => BigInt(node.peer))) - - const _signature = withPtrArray(_parameters, Access.READWRITE, (_parameters: BigUint64Array) => { + const _signature = withNodeArray(parameters, (_parameters: BigUint64Array) => { return nativeModule._CreateFunctionSignature( Global.context, NULLPTR, @@ -742,43 +701,37 @@ export function createNodeFactory(): NodeFactory { const peer = nativeModule._CreateETSFunctionTypeIr( Global.context, _signature, - 0 + Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_NONE ) - // TODO: not sure about it, maybe parent should be signature somehow - parameters.forEach(function (parameter: ParameterDeclaration) { - nativeModule._AstNodeSetParent(Global.context, parameter.peer, peer) - }) + updateChildren(peer) return new FunctionTypeNode(peer) } + // TODO: fix modifiers // @api - // tsc: updateMethodDeclaration( - // node: MethodDeclaration, + // createMethodDeclaration( // modifiers: readonly ModifierLike[] | undefined, // asteriskToken: AsteriskToken | undefined, - // name: PropertyName, + // name: string | PropertyName, // questionToken: QuestionToken | undefined, // typeParameters: readonly TypeParameterDeclaration[] | undefined, // parameters: readonly ParameterDeclaration[], // type: TypeNode | undefined, // body: Block | undefined // ): MethodDeclaration; - function updateMethodDeclaration( - node: MethodDeclaration, - modifiers: undefined, // TODO: support (now default public, static) + function createMethodDeclaration( + modifiers: readonly ModifierLike[] | undefined, asteriskToken: undefined, - name: Identifier, + name: string | Identifier, questionToken: undefined, typeParameters: undefined, parameters: readonly ParameterDeclaration[], - type: undefined, - body: Block + type: TypeNode | undefined, + body: Block | undefined ): MethodDeclaration { - const peer = withPtrArray( - new BigUint64Array(parameters.map(node => BigInt(node.peer))), - Access.READWRITE, - (_parameters: BigUint64Array) => { + const peer = withString((name instanceof Identifier) ? name.text : name, (_name: string) => { + return withNodeArray(parameters, (_parameters: BigUint64Array) => { const _context = Global.context const _signature = nativeModule._CreateFunctionSignature( @@ -786,41 +739,168 @@ export function createNodeFactory(): NodeFactory { NULLPTR, _parameters, _parameters.length, - NULLPTR + (type !== undefined) ? type.peer : NULLPTR ) - const _scriptFunc = nativeModule._CreateScriptFunction( - _context, - body.peer, + + const _ident = nativeModule._CreateIdentifier1(_context, _name) + const _scriptFunc = createScriptFunction( + (body !== undefined) ? body.peer : NULLPTR, _signature, - // TODO: fix flag params - 0, - 0, - false + (modifiers !== undefined) ? passScriptFuncModifiers(modifiers) : Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_NONE, + (modifiers !== undefined) ? passModifiers(modifiers) : Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, + false, + _ident ) - nativeModule._ScriptFunctionSetIdent(Global.context, _scriptFunc, name.peer) - util.updateChildren(_scriptFunc) const _funcExpr = nativeModule._CreateFunctionExpression( Global.context, _scriptFunc ) - util.updateChildren(_funcExpr) + updateChildren(_funcExpr) - const _methodDefinition = nativeModule._UpdateMethodDefinition( - Global.context, - node.peer, + return nativeModule._CreateMethodDefinition( + _context, Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_METHOD, - name.peer, + _ident, _funcExpr, - Es2pandaModifierFlags.MODIFIER_FLAGS_STATIC | Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC, + (modifiers !== undefined) ? passModifiers(modifiers) : Es2pandaModifierFlags.MODIFIER_FLAGS_NONE, false ) - util.updateChildren(_methodDefinition) - - return _methodDefinition }) + }) + updateChildren(peer) + return new MethodDeclaration(peer) } + + // @api + // tsc: updateMethodDeclaration( + // node: MethodDeclaration, + // modifiers: readonly ModifierLike[] | undefined, + // asteriskToken: AsteriskToken | undefined, + // name: PropertyName, + // questionToken: QuestionToken | undefined, + // typeParameters: readonly TypeParameterDeclaration[] | undefined, + // parameters: readonly ParameterDeclaration[], + // type: TypeNode | undefined, + // body: Block | undefined + // ): MethodDeclaration; + function updateMethodDeclaration( + node: MethodDeclaration, + modifiers: undefined, // TODO: support (now default public, static) + asteriskToken: undefined, + name: Identifier, + questionToken: undefined, + typeParameters: undefined, + parameters: readonly ParameterDeclaration[], + type: undefined, + body: Block + ): MethodDeclaration { + const peer = withNodeArray(parameters, (_parameters: BigUint64Array) => { + const _context = Global.context + + const _oldFuncExpr = nativeModule._MethodDefinitionFunction(_context, node.peer) + const _oldScriptFunc = nativeModule._ArrowFunctionExpressionFunction(_context, _oldFuncExpr) + + const _signature = nativeModule._CreateFunctionSignature( + _context, + NULLPTR, + _parameters, + _parameters.length, + NULLPTR + ) + + const _scriptFunc = updateScriptFunction( + _oldScriptFunc, + body.peer, + _signature, + // TODO: fix this + // nativeModule._ScriptFunctionFlagsConst(_context, _oldScriptFunc), + Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_NONE, + nativeModule._AstNodeModifiers(_context, _oldScriptFunc), + false, + name.peer + ) + + const _funcExpr = nativeModule._UpdateFunctionExpression( + Global.context, + _oldFuncExpr, + _scriptFunc + ) + updateChildren(_funcExpr) + + return nativeModule._UpdateMethodDefinition( + Global.context, + node.peer, + nativeModule._MethodDefinitionKindConst(_context, node.peer), + name.peer, + _funcExpr, + nativeModule._AstNodeModifiers(_context, node.peer), + false + ) + }) + updateNode(peer, node.peer) + updateChildren(peer) + + return new MethodDeclaration(peer) + } + + // TODO: fix modifiers + // @api + // createConstructorDeclaration( + // modifiers: readonly ModifierLike[] | undefined, + // parameters: readonly ParameterDeclaration[], + // body: Block | undefined + // ): ConstructorDeclaration; + function createConstructorDeclaration( + modifiers: readonly ModifierLike[] | undefined, + parameters: readonly ParameterDeclaration[], + body: Block | undefined + ): ConstructorDeclaration { + const peer = withNodeArray(parameters, (_parameters: BigUint64Array) => { + const _context = Global.context + + const _signature = nativeModule._CreateFunctionSignature( + _context, + NULLPTR, + _parameters, + _parameters.length, + // TODO: change void maybe + NULLPTR + ) + + const _ident = nativeModule._CreateIdentifier1(_context, "constructor") + const _scriptFunc = createScriptFunction( + (body !== undefined) ? body.peer : NULLPTR, + _signature, + Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_CONSTRUCTOR | + ((modifiers !== undefined) ? passScriptFuncModifiers(modifiers) : Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_NONE), + Es2pandaModifierFlags.MODIFIER_FLAGS_CONSTRUCTOR | + ((modifiers !== undefined) ? passModifiers(modifiers) : Es2pandaModifierFlags.MODIFIER_FLAGS_NONE), + false, + _ident + ) + + const _funcExpr = nativeModule._CreateFunctionExpression( + Global.context, + _scriptFunc + ) + updateChildren(_funcExpr) + + return nativeModule._CreateMethodDefinition( + _context, + Es2pandaMethodDefinitionKind.METHOD_DEFINITION_KIND_CONSTRUCTOR, + _ident, + _funcExpr, + Es2pandaModifierFlags.MODIFIER_FLAGS_CONSTRUCTOR | + ((modifiers !== undefined) ? passModifiers(modifiers) : Es2pandaModifierFlags.MODIFIER_FLAGS_NONE), + false + ) + }) + updateChildren(peer) + + return new ConstructorDeclaration(peer) + } } -export const factory: NodeFactory = createNodeFactory(); +export const factory = createNodeFactory(); diff --git a/arkoala-arkts/libarkts/src/arkts/factory/nodeTests.ts b/arkoala-arkts/libarkts/src/arkts/factory/nodeTests.ts index 3e611fbd4..2afce8fa4 100644 --- a/arkoala-arkts/libarkts/src/arkts/factory/nodeTests.ts +++ b/arkoala-arkts/libarkts/src/arkts/factory/nodeTests.ts @@ -30,21 +30,37 @@ import { } from "../types" export function isIdentifier(node: Node): node is Identifier { - return node.kind === SyntaxKind.Identifier; + return node.kind === SyntaxKind.Identifier } export function isCallExpression(node: Node): node is CallExpression { - return node.kind === SyntaxKind.CallExpression; + return node.kind === SyntaxKind.CallExpression } export function isPropertyAccessExpression(node: Node): node is PropertyAccessExpression { - return node.kind === SyntaxKind.PropertyAccessExpression; + return node.kind === SyntaxKind.PropertyAccessExpression } export function isFunctionDeclaration(node: Node): node is FunctionDeclaration { - return node.kind === SyntaxKind.FunctionDeclaration; + return node.kind === SyntaxKind.FunctionDeclaration } export function isMethodDeclaration(node: Node): node is MethodDeclaration { - return node.kind === SyntaxKind.MethodDeclaration; + return node.kind === SyntaxKind.MethodDeclaration +} + +export function isSourceFile(node: Node): node is SourceFile { + return node.kind === SyntaxKind.SourceFile +} + +export function isExpressionStatement(node: Node): node is ExpressionStatement { + return node.kind === SyntaxKind.ExpressionStatement +} + +export function isArrowFunction(node: Node): node is ArrowFunction { + return node.kind === SyntaxKind.ArrowFunction +} + +export function isClassDeclaration(node: Node): node is ClassDeclaration { + return node.kind === SyntaxKind.ClassDeclaration } diff --git a/arkoala-arkts/libarkts/src/arkts/factory/utilities.ts b/arkoala-arkts/libarkts/src/arkts/factory/utilities.ts new file mode 100644 index 000000000..493037a40 --- /dev/null +++ b/arkoala-arkts/libarkts/src/arkts/factory/utilities.ts @@ -0,0 +1,199 @@ +/* + * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { nativeModule } from "../../NativeModule" +import { KNativePointer, KInt, KBoolean } from "@koalaui/interop" +import * as arkts from "../types" +import { + SyntaxKind, + TokenSyntaxKind, + Es2pandaModifierFlags, + Es2pandaScriptFunctionFlags, + Es2pandaTokenType, +} from "../enums" +import { throwError } from "../utilities" +export { throwError } from "../utilities" + +export function setParent(node: KNativePointer, parent: KNativePointer) { + nativeModule._AstNodeSetParent(arkts.Global.context, node, parent) +} + +export function getModifierFlags(node: KNativePointer): KInt { + return nativeModule._AstNodeModifiers(arkts.Global.context, node) +} + +export function setModifierFlags(node: KNativePointer, flags: KInt) { + nativeModule._AstNodeClearModifier(arkts.Global.context, node, arkts.ALL_FLAGS) + nativeModule._AstNodeAddModifier(arkts.Global.context, node, flags) +} + +export function updateAllChildren(peer: KNativePointer) { + nativeModule._AstNodeUpdateAll(arkts.Global.context, peer) +} + +export function updateChildren(peer: KNativePointer) { + nativeModule._AstNodeUpdateChildren(arkts.Global.context, peer) +} + +// TODO: update scopes and other data +export function updateNode(peer: KNativePointer, original: KNativePointer) { + setModifierFlags(peer, getModifierFlags(original)) +} + +export function createScriptFunction( + body: KNativePointer, + signature: KNativePointer, + // Es2pandaScriptFunctionFlags + functionFlags: KInt, + // Es2pandaModifierFlags + modifierFlags: KInt, + declare: KBoolean, + ident: KNativePointer | undefined +): KNativePointer { + const peer = nativeModule._CreateScriptFunction( + arkts.Global.context, + body, + signature, + functionFlags, + modifierFlags, + declare + ) + if (ident !== undefined) { + nativeModule._ScriptFunctionSetIdent(arkts.Global.context, peer, ident) + } + updateChildren(peer) + return peer +} + +export function updateScriptFunction( + original: KNativePointer, + body: KNativePointer, + signature: KNativePointer, + // Es2pandaScriptFunctionFlags + functionFlags: KInt, + // Es2pandaModifierFlags + modifierFlags: KInt, + declare: KBoolean, + ident: KNativePointer | undefined +): KNativePointer { + const peer = nativeModule._UpdateScriptFunction( + arkts.Global.context, + original, + body, + signature, + functionFlags, + modifierFlags, + declare + ) + if (ident !== undefined) { + nativeModule._ScriptFunctionSetIdent(arkts.Global.context, peer, ident) + } + updateChildren(peer) + return peer +} + +export function withString( + data: string | undefined, + exec: (str: string) => TOut +): TOut { + return exec(data ?? "") +} + +export function withNodeArray( + data: readonly arkts.Node[] | undefined, + exec: (nodes: BigUint64Array) => TOut +): TOut { + const _data = new BigUint64Array((data === undefined) ? [] : data.map(node => BigInt(node.peer))) + return exec(_data) +} + +// TODO: rewrite this maybe +class Global { + private static _tokenKinds?: Map + + public static get tokenKinds(): Map { + if (this._tokenKinds === undefined) { + this._tokenKinds = + new Map([ + [SyntaxKind.PlusToken, Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_PLUS], + ]) + } + return this._tokenKinds + } + + private static _scriptFunctionFlags?: Map + + public static get scriptFunctionFlags(): Map { + if (this._scriptFunctionFlags === undefined) { + this._scriptFunctionFlags = + new Map([ + [SyntaxKind.StaticKeyword, Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_STATIC_BLOCK], + [SyntaxKind.AsyncKeyword, Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_ASYNC], + [SyntaxKind.PublicKeyword, Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_NONE], + ]) + } + return this._scriptFunctionFlags + } + + private static _modifierFlags?: Map + + public static get modifierFlags(): Map { + if (this._modifierFlags === undefined) { + this._modifierFlags = + new Map([ + [SyntaxKind.StaticKeyword, Es2pandaModifierFlags.MODIFIER_FLAGS_STATIC], + [SyntaxKind.AsyncKeyword, Es2pandaModifierFlags.MODIFIER_FLAGS_ASYNC], + [SyntaxKind.PublicKeyword, Es2pandaModifierFlags.MODIFIER_FLAGS_PUBLIC], + ]) + } + return this._modifierFlags + } +} + +export function passToken(token: arkts.Token): KInt { + return Global.tokenKinds.get(token.kind) ?? throwError('unsupported token') +} + +export function passScriptFuncModifier(modifierToken: arkts.ModifierLike) { + return Global.scriptFunctionFlags.get(modifierToken.kind) ?? throwError('unsupported ScriptFunction flag') +} + +export function passScriptFuncModifiers(modifiers: readonly arkts.ModifierLike[]): KInt { + let flags = Es2pandaScriptFunctionFlags.SCRIPT_FUNCTION_FLAGS_NONE + + modifiers.forEach( + flag => { + flags = flags | passScriptFuncModifier(flag) + } + ) + + return flags +} + +export function passModifier(modifierToken: arkts.ModifierLike) { + return Global.modifierFlags.get(modifierToken.kind) ?? throwError('unsupported Modifier flag') +} + +export function passModifiers(modifiers: readonly arkts.ModifierLike[]): KInt { + let flags = Es2pandaModifierFlags.MODIFIER_FLAGS_NONE + + modifiers.forEach( + flag => { + flags = flags | passModifier(flag) + } + ) + + return flags +} diff --git a/arkoala-arkts/libarkts/src/arkts/index.ts b/arkoala-arkts/libarkts/src/arkts/index.ts index 29e357012..4ee61c3be 100644 --- a/arkoala-arkts/libarkts/src/arkts/index.ts +++ b/arkoala-arkts/libarkts/src/arkts/index.ts @@ -14,6 +14,8 @@ */ export * from "./types" +export * from "./utilitiesPublic" +// TODO: remove this export export * from "./utilities" export * from "./factory/nodeFactory" export * from "./factory/nodeTests" diff --git a/arkoala-arkts/libarkts/src/arkts/nodeByPeer.ts b/arkoala-arkts/libarkts/src/arkts/nodeByPeer.ts new file mode 100644 index 000000000..fbda61f60 --- /dev/null +++ b/arkoala-arkts/libarkts/src/arkts/nodeByPeer.ts @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as arkts from "./types" +import { KNativePointer } from "@koalaui/interop" +import { es2pandaKind } from "./enums" +import { nativeModule } from "../NativeModule" + +// TODO: rewrite this maybe +class Global { + private static _kinds?: Map + + public static get kinds(): Map { + if (this._kinds === undefined) { + this._kinds = + new Map([ + [es2pandaKind.Identifier, arkts.Identifier], + [es2pandaKind.StringLiteral, arkts.StringLiteral], + [es2pandaKind.Block, arkts.Block], + [es2pandaKind.MethodDeclaration, arkts.MethodDeclaration], + [es2pandaKind.ClassDeclaration, arkts.ClassDeclaration], + [es2pandaKind.FunctionDeclaration, arkts.FunctionDeclaration], + [es2pandaKind.PropertyDeclaration, arkts.PropertyDeclaration], + [es2pandaKind.ETSFunctionType, arkts.FunctionTypeNode], + [es2pandaKind.CallExpression, arkts.CallExpression], + [es2pandaKind.ExpressionStatement, arkts.ExpressionStatement], + [es2pandaKind.MemberExpression, arkts.PropertyAccessExpression], + [es2pandaKind.ArrowFunctionExpression, arkts.ArrowFunction], + [es2pandaKind.ReturnStatement, arkts.ReturnStatement], + [es2pandaKind.Parameter, arkts.ParameterDeclaration], + [es2pandaKind.ETSParameterExpression, arkts.ParameterDeclaration], + [es2pandaKind.NumberLiteral, arkts.NumericLiteral], + [es2pandaKind.VariableDeclaration, arkts.VariableStatement], + [es2pandaKind.Program, arkts.SourceFile], + ]) + } + return this._kinds + } +} + +// TODO: maybe rewrite to (new Node(peer)) +export function nodeByPeer(peer: KNativePointer): arkts.Node { + const kind = nativeModule._GetKind(arkts.Global.context, peer) + return new (Global.kinds.get(kind) ?? arkts.UnsupportedNode)(peer) +} diff --git a/arkoala-arkts/libarkts/src/arkts/types.ts b/arkoala-arkts/libarkts/src/arkts/types.ts index 340d72c1b..864f51ef3 100644 --- a/arkoala-arkts/libarkts/src/arkts/types.ts +++ b/arkoala-arkts/libarkts/src/arkts/types.ts @@ -1,22 +1,9 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - +// TODO: remove ts (ts.SyntaxKind -> SyntaxKind) import * as ts from "@koalaui/ets-tsc" import { nativeModule } from "../NativeModule" import { KInt, KNativePointer, withStringResult } from "@koalaui/interop" import * as util from "./utilities" +import { todo } from "./utilities" import { Es2pandaModifierFlags, Es2pandaTokenType, @@ -75,9 +62,7 @@ export class Global { } } -function todo(): any { - throw new Error("Not yet implemented") -} +export type NodeArray = ts.NodeArray export abstract class Node implements ts.Node { peer: KNativePointer @@ -87,7 +72,7 @@ export abstract class Node implements ts.Node { } get parent(): Node { - return util.makeView(nativeModule._AstNodeParent(Global.context, this.peer)) + return util.nodeByPeer(nativeModule._AstNodeParent(Global.context, this.peer)) } set parent(node: Node) { @@ -128,6 +113,85 @@ export abstract class Node implements ts.Node { abstract kind: ts.SyntaxKind } +// TODO: add all tokens +export type BinaryOperator = + | ts.SyntaxKind.PlusToken + +export type BinaryOperatorToken = Token; + +// TODO: rethink maybe (temporary solution) +export class Token { + constructor(kind: TKind) { + this.kind = kind + } + + readonly kind: TKind; +} + +export type ModifierSyntaxKind = + | ts.SyntaxKind.AbstractKeyword + | ts.SyntaxKind.AccessorKeyword + | ts.SyntaxKind.AsyncKeyword + | ts.SyntaxKind.ConstKeyword + | ts.SyntaxKind.DeclareKeyword + | ts.SyntaxKind.DefaultKeyword + | ts.SyntaxKind.ExportKeyword + | ts.SyntaxKind.InKeyword + | ts.SyntaxKind.PrivateKeyword + | ts.SyntaxKind.ProtectedKeyword + | ts.SyntaxKind.PublicKeyword + | ts.SyntaxKind.ReadonlyKeyword + | ts.SyntaxKind.OutKeyword + | ts.SyntaxKind.OverrideKeyword + | ts.SyntaxKind.StaticKeyword; + +// TODO: rethink maybe (temporary solution) +export class ModifierToken extends Token { + constructor(kind: TKind) { + super(kind) + this.kind = kind + } + + readonly kind: TKind; +} + +export type AbstractKeyword = ModifierToken; +export type AccessorKeyword = ModifierToken; +export type AsyncKeyword = ModifierToken; +export type ConstKeyword = ModifierToken; +export type DeclareKeyword = ModifierToken; +export type DefaultKeyword = ModifierToken; +export type ExportKeyword = ModifierToken; +export type InKeyword = ModifierToken; +export type PrivateKeyword = ModifierToken; +export type ProtectedKeyword = ModifierToken; +export type PublicKeyword = ModifierToken; +export type ReadonlyKeyword = ModifierToken; +export type OutKeyword = ModifierToken; +export type OverrideKeyword = ModifierToken; +export type StaticKeyword = ModifierToken; + +export type Modifier = + | AbstractKeyword + | AccessorKeyword + | AsyncKeyword + | ConstKeyword + | DeclareKeyword + | DefaultKeyword + | ExportKeyword + | InKeyword + | PrivateKeyword + | ProtectedKeyword + | PublicKeyword + | OutKeyword + | OverrideKeyword + | ReadonlyKeyword + | StaticKeyword; + +// export type ModifierLike = Modifier | Decorator; +export type ModifierLike = Modifier; + + export class FunctionDeclaration extends Node implements ts.FunctionDeclaration { constructor(peer: KNativePointer) { super(peer) @@ -138,16 +202,16 @@ export class FunctionDeclaration extends Node implements ts.FunctionDeclaration } get name(): Identifier { - return util.makeView(nativeModule._ScriptFunctionId(Global.context, this._scriptFunction)) as Identifier + return util.nodeByPeer(nativeModule._ScriptFunctionId(Global.context, this._scriptFunction)) as Identifier } get body(): Block { - return util.makeView(nativeModule._ScriptFunctionBody(Global.context, this._scriptFunction)) as Block + return util.nodeByPeer(nativeModule._ScriptFunctionBody(Global.context, this._scriptFunction)) as Block } - get parameters(): ts.NodeArray { + get parameters(): NodeArray { const params = nativeModule._ScriptFunctionParams(Global.context, this._scriptFunction) - return util.unpack(params) as ts.NodeArray + return util.unpack(params) as NodeArray } // TODO: support minimal interface @@ -189,11 +253,11 @@ export class Block extends Node implements ts.Block { super(peer) } - private _statements?: ts.NodeArray - get statements(): ts.NodeArray { + private _statements?: NodeArray + get statements(): NodeArray { if (this._statements === undefined) { const statementsPtr = nativeModule._BlockStatementStatements(Global.context, this.peer) - this._statements = util.unpack(statementsPtr) as ts.NodeArray + this._statements = util.unpack(statementsPtr) as NodeArray } return this._statements } @@ -208,11 +272,11 @@ export class SourceFile extends Node implements ts.SourceFile { super(peer) } - private _statements?: ts.NodeArray - get statements(): ts.NodeArray { + private _statements?: NodeArray + get statements(): NodeArray { if (this._statements === undefined) { const statementsPtr = nativeModule._BlockStatementStatements(Global.context, this.peer) - this._statements = util.unpack(statementsPtr) as ts.NodeArray + this._statements = util.unpack(statementsPtr) as NodeArray } return this._statements } @@ -259,7 +323,7 @@ export class ExpressionStatement extends Node implements ts.ExpressionStatement, } get expression(): Expression { - return util.makeView(nativeModule._ExpressionStatementGetExpression(Global.context, this.peer)) as Expression + return util.nodeByPeer(nativeModule._ExpressionStatementGetExpression(Global.context, this.peer)) as Expression } // TODO: support minimal interface @@ -275,16 +339,16 @@ export class CallExpression extends Node implements ts.CallExpression, LeftHandS private _expression?: LeftHandSideExpression get expression(): LeftHandSideExpression { if (this._expression === undefined) { - this._expression = util.makeView(nativeModule._CallExpressionCallee(Global.context, this.peer)) as LeftHandSideExpression + this._expression = util.nodeByPeer(nativeModule._CallExpressionCallee(Global.context, this.peer)) as LeftHandSideExpression } return this._expression } - private _arguments?: ts.NodeArray - get arguments(): ts.NodeArray { + private _arguments?: NodeArray + get arguments(): NodeArray { if (this._arguments === undefined) { const argumentsPtr = nativeModule._CallExpressionArguments(Global.context, this.peer, NULLPTR) - this._arguments = util.unpack(argumentsPtr) as ts.NodeArray + this._arguments = util.unpack(argumentsPtr) as NodeArray } return this._arguments } @@ -306,7 +370,7 @@ export class PropertyAccessExpression extends Node implements ts.PropertyAccessE private _name?: Identifier get name() { if (this._name === undefined) { - this._name = util.makeView(nativeModule._MemberExpressionProperty(Global.context, this.peer)) as Identifier + this._name = util.nodeByPeer(nativeModule._MemberExpressionProperty(Global.context, this.peer)) as Identifier } return this._name } @@ -314,7 +378,7 @@ export class PropertyAccessExpression extends Node implements ts.PropertyAccessE private _expression?: LeftHandSideExpression get expression(): LeftHandSideExpression { if (this._expression === undefined) { - this._expression = util.makeView(nativeModule._MemberExpressionObject(Global.context, this.peer)) as LeftHandSideExpression + this._expression = util.nodeByPeer(nativeModule._MemberExpressionObject(Global.context, this.peer)) as LeftHandSideExpression } return this._expression } @@ -354,51 +418,76 @@ export class ClassDeclaration extends Node implements ts.ClassDeclaration { constructor(peer: KNativePointer) { super(peer) this._definition = nativeModule._ClassDeclarationDefinition(Global.context, peer) - this.members = util.unpack(nativeModule._ClassDefinitionBody(Global.context, this._definition)) as ts.NodeArray - this.name = util.makeView(nativeModule._ClassDefinitionIdent(Global.context, this._definition)) as Identifier + this.members = util.unpack(nativeModule._ClassDefinitionBody(Global.context, this._definition)) as NodeArray + this.name = util.nodeByPeer(nativeModule._ClassDefinitionIdent(Global.context, this._definition)) as Identifier } private _definition - readonly members: ts.NodeArray + readonly members: NodeArray readonly name: Identifier // TODO: support minimal interface _declarationBrand: any _statementBrand: any - kind: ts.SyntaxKind.ClassDeclaration = ts.SyntaxKind.ClassDeclaration; + kind: ts.SyntaxKind.ClassDeclaration = ts.SyntaxKind.ClassDeclaration +} + +export abstract class ClassElement extends Node implements ts.ClassElement { + // tsc: readonly name?: PropertyName + readonly name?: Identifier + + // TODO: support minimal interface + _declarationBrand: any + _classElementBrand: any + kind: any } -export class ClassElement extends Node implements ts.ClassElement { +// ets: MethodDefinition +export class MethodDeclaration extends Node implements ts.MethodDeclaration, ClassElement { constructor(peer: KNativePointer) { super(peer) + this._scriptFunction = nativeModule._MethodDefinitionFunction(Global.context, peer) + this.name = util.nodeByPeer(nativeModule._ScriptFunctionId(Global.context, this._scriptFunction)) as Identifier + this.parameters = util.unpack(nativeModule._ScriptFunctionParams(Global.context, this._scriptFunction)) as NodeArray + this.body = util.nodeByPeer(nativeModule._ScriptFunctionBody(Global.context, this._scriptFunction)) as Block } - // tsc: readonly name?: PropertyName; - readonly name?: Identifier; + // tsc: readonly name?: PropertyName + readonly name: Identifier + + readonly parameters: NodeArray + + // tsc: readonly body?: FunctionBody | undefined + readonly body: Block + + private readonly _scriptFunction: KNativePointer // TODO: support minimal interface - _declarationBrand: any + get parent(): any { return todo() } + _functionLikeDeclarationBrand: any _classElementBrand: any - kind: ts.SyntaxKind.ClassExpression = ts.SyntaxKind.ClassExpression; + _objectLiteralBrand: any + _declarationBrand: any + kind: ts.SyntaxKind.MethodDeclaration = ts.SyntaxKind.MethodDeclaration } // ets: MethodDefinition -export class MethodDeclaration extends Node implements ts.MethodDeclaration { +export class ConstructorDeclaration extends Node implements ts.ConstructorDeclaration, ClassElement { constructor(peer: KNativePointer) { super(peer) this._scriptFunction = nativeModule._MethodDefinitionFunction(Global.context, peer) - this.name = util.makeView(nativeModule._ScriptFunctionId(Global.context, this._scriptFunction)) as Identifier - this.parameters = util.unpack(nativeModule._ScriptFunctionParams(Global.context, this._scriptFunction)) as ts.NodeArray - this.body = util.makeView(nativeModule._ScriptFunctionBody(Global.context, this._scriptFunction)) as Block + this.name = util.nodeByPeer(nativeModule._ScriptFunctionId(Global.context, this._scriptFunction)) as Identifier + this.parameters = util.unpack(nativeModule._ScriptFunctionParams(Global.context, this._scriptFunction)) as NodeArray + this.body = util.nodeByPeer(nativeModule._ScriptFunctionBody(Global.context, this._scriptFunction)) as Block } - // tsc: readonly name?: PropertyName; + // tsc: readonly name?: PropertyName readonly name: Identifier - readonly parameters: ts.NodeArray + readonly parameters: NodeArray - // tsc: readonly body?: FunctionBody | undefined; + // tsc: readonly body?: FunctionBody | undefined readonly body: Block private readonly _scriptFunction: KNativePointer @@ -409,7 +498,7 @@ export class MethodDeclaration extends Node implements ts.MethodDeclaration { _classElementBrand: any _objectLiteralBrand: any _declarationBrand: any - kind: ts.SyntaxKind.MethodDeclaration = ts.SyntaxKind.MethodDeclaration; + kind: ts.SyntaxKind.Constructor = ts.SyntaxKind.Constructor } export class PropertyDeclaration extends Node implements ts.PropertyDeclaration { @@ -422,7 +511,7 @@ export class PropertyDeclaration extends Node implements ts.PropertyDeclaration get name(): ts.PropertyName { return todo() } _classElementBrand: any _declarationBrand: any - kind: ts.SyntaxKind.PropertyDeclaration = ts.SyntaxKind.PropertyDeclaration; + kind: ts.SyntaxKind.PropertyDeclaration = ts.SyntaxKind.PropertyDeclaration } export class ParameterDeclaration extends Node implements ts.ParameterDeclaration { @@ -434,15 +523,17 @@ export class ParameterDeclaration extends Node implements ts.ParameterDeclaratio get parent(): any { return todo() } get name(): ts.BindingName { return todo() } _declarationBrand: any - kind: ts.SyntaxKind.Parameter = ts.SyntaxKind.Parameter; + kind: ts.SyntaxKind.Parameter = ts.SyntaxKind.Parameter } -export class ETSPrimitiveType extends Node implements ts.Node { +export class ETSPrimitiveType extends Node implements ts.Node, TypeNode { constructor(peer: KNativePointer) { super(peer) } - kind: ts.SyntaxKind.Unknown = ts.SyntaxKind.Unknown; + // TODO: support minimal interface + _typeNodeBrand: any + kind: ts.SyntaxKind.Unknown = ts.SyntaxKind.Unknown } // TODO: should be interface, not abstract class @@ -483,7 +574,7 @@ export class FunctionTypeNode extends Node implements ts.FunctionTypeNode, TypeN type: any _typeNodeBrand: any _declarationBrand: any - kind: ts.SyntaxKind.FunctionType = ts.SyntaxKind.FunctionType; + kind: ts.SyntaxKind.FunctionType = ts.SyntaxKind.FunctionType } export class ReturnStatement extends Node implements ts.ReturnStatement, Statement { @@ -491,17 +582,17 @@ export class ReturnStatement extends Node implements ts.ReturnStatement, Stateme super(peer) } - private _expression?: Expression; + private _expression?: Expression get expression(): Expression | undefined { if (this._expression === undefined) { - this._expression = util.makeView(nativeModule._ReturnStatementArgument(Global.context, this.peer)) as Expression + this._expression = util.nodeByPeer(nativeModule._ReturnStatementArgument(Global.context, this.peer)) as Expression } return this._expression } // TODO: support minimal interface _statementBrand: any - kind: ts.SyntaxKind.ReturnStatement = ts.SyntaxKind.ReturnStatement; + kind: ts.SyntaxKind.ReturnStatement = ts.SyntaxKind.ReturnStatement } export class IfStatement extends Node implements ts.IfStatement { @@ -513,7 +604,7 @@ export class IfStatement extends Node implements ts.IfStatement { thenStatement: any expression: any _statementBrand: any - kind: ts.SyntaxKind.IfStatement = ts.SyntaxKind.IfStatement; + kind: ts.SyntaxKind.IfStatement = ts.SyntaxKind.IfStatement } export class BinaryExpression extends Node implements ts.BinaryExpression { @@ -527,45 +618,22 @@ export class BinaryExpression extends Node implements ts.BinaryExpression { operatorToken: any _expressionBrand: any _declarationBrand: any - kind: ts.SyntaxKind.BinaryExpression = ts.SyntaxKind.BinaryExpression; -} - -// should be Token -export class BinaryOperatorToken extends Node implements ts.BinaryOperatorToken { - constructor(token: ts.TokenSyntaxKind) { - super(NULLPTR) - this._token = BinaryOperatorToken.tokenKinds.get(token) - } - - private static readonly tokenKinds = new Map([ - [ts.SyntaxKind.PlusToken, Es2pandaTokenType.TOKEN_TYPE_PUNCTUATOR_PLUS], - ]) - - - private _token: KInt - get token(): KInt { - return this._token - } - - // TODO: support minimal interface - decorators: any - modifiers: any - kind: any + kind: ts.SyntaxKind.BinaryExpression = ts.SyntaxKind.BinaryExpression } export class ArrowFunction extends Node implements ts.ArrowFunction { constructor(peer: KNativePointer) { super(peer) this._scriptFunction = nativeModule._ArrowFunctionExpressionFunction(Global.context, this.peer) - this.parameters = util.unpack(nativeModule._ScriptFunctionParams(Global.context, this._scriptFunction)) as ts.NodeArray - this.body = util.makeView(nativeModule._ScriptFunctionBody(Global.context, this._scriptFunction)) as Block + this.parameters = util.unpack(nativeModule._ScriptFunctionParams(Global.context, this._scriptFunction)) as NodeArray + this.body = util.nodeByPeer(nativeModule._ScriptFunctionBody(Global.context, this._scriptFunction)) as Block } get name(): never { return this.name } - readonly parameters: ts.NodeArray + readonly parameters: NodeArray body: Block private _scriptFunction: KNativePointer @@ -575,7 +643,7 @@ export class ArrowFunction extends Node implements ts.ArrowFunction { _expressionBrand: any _functionLikeDeclarationBrand: any _declarationBrand: any - readonly kind: ts.SyntaxKind.ArrowFunction = ts.SyntaxKind.ArrowFunction; + readonly kind: ts.SyntaxKind.ArrowFunction = ts.SyntaxKind.ArrowFunction } export class NumericLiteral extends Node implements ts.NumericLiteral { @@ -593,7 +661,7 @@ export class NumericLiteral extends Node implements ts.NumericLiteral { _updateExpressionBrand: any _unaryExpressionBrand: any _expressionBrand: any - readonly kind: ts.SyntaxKind.NumericLiteral = ts.SyntaxKind.NumericLiteral; + readonly kind: ts.SyntaxKind.NumericLiteral = ts.SyntaxKind.NumericLiteral } export class VariableStatement extends Node implements ts.VariableStatement { @@ -608,7 +676,7 @@ export class VariableStatement extends Node implements ts.VariableStatement { locals?: ts.SymbolTable | undefined skipCheck?: boolean | undefined decorators?: undefined - readonly kind: ts.SyntaxKind.VariableStatement = ts.SyntaxKind.VariableStatement; + readonly kind: ts.SyntaxKind.VariableStatement = ts.SyntaxKind.VariableStatement } export class UnsupportedNode extends Node implements ts.Node { diff --git a/arkoala-arkts/libarkts/src/arkts/utilities.ts b/arkoala-arkts/libarkts/src/arkts/utilities.ts index 6d5397bda..ef8db6e8c 100644 --- a/arkoala-arkts/libarkts/src/arkts/utilities.ts +++ b/arkoala-arkts/libarkts/src/arkts/utilities.ts @@ -13,120 +13,37 @@ * limitations under the License. */ -import * as ts from "@koalaui/ets-tsc" import { nativeModule } from "../NativeModule" -import { fromPtrArray, KNativePointer, withString, withStringArray, withStringResult, KInt } from "@koalaui/interop" +import { fromPtrArray, KNativePointer, withStringResult, withString } from "@koalaui/interop" import { NativePtrDecoder } from "../node/Platform" import * as arkts from "./types" -import { - ContextState, - es2pandaKind, - Es2pandaModifierFlags, -} from "./enums" -export { KNativePointerArray } from "../NativeModule" +import { nodeByPeer } from "./nodeByPeer" +export { nodeByPeer } from "./nodeByPeer" export function throwError(error: string): never { throw new Error(error) } +export function todo(): any { + throwError("Not yet implemented") +} + /** TODO batch this */ export function unpack(arrayPtr: KNativePointer): ReadonlyArray { const array = (new NativePtrDecoder).decode(arrayPtr) return fromPtrArray(array, (peer: KNativePointer) => { - return makeView(peer) + return nodeByPeer(peer) }) } -export function createConfig(input: string[]): KNativePointer { - return withStringArray(input, (stringArray: string[]) => { - return nativeModule._CreateConfig(input.length, stringArray) - }) -} - -export function createContextFromString(config: KNativePointer, source: string, filename: string): KNativePointer { - return withString(source, (sourcePtr: string) => { - return withString(filename, (filenamePtr: string) => { - return nativeModule._CreateContextFromString(config, sourcePtr, filenamePtr) - }) - }) -} - -export function proceedToState(state: ContextState): void { - nativeModule._ProceedToState(arkts.Global.context, state) - if (nativeModule._ContextState(arkts.Global.context) === ContextState.ES2PANDA_STATE_ERROR) { - throwError("FAILED PROCEED TO: " + ContextState[state] + "\n" + withStringResult(nativeModule._ContextErrorMessage(arkts.Global.context)) ?? throwError(`COULDN'T GET: _ContextErrorMessage`)) - } -} - -export function startChecker(): boolean { - return nativeModule._CheckerStartChecker(arkts.Global.context) -} - export function contextProgram(): KNativePointer { return nativeModule._ContextProgram(arkts.Global.context) } -export function programAst(program: KNativePointer) { // TODO: return type - const nativePtr: KNativePointer = nativeModule._ProgramAst(program) - return nativePtr -} - -const kinds = new Map([ - [es2pandaKind.Identifier, ts.SyntaxKind.Identifier], - [es2pandaKind.StringLiteral, ts.SyntaxKind.StringLiteral], - [es2pandaKind.Block, ts.SyntaxKind.Block], - [es2pandaKind.MethodDeclaration, ts.SyntaxKind.MethodDeclaration], - [es2pandaKind.ClassDeclaration, ts.SyntaxKind.ClassDeclaration], - [es2pandaKind.FunctionDeclaration, ts.SyntaxKind.FunctionDeclaration], - [es2pandaKind.PropertyDeclaration, ts.SyntaxKind.PropertyDeclaration], - [es2pandaKind.ETSFunctionType, ts.SyntaxKind.FunctionType], - [es2pandaKind.CallExpression, ts.SyntaxKind.CallExpression], - [es2pandaKind.ExpressionStatement, ts.SyntaxKind.ExpressionStatement], - [es2pandaKind.MemberExpression, ts.SyntaxKind.PropertyAccessExpression], - [es2pandaKind.ArrowFunctionExpression, ts.SyntaxKind.ArrowFunction], - [es2pandaKind.ReturnStatement, ts.SyntaxKind.ReturnStatement], - // TODO: drop one Parameter (?) - [es2pandaKind.Parameter, ts.SyntaxKind.Parameter], - [es2pandaKind.ETSParameterExpression, ts.SyntaxKind.Parameter], - [es2pandaKind.NumberLiteral, ts.SyntaxKind.NumericLiteral], - [es2pandaKind.VariableDeclaration, ts.SyntaxKind.VariableStatement], - // [es2pandaKind.ClassStaticBlock, ts.SyntaxKind.ClassDeclaration], -]) - -export function makeView(peer: KNativePointer): arkts.Node { - const es2pandaKind = nativeModule._GetKind(peer) - if (nativeModule._IsProgram(arkts.Global.context, peer)) { - return new arkts.SourceFile(peer) - } - - const kind: ts.SyntaxKind | undefined = kinds.get(es2pandaKind) - - if (!kind) { - // console.log(dumpJson(peer)) - // throw new Error(`Unsupported node kind: ${kind}`) - return new arkts.UnsupportedNode(peer) - } - - if (kind == ts.SyntaxKind.Identifier) return new arkts.Identifier(peer) - if (kind == ts.SyntaxKind.StringLiteral) return new arkts.StringLiteral(peer) - if (kind == ts.SyntaxKind.Block) return new arkts.Block(peer) - if (kind == ts.SyntaxKind.MethodDeclaration) return new arkts.MethodDeclaration(peer) - if (kind == ts.SyntaxKind.ClassDeclaration) return new arkts.ClassDeclaration(peer) - if (kind == ts.SyntaxKind.FunctionDeclaration) return new arkts.FunctionDeclaration(peer) - if (kind == ts.SyntaxKind.PropertyDeclaration) return new arkts.PropertyDeclaration(peer) - if (kind == ts.SyntaxKind.FunctionType) return new arkts.FunctionTypeNode(peer) - if (kind == ts.SyntaxKind.CallExpression) return new arkts.CallExpression(peer) - if (kind == ts.SyntaxKind.ExpressionStatement) return new arkts.ExpressionStatement(peer) - if (kind == ts.SyntaxKind.PropertyAccessExpression) return new arkts.PropertyAccessExpression(peer) - if (kind == ts.SyntaxKind.ArrowFunction) return new arkts.ArrowFunction(peer) - if (kind == ts.SyntaxKind.ReturnStatement) return new arkts.ReturnStatement(peer) - if (kind == ts.SyntaxKind.Parameter) return new arkts.ParameterDeclaration(peer) - if (kind == ts.SyntaxKind.NumericLiteral) return new arkts.NumericLiteral(peer) - if (kind == ts.SyntaxKind.VariableStatement) return new arkts.VariableStatement(peer) - - throw new Error(`Unknown node kind: ${kind}`) +export function programAst(program: KNativePointer) { + return nodeByPeer(nativeModule._ProgramAst(program)) } export function dumpJson(peer: KNativePointer): string { @@ -141,43 +58,16 @@ export function dumpSrcNode(node: arkts.Node): string { return withStringResult(nativeModule._AstNodeDumpEtsSrcConst(arkts.Global.context, node.peer)) ?? throwError(`COULDN'T DUMP TO SOURCE`) } -export function dumpScriptFunction(peer: KNativePointer) { - return '' - + 'ID: ' + dumpJson(nativeModule._ScriptFunctionId(arkts.Global.context, peer)) + '\n' - + 'BODY: ' + dumpJson(nativeModule._ScriptFunctionBody(arkts.Global.context, peer)) + '\n' - + 'MODS: ' + getModifierFlags(peer) + '\n' -} - -export function setParent(node: KNativePointer, parent: KNativePointer) { - nativeModule._AstNodeSetParent(arkts.Global.context, node, parent) -} - -export function getModifierFlags(node: KNativePointer): Es2pandaModifierFlags { - return nativeModule._AstNodeModifiers(arkts.Global.context, node) +export function dumpModifiers(peer: KNativePointer): string { + return withStringResult(nativeModule._AstNodeDumpModifiers(arkts.Global.context, peer)) ?? throwError(`COULDN'T DUMP MODIFIERS`) } -export function setModifierFlags(node: KNativePointer, flags: Es2pandaModifierFlags) { - nativeModule._AstNodeClearModifier(arkts.Global.context, node, arkts.ALL_FLAGS) - nativeModule._AstNodeAddModifier(arkts.Global.context, node, flags as KInt) +export function dumpModifiersNode(node: arkts.Node): string { + return dumpModifiers(node.peer) } -export function updateChildren(peer: KNativePointer) { - nativeModule._AstNodeUpdateChildren(arkts.Global.context, peer) -} - -export function getDecl(node: arkts.Node): arkts.Node | undefined { - let decl = node.peer - decl = nativeModule._AstNodeVariableConst(arkts.Global.context, decl) - if (decl === arkts.NULLPTR) { - return undefined - } - decl = nativeModule._VariableDeclaration(arkts.Global.context, decl) - if (decl === arkts.NULLPTR) { - return undefined - } - decl = nativeModule._DeclNode(arkts.Global.context, decl) - if (decl === arkts.NULLPTR) { - return undefined - } - return makeView(decl) +export function createAstDumper(peer: KNativePointer, source: string): KNativePointer { + return withString(source, (_source: string) => { + return nativeModule._CreateAstDumper(arkts.Global.context, peer, _source) + }) } diff --git a/arkoala-arkts/libarkts/src/arkts/utilitiesPublic.ts b/arkoala-arkts/libarkts/src/arkts/utilitiesPublic.ts new file mode 100644 index 000000000..8ac100d1a --- /dev/null +++ b/arkoala-arkts/libarkts/src/arkts/utilitiesPublic.ts @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { nativeModule } from "../NativeModule" +import { KNativePointer, withString, withStringArray, withStringResult } from "@koalaui/interop" +import * as arkts from "./types" +import { + ContextState, +} from "./enums" +import { nodeByPeer } from "./nodeByPeer" +import { throwError } from "./utilities" + +export function createConfig(input: string[]): KNativePointer { + return withStringArray(input, (stringArray: string[]) => { + return nativeModule._CreateConfig(input.length, stringArray) + }) +} + +export function createContextFromString(config: KNativePointer, source: string, filename: string): KNativePointer { + return withString(source, (sourcePtr: string) => { + return withString(filename, (filenamePtr: string) => { + return nativeModule._CreateContextFromString(config, sourcePtr, filenamePtr) + }) + }) +} + +export function proceedToState(state: ContextState): void { + nativeModule._ProceedToState(arkts.Global.context, state) + if (nativeModule._ContextState(arkts.Global.context) === ContextState.ES2PANDA_STATE_ERROR) { + const errorMessage = withStringResult(nativeModule._ContextErrorMessage(arkts.Global.context)) + if (errorMessage === undefined) { + throwError(`COULDN'T GET: _ContextErrorMessage`) + } + throwError("FAILED PROCEED TO: " + ContextState[state] + "\n" + errorMessage) + } +} + +export function startChecker(): boolean { + return nativeModule._CheckerStartChecker(arkts.Global.context) +} + +export function getDecl(node: arkts.Node): arkts.Node | undefined { + let decl = node.peer + decl = nativeModule._AstNodeVariableConst(arkts.Global.context, decl) + if (decl === arkts.NULLPTR) { + return undefined + } + decl = nativeModule._VariableDeclaration(arkts.Global.context, decl) + if (decl === arkts.NULLPTR) { + return undefined + } + decl = nativeModule._DeclNode(arkts.Global.context, decl) + if (decl === arkts.NULLPTR) { + return undefined + } + return nodeByPeer(decl) +} diff --git a/arkoala-arkts/libarkts/src/arkts/visitor.ts b/arkoala-arkts/libarkts/src/arkts/visitor.ts index c36a474bb..0062bed96 100644 --- a/arkoala-arkts/libarkts/src/arkts/visitor.ts +++ b/arkoala-arkts/libarkts/src/arkts/visitor.ts @@ -1,22 +1,7 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import * as ts from "@koalaui/ets-tsc" import * as arkts from "./types" import { factory } from "./factory/nodeFactory" import * as util from "./utilities" +import { SyntaxKind } from "./enums" type Visitor = (node: arkts.Node) => arkts.Node @@ -29,7 +14,7 @@ function nodeVisitor(node: T, visitor: Visitor } // TODO: rethink -function nodesVisitor(nodes: ts.NodeArray | undefined, visitor: Visitor): T[] { +function nodesVisitor(nodes: arkts.NodeArray | undefined, visitor: Visitor): T[] { if (nodes === undefined) { return [] } @@ -53,31 +38,31 @@ type VisitEachChildTable = { [TNode in HasChildren as TNode["kind"]]: VisitEachC // TODO: add more nodes const visitEachChildTable: VisitEachChildTable = { - [ts.SyntaxKind.SourceFile]: function (node: arkts.SourceFile, visitor: Visitor) { + [SyntaxKind.SourceFile]: function (node: arkts.SourceFile, visitor: Visitor) { return factory.updateSourceFile( node, nodesVisitor(node.statements, visitor) ) }, - [ts.SyntaxKind.FunctionDeclaration]: function (node: arkts.FunctionDeclaration, visitor: Visitor) { + [SyntaxKind.FunctionDeclaration]: function (node: arkts.FunctionDeclaration, visitor: Visitor) { return factory.updateFunctionDeclaration( node, undefined, undefined, - nodeVisitor(node.name!, visitor), + nodeVisitor(node.name, visitor), undefined, nodesVisitor(node.parameters, visitor), undefined, nodeVisitor(node.body, visitor), ) }, - [ts.SyntaxKind.ExpressionStatement]: function (node: arkts.ExpressionStatement, visitor: Visitor) { + [SyntaxKind.ExpressionStatement]: function (node: arkts.ExpressionStatement, visitor: Visitor) { return factory.updateExpressionStatement( node, nodeVisitor(node.expression, visitor) ) }, - [ts.SyntaxKind.CallExpression]: function (node: arkts.CallExpression, visitor: Visitor) { + [SyntaxKind.CallExpression]: function (node: arkts.CallExpression, visitor: Visitor) { return factory.updateCallExpression( node, nodeVisitor(node.expression, visitor), @@ -85,14 +70,14 @@ const visitEachChildTable: VisitEachChildTable = { nodesVisitor(node.arguments, visitor) ) }, - [ts.SyntaxKind.PropertyAccessExpression]: function (node: arkts.PropertyAccessExpression, visitor: Visitor) { + [SyntaxKind.PropertyAccessExpression]: function (node: arkts.PropertyAccessExpression, visitor: Visitor) { return factory.updatePropertyAccessExpression( node, nodeVisitor(node.expression, visitor), - nodeVisitor(node.name, visitor) as arkts.Identifier + nodeVisitor(node.name, visitor) ) }, - [ts.SyntaxKind.ClassDeclaration]: function (node: arkts.ClassDeclaration, visitor: Visitor) { + [SyntaxKind.ClassDeclaration]: function (node: arkts.ClassDeclaration, visitor: Visitor) { return factory.updateClassDeclaration( node, undefined, @@ -102,7 +87,7 @@ const visitEachChildTable: VisitEachChildTable = { nodesVisitor(node.members, visitor) ) }, - [ts.SyntaxKind.MethodDeclaration]: function (node: arkts.MethodDeclaration, visitor: Visitor) { + [SyntaxKind.MethodDeclaration]: function (node: arkts.MethodDeclaration, visitor: Visitor) { return factory.updateMethodDeclaration( node, undefined, @@ -115,7 +100,7 @@ const visitEachChildTable: VisitEachChildTable = { nodeVisitor(node.body, visitor), ) }, - [ts.SyntaxKind.Block]: function (node: arkts.Block, visitor: Visitor) { + [SyntaxKind.Block]: function (node: arkts.Block, visitor: Visitor) { return factory.updateBlock( node, nodesVisitor(node.statements, visitor), @@ -123,7 +108,7 @@ const visitEachChildTable: VisitEachChildTable = { }, } -function nodeHasChildren(node: ts.Node): node is HasChildren { +function nodeHasChildren(node: arkts.Node): node is HasChildren { return node.kind in visitEachChildTable } @@ -132,7 +117,7 @@ export function visitEachChild( visitor: Visitor, // context: ts.TransformationContext ): T { - const visitFunc = (visitEachChildTable as Record | undefined>)[node.kind]; + const visitFunc = (visitEachChildTable as Record | undefined>)[node.kind]; if (nodeHasChildren(node) && visitFunc === undefined) { util.throwError('Unsupported node kind: ' + node.kind) } diff --git a/arkoala-arkts/libarkts/src/es2panda.ts b/arkoala-arkts/libarkts/src/es2panda.ts index 7524d54f7..1040dea0d 100644 --- a/arkoala-arkts/libarkts/src/es2panda.ts +++ b/arkoala-arkts/libarkts/src/es2panda.ts @@ -34,8 +34,7 @@ function es2panda(configPath: string, filePath: string, transform: (ast: arkts.N arkts.Global.context = arkts.createContextFromString(arkts.Global.config, source, filePath) arkts.proceedToState(arkts.ContextState.ES2PANDA_STATE_PARSED) const program = arkts.contextProgram() - const peer = arkts.programAst(program) - const ast = arkts.makeView(peer) + const ast = arkts.programAst(program) transform(ast) diff --git a/arkoala-arkts/libarkts/test/es2panda/abc-gen.test.ts b/arkoala-arkts/libarkts/test/es2panda/abc-gen.test.ts index ebd42d4b8..7791c6af8 100644 --- a/arkoala-arkts/libarkts/test/es2panda/abc-gen.test.ts +++ b/arkoala-arkts/libarkts/test/es2panda/abc-gen.test.ts @@ -15,9 +15,11 @@ suite(util.getSuiteTitle(__filename), () => { util.getDefaultSetup(sample_in) - const sourceFile = arkts.makeView(util.AstProvider.provideAst()) as arkts.SourceFile + const sourceFile = arkts.nodeByPeer(util.AstProvider.provideAst()) + util.assert(arkts.isSourceFile(sourceFile)) - const expressionStatement = sourceFile.statements[1] as arkts.ExpressionStatement + const expressionStatement = sourceFile.statements[1] + util.assert(arkts.isExpressionStatement(expressionStatement)) const newStatements = [ sourceFile.statements[0], @@ -45,9 +47,11 @@ suite(util.getSuiteTitle(__filename), () => { util.getDefaultSetup(sample_in) - const sourceFile = arkts.makeView(util.AstProvider.provideAst()) as arkts.SourceFile + const sourceFile = arkts.nodeByPeer(util.AstProvider.provideAst()) + util.assert(arkts.isSourceFile(sourceFile)) - const funcDecl = sourceFile.statements[0] as arkts.FunctionDeclaration + const funcDecl = sourceFile.statements[0] + util.assert(arkts.isFunctionDeclaration(funcDecl)) const newStatements = [ arkts.factory.updateFunctionDeclaration( @@ -78,10 +82,14 @@ suite(util.getSuiteTitle(__filename), () => { util.getDefaultSetup(sample_in) - const sourceFile = arkts.makeView(util.AstProvider.provideAst()) as arkts.SourceFile - const exprStatement = sourceFile.statements[1] as arkts.ExpressionStatement - const callExpr = exprStatement.expression as arkts.CallExpression + const sourceFile = arkts.nodeByPeer(util.AstProvider.provideAst()) + util.assert(arkts.isSourceFile(sourceFile)) + const exprStatement = sourceFile.statements[1] + util.assert(arkts.isExpressionStatement(exprStatement)) + const callExpr = exprStatement.expression + util.assert(arkts.isCallExpression(callExpr)) + util.assert(arkts.isArrowFunction(callExpr.arguments[0])) const lambdaArg = arkts.factory.createArrowFunction( undefined, @@ -89,16 +97,17 @@ suite(util.getSuiteTitle(__filename), () => { [], undefined, undefined, - (callExpr.arguments[0] as arkts.ArrowFunction).body + callExpr.arguments[0].body ) + util.assert(arkts.isIdentifier(callExpr.expression)) const newStatements = [ sourceFile.statements[0], arkts.factory.updateExpressionStatement( exprStatement, arkts.factory.updateCallExpression( callExpr, - arkts.factory.updateIdentifier(callExpr.expression as arkts.Identifier, 'foo'), + arkts.factory.updateIdentifier(callExpr.expression, 'foo'), undefined, [ lambdaArg, diff --git a/arkoala-arkts/libarkts/test/es2panda/builder-lambda-rewrite.test.ts b/arkoala-arkts/libarkts/test/es2panda/builder-lambda-rewrite.test.ts index a36a7c273..3de1f3019 100644 --- a/arkoala-arkts/libarkts/test/es2panda/builder-lambda-rewrite.test.ts +++ b/arkoala-arkts/libarkts/test/es2panda/builder-lambda-rewrite.test.ts @@ -19,17 +19,26 @@ suite(util.getSuiteTitle(__filename), () => { util.getDefaultSetup(sample_in) + let sourceFile = arkts.nodeByPeer(util.AstProvider.provideAst()) + util.assert(arkts.isSourceFile(sourceFile)) + const newName = "_Foo" const paramName = "instance" - const node = (arkts.makeView(util.getStatement(0)) as arkts.ExpressionStatement).expression as arkts.CallExpression + const firstStatement = arkts.nodeByPeer(util.getStatement(0)) + util.assert(arkts.isExpressionStatement(firstStatement)) + const node = firstStatement.expression + util.assert(arkts.isCallExpression(node)) const instanceLambdaBody = arkts.factory.createBlock([]) const lambdaParams = [ arkts.factory.createParameterDeclaration( undefined, undefined, - arkts.factory.createIdentifier(paramName, arkts.factory.createKeywordTypeNode(arkts.SyntaxKind.StringKeyword)) + arkts.factory.createIdentifier(paramName), + undefined, + arkts.factory.createKeywordTypeNode(arkts.SyntaxKind.StringKeyword), + undefined ) ] @@ -51,14 +60,21 @@ suite(util.getSuiteTitle(__filename), () => { ...node.arguments ] ) - - util.assertEqualsGolden(arkts.dumpJsonNode(result), this) - const sample_out = - ` - _Foo(((instance: string) => {}), "label") - ` - util.assertEqualsSource(arkts.dumpSrcNode(result), sample_out) + sourceFile = arkts.factory.updateSourceFile( + sourceFile, + [ + arkts.factory.createExpressionStatement(result) + ] + ) + + util.assertAstEqualsAfter( + sourceFile, + arkts.ContextState.ES2PANDA_STATE_PARSED, + ` + _Foo(((instance: string) => {}), "label") + ` + ) }) test("adding-body-to-lambda-param", function() { @@ -73,10 +89,17 @@ suite(util.getSuiteTitle(__filename), () => { util.getDefaultSetup(sample_in) + let sourceFile = arkts.nodeByPeer(util.AstProvider.provideAst()) + util.assert(arkts.isSourceFile(sourceFile)) + const newName = "_Foo" const paramName = "instance" - const node = (arkts.makeView(util.getStatement(0)) as arkts.ExpressionStatement).expression as arkts.CallExpression + const firstStatement = arkts.nodeByPeer(util.getStatement(0)) + util.assert(arkts.isExpressionStatement(firstStatement)) + + const node = firstStatement.expression + util.assert(arkts.isCallExpression(node)) const instanceLambdaBody = arkts.factory.createBlock([ arkts.factory.createExpressionStatement( @@ -87,7 +110,10 @@ suite(util.getSuiteTitle(__filename), () => { arkts.factory.createParameterDeclaration( undefined, undefined, - arkts.factory.createIdentifier(paramName, arkts.factory.createKeywordTypeNode(arkts.SyntaxKind.StringKeyword)) + arkts.factory.createIdentifier(paramName), + undefined, + arkts.factory.createKeywordTypeNode(arkts.SyntaxKind.StringKeyword), + undefined ) ] @@ -110,15 +136,22 @@ suite(util.getSuiteTitle(__filename), () => { ] ) - util.assertEqualsGolden(arkts.dumpJsonNode(result), this) - - const sample_out = - ` - _Foo(((instance: string) => { - instance.bar().qux(); - }), "label1", "label2") - ` - util.assertEqualsSource(arkts.dumpSrcNode(result), sample_out) + sourceFile = arkts.factory.updateSourceFile( + sourceFile, + [ + arkts.factory.createExpressionStatement(result) + ] + ) + + util.assertAstEqualsAfter( + sourceFile, + arkts.ContextState.ES2PANDA_STATE_PARSED, + ` + _Foo(((instance: string) => { + instance.bar().qux(); + }), "label1", "label2") + ` + ) }) test("builder-lambda-transformer-sample-1", function() { @@ -133,20 +166,22 @@ suite(util.getSuiteTitle(__filename), () => { util.getDefaultSetup(sample_in) - const sourceFile = arkts.makeView(util.AstProvider.provideAst()) - const builderLambdaTransformer = new BuilderLambdaTransformer() + let sourceFile = arkts.nodeByPeer(util.AstProvider.provideAst()) + util.assert(arkts.isSourceFile(sourceFile)) - const transformed = builderLambdaTransformer.visitor(sourceFile) + const builderLambdaTransformer = new BuilderLambdaTransformer() - util.assertEqualsGolden(arkts.dumpJsonNode(transformed), this) + sourceFile = builderLambdaTransformer.visitor(sourceFile) - const sample_out = - ` - foo(((instance: string) => { - return instance; - }), "label") - ` - util.assertEqualsSource(arkts.dumpSrcNode(transformed), sample_out) + util.assertAstEqualsAfter( + sourceFile, + arkts.ContextState.ES2PANDA_STATE_PARSED, + ` + foo(((instance: string) => { + return instance; + }), "label") + ` + ) }) test("builder-lambda-transformer-sample-2", function() { @@ -161,20 +196,22 @@ suite(util.getSuiteTitle(__filename), () => { util.getDefaultSetup(sample_in) - const sourceFile = arkts.makeView(util.AstProvider.provideAst()) - const builderLambdaTransformer = new BuilderLambdaTransformer() + let sourceFile = arkts.nodeByPeer(util.AstProvider.provideAst()) + util.assert(arkts.isSourceFile(sourceFile)) - const transformed = builderLambdaTransformer.visitor(sourceFile) + const builderLambdaTransformer = new BuilderLambdaTransformer() - util.assertEqualsGolden(arkts.dumpJsonNode(transformed), this) + sourceFile = builderLambdaTransformer.visitor(sourceFile) - const sample_out = - ` - foo(((instance: string) => { - return instance.bar().qux(); - }), "label1", "label2") - ` - util.assertEqualsSource(arkts.dumpSrcNode(transformed), sample_out) + util.assertAstEqualsAfter( + sourceFile, + arkts.ContextState.ES2PANDA_STATE_PARSED, + ` + foo(((instance: string) => { + return instance.bar().qux(); + }), "label1", "label2") + ` + ) }) // TODO: update nodes properly (now failing to generate bin) @@ -197,23 +234,25 @@ suite(util.getSuiteTitle(__filename), () => { util.getDefaultSetup(sample_in) - const sourceFile = arkts.makeView(util.AstProvider.provideAst()) + let sourceFile = arkts.nodeByPeer(util.AstProvider.provideAst()) + util.assert(arkts.isSourceFile(sourceFile)) + const builderLambdaTransformer = new BuilderLambdaTransformer() - const transformed = builderLambdaTransformer.visitor(sourceFile) - - util.assertEqualsGolden(arkts.dumpJsonNode(transformed), this) - - const sample_out = - ` - function Foo(builder: ((instance: string)=> string), arg1: string): void { - console.log(((arg1) + (builder("ABC")))); - } - - Foo(((instance: string) => { - return instance.charAt(1); - }), "> second_char_of_ABC: ") - ` - util.assertEqualsSource(arkts.dumpSrcNode(transformed), sample_out) + sourceFile = builderLambdaTransformer.visitor(sourceFile) + + util.assertAstEqualsAfter( + sourceFile, + arkts.ContextState.ES2PANDA_STATE_PARSED, + ` + function Foo(builder: ((instance: string)=> string), arg1: string): void { + console.log(((arg1) + (builder("ABC")))); + } + + Foo(((instance: string) => { + return instance.charAt(1); + }), "> second_char_of_ABC: ") + ` + ) }) }) diff --git a/arkoala-arkts/libarkts/test/es2panda/create-function-declaration.test.ts b/arkoala-arkts/libarkts/test/es2panda/create-function-declaration.test.ts index aca03cffd..e9c926481 100644 --- a/arkoala-arkts/libarkts/test/es2panda/create-function-declaration.test.ts +++ b/arkoala-arkts/libarkts/test/es2panda/create-function-declaration.test.ts @@ -11,6 +11,9 @@ suite(util.getSuiteTitle(__filename), () => { util.getDefaultSetup(sample_in) + let sourceFile = arkts.nodeByPeer(util.AstProvider.provideAst()) + util.assert(arkts.isSourceFile(sourceFile)) + const funcDecl = arkts.factory.createFunctionDeclaration( undefined, undefined, @@ -24,13 +27,20 @@ suite(util.getSuiteTitle(__filename), () => { ) ) - util.assertEqualsGolden(arkts.dumpJsonNode(funcDecl), this) + sourceFile = arkts.factory.updateSourceFile( + sourceFile, + [ + funcDecl + ] + ) - const sample_out = - ` - function test_func() {} - ` - util.assertEqualsSource(arkts.dumpSrcNode(funcDecl), sample_out) + util.assertAstEqualsAfter( + sourceFile, + arkts.ContextState.ES2PANDA_STATE_PARSED, + ` + function test_func() {} + ` + ) }) test("empty-function-with-param", function() { @@ -39,14 +49,18 @@ suite(util.getSuiteTitle(__filename), () => { // } util.getDefaultSetup('') - const sourceFile: arkts.SourceFile = arkts.makeView(util.AstProvider.provideAst()) as arkts.SourceFile - const typeAnnotation = arkts.factory.createEtsPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_INT) + let sourceFile = arkts.nodeByPeer(util.AstProvider.provideAst()) + util.assert(arkts.isSourceFile(sourceFile)) + const funcParams = [ arkts.factory.createParameterDeclaration( undefined, undefined, - arkts.factory.createIdentifier("x", typeAnnotation) + arkts.factory.createIdentifier("x"), + undefined, + arkts.factory.createEtsPrimitiveType(arkts.Es2pandaPrimitiveType.PRIMITIVE_TYPE_INT), + undefined ) ] const funcDecl = arkts.factory.createFunctionDeclaration( @@ -62,15 +76,20 @@ suite(util.getSuiteTitle(__filename), () => { ) ) - arkts.factory.updateSourceFile(sourceFile, [funcDecl]) - - util.assertEqualsGolden(arkts.dumpJsonNode(sourceFile), this) + sourceFile = arkts.factory.updateSourceFile( + sourceFile, + [ + funcDecl + ] + ) - const sample_out = - ` - function test_func(x: long) {} - ` - util.assertEqualsSource(arkts.dumpSrcNode(sourceFile), sample_out) + util.assertAstEqualsAfter( + sourceFile, + arkts.ContextState.ES2PANDA_STATE_PARSED, + ` + function test_func(x: long) {} + ` + ) }) test("empty-function-with-string-param", function() { @@ -79,14 +98,18 @@ suite(util.getSuiteTitle(__filename), () => { // } util.getDefaultSetup('') - const sourceFile: arkts.SourceFile = arkts.makeView(util.AstProvider.provideAst()) as arkts.SourceFile - const typeAnnotation = arkts.factory.createKeywordTypeNode(arkts.SyntaxKind.StringKeyword) + let sourceFile = arkts.nodeByPeer(util.AstProvider.provideAst()) + util.assert(arkts.isSourceFile(sourceFile)) + const funcParams = [ arkts.factory.createParameterDeclaration( undefined, undefined, - arkts.factory.createIdentifier("x", typeAnnotation) + arkts.factory.createIdentifier("x"), + undefined, + arkts.factory.createKeywordTypeNode(arkts.SyntaxKind.StringKeyword), + undefined ) ] const funcDecl = arkts.factory.createFunctionDeclaration( @@ -102,14 +125,137 @@ suite(util.getSuiteTitle(__filename), () => { ) ) - arkts.factory.updateSourceFile(sourceFile, [funcDecl]) + sourceFile = arkts.factory.updateSourceFile( + sourceFile, + [ + funcDecl + ] + ) + + util.assertAstEqualsAfter( + sourceFile, + arkts.ContextState.ES2PANDA_STATE_PARSED, + ` + function test_func(x: string) {} + ` + ) + }) + + test("async-empty-function", function() { + // async function test_func() {} + + const sample_in = `` - util.assertEqualsGolden(arkts.dumpJsonNode(sourceFile), this) + util.getDefaultSetup(sample_in) + + let sourceFile = arkts.nodeByPeer(util.AstProvider.provideAst()) + util.assert(arkts.isSourceFile(sourceFile)) - const sample_out = + const funcDecl = arkts.factory.createFunctionDeclaration( + [ + arkts.factory.createToken(arkts.SyntaxKind.AsyncKeyword) + ], + undefined, + arkts.factory.createIdentifier("test_func"), + undefined, + [], + undefined, + arkts.factory.createBlock( + [], + true + ) + ) + + sourceFile = arkts.factory.updateSourceFile( + sourceFile, + [ + funcDecl + ] + ) + + util.assertAstEqualsAfter( + sourceFile, + arkts.ContextState.ES2PANDA_STATE_PARSED, + ` + async function test_func() {} + ` + ) + }) + + test("empty-method-with-public-static-modifiers", function() { + // class A { + // static test_func() { + // } + // } + + const sample_in = ` - function test_func(x: string) {} + class A { + } ` - util.assertEqualsSource(arkts.dumpSrcNode(sourceFile), sample_out) + + util.getDefaultSetup(sample_in) + + let sourceFile = arkts.nodeByPeer(util.AstProvider.provideAst()) + util.assert(arkts.isSourceFile(sourceFile)) + + let classDecl = sourceFile.statements[0] + util.assert(arkts.isClassDeclaration(classDecl)) + + classDecl = arkts.factory.updateClassDeclaration( + classDecl, + undefined, + arkts.factory.createIdentifier("A"), + undefined, + undefined, + [ + arkts.factory.createMethodDeclaration( + [ + arkts.factory.createToken(arkts.SyntaxKind.PublicKeyword), + arkts.factory.createToken(arkts.SyntaxKind.StaticKeyword) + ], + undefined, + arkts.factory.createIdentifier("test_func"), + undefined, + undefined, + [], + undefined, + arkts.factory.createBlock( + [], + false + ) + ), + arkts.factory.createConstructorDeclaration( + [ + arkts.factory.createToken(arkts.SyntaxKind.PublicKeyword) + ], + [], + arkts.factory.createBlock( + [], + false + ) + ) + ] + ) + + sourceFile = arkts.factory.updateSourceFile( + sourceFile, + [ + classDecl + ] + ) + + util.assertAstEqualsAfter( + sourceFile, + arkts.ContextState.ES2PANDA_STATE_PARSED, + ` + class A { + public static test_func() {} + + public constructor() {} + + } + ` + ) }) }) diff --git a/arkoala-arkts/libarkts/test/es2panda/function-rewrite.test.ts b/arkoala-arkts/libarkts/test/es2panda/function-rewrite.test.ts index 4064d703a..0c4441260 100644 --- a/arkoala-arkts/libarkts/test/es2panda/function-rewrite.test.ts +++ b/arkoala-arkts/libarkts/test/es2panda/function-rewrite.test.ts @@ -20,17 +20,26 @@ suite(util.getSuiteTitle(__filename), () => { // arkts.proceedToState(arkts.ContextState.ES2PANDA_STATE_CHECKED) - // const sourceFile = arkts.makeView(util.AstProvider.provideAst()) + // let sourceFile = arkts.nodeByPeer(util.AstProvider.provideAst()) - // const memoTransformer = new FunctionTransformer() - // const transformed = memoTransformer.visitor(sourceFile) + // sourceFile = new FunctionTransformer().visitor(sourceFile) - // util.nativeModule._VarBinderInitTopScope(arkts.Global.context) - // util.nativeModule._VarBinderIdentifierAnalysis(arkts.Global.context) - // console.log(arkts.startChecker()) + // util.assertAstEqualsAfter( + // sourceFile, + // arkts.ContextState.ES2PANDA_STATE_CHECKED, + // ` + // const x: string = "A" + + // function foo(x: string) { + // console.log("FUNC CALLED: " + x) + // } - // console.log(arkts.dumpSrcNode(sourceFile)) + // foo("SAMPLE") + // ` + // ) + // util.nativeModule._VarBinderInitTopScope(arkts.Global.context) + // util.nativeModule._VarBinderIdentifierAnalysis(arkts.Global.context) // arkts.proceedToState(arkts.ContextState.ES2PANDA_STATE_BIN_GENERATED) }) }) diff --git a/arkoala-arkts/libarkts/test/es2panda/lambda-param-memoization.test.ts b/arkoala-arkts/libarkts/test/es2panda/lambda-param-memoization.test.ts index 66032ff4e..decf399ba 100644 --- a/arkoala-arkts/libarkts/test/es2panda/lambda-param-memoization.test.ts +++ b/arkoala-arkts/libarkts/test/es2panda/lambda-param-memoization.test.ts @@ -26,7 +26,11 @@ suite(util.getSuiteTitle(__filename), () => { util.getDefaultSetup(sample_in) - let testFunc = arkts.makeView(util.getStatement(0)) as arkts.FunctionDeclaration + let sourceFile = arkts.nodeByPeer(util.AstProvider.provideAst()) + util.assert(arkts.isSourceFile(sourceFile)) + + let testFunc = arkts.nodeByPeer(util.getStatement(0)) + util.assert(arkts.isFunctionDeclaration(testFunc)) let body_statements = [ arkts.factory.createIfStatement( @@ -34,12 +38,14 @@ suite(util.getSuiteTitle(__filename), () => { arkts.factory.createIdentifier("__memo_scope"), arkts.factory.createIdentifier("unchanged") ), - arkts.factory.createReturnStatement( - arkts.factory.createPropertyAccessExpression( - arkts.factory.createIdentifier("__memo_scope"), - arkts.factory.createIdentifier("cached") + arkts.factory.createBlock([ + arkts.factory.createReturnStatement( + arkts.factory.createPropertyAccessExpression( + arkts.factory.createIdentifier("__memo_scope"), + arkts.factory.createIdentifier("cached") + ) ) - ), + ]), undefined ), arkts.factory.createExpressionStatement( @@ -66,6 +72,7 @@ suite(util.getSuiteTitle(__filename), () => { ] testFunc = util.addMemoParamsToFunctionDeclaration(testFunc) + util.assert(arkts.isFunctionDeclaration(testFunc)) const newLambdaParams = [ arkts.factory.createParameterDeclaration( @@ -120,19 +127,27 @@ suite(util.getSuiteTitle(__filename), () => { body_statements ) ) + util.assert(arkts.isFunctionDeclaration(testFunc)) - util.assertEqualsGolden(arkts.dumpJsonNode(testFunc), this) + sourceFile = arkts.factory.updateSourceFile( + sourceFile, + [ + testFunc + ] + ) - const sample_out = - ` - function foo(__memo_context: __memo_context_type, __memo_id: __memo_id_type, content: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)) { - if (__memo_scope.unchanged) { - return __memo_scope.cached; - } - content(__memo_context, ((__memo_id) + ("key_id_main.ts"))); - return __memo_scope.recache(); - } - ` - util.assertEqualsSource(arkts.dumpSrcNode(testFunc), sample_out) + util.assertAstEqualsAfter( + sourceFile, + arkts.ContextState.ES2PANDA_STATE_PARSED, + ` + function foo(__memo_context: __memo_context_type, __memo_id: __memo_id_type, content: ((__memo_context: __memo_context_type, __memo_id: __memo_id_type)=> void)) { + if (__memo_scope.unchanged) { + return __memo_scope.cached; + } + content(__memo_context, ((__memo_id) + ("key_id_main.ts"))); + return __memo_scope.recache(); + } + ` + ) }) }) diff --git a/arkoala-arkts/libarkts/test/es2panda/print-visitor.test.ts b/arkoala-arkts/libarkts/test/es2panda/print-visitor.test.ts index ea271c297..e38afc82c 100644 --- a/arkoala-arkts/libarkts/test/es2panda/print-visitor.test.ts +++ b/arkoala-arkts/libarkts/test/es2panda/print-visitor.test.ts @@ -5,64 +5,64 @@ import { PrintVisitor } from "../../compatible/src/print-visitor" suite(util.getSuiteTitle(__filename), () => { test("sample-1", function() { const source = -` -class Base { - public a: int = 1; - public method() { - this.a = 2; - } -} -class Derived extends Base {} -function foo() { -} -function goo() { -} -function main(): void { - let derived: Base = new Derived(); - derived.method(); -} -` + ` + class Base { + public a: int = 1; + public method() { + this.a = 2; + } + } + class Derived extends Base {} + function foo() { + } + function goo() { + } + function main(): void { + let derived: Base = new Derived(); + derived.method(); + } + ` const expected = -` -SourceFile - ClassDeclaration - Identifier - PropertyDeclaration - MethodDeclaration - Identifier - Block - ExpressionStatement - UnsupportedNode - MethodDeclaration - Identifier - Block - ClassDeclaration - Identifier - MethodDeclaration - Identifier - Block - FunctionDeclaration - Identifier - Block - FunctionDeclaration - Identifier - Block - FunctionDeclaration - Identifier - Block - VariableStatement - ExpressionStatement - CallExpression - PropertyAccessExpression - Identifier - Identifier -` + ` + SourceFile (mod: 0) + ClassDeclaration (mod: 5) + Identifier (mod: 0) + PropertyDeclaration (mod: 4) + MethodDeclaration (mod: 4) + Identifier (mod: 0) + Block (mod: 0) + ExpressionStatement (mod: 0) + UnsupportedNode (mod: 0) + MethodDeclaration (mod: 0) + Identifier (mod: 0) + Block (mod: 0) + ClassDeclaration (mod: 5) + Identifier (mod: 0) + MethodDeclaration (mod: 0) + Identifier (mod: 0) + Block (mod: 0) + FunctionDeclaration (mod: 5) + Identifier (mod: 0) + Block (mod: 0) + FunctionDeclaration (mod: 5) + Identifier (mod: 0) + Block (mod: 0) + FunctionDeclaration (mod: 5) + Identifier (mod: 0) + Block (mod: 0) + VariableStatement (mod: 0) + ExpressionStatement (mod: 0) + CallExpression (mod: 0) + PropertyAccessExpression (mod: 0) + Identifier (mod: 0) + Identifier (mod: 0) + ` util.getDefaultSetup(source) const peer = util.AstProvider.provideAst() - const ast = arkts.makeView(peer) + const ast = arkts.nodeByPeer(peer) const output = (new PrintVisitor()).astToString(ast) - util.assert.equal(output.trim(), expected.trim()) + util.assert.equal(util.alignText(output), util.alignText(expected)) }) }) diff --git a/arkoala-arkts/libarkts/test/es2panda/update-function-declaration.test.ts b/arkoala-arkts/libarkts/test/es2panda/update-function-declaration.test.ts index a6c6d6e8c..7755959f7 100644 --- a/arkoala-arkts/libarkts/test/es2panda/update-function-declaration.test.ts +++ b/arkoala-arkts/libarkts/test/es2panda/update-function-declaration.test.ts @@ -17,29 +17,47 @@ suite(util.getSuiteTitle(__filename), () => { util.getDefaultSetup(sample_in) - let testFunc = arkts.makeView(util.getStatement(0)) as arkts.FunctionDeclaration - const oldParams = testFunc.parameters - const newParamTypeAnnotation = arkts.factory.createKeywordTypeNode(arkts.SyntaxKind.StringKeyword) - const newParam = arkts.factory.createParameterDeclaration(undefined, undefined, arkts.factory.createIdentifier("y", newParamTypeAnnotation)) - const newParams = [...oldParams, newParam] + let sourceFile = arkts.nodeByPeer(util.AstProvider.provideAst()) + util.assert(arkts.isSourceFile(sourceFile)) + + let testFunc = sourceFile.statements[0] + util.assert(arkts.isFunctionDeclaration(testFunc)) + + const newParam = arkts.factory.createParameterDeclaration( + undefined, + undefined, + arkts.factory.createIdentifier("y"), + undefined, + arkts.factory.createKeywordTypeNode(arkts.SyntaxKind.StringKeyword), + undefined + ) testFunc = arkts.factory.updateFunctionDeclaration( testFunc, undefined, undefined, arkts.factory.createIdentifier("new_test_func"), undefined, - newParams, + [ + ...testFunc.parameters, + newParam + ], undefined, testFunc.body ) + sourceFile = arkts.factory.updateSourceFile( + sourceFile, + [ + testFunc + ] + ) - util.assertEqualsGolden(arkts.dumpJsonNode(testFunc), this) - - const sample_out = - ` - function new_test_func(x: number, y: string) {} - ` - util.assertEqualsSource(arkts.dumpSrcNode(testFunc), sample_out) + util.assertAstEqualsAfter( + sourceFile, + arkts.ContextState.ES2PANDA_STATE_PARSED, + ` + function new_test_func(x: number, y: string) {} + ` + ) }) // adding memo params to signature @@ -57,17 +75,29 @@ suite(util.getSuiteTitle(__filename), () => { util.getDefaultSetup(sample_in) - let testFunc = arkts.makeView(util.getStatement(0)) as arkts.FunctionDeclaration + let sourceFile = arkts.nodeByPeer(util.AstProvider.provideAst()) + util.assert(arkts.isSourceFile(sourceFile)) + + let testFunc = arkts.nodeByPeer(util.getStatement(0)) + util.assert(arkts.isFunctionDeclaration(testFunc)) testFunc = util.addMemoParamsToFunctionDeclaration(testFunc) + util.assert(arkts.isFunctionDeclaration(testFunc)) - util.assertEqualsGolden(arkts.dumpJsonNode(testFunc), this) + sourceFile = arkts.factory.updateSourceFile( + sourceFile, + [ + testFunc + ] + ) - const sample_out = - ` - function foo(__memo_context: __memo_context_type, __memo_id: __memo_id_type, x: number) {} - ` - util.assertEqualsSource(arkts.dumpSrcNode(testFunc), sample_out) + util.assertAstEqualsAfter( + sourceFile, + arkts.ContextState.ES2PANDA_STATE_PARSED, + ` + function foo(__memo_context: __memo_context_type, __memo_id: __memo_id_type, x: number) {} + ` + ) }) // adding identifier x @@ -85,7 +115,11 @@ suite(util.getSuiteTitle(__filename), () => { util.getDefaultSetup(sample_in) - let testFunc = arkts.makeView(util.getStatement(0)) as arkts.FunctionDeclaration + let sourceFile = arkts.nodeByPeer(util.AstProvider.provideAst()) + util.assert(arkts.isSourceFile(sourceFile)) + + let testFunc = arkts.nodeByPeer(util.getStatement(0)) + util.assert(arkts.isFunctionDeclaration(testFunc)) let body_statements = [ ...testFunc.body.statements, @@ -105,16 +139,24 @@ suite(util.getSuiteTitle(__filename), () => { body_statements ) ) + util.assert(arkts.isFunctionDeclaration(testFunc)) - util.assertEqualsGolden(arkts.dumpJsonNode(testFunc), this) + sourceFile = arkts.factory.updateSourceFile( + sourceFile, + [ + testFunc + ] + ) - const sample_out = - ` - function foo() { - x; - } - ` - util.assertEqualsSource(arkts.dumpSrcNode(testFunc), sample_out) + util.assertAstEqualsAfter( + sourceFile, + arkts.ContextState.ES2PANDA_STATE_PARSED, + ` + function foo() { + x; + } + ` + ) }) // adding __memo_scope.recache @@ -132,7 +174,11 @@ suite(util.getSuiteTitle(__filename), () => { util.getDefaultSetup(sample_in) - let testFunc = arkts.makeView(util.getStatement(0)) as arkts.FunctionDeclaration + let sourceFile = arkts.nodeByPeer(util.AstProvider.provideAst()) + util.assert(arkts.isSourceFile(sourceFile)) + + let testFunc = arkts.nodeByPeer(util.getStatement(0)) + util.assert(arkts.isFunctionDeclaration(testFunc)) let body_statements = [ ...testFunc.body.statements, @@ -157,16 +203,24 @@ suite(util.getSuiteTitle(__filename), () => { body_statements ) ) + util.assert(arkts.isFunctionDeclaration(testFunc)) - util.assertEqualsGolden(arkts.dumpJsonNode(testFunc), this) + sourceFile = arkts.factory.updateSourceFile( + sourceFile, + [ + testFunc + ] + ) - const sample_out = - ` - function foo() { - __memo_scope.recache; - } - ` - util.assertEqualsSource(arkts.dumpSrcNode(testFunc), sample_out) + util.assertAstEqualsAfter( + sourceFile, + arkts.ContextState.ES2PANDA_STATE_PARSED, + ` + function foo() { + __memo_scope.recache; + } + ` + ) }) // body memo rewrite (adding return statement) @@ -187,7 +241,11 @@ suite(util.getSuiteTitle(__filename), () => { util.getDefaultSetup(sample_in) - let testFunc = arkts.makeView(util.getStatement(0)) as arkts.FunctionDeclaration + let sourceFile = arkts.nodeByPeer(util.AstProvider.provideAst()) + util.assert(arkts.isSourceFile(sourceFile)) + + let testFunc = arkts.nodeByPeer(util.getStatement(0)) + util.assert(arkts.isFunctionDeclaration(testFunc)) let body_statements = [ ...testFunc.body.statements, @@ -213,17 +271,25 @@ suite(util.getSuiteTitle(__filename), () => { testFunc.body, body_statements ) - ) as arkts.FunctionDeclaration + ) + util.assert(arkts.isFunctionDeclaration(testFunc)) - util.assertEqualsGolden(arkts.dumpJsonNode(testFunc), this) + sourceFile = arkts.factory.updateSourceFile( + sourceFile, + [ + testFunc + ] + ) - const sample_out = - ` - function foo() { - return __memo_scope.recache(); - } - ` - util.assertEqualsSource(arkts.dumpSrcNode(testFunc), sample_out) + util.assertAstEqualsAfter( + sourceFile, + arkts.ContextState.ES2PANDA_STATE_PARSED, + ` + function foo() { + return __memo_scope.recache(); + } + ` + ) }) // body memo rewrite (adding if statement) @@ -244,7 +310,11 @@ suite(util.getSuiteTitle(__filename), () => { util.getDefaultSetup(sample_in) - let testFunc = arkts.makeView(util.getStatement(0)) as arkts.FunctionDeclaration + let sourceFile = arkts.nodeByPeer(util.AstProvider.provideAst()) + util.assert(arkts.isSourceFile(sourceFile)) + + let testFunc = arkts.nodeByPeer(util.getStatement(0)) + util.assert(arkts.isFunctionDeclaration(testFunc)) let body_statements = [ arkts.factory.createIfStatement( @@ -252,12 +322,14 @@ suite(util.getSuiteTitle(__filename), () => { arkts.factory.createIdentifier("__memo_scope"), arkts.factory.createIdentifier("unchanged") ), - arkts.factory.createReturnStatement( - arkts.factory.createPropertyAccessExpression( - arkts.factory.createIdentifier("__memo_scope"), - arkts.factory.createIdentifier("cached") + arkts.factory.createBlock([ + arkts.factory.createReturnStatement( + arkts.factory.createPropertyAccessExpression( + arkts.factory.createIdentifier("__memo_scope"), + arkts.factory.createIdentifier("cached") + ) ) - ), + ]), undefined ), ...testFunc.body.statements @@ -276,18 +348,26 @@ suite(util.getSuiteTitle(__filename), () => { body_statements ) ) + util.assert(arkts.isFunctionDeclaration(testFunc)) - util.assertEqualsGolden(arkts.dumpJsonNode(testFunc), this) + sourceFile = arkts.factory.updateSourceFile( + sourceFile, + [ + testFunc + ] + ) - const sample_out = - ` - function foo() { - if (__memo_scope.unchanged) { - return __memo_scope.cached; + util.assertAstEqualsAfter( + sourceFile, + arkts.ContextState.ES2PANDA_STATE_PARSED, + ` + function foo() { + if (__memo_scope.unchanged) { + return __memo_scope.cached; + } } - } - ` - util.assertEqualsSource(arkts.dumpSrcNode(testFunc), sample_out) + ` + ) }) // body memo rewrite @@ -308,7 +388,11 @@ suite(util.getSuiteTitle(__filename), () => { util.getDefaultSetup(sample_in) - let testFunc = arkts.makeView(util.getStatement(0)) as arkts.FunctionDeclaration + let sourceFile = arkts.nodeByPeer(util.AstProvider.provideAst()) + util.assert(arkts.isSourceFile(sourceFile)) + + let testFunc = arkts.nodeByPeer(util.getStatement(0)) + util.assert(arkts.isFunctionDeclaration(testFunc)) let body_statements = [ arkts.factory.createIfStatement( @@ -316,12 +400,14 @@ suite(util.getSuiteTitle(__filename), () => { arkts.factory.createIdentifier("__memo_scope"), arkts.factory.createIdentifier("unchanged") ), - arkts.factory.createReturnStatement( - arkts.factory.createPropertyAccessExpression( - arkts.factory.createIdentifier("__memo_scope"), - arkts.factory.createIdentifier("cached") + arkts.factory.createBlock([ + arkts.factory.createReturnStatement( + arkts.factory.createPropertyAccessExpression( + arkts.factory.createIdentifier("__memo_scope"), + arkts.factory.createIdentifier("cached") + ) ) - ), + ]), undefined ), arkts.factory.createExpressionStatement( @@ -349,6 +435,7 @@ suite(util.getSuiteTitle(__filename), () => { ] testFunc = util.addMemoParamsToFunctionDeclaration(testFunc) + util.assert(arkts.isFunctionDeclaration(testFunc)) testFunc = arkts.factory.updateFunctionDeclaration( testFunc, @@ -362,20 +449,28 @@ suite(util.getSuiteTitle(__filename), () => { testFunc.body, body_statements ) - ) as arkts.FunctionDeclaration + ) + util.assert(arkts.isFunctionDeclaration(testFunc)) - util.assertEqualsGolden(arkts.dumpJsonNode(testFunc), this) + sourceFile = arkts.factory.updateSourceFile( + sourceFile, + [ + testFunc + ] + ) - const sample_out = - ` - function foo(__memo_context: __memo_context_type, __memo_id: __memo_id_type) { - if (__memo_scope.unchanged) { - return __memo_scope.cached; + util.assertAstEqualsAfter( + sourceFile, + arkts.ContextState.ES2PANDA_STATE_PARSED, + ` + function foo(__memo_context: __memo_context_type, __memo_id: __memo_id_type) { + if (__memo_scope.unchanged) { + return __memo_scope.cached; + } + content(__memo_context, ((__memo_id) + ("key_id_main.ts"))); + return __memo_scope.recache(); } - content(__memo_context, ((__memo_id) + ("key_id_main.ts"))); - return __memo_scope.recache(); - } - ` - util.assertEqualsSource(arkts.dumpSrcNode(testFunc), sample_out) + ` + ) }) }) diff --git a/arkoala-arkts/libarkts/test/golden/builder-lambda-rewrite_adding-body-to-lambda-param.test.ts_dump b/arkoala-arkts/libarkts/test/golden/builder-lambda-rewrite_adding-body-to-lambda-param.test.ts_dump deleted file mode 100644 index e02b4c13d..000000000 --- a/arkoala-arkts/libarkts/test/golden/builder-lambda-rewrite_adding-body-to-lambda-param.test.ts_dump +++ /dev/null @@ -1,93 +0,0 @@ -{ - "type": "CallExpression", - "callee": { - "type": "Identifier", - "name": "_Foo", - "decorators": [] - }, - "arguments": [ - { - "type": "ArrowFunctionExpression", - "function": { - "type": "ScriptFunction", - "id": null, - "generator": false, - "async": false, - "expression": false, - "params": [ - { - "type": "ETSParameterExpression", - "name": { - "type": "Identifier", - "name": "instance", - "typeAnnotation": { - "type": "ETSTypeReference", - "part": { - "type": "ETSTypeReferencePart", - "name": { - "type": "Identifier", - "name": "string", - "decorators": [] - } - } - }, - "decorators": [] - } - } - ], - "body": { - "type": "BlockStatement", - "statements": [ - { - "type": "ExpressionStatement", - "expression": { - "type": "CallExpression", - "callee": { - "type": "MemberExpression", - "object": { - "type": "CallExpression", - "callee": { - "type": "MemberExpression", - "object": { - "type": "Identifier", - "name": "instance", - "decorators": [] - }, - "property": { - "type": "Identifier", - "name": "bar", - "decorators": [] - }, - "computed": false, - "optional": false - }, - "arguments": [], - "optional": false - }, - "property": { - "type": "Identifier", - "name": "qux", - "decorators": [] - }, - "computed": false, - "optional": false - }, - "arguments": [], - "optional": false - } - } - ] - } - } - }, - { - "type": "StringLiteral", - "value": "label1" - }, - { - "type": "StringLiteral", - "value": "label2" - } - ], - "optional": false -} \ No newline at end of file diff --git a/arkoala-arkts/libarkts/test/golden/builder-lambda-rewrite_adding-lambda-param-to-signature.test.ts_dump b/arkoala-arkts/libarkts/test/golden/builder-lambda-rewrite_adding-lambda-param-to-signature.test.ts_dump deleted file mode 100644 index d7e34adea..000000000 --- a/arkoala-arkts/libarkts/test/golden/builder-lambda-rewrite_adding-lambda-param-to-signature.test.ts_dump +++ /dev/null @@ -1,50 +0,0 @@ -{ - "type": "CallExpression", - "callee": { - "type": "Identifier", - "name": "_Foo", - "decorators": [] - }, - "arguments": [ - { - "type": "ArrowFunctionExpression", - "function": { - "type": "ScriptFunction", - "id": null, - "generator": false, - "async": false, - "expression": false, - "params": [ - { - "type": "ETSParameterExpression", - "name": { - "type": "Identifier", - "name": "instance", - "typeAnnotation": { - "type": "ETSTypeReference", - "part": { - "type": "ETSTypeReferencePart", - "name": { - "type": "Identifier", - "name": "string", - "decorators": [] - } - } - }, - "decorators": [] - } - } - ], - "body": { - "type": "BlockStatement", - "statements": [] - } - } - }, - { - "type": "StringLiteral", - "value": "label" - } - ], - "optional": false -} \ No newline at end of file diff --git a/arkoala-arkts/libarkts/test/golden/builder-lambda-rewrite_builder-lambda-transformer-sample-1.test.ts_dump b/arkoala-arkts/libarkts/test/golden/builder-lambda-rewrite_builder-lambda-transformer-sample-1.test.ts_dump deleted file mode 100644 index bb25e742d..000000000 --- a/arkoala-arkts/libarkts/test/golden/builder-lambda-rewrite_builder-lambda-transformer-sample-1.test.ts_dump +++ /dev/null @@ -1,67 +0,0 @@ -{ - "type": "Program", - "statements": [ - { - "type": "ExpressionStatement", - "expression": { - "type": "CallExpression", - "callee": { - "type": "Identifier", - "name": "foo", - "decorators": [] - }, - "arguments": [ - { - "type": "ArrowFunctionExpression", - "function": { - "type": "ScriptFunction", - "id": null, - "generator": false, - "async": false, - "expression": false, - "params": [ - { - "type": "ETSParameterExpression", - "name": { - "type": "Identifier", - "name": "instance", - "typeAnnotation": { - "type": "ETSTypeReference", - "part": { - "type": "ETSTypeReferencePart", - "name": { - "type": "Identifier", - "name": "string", - "decorators": [] - } - } - }, - "decorators": [] - } - } - ], - "body": { - "type": "BlockStatement", - "statements": [ - { - "type": "ReturnStatement", - "argument": { - "type": "Identifier", - "name": "instance", - "decorators": [] - } - } - ] - } - } - }, - { - "type": "StringLiteral", - "value": "label" - } - ], - "optional": false - } - } - ] -} \ No newline at end of file diff --git a/arkoala-arkts/libarkts/test/golden/builder-lambda-rewrite_builder-lambda-transformer-sample-2.test.ts_dump b/arkoala-arkts/libarkts/test/golden/builder-lambda-rewrite_builder-lambda-transformer-sample-2.test.ts_dump deleted file mode 100644 index 74d03b766..000000000 --- a/arkoala-arkts/libarkts/test/golden/builder-lambda-rewrite_builder-lambda-transformer-sample-2.test.ts_dump +++ /dev/null @@ -1,101 +0,0 @@ -{ - "type": "Program", - "statements": [ - { - "type": "ExpressionStatement", - "expression": { - "type": "CallExpression", - "callee": { - "type": "Identifier", - "name": "foo", - "decorators": [] - }, - "arguments": [ - { - "type": "ArrowFunctionExpression", - "function": { - "type": "ScriptFunction", - "id": null, - "generator": false, - "async": false, - "expression": false, - "params": [ - { - "type": "ETSParameterExpression", - "name": { - "type": "Identifier", - "name": "instance", - "typeAnnotation": { - "type": "ETSTypeReference", - "part": { - "type": "ETSTypeReferencePart", - "name": { - "type": "Identifier", - "name": "string", - "decorators": [] - } - } - }, - "decorators": [] - } - } - ], - "body": { - "type": "BlockStatement", - "statements": [ - { - "type": "ReturnStatement", - "argument": { - "type": "CallExpression", - "callee": { - "type": "MemberExpression", - "object": { - "type": "CallExpression", - "callee": { - "type": "MemberExpression", - "object": { - "type": "Identifier", - "name": "instance", - "decorators": [] - }, - "property": { - "type": "Identifier", - "name": "bar", - "decorators": [] - }, - "computed": false, - "optional": false - }, - "arguments": [], - "optional": false - }, - "property": { - "type": "Identifier", - "name": "qux", - "decorators": [] - }, - "computed": false, - "optional": false - }, - "arguments": [], - "optional": false - } - } - ] - } - } - }, - { - "type": "StringLiteral", - "value": "label1" - }, - { - "type": "StringLiteral", - "value": "label2" - } - ], - "optional": false - } - } - ] -} \ No newline at end of file diff --git a/arkoala-arkts/libarkts/test/golden/builder-lambda-rewrite_builder-lambda-transformer-sample-3.test.ts_dump b/arkoala-arkts/libarkts/test/golden/builder-lambda-rewrite_builder-lambda-transformer-sample-3.test.ts_dump deleted file mode 100644 index b5b55ac2f..000000000 --- a/arkoala-arkts/libarkts/test/golden/builder-lambda-rewrite_builder-lambda-transformer-sample-3.test.ts_dump +++ /dev/null @@ -1,221 +0,0 @@ -{ - "type": "Program", - "statements": [ - { - "type": "FunctionDeclaration", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "Foo", - "decorators": [] - }, - "generator": false, - "async": false, - "expression": false, - "params": [ - { - "type": "ETSParameterExpression", - "name": { - "type": "Identifier", - "name": "builder", - "typeAnnotation": { - "type": "ETSFunctionType", - "params": [ - { - "type": "ETSParameterExpression", - "name": { - "type": "Identifier", - "name": "instance", - "typeAnnotation": { - "type": "ETSTypeReference", - "part": { - "type": "ETSTypeReferencePart", - "name": { - "type": "Identifier", - "name": "string", - "decorators": [] - } - } - }, - "decorators": [] - } - } - ], - "returnType": { - "type": "ETSTypeReference", - "part": { - "type": "ETSTypeReferencePart", - "name": { - "type": "Identifier", - "name": "string", - "decorators": [] - } - } - } - }, - "decorators": [] - } - }, - { - "type": "ETSParameterExpression", - "name": { - "type": "Identifier", - "name": "arg1", - "typeAnnotation": { - "type": "ETSTypeReference", - "part": { - "type": "ETSTypeReferencePart", - "name": { - "type": "Identifier", - "name": "string", - "decorators": [] - } - } - }, - "decorators": [] - } - } - ], - "returnType": { - "type": "ETSPrimitiveType" - }, - "body": { - "type": "BlockStatement", - "statements": [ - { - "type": "ExpressionStatement", - "expression": { - "type": "CallExpression", - "callee": { - "type": "MemberExpression", - "object": { - "type": "Identifier", - "name": "console", - "decorators": [] - }, - "property": { - "type": "Identifier", - "name": "log", - "decorators": [] - }, - "computed": false, - "optional": false - }, - "arguments": [ - { - "type": "BinaryExpression", - "operator": "+", - "left": { - "type": "Identifier", - "name": "arg1", - "decorators": [] - }, - "right": { - "type": "CallExpression", - "callee": { - "type": "Identifier", - "name": "builder", - "decorators": [] - }, - "arguments": [ - { - "type": "StringLiteral", - "value": "ABC" - } - ], - "optional": false - } - } - ], - "optional": false - } - } - ] - } - } - }, - { - "type": "ExpressionStatement", - "expression": { - "type": "CallExpression", - "callee": { - "type": "Identifier", - "name": "Foo", - "decorators": [] - }, - "arguments": [ - { - "type": "ArrowFunctionExpression", - "function": { - "type": "ScriptFunction", - "id": null, - "generator": false, - "async": false, - "expression": false, - "params": [ - { - "type": "ETSParameterExpression", - "name": { - "type": "Identifier", - "name": "instance", - "typeAnnotation": { - "type": "ETSTypeReference", - "part": { - "type": "ETSTypeReferencePart", - "name": { - "type": "Identifier", - "name": "string", - "decorators": [] - } - } - }, - "decorators": [] - } - } - ], - "body": { - "type": "BlockStatement", - "statements": [ - { - "type": "ReturnStatement", - "argument": { - "type": "CallExpression", - "callee": { - "type": "MemberExpression", - "object": { - "type": "Identifier", - "name": "instance", - "decorators": [] - }, - "property": { - "type": "Identifier", - "name": "charAt", - "decorators": [] - }, - "computed": false, - "optional": false - }, - "arguments": [ - { - "type": "NumberLiteral", - "value": 1 - } - ], - "optional": false - } - } - ] - } - } - }, - { - "type": "StringLiteral", - "value": "> second_char_of_ABC: " - } - ], - "optional": false - } - } - ] -} \ No newline at end of file diff --git a/arkoala-arkts/libarkts/test/golden/create-function-declaration_empty-function-with-param.test.ts_dump b/arkoala-arkts/libarkts/test/golden/create-function-declaration_empty-function-with-param.test.ts_dump deleted file mode 100644 index 9e3114788..000000000 --- a/arkoala-arkts/libarkts/test/golden/create-function-declaration_empty-function-with-param.test.ts_dump +++ /dev/null @@ -1,36 +0,0 @@ -{ - "type": "Program", - "statements": [ - { - "type": "FunctionDeclaration", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "test_func", - "decorators": [] - }, - "generator": false, - "async": false, - "expression": false, - "params": [ - { - "type": "ETSParameterExpression", - "name": { - "type": "Identifier", - "name": "x", - "typeAnnotation": { - "type": "ETSPrimitiveType" - }, - "decorators": [] - } - } - ], - "body": { - "type": "BlockStatement", - "statements": [] - } - } - } - ] -} \ No newline at end of file diff --git a/arkoala-arkts/libarkts/test/golden/create-function-declaration_empty-function-with-string-param.test.ts_dump b/arkoala-arkts/libarkts/test/golden/create-function-declaration_empty-function-with-string-param.test.ts_dump deleted file mode 100644 index 613b7e83f..000000000 --- a/arkoala-arkts/libarkts/test/golden/create-function-declaration_empty-function-with-string-param.test.ts_dump +++ /dev/null @@ -1,44 +0,0 @@ -{ - "type": "Program", - "statements": [ - { - "type": "FunctionDeclaration", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "test_func", - "decorators": [] - }, - "generator": false, - "async": false, - "expression": false, - "params": [ - { - "type": "ETSParameterExpression", - "name": { - "type": "Identifier", - "name": "x", - "typeAnnotation": { - "type": "ETSTypeReference", - "part": { - "type": "ETSTypeReferencePart", - "name": { - "type": "Identifier", - "name": "string", - "decorators": [] - } - } - }, - "decorators": [] - } - } - ], - "body": { - "type": "BlockStatement", - "statements": [] - } - } - } - ] -} \ No newline at end of file diff --git a/arkoala-arkts/libarkts/test/golden/create-function-declaration_empty-function.test.ts_dump b/arkoala-arkts/libarkts/test/golden/create-function-declaration_empty-function.test.ts_dump deleted file mode 100644 index f380e3b1b..000000000 --- a/arkoala-arkts/libarkts/test/golden/create-function-declaration_empty-function.test.ts_dump +++ /dev/null @@ -1,19 +0,0 @@ -{ - "type": "FunctionDeclaration", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "test_func", - "decorators": [] - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [] - } - } -} \ No newline at end of file diff --git a/arkoala-arkts/libarkts/test/golden/lambda-param-memoization_memo-function-with-lambda-memo-param.test.ts_dump b/arkoala-arkts/libarkts/test/golden/lambda-param-memoization_memo-function-with-lambda-memo-param.test.ts_dump deleted file mode 100644 index 332d3c89b..000000000 --- a/arkoala-arkts/libarkts/test/golden/lambda-param-memoization_memo-function-with-lambda-memo-param.test.ts_dump +++ /dev/null @@ -1,205 +0,0 @@ -{ - "type": "FunctionDeclaration", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "foo", - "decorators": [] - }, - "generator": false, - "async": false, - "expression": false, - "params": [ - { - "type": "ETSParameterExpression", - "name": { - "type": "Identifier", - "name": "__memo_context", - "typeAnnotation": { - "type": "ETSTypeReference", - "part": { - "type": "ETSTypeReferencePart", - "name": { - "type": "Identifier", - "name": "__memo_context_type", - "decorators": [] - } - } - }, - "decorators": [] - } - }, - { - "type": "ETSParameterExpression", - "name": { - "type": "Identifier", - "name": "__memo_id", - "typeAnnotation": { - "type": "ETSTypeReference", - "part": { - "type": "ETSTypeReferencePart", - "name": { - "type": "Identifier", - "name": "__memo_id_type", - "decorators": [] - } - } - }, - "decorators": [] - } - }, - { - "type": "ETSParameterExpression", - "name": { - "type": "Identifier", - "name": "content", - "typeAnnotation": { - "type": "ETSFunctionType", - "params": [ - { - "type": "ETSParameterExpression", - "name": { - "type": "Identifier", - "name": "__memo_context", - "typeAnnotation": { - "type": "ETSTypeReference", - "part": { - "type": "ETSTypeReferencePart", - "name": { - "type": "Identifier", - "name": "__memo_context_type", - "decorators": [] - } - } - }, - "decorators": [] - } - }, - { - "type": "ETSParameterExpression", - "name": { - "type": "Identifier", - "name": "__memo_id", - "typeAnnotation": { - "type": "ETSTypeReference", - "part": { - "type": "ETSTypeReferencePart", - "name": { - "type": "Identifier", - "name": "__memo_id_type", - "decorators": [] - } - } - }, - "decorators": [] - } - } - ], - "returnType": { - "type": "ETSPrimitiveType" - } - }, - "decorators": [] - } - } - ], - "body": { - "type": "BlockStatement", - "statements": [ - { - "type": "IfStatement", - "test": { - "type": "MemberExpression", - "object": { - "type": "Identifier", - "name": "__memo_scope", - "decorators": [] - }, - "property": { - "type": "Identifier", - "name": "unchanged", - "decorators": [] - }, - "computed": false, - "optional": false - }, - "consequent": { - "type": "ReturnStatement", - "argument": { - "type": "MemberExpression", - "object": { - "type": "Identifier", - "name": "__memo_scope", - "decorators": [] - }, - "property": { - "type": "Identifier", - "name": "cached", - "decorators": [] - }, - "computed": false, - "optional": false - } - }, - "alternate": null - }, - { - "type": "ExpressionStatement", - "expression": { - "type": "CallExpression", - "callee": { - "type": "Identifier", - "name": "content", - "decorators": [] - }, - "arguments": [ - { - "type": "Identifier", - "name": "__memo_context", - "decorators": [] - }, - { - "type": "BinaryExpression", - "operator": "+", - "left": { - "type": "Identifier", - "name": "__memo_id", - "decorators": [] - }, - "right": { - "type": "StringLiteral", - "value": "key_id_main.ts" - } - } - ], - "optional": false - } - }, - { - "type": "ReturnStatement", - "argument": { - "type": "CallExpression", - "callee": { - "type": "MemberExpression", - "object": { - "type": "Identifier", - "name": "__memo_scope", - "decorators": [] - }, - "property": { - "type": "Identifier", - "name": "recache", - "decorators": [] - }, - "computed": false, - "optional": false - }, - "arguments": [], - "optional": false - } - } - ] - } - } -} \ No newline at end of file diff --git a/arkoala-arkts/libarkts/test/golden/update-function-declaration_add-identifier-to-function-body.test.ts_dump b/arkoala-arkts/libarkts/test/golden/update-function-declaration_add-identifier-to-function-body.test.ts_dump deleted file mode 100644 index 44d4b6777..000000000 --- a/arkoala-arkts/libarkts/test/golden/update-function-declaration_add-identifier-to-function-body.test.ts_dump +++ /dev/null @@ -1,28 +0,0 @@ -{ - "type": "FunctionDeclaration", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "foo", - "decorators": [] - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [ - { - "type": "ExpressionStatement", - "expression": { - "type": "Identifier", - "name": "x", - "decorators": [] - } - } - ] - } - } -} \ No newline at end of file diff --git a/arkoala-arkts/libarkts/test/golden/update-function-declaration_add-if-statement-to-function-body.test.ts_dump b/arkoala-arkts/libarkts/test/golden/update-function-declaration_add-if-statement-to-function-body.test.ts_dump deleted file mode 100644 index 1a1578cdf..000000000 --- a/arkoala-arkts/libarkts/test/golden/update-function-declaration_add-if-statement-to-function-body.test.ts_dump +++ /dev/null @@ -1,57 +0,0 @@ -{ - "type": "FunctionDeclaration", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "foo", - "decorators": [] - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [ - { - "type": "IfStatement", - "test": { - "type": "MemberExpression", - "object": { - "type": "Identifier", - "name": "__memo_scope", - "decorators": [] - }, - "property": { - "type": "Identifier", - "name": "unchanged", - "decorators": [] - }, - "computed": false, - "optional": false - }, - "consequent": { - "type": "ReturnStatement", - "argument": { - "type": "MemberExpression", - "object": { - "type": "Identifier", - "name": "__memo_scope", - "decorators": [] - }, - "property": { - "type": "Identifier", - "name": "cached", - "decorators": [] - }, - "computed": false, - "optional": false - } - }, - "alternate": null - } - ] - } - } -} \ No newline at end of file diff --git a/arkoala-arkts/libarkts/test/golden/update-function-declaration_add-params-to-memo-function.test.ts_dump b/arkoala-arkts/libarkts/test/golden/update-function-declaration_add-params-to-memo-function.test.ts_dump deleted file mode 100644 index a05e48c8b..000000000 --- a/arkoala-arkts/libarkts/test/golden/update-function-declaration_add-params-to-memo-function.test.ts_dump +++ /dev/null @@ -1,77 +0,0 @@ -{ - "type": "FunctionDeclaration", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "foo", - "decorators": [] - }, - "generator": false, - "async": false, - "expression": false, - "params": [ - { - "type": "ETSParameterExpression", - "name": { - "type": "Identifier", - "name": "__memo_context", - "typeAnnotation": { - "type": "ETSTypeReference", - "part": { - "type": "ETSTypeReferencePart", - "name": { - "type": "Identifier", - "name": "__memo_context_type", - "decorators": [] - } - } - }, - "decorators": [] - } - }, - { - "type": "ETSParameterExpression", - "name": { - "type": "Identifier", - "name": "__memo_id", - "typeAnnotation": { - "type": "ETSTypeReference", - "part": { - "type": "ETSTypeReferencePart", - "name": { - "type": "Identifier", - "name": "__memo_id_type", - "decorators": [] - } - } - }, - "decorators": [] - } - }, - { - "type": "ETSParameterExpression", - "name": { - "type": "Identifier", - "name": "x", - "typeAnnotation": { - "type": "ETSTypeReference", - "part": { - "type": "ETSTypeReferencePart", - "name": { - "type": "Identifier", - "name": "number", - "decorators": [] - } - } - }, - "decorators": [] - } - } - ], - "body": { - "type": "BlockStatement", - "statements": [] - } - } -} \ No newline at end of file diff --git a/arkoala-arkts/libarkts/test/golden/update-function-declaration_add-property-access-expression-to-function-body.test.ts_dump b/arkoala-arkts/libarkts/test/golden/update-function-declaration_add-property-access-expression-to-function-body.test.ts_dump deleted file mode 100644 index f7d17b74f..000000000 --- a/arkoala-arkts/libarkts/test/golden/update-function-declaration_add-property-access-expression-to-function-body.test.ts_dump +++ /dev/null @@ -1,38 +0,0 @@ -{ - "type": "FunctionDeclaration", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "foo", - "decorators": [] - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [ - { - "type": "ExpressionStatement", - "expression": { - "type": "MemberExpression", - "object": { - "type": "Identifier", - "name": "__memo_scope", - "decorators": [] - }, - "property": { - "type": "Identifier", - "name": "recache", - "decorators": [] - }, - "computed": false, - "optional": false - } - } - ] - } - } -} \ No newline at end of file diff --git a/arkoala-arkts/libarkts/test/golden/update-function-declaration_add-return-statement-to-function-body.test.ts_dump b/arkoala-arkts/libarkts/test/golden/update-function-declaration_add-return-statement-to-function-body.test.ts_dump deleted file mode 100644 index 7b5560cff..000000000 --- a/arkoala-arkts/libarkts/test/golden/update-function-declaration_add-return-statement-to-function-body.test.ts_dump +++ /dev/null @@ -1,43 +0,0 @@ -{ - "type": "FunctionDeclaration", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "foo", - "decorators": [] - }, - "generator": false, - "async": false, - "expression": false, - "params": [], - "body": { - "type": "BlockStatement", - "statements": [ - { - "type": "ReturnStatement", - "argument": { - "type": "CallExpression", - "callee": { - "type": "MemberExpression", - "object": { - "type": "Identifier", - "name": "__memo_scope", - "decorators": [] - }, - "property": { - "type": "Identifier", - "name": "recache", - "decorators": [] - }, - "computed": false, - "optional": false - }, - "arguments": [], - "optional": false - } - } - ] - } - } -} \ No newline at end of file diff --git a/arkoala-arkts/libarkts/test/golden/update-function-declaration_function-declaration-memo-rewrite.test.ts_dump b/arkoala-arkts/libarkts/test/golden/update-function-declaration_function-declaration-memo-rewrite.test.ts_dump deleted file mode 100644 index aa97fb990..000000000 --- a/arkoala-arkts/libarkts/test/golden/update-function-declaration_function-declaration-memo-rewrite.test.ts_dump +++ /dev/null @@ -1,151 +0,0 @@ -{ - "type": "FunctionDeclaration", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "foo", - "decorators": [] - }, - "generator": false, - "async": false, - "expression": false, - "params": [ - { - "type": "ETSParameterExpression", - "name": { - "type": "Identifier", - "name": "__memo_context", - "typeAnnotation": { - "type": "ETSTypeReference", - "part": { - "type": "ETSTypeReferencePart", - "name": { - "type": "Identifier", - "name": "__memo_context_type", - "decorators": [] - } - } - }, - "decorators": [] - } - }, - { - "type": "ETSParameterExpression", - "name": { - "type": "Identifier", - "name": "__memo_id", - "typeAnnotation": { - "type": "ETSTypeReference", - "part": { - "type": "ETSTypeReferencePart", - "name": { - "type": "Identifier", - "name": "__memo_id_type", - "decorators": [] - } - } - }, - "decorators": [] - } - } - ], - "body": { - "type": "BlockStatement", - "statements": [ - { - "type": "IfStatement", - "test": { - "type": "MemberExpression", - "object": { - "type": "Identifier", - "name": "__memo_scope", - "decorators": [] - }, - "property": { - "type": "Identifier", - "name": "unchanged", - "decorators": [] - }, - "computed": false, - "optional": false - }, - "consequent": { - "type": "ReturnStatement", - "argument": { - "type": "MemberExpression", - "object": { - "type": "Identifier", - "name": "__memo_scope", - "decorators": [] - }, - "property": { - "type": "Identifier", - "name": "cached", - "decorators": [] - }, - "computed": false, - "optional": false - } - }, - "alternate": null - }, - { - "type": "ExpressionStatement", - "expression": { - "type": "CallExpression", - "callee": { - "type": "Identifier", - "name": "content", - "decorators": [] - }, - "arguments": [ - { - "type": "Identifier", - "name": "__memo_context", - "decorators": [] - }, - { - "type": "BinaryExpression", - "operator": "+", - "left": { - "type": "Identifier", - "name": "__memo_id", - "decorators": [] - }, - "right": { - "type": "StringLiteral", - "value": "key_id_main.ts" - } - } - ], - "optional": false - } - }, - { - "type": "ReturnStatement", - "argument": { - "type": "CallExpression", - "callee": { - "type": "MemberExpression", - "object": { - "type": "Identifier", - "name": "__memo_scope", - "decorators": [] - }, - "property": { - "type": "Identifier", - "name": "recache", - "decorators": [] - }, - "computed": false, - "optional": false - }, - "arguments": [], - "optional": false - } - } - ] - } - } -} \ No newline at end of file diff --git a/arkoala-arkts/libarkts/test/golden/update-function-declaration_update-name-and-add-param-to-function.test.ts_dump b/arkoala-arkts/libarkts/test/golden/update-function-declaration_update-name-and-add-param-to-function.test.ts_dump deleted file mode 100644 index 0c9fba977..000000000 --- a/arkoala-arkts/libarkts/test/golden/update-function-declaration_update-name-and-add-param-to-function.test.ts_dump +++ /dev/null @@ -1,58 +0,0 @@ -{ - "type": "FunctionDeclaration", - "function": { - "type": "ScriptFunction", - "id": { - "type": "Identifier", - "name": "new_test_func", - "decorators": [] - }, - "generator": false, - "async": false, - "expression": false, - "params": [ - { - "type": "ETSParameterExpression", - "name": { - "type": "Identifier", - "name": "x", - "typeAnnotation": { - "type": "ETSTypeReference", - "part": { - "type": "ETSTypeReferencePart", - "name": { - "type": "Identifier", - "name": "number", - "decorators": [] - } - } - }, - "decorators": [] - } - }, - { - "type": "ETSParameterExpression", - "name": { - "type": "Identifier", - "name": "y", - "typeAnnotation": { - "type": "ETSTypeReference", - "part": { - "type": "ETSTypeReferencePart", - "name": { - "type": "Identifier", - "name": "string", - "decorators": [] - } - } - }, - "decorators": [] - } - } - ], - "body": { - "type": "BlockStatement", - "statements": [] - } - } -} \ No newline at end of file diff --git a/arkoala-arkts/libarkts/test/test-util.ts b/arkoala-arkts/libarkts/test/test-util.ts index 65f6d31a4..3c52d11be 100644 --- a/arkoala-arkts/libarkts/test/test-util.ts +++ b/arkoala-arkts/libarkts/test/test-util.ts @@ -14,12 +14,12 @@ */ import * as arkts from "../src/arkts" -import * as fs from "fs" import * as path from "path" import { KNativePointer } from "@koalaui/interop" import { nativeModule } from "../src/NativeModule" import { NativePtrDecoder } from "../src/node/Platform" import { assert } from "chai" +import { PrintVisitor } from "../compatible/src/print-visitor" class DefaultConfig { static readonly configFile = "./arktsconfig.json" @@ -38,14 +38,32 @@ export function getDefaultSetup(source: string): void { export class AstProvider { public static provideAst(): KNativePointer { const program = arkts.contextProgram() - const peer = arkts.programAst(program) - return peer + return arkts.programAst(program).peer } } export function alignText(text: string): string { - // TODO: remove spaces/tabs at the beginning of each line - return text + const lines = text.replace(/\t/gy, ' ').split('\n') + + const shift = + lines + .map((str: string) => str.search(/\S/)) + .reduce( + (prev: number, curr: number) => { + if (prev === -1) { + return curr + } + if (curr === -1) { + return prev + } + return Math.min(prev, curr) + } + ) + return lines.map(str => str.slice((shift === -1) ? 0 : shift)).join('\n').trim() +} + +export function printVisitorOutput(node: arkts.Node): string { + return (new PrintVisitor()).astToString(node) } export function getStatement(index: number): KNativePointer { @@ -57,19 +75,6 @@ export function getSuiteTitle(fileName: string) { return path.basename(fileName).split('.')[0] } -function loadGoldenDump(suiteTitle: string, testTitle: string): string | undefined { - const dirname = __dirname - const dumpFile = `${dirname}/golden/${suiteTitle}_${testTitle}.test.ts_dump` - const dump = fs.readFileSync(dumpFile, { encoding: 'utf8', flag: 'a+' }) - return (dump && dump.includes('\r')) - ? dump.replace(/[\r]/g, '') - : dump -} - -export function assertEqualsGolden(text: string, testCtx: Mocha.Context) { - assert.equal(text, loadGoldenDump(testCtx.test!.parent!.title, testCtx.test!.title)) -} - export function assertEqualsSource(sourceResult: string, sourceExpect: string) { assert.equal( sourceResult.trim().split('\n').map((line: string) => line.trim()).join('\n'), @@ -77,24 +82,56 @@ export function assertEqualsSource(sourceResult: string, sourceExpect: string) { ) } +export function assertAstEqualsAfter(node: arkts.Node, state: arkts.ContextState, source: string) { + const ast = arkts.dumpJsonNode(node) + const src = arkts.dumpSrcNode(node) + const mods = arkts.dumpModifiers(node.peer) + + const _oldContext = arkts.Global.context + arkts.Global.context = arkts.createContextFromString(arkts.Global.config, source, DefaultConfig.sourceFile) + arkts.proceedToState(state) + const peer = AstProvider.provideAst() + arkts.Global.context = _oldContext + + assert.equal(ast, arkts.dumpJson(peer)) + assertEqualsSource(src, arkts.dumpSrcNode(arkts.nodeByPeer(peer))) + assert.equal(mods, arkts.dumpModifiers(peer)) +} + export function dumpFirst() { return arkts.dumpJson(getStatement(0)) } export function addMemoParamsToFunctionDeclaration(func: arkts.FunctionDeclaration): arkts.FunctionDeclaration { - const oldParams = func.parameters - const memoContextAnnotation = arkts.factory.createTypeReferenceNode(arkts.factory.createIdentifier("__memo_context_type")) - const memoContextParam = arkts.factory.createParameterDeclaration(undefined, undefined, arkts.factory.createIdentifier("__memo_context", memoContextAnnotation)) - const memoIdAnnotation = arkts.factory.createTypeReferenceNode(arkts.factory.createIdentifier("__memo_id_type")) - const memoIdParam = arkts.factory.createParameterDeclaration(undefined, undefined, arkts.factory.createIdentifier("__memo_id", memoIdAnnotation)) - const newParams = [memoContextParam, memoIdParam, ...oldParams] return arkts.factory.updateFunctionDeclaration( func, undefined, undefined, - func.name!, + func.name, undefined, - newParams, + [ + arkts.factory.createParameterDeclaration( + undefined, + undefined, + arkts.factory.createIdentifier("__memo_context"), + undefined, + arkts.factory.createTypeReferenceNode( + arkts.factory.createIdentifier("__memo_context_type") + ), + undefined + ), + arkts.factory.createParameterDeclaration( + undefined, + undefined, + arkts.factory.createIdentifier("__memo_id"), + undefined, + arkts.factory.createTypeReferenceNode( + arkts.factory.createIdentifier("__memo_id_type") + ), + undefined + ), + ...func.parameters + ], undefined, func.body ) diff --git a/arkoala/framework/native/src/callbacks.h b/arkoala/framework/native/src/callbacks.h deleted file mode 100644 index d4a47240d..000000000 --- a/arkoala/framework/native/src/callbacks.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2024 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef _ARKOALA_CALLBACKS_H -#define _ARKOALA_CALLBACKS_H - -#include -#include -#include "arkoala_api_generated.h" -#include "callback_kind.h" -#include "SerializerBase.h" - -struct CallbackBuffer { - CallbackKind kind; - uint8_t buffer[60 * 4]; - CallbackResourceHolder resourceHolder; -}; -void enqueueArkoalaCallback(const CallbackBuffer* event); - -#endif \ No newline at end of file -- Gitee