From a014cd2b9b5be9e084e619f346081a1e827a9886 Mon Sep 17 00:00:00 2001 From: zhangrengao Date: Tue, 13 Sep 2022 10:32:30 +0800 Subject: [PATCH 1/7] Add HowToWriteProtoForAssemblyStuff.md Signed-off-by: zhangrengao Change-Id: Iad80fb375ca1a61bd6ee088fe63b95846812691c --- merge_abc/HowToWriteProtoForAssemblyStuff.md | 281 +++++++++++++++++++ 1 file changed, 281 insertions(+) create mode 100644 merge_abc/HowToWriteProtoForAssemblyStuff.md diff --git a/merge_abc/HowToWriteProtoForAssemblyStuff.md b/merge_abc/HowToWriteProtoForAssemblyStuff.md new file mode 100644 index 0000000000..83f76ebe34 --- /dev/null +++ b/merge_abc/HowToWriteProtoForAssemblyStuff.md @@ -0,0 +1,281 @@ +# How To Write Proto For Assembly + +## 消息格式 + +``` +syntax = "proto3" // 指定版本信息 +message Test // message为关键字,作用为定义一种消息类型 +{ + string test = 1; +} +``` + +消息由字段组合而成 +``` +限定修饰符 数据类型 字段名称 = 唯一编号标签值 +``` + +## 限定修饰符说明 + +### required + +required 在发送消息之前必须设置该字段的值。对于接收方,必须能够识别该字段的意思。发送之前没有设置required字段或者无法识别required字段都会引发编解码异常,导致消息被丢弃。 + +``` +syntax = "proto3" +message Test +{ + required string test = 1; +} +``` + +### repeated + +repeated 代表可重复,我们可以理解为数组 + +``` +syntax = "proto3" +message Test +{ + string test = 1; +} + +message TestArr +{ + repeated Test arr = 1; +} +``` + +### optional + +optional 表示是一个可选字段,可选对于发送方,在发送消息时,可以有选择性的设置或者不设置该字段的值。如果无法识别,则忽略该字段,消息中的其它字段正常处理。 + +## 数据类型 + +| proto类型 | C++类型 | 备注 | +|:-----------|:---------------|:------------| +|double |double | 64位浮点数 +|float |float | 32位浮点数 +|int32 |int32 | 32位整数 +|int64 |int64 | 64位整数 +|uint32 |uint32 | 32位无符号整数 +|uint64 |uint64 | 64位无符号整数 +|sint32 |int32 | 32位整数,处理负数效率比int32更高 +|sint32 |sint64 | 64位整数,处理负数效率比int64更高 +|fixed32 | uint32 | 总是4个字节。如果数值总是比总是比228大的话,这个类型会比uint32高效。 +|fixed64 | uint64 | 总是8个字节。如果数值总是比总是比256大的话,这个类型会比uint64高效。 +|sfixed32 | int32 | 总是4个字节 +|sfixed64 | int64 | 总是8个字节 +|bool | bool | 布尔类型 +|string | string | 一个字符串必须是UTF-8编码或者7-bit ASCII编码的文本 +|bytes | string | 处理多字节的语言字符、如中文 +|enum | enum | 枚举(proto2 从1开始,proto3从0开始) +|message | object of class | 自定义的消息类型 + + +## 字段名称 + +protobuf建议以下划线命名而非驼峰式 + +## 唯一的编号标签 + +代表每个字段的一个唯一的编号标签,在同一个消息里不可以重复。这些编号标签用与在消息二进制格式中标识你的字段,并且消息一旦定义就不能更改。需要说明的是标签在1到15范围的采用一个字节进行编码,所以通常将标签1到15用于频繁发生的消息字段。编号标签大小的范围是1到229。此外不能使用protobuf系统预留的编号标签(19000 ~19999) + +## import + +protobuf 接口文件可以像C语言的h文件一个,分离为多个,在需要的时候通过 import导入需要对文件。其行为和C语言的#include或者java的import的行为大致相同。 + +## enum + +``` +syntax = "proto3" // 指定版本信息 +enum COLOR +{ + RED = 0; + BLUE = 1; + YELLOW = 2; +} + +message Test // message为关键字,作用为定义一种消息类型 +{ + string test = 1; + COLOR type = 2; +} +``` + +## package + +``` +syntax = "proto3" // 指定版本信息 + +package tutorial; + +message Test // message为关键字,作用为定义一种消息类型 +{ + string test = 1; +} +``` + +## oneof + +message 包含许多可选字段,并且最多只能同时设置其中一个字段,则可以使用 oneof 功能强制执行此行为并节省内存 + +# Assembly对应Proto + +## class\struct + +protobuf中将类型信息结构化处理,通过自定义消息message结构对C++中class或struct进行解析处理 + +C++ +``` +struct Ins { + size_t line_number = 0; + uint32_t column_number = 0; + std::string whole_line = ""; // TODO(mbolshov): redundant given file and line_number + size_t bound_left = 0; + size_t bound_right = 0; +} +``` + +proto +``` +message DebuginfoIns { + uint64 lineNumber = 1; + uint32 columnNumber = 2; + bytes wholeLine = 3; + uint64 boundLeft = 4; + uint64 boundRight = 5; +} +``` + + +## enum + +protobuf中存在enum类型,proto2 从1开始,proto3从0开始 + +对于Assembly中的转换,优化序列化速度,通过uint32位直接进行转换: + +C++ +``` +class Value { +public: + enum class Type { + U1, + I8, + U8, + I16, + U16, + I32, + U32, + I64, + U64, + F32, + F64, + STRING, + STRING_NULLPTR, + RECORD, + METHOD, + ENUM, + ANNOTATION, + ARRAY, + VOID, + METHOD_HANDLE, + UNKNOWN + }; + ... +} + +``` + + +proto +``` +message Value { + uint32 type = 1; +} +``` +## inheritance + +protobuf中message无继承信息,开发者自己实现继承信息 + +C++ +``` +class Value { +... +} + +class ArrayValue : public Value { +... +} +``` + +proto +``` + +message Value { + uint32 type = 1; +} + +message ArrayValue { + Value father = 1; +} + +``` + +## std::variant + +通过oneof关键字实现std::variant + +C++ +``` +std::variant value_; +``` + +proto +``` +oneof value { + uint64 valueU64 = 2; + float valueFloat = 3; + double valueDouble = 4; + bytes valueStr = 5; + Type valueType = 6; + AnnotationData valueAnno = 7; +} +``` + +## unique_ptr + +查看源码中的变量关系,通过oneof实现智能指针 + +C++ +``` +class Value { +} + +class ArrayValue { +} + +class ScalarValue { +} + +std::unique_ptr value_; +``` + +proto +``` +message Value { +} + +message ScalarValue { + Value father = 1; +} + +message ArrayValue { + Value father = 1; +} + +oneof value { + ScalarValue scalar = 2; + ArrayValue array = 3; +} +``` -- Gitee From fc1dd5d5c5a18846267c80da40b699c8beca4e5f Mon Sep 17 00:00:00 2001 From: gavin1012_hw Date: Tue, 6 Sep 2022 10:58:17 +0800 Subject: [PATCH 2/7] Support serializing proto bin && record-name && record-name testing in ts2abc Signed-off-by: gavin1012_hw Change-Id: I63bab0c084d4b1bbd22dd8cb5f39dc70165266ce --- es2panda/aot/options.cpp | 3 +- merge_abc/src/assemblyFileLocationProto.cpp | 12 ++-- merge_abc/src/assemblyFileLocationProto.h | 3 +- merge_abc/src/assemblyFunctionProto.cpp | 2 +- merge_abc/src/assemblyLabelProto.cpp | 2 +- merge_abc/src/assemblyRecordProto.cpp | 2 +- test262/run_sunspider.py | 39 +++++++++--- ts2panda/src/cmdOptions.ts | 13 ++++ ts2panda/src/compilerDriver.ts | 17 +++--- ts2panda/src/index.ts | 32 +++++++--- ts2panda/src/pandasm.ts | 16 +---- ts2panda/src/ts2panda.ts | 20 ++++++- ts2panda/tests/builtIns.test.ts | 2 +- ts2panda/tests/commonjs.test.ts | 6 +- ts2panda/tests/esmodule.test.ts | 2 +- ts2panda/tests/expression/arguments.test.ts | 4 +- ts2panda/tests/expression/commalist.test.ts | 2 +- .../expression/functionExpression.test.ts | 38 ++++++------ ts2panda/tests/expression/thisKeyWord.test.ts | 2 +- ts2panda/tests/hoist.test.ts | 18 +++--- ts2panda/tests/lexenv.test.ts | 30 +++++----- .../statements/functionDeclaration.test.ts | 19 +++--- .../statements/variableDeclaration.test.ts | 8 +-- ts2panda/tests/types/array.test.ts | 12 ++-- ts2panda/tests/types/class.test.ts | 16 ++--- ts2panda/tests/types/function.test.ts | 10 ++-- ts2panda/tests/types/object.test.ts | 4 +- ts2panda/tests/types/primitives.test.ts | 30 +++++----- ts2panda/tests/types/union.test.ts | 8 +-- ts2panda/tests/utils/base.ts | 10 ++-- ts2panda/ts2abc/ts2abc.cpp | 60 +++++++------------ ts2panda/ts2abc/ts2abc_options.h | 2 +- 32 files changed, 243 insertions(+), 201 deletions(-) diff --git a/es2panda/aot/options.cpp b/es2panda/aot/options.cpp index d581dab53a..5d189f5203 100644 --- a/es2panda/aot/options.cpp +++ b/es2panda/aot/options.cpp @@ -149,7 +149,8 @@ bool Options::Parse(int argc, const char **argv) panda::PandArg base64Output("base64Output", false, "output panda file content as base64 to std out"); panda::PandArg sourceFile("source-file", "", "specify the file path info recorded in generated abc"); - panda::PandArg outputProto("outputProto", "", "compiler proto serialize binary output (.proto)"); + panda::PandArg outputProto("outputProto", "", + "specify the output name for serializd protobuf file (.protoBin)"); panda::PandArg opCacheFile("cache-file", "", "cache file for incremental compile"); panda::PandArg opNpmModuleEntryList("npm-module-entry-list", "", "entry list file for module compile"); panda::PandArg opMergeAbc("merge-abc", false, "Compile as merge abc"); diff --git a/merge_abc/src/assemblyFileLocationProto.cpp b/merge_abc/src/assemblyFileLocationProto.cpp index 9f4a0f23bd..e3ef08e976 100644 --- a/merge_abc/src/assemblyFileLocationProto.cpp +++ b/merge_abc/src/assemblyFileLocationProto.cpp @@ -21,14 +21,16 @@ void FileLocation::Serialize(const panda::pandasm::FileLocation &location, proto protoLocation.set_wholeline(location.whole_line); protoLocation.set_boundleft(location.bound_left); protoLocation.set_boundright(location.bound_right); + protoLocation.set_linenumber(location.line_number); protoLocation.set_isdefined(location.is_defined); } -void FileLocation::Deserialize(const protoPanda::FileLocation &protoLocation, panda::pandasm::FileLocation &location) +void FileLocation::Deserialize(const protoPanda::FileLocation &protoLocation, + std::optional &location) { - location.whole_line = protoLocation.wholeline(); - location.bound_left = protoLocation.boundleft(); - location.bound_right = protoLocation.boundright(); - location.is_defined = protoLocation.isdefined(); + std::string wholeLine = protoLocation.wholeline(); + panda::pandasm::FileLocation fileLocation(wholeLine, protoLocation.boundleft(), protoLocation.boundright(), + protoLocation.linenumber(), protoLocation.isdefined()); + location = fileLocation; } } // panda::proto diff --git a/merge_abc/src/assemblyFileLocationProto.h b/merge_abc/src/assemblyFileLocationProto.h index 83afe39022..2c13264974 100644 --- a/merge_abc/src/assemblyFileLocationProto.h +++ b/merge_abc/src/assemblyFileLocationProto.h @@ -23,7 +23,8 @@ namespace panda::proto { class FileLocation { public: static void Serialize(const panda::pandasm::FileLocation &location, protoPanda::FileLocation &protoLocation); - static void Deserialize(const protoPanda::FileLocation &protoLocation, panda::pandasm::FileLocation &location); + static void Deserialize(const protoPanda::FileLocation &protoLocation, + std::optional &location); }; } // panda::proto #endif diff --git a/merge_abc/src/assemblyFunctionProto.cpp b/merge_abc/src/assemblyFunctionProto.cpp index 0b56bf70f5..f5f9972365 100644 --- a/merge_abc/src/assemblyFunctionProto.cpp +++ b/merge_abc/src/assemblyFunctionProto.cpp @@ -161,7 +161,7 @@ void Function::Deserialize(const protoPanda::Function &protoFunction, panda::pan SourceLocation::Deserialize(protoFunction.bodylocation(), function.body_location); if (protoFunction.has_filelocation()) { - FileLocation::Deserialize(protoFunction.filelocation(), function.file_location.value()); + FileLocation::Deserialize(protoFunction.filelocation(), function.file_location); } function.SetFunctionKind(static_cast(protoFunction.function_kind())); } diff --git a/merge_abc/src/assemblyLabelProto.cpp b/merge_abc/src/assemblyLabelProto.cpp index f355a80490..63b18cefc1 100644 --- a/merge_abc/src/assemblyLabelProto.cpp +++ b/merge_abc/src/assemblyLabelProto.cpp @@ -31,7 +31,7 @@ void Label::Deserialize(const protoPanda::Label &protoLabel, panda::pandasm::Lab label.name = protoLabel.name(); if (protoLabel.has_filelocation()) { protoPanda::FileLocation protoLocation = protoLabel.filelocation(); - FileLocation::Deserialize(protoLocation, label.file_location.value()); + FileLocation::Deserialize(protoLocation, label.file_location); } } } // panda::proto diff --git a/merge_abc/src/assemblyRecordProto.cpp b/merge_abc/src/assemblyRecordProto.cpp index cfd7d34d44..9409ff1297 100644 --- a/merge_abc/src/assemblyRecordProto.cpp +++ b/merge_abc/src/assemblyRecordProto.cpp @@ -56,7 +56,7 @@ void Record::Deserialize(const protoPanda::Record &protoRecord, panda::pandasm:: record.source_file = protoRecord.sourcefile(); if (protoRecord.has_filelocation()) { const auto &protoLocation = protoRecord.filelocation(); - FileLocation::Deserialize(protoLocation, record.file_location.value()); + FileLocation::Deserialize(protoLocation, record.file_location); } } } // panda::proto diff --git a/test262/run_sunspider.py b/test262/run_sunspider.py index 0a06caa4bd..30dbaca4bd 100755 --- a/test262/run_sunspider.py +++ b/test262/run_sunspider.py @@ -230,9 +230,23 @@ class ArkProgram(): output_file = os.path.splitext(os.path.join(BASE_OUT_DIR, os.path.split(dependency)[1]))[0] output_abc = f"{output_file}.abc" + proto_bin_file = f"{output_file}.bin" + output_abc_name = os.path.basename(output_abc) + frontend_tool = self.ark_frontend_binary - cmd_args = [frontend_tool, dependency, '--output', output_abc, - '--module'] + merge_abc_binary = self.args.merge_abc_binary + merge_abc_mode = self.merge_abc_mode + + if merge_abc_mode != "0": + cmd_args = [frontend_tool, dependency, '--outputProto', + proto_bin_file, '--module', '--merge-abc'] + proc = subprocess.call(cmd_args) + cmd_args = [merge_abc_binary, '--input', proto_bin_file, '--suffix', + "bin", '--outputFilePath', BASE_OUT_DIR, '--output', + output_abc_name] + else: + cmd_args = [frontend_tool, dependency, '--output', output_abc, + '--module', '--merge-abc'] proc = subprocess.Popen(cmd_args) proc.wait() @@ -262,8 +276,13 @@ class ArkProgram(): if self.ark_frontend == ARK_FRONTEND_LIST[0]: mod_opt_index = 3 - cmd_args = ['node', '--expose-gc', frontend_tool, - js_file, '-o', out_file] + if merge_abc_mode != "0": + # '--opt-level=0' is added due to failure in optimizer, should be removed later + cmd_args = ['node', '--expose-gc', frontend_tool, js_file, + '--output-proto', proto_bin_file, '--opt-level=0'] + else: + cmd_args = ['node', '--expose-gc', frontend_tool, + js_file, '-o', out_file] if file_name in self.module_list: cmd_args.insert(mod_opt_index, "-m") self.module = True @@ -271,7 +290,7 @@ class ArkProgram(): mod_opt_index = 1 if merge_abc_mode != "0": cmd_args = [frontend_tool, '--outputProto', - proto_bin_file, js_file] + proto_bin_file, js_file, '--merge-abc'] else: cmd_args = [frontend_tool, '--opt-level=' + str(self.opt_level), '--function-threads=' + @@ -293,13 +312,15 @@ class ArkProgram(): abc_file = os.path.abspath(f'{js_dir}/{abc_file}') if self.abc_file.find(abc_file) < 0: self.abc_file += f':{abc_file}' - retcode = exec_command(cmd_args) self.abc_cmd = cmd_args - if self.ark_frontend == ARK_FRONTEND_LIST[1] and merge_abc_mode != "0": + if merge_abc_mode != "0": + proc = subprocess.call(cmd_args) cmd_args = [merge_abc_binary, '--input', proto_bin_file, '--suffix', "bin", '--outputFilePath', file_dir, '--output', proto_abc_file] retcode = exec_command(cmd_args) + else: + retcode = exec_command(cmd_args) return retcode def compile_aot(self): @@ -353,6 +374,8 @@ class ArkProgram(): f'--aot-file={file_name_pre}', f'{file_name_pre}.abc'] + record_name = os.path.splitext(os.path.split(self.js_file)[1])[0] + cmd_args.insert(-1, f'--entry-point={record_name}') retcode = exec_command(cmd_args) if retcode: print_command(cmd_args) @@ -388,6 +411,8 @@ class ArkProgram(): cmd_args = [self.ark_tool, ICU_PATH, f'{file_name_pre}.abc'] + record_name = os.path.splitext(os.path.split(self.js_file)[1])[0] + cmd_args.insert(-1, f'--entry-point={record_name}') retcode = exec_command(cmd_args) if retcode: print_command(cmd_args) diff --git a/ts2panda/src/cmdOptions.ts b/ts2panda/src/cmdOptions.ts index bf19d72cd5..94b151eaff 100644 --- a/ts2panda/src/cmdOptions.ts +++ b/ts2panda/src/cmdOptions.ts @@ -51,6 +51,8 @@ const ts2pandaOptions = [ { name: 'expression-watch-toolchain', type: String, defaultValue: "es2panda", description: "Specify the tool chain used to transform the expression" }, { name: 'source-file', type: String, defaultValue: "", description: "specify the file path info recorded in generated abc" }, { name: 'generate-tmp-file', type: Boolean, defaultValue: false, description: "whether to generate intermediate temporary files"}, + { name: 'record-name', type: String, defaultValue: "", description: "specify the record name." }, + { name: 'output-proto', type: String, defaultValue: "", description: "specify the output name for serializd protobuf file (.protoBin)" }, ] @@ -209,6 +211,13 @@ export class CmdOptions { return outputFile; } + static getRecordName(): string { + if (!this.options) { + return ""; + } + return this.options["record-name"]; + } + static getTimeOut(): Number { if (!this.options) { return 0; @@ -315,6 +324,10 @@ export class CmdOptions { return this.options["generate-tmp-file"]; } + static getOutputproto(): string { + return this.options["output-proto"]; + } + // @ts-ignore static parseUserCmd(args: string[]): ts.ParsedCommandLine | undefined { this.options = commandLineArgs(ts2pandaOptions, { partial: true }); diff --git a/ts2panda/src/compilerDriver.ts b/ts2panda/src/compilerDriver.ts index b4c4413c6b..2897861533 100644 --- a/ts2panda/src/compilerDriver.ts +++ b/ts2panda/src/compilerDriver.ts @@ -67,6 +67,7 @@ export class CompilerDriver { static srcNode: ts.SourceFile | undefined = undefined; static isTsFile: boolean = false; private fileName: string; + private recordName: string; private passes: Pass[] = []; private compilationUnits: PandaGen[]; pendingCompilationUnits: PendingCompilationUnit[]; @@ -76,8 +77,9 @@ export class CompilerDriver { private needDumpHeader: boolean = true; private ts2abcProcess: any = undefined; - constructor(fileName: string) { + constructor(fileName: string, recordName: string) { this.fileName = fileName; + this.recordName = recordName; // register passes here this.passes = [ new CacheExpander(), @@ -184,6 +186,7 @@ export class CompilerDriver { listenErrorEvent(ts2abcProc); try { + Ts2Panda.dumpRecord(ts2abcProc, this.recordName); Ts2Panda.dumpCmdOptions(ts2abcProc); Ts2Panda.dumpRecordName(ts2abcProc, getRecordName(CompilerDriver.srcNode)); @@ -367,20 +370,20 @@ export class CompilerDriver { name = "func_main_0"; } else if (ts.isConstructorDeclaration(node)) { let classNode = node.parent; - name = this.getInternalNameForCtor(classNode, node); + return this.getInternalNameForCtor(classNode, node); } else { let funcNode = node; name = (recorder.getScopeOfNode(funcNode)).getFuncName(); if (name == '') { if ((ts.isFunctionDeclaration(node) && hasExportKeywordModifier(node) && hasDefaultKeywordModifier(node)) || ts.isExportAssignment(findOuterNodeOfParenthesis(node))) { - return 'default'; + return `${this.recordName}.default`; } - return `#${this.getFuncId(funcNode)}#`; + return `${this.recordName}.#${this.getFuncId(funcNode)}#`; } if (name == "func_main_0") { - return `#${this.getFuncId(funcNode)}#${name}`; + return `${this.recordName}.#${this.getFuncId(funcNode)}#${name}`; } let funcNameMap = recorder.getFuncNameMap(); @@ -397,7 +400,7 @@ export class CompilerDriver { name = `#${this.getFuncId(funcNode)}#` } } - return name; + return `${this.recordName}.${name}`; } getInternalNameForCtor(node: ts.ClassLikeDeclaration, ctor: ts.ConstructorDeclaration) { @@ -406,7 +409,7 @@ export class CompilerDriver { if (name.lastIndexOf(".") != -1) { name = `#${this.getFuncId(ctor)}#` } - return name; + return `${this.recordName}.${name}`; } writeBinaryFile(pandaGen: PandaGen) { diff --git a/ts2panda/src/index.ts b/ts2panda/src/index.ts index 62cfa8cbb5..26eb031a6d 100644 --- a/ts2panda/src/index.ts +++ b/ts2panda/src/index.ts @@ -45,7 +45,7 @@ function checkIsGlobalDeclaration(sourceFile: ts.SourceFile) { function generateDTs(node: ts.SourceFile, options: ts.CompilerOptions) { let outputBinName = getOutputBinName(node); - let compilerDriver = new CompilerDriver(outputBinName); + let compilerDriver = new CompilerDriver(outputBinName, getRecordName(node)); setGlobalStrict(jshelpers.isEffectiveStrictModeSourceFile(node, options)); compilerDriver.compile(node); compilerDriver.showStatistics(); @@ -90,7 +90,7 @@ function main(fileNames: string[], options: ts.CompilerOptions) { (ctx: ts.TransformationContext) => { return (node: ts.SourceFile) => { let outputBinName = getOutputBinName(node); - let compilerDriver = new CompilerDriver(outputBinName); + let compilerDriver = new CompilerDriver(outputBinName, getRecordName(node)); compilerDriver.compileForSyntaxCheck(node); return node; } @@ -118,7 +118,7 @@ function main(fileNames: string[], options: ts.CompilerOptions) { node = transformCommonjsModule(node); } let outputBinName = getOutputBinName(node); - let compilerDriver = new CompilerDriver(outputBinName); + let compilerDriver = new CompilerDriver(outputBinName, getRecordName(node)); CompilerDriver.srcNode = node; setGlobalStrict(jshelpers.isEffectiveStrictModeSourceFile(node, options)); compilerDriver.compile(node); @@ -177,6 +177,17 @@ function getDtsFiles(libDir: string): string[] { return dtsFiles; } +function getRecordName(node: ts.SourceFile): string { + let recordName = CmdOptions.getRecordName(); + + if (recordName == "") { + let outputBinName = getOutputBinName(node); + recordName = path.basename(outputBinName, path.extname(outputBinName)); + } + + return recordName; +} + function specifyCustomLib(customLib) { Compiler.Options.Default["lib"] = customLib; let curFiles = fs.readdirSync(__dirname); @@ -203,12 +214,14 @@ function specifyCustomLib(customLib) { const stopWatchingStr = "####"; const watchAbcFileDefaultTimeOut = 10; const watchFileName = "watch_expressions"; +const watchOutputFileName = "Base64Output"; // this path is only available in sdk const es2abcBinaryPath = path["join"](__dirname, "..", "bin", path.sep); const es2abcBinaryName = /^win/.test(require('os').platform()) ? "es2abc.exe" : "es2abc"; const es2abcBase64Input = "--base64Input"; const es2abcDebuggerEvaluateFlag = "--debugger-evaluate-expression"; const es2abcBase64Output = "--base64Output"; +// need to specify the record name as 'Base64Output' in es2abc's commandline; cancel the opMergeAbc option function callEs2pandaToolChain(ideInputStr: string) { let commandLine = "\"" + es2abcBinaryPath + es2abcBinaryName + "\" " + es2abcBase64Input + " \"" + ideInputStr @@ -306,7 +319,7 @@ function compileWatchExpression(jsFileName: string, errorMsgFileName: string, op return (node: ts.SourceFile) => { if (path.basename(node.fileName) == fileName) { node = sourceFile; } let outputBinName = getOutputBinName(node); - let compilerDriver = new CompilerDriver(outputBinName); + let compilerDriver = new CompilerDriver(outputBinName, watchOutputFileName); compilerDriver.compileForSyntaxCheck(node); return node; } @@ -331,7 +344,7 @@ function compileWatchExpression(jsFileName: string, errorMsgFileName: string, op node = ts.factory.updateSourceFile(node, newStatements); } let outputBinName = getOutputBinName(node); - let compilerDriver = new CompilerDriver(outputBinName); + let compilerDriver = new CompilerDriver(outputBinName, watchOutputFileName); setGlobalStrict(jshelpers.isEffectiveStrictModeSourceFile(node, options)); compilerDriver.compile(node); return node; @@ -347,10 +360,11 @@ function launchWatchEvaluateDeamon(parsed: ts.ParsedCommandLine | undefined) { console.log("startWatchingSuccess supportTimeout"); return; } - let deamonFilePrefix = CmdOptions.getEvaluateDeamonPath() + path.sep + watchFileName; - let jsFileName = deamonFilePrefix + ".js"; - let abcFileName = deamonFilePrefix + ".abc"; - let errorMsgFileName = deamonFilePrefix + ".err"; + let deamonJSFilePrefix = CmdOptions.getEvaluateDeamonPath() + path.sep + watchFileName; + let deamonABCFilePrefix = CmdOptions.getEvaluateDeamonPath() + path.sep + watchOutputFileName; + let jsFileName = deamonJSFilePrefix + ".js"; + let abcFileName = deamonABCFilePrefix + ".abc"; + let errorMsgFileName = deamonJSFilePrefix + ".err"; if (fs.existsSync(jsFileName)) { console.log("watchFileServer has been initialized supportTimeout"); diff --git a/ts2panda/src/pandasm.ts b/ts2panda/src/pandasm.ts index 50231d9279..bc12caea96 100644 --- a/ts2panda/src/pandasm.ts +++ b/ts2panda/src/pandasm.ts @@ -115,24 +115,10 @@ export class Function { export class Record { public name: string; - public whole_line: string; - public bound_left: number; - public bound_right: number; - public line_number: number; public metadata: Metadata; - constructor( - name: string, - whole_line: string, - bound_left: number, - bound_right: number, - line_number: number - ) { + constructor(name: string) { this.name = name; - this.whole_line = whole_line; - this.bound_left = bound_left; - this.bound_right = bound_right; - this.line_number = line_number; this.metadata = new Metadata(); } } diff --git a/ts2panda/src/ts2panda.ts b/ts2panda/src/ts2panda.ts index a97288f3f3..271a015000 100644 --- a/ts2panda/src/ts2panda.ts +++ b/ts2panda/src/ts2panda.ts @@ -37,7 +37,8 @@ import { ModuleRecord, NamespaceImportEntry, RegularImportEntry, - Signature + Signature, + Record } from "./pandasm"; import { generateCatchTables } from "./statement/tryStatement"; import { @@ -237,6 +238,8 @@ export class Ts2Panda { "opt_log_level": CmdOptions.getOptLogLevel(), "display_typeinfo": CmdOptions.getDisplayTypeinfo(), "is_dts_file": isGlobalDeclare(), + "output-proto": CmdOptions.isOutputproto(), + "proto-name": CmdOptions.getProtoName(), "record_type": enableRecordType }; let jsonOpt = JSON.stringify(options, null, 2); @@ -247,6 +250,19 @@ export class Ts2Panda { ts2abc.stdio[3].write(jsonOpt + '\n'); } + static dumpRecord(ts2abc: any, recordName: string): void { + let record = { + "t": JsonType.record, + "rb": new Record(recordName) + } + let jsonRecord = escapeUnicode(JSON.stringify(record, null, 2)); + jsonRecord = "$" + jsonRecord.replace(dollarSign, '#$') + "$"; + if (CmdOptions.isEnableDebugLog()) { + Ts2Panda.jsonString += jsonRecord; + } + ts2abc.stdio[3].write(jsonRecord + '\n'); + } + // @ts-ignore static dumpInstTypeMap(pg: PandaGen): any { let insts = pg.getInsns(); @@ -356,7 +372,7 @@ export class Ts2Panda { } typeInfo = Ts2Panda.dumpInstTypeMap(pg); - if (funcName == "func_main_0") { + if (funcName.endsWith("func_main_0")) { let exportedTypes = PandaGen.getExportedTypes(); let declareddTypes = PandaGen.getDeclaredTypes(); if (exportedTypes.size != 0) { diff --git a/ts2panda/tests/builtIns.test.ts b/ts2panda/tests/builtIns.test.ts index 2ec85828da..d17b95e933 100644 --- a/ts2panda/tests/builtIns.test.ts +++ b/ts2panda/tests/builtIns.test.ts @@ -45,7 +45,7 @@ describe("FunctionToStringTest", function () { let snippetCompiler = new SnippetCompiler(); snippetCompiler.compileAfter(`function foo() {return 123;}\nfunction bar() {return 321;}\n`, 'toStringTest.js'); CmdOptions.needRecordSourceCode = () => {return false}; - let pandaGen = snippetCompiler.getPandaGenByName('foo'); + let pandaGen = snippetCompiler.getPandaGenByName('UnitTest.foo'); let expected = "function foo() {return 123;}"; expect(pandaGen.getSourceCode() == expected).to.be.true; }) diff --git a/ts2panda/tests/commonjs.test.ts b/ts2panda/tests/commonjs.test.ts index 60c24b23ce..f814112ec4 100644 --- a/ts2panda/tests/commonjs.test.ts +++ b/ts2panda/tests/commonjs.test.ts @@ -49,7 +49,7 @@ describe("CommonJsTest", function () { CmdOptions.isCommonJs = () => {return false}; let funcMainInsns = snippetCompiler.getGlobalInsns(); let expected = [ - new Definefunc(new Imm(0), '#1#', new Imm(5)), + new Definefunc(new Imm(0), 'UnitTest.#1#', new Imm(5)), new Sta(new VReg()), new Lda(new VReg()), new Sta(new VReg()), @@ -74,7 +74,7 @@ describe("CommonJsTest", function () { snippetCompiler.compileCommonjs(`let a = require('a.js')`, 'cjs.js'); IRNode.pg = new PandaGen("foo", creatAstFromSnippet(`let a = require('a.js')`), 0, undefined); CmdOptions.isCommonJs = () => {return false}; - let execInsns = snippetCompiler.getPandaGenByName('#1#')!.getInsns(); + let execInsns = snippetCompiler.getPandaGenByName('UnitTest.#1#')!.getInsns(); let requirePara = new VReg(); let requireReg = new VReg(); let moduleRequest = new VReg(); @@ -97,7 +97,7 @@ describe("CommonJsTest", function () { snippetCompiler.compileCommonjs(`let a = 1; exports.a = a;`, 'cjs.js'); IRNode.pg = new PandaGen("foo", creatAstFromSnippet(`let a = 1; exports.a = a;`), 0, undefined); CmdOptions.isCommonJs = () => {return false}; - let execInsns = snippetCompiler.getPandaGenByName('#1#')!.getInsns(); + let execInsns = snippetCompiler.getPandaGenByName('UnitTest.#1#')!.getInsns(); let exportsPara = new VReg(); let exportsReg = new VReg(); let tmpReg = new VReg(); diff --git a/ts2panda/tests/esmodule.test.ts b/ts2panda/tests/esmodule.test.ts index ff7e32c244..e73c64d565 100644 --- a/ts2panda/tests/esmodule.test.ts +++ b/ts2panda/tests/esmodule.test.ts @@ -49,7 +49,7 @@ describe("ExportDeclaration", function () { let classReg = new VReg(); let expected = [ new Mov(new VReg(), new VReg()), - new Defineclasswithbuffer(new Imm(0), "#1#C", "_0", new Imm(0), new VReg()), + new Defineclasswithbuffer(new Imm(0), "UnitTest.#1#C", "_0", new Imm(0), new VReg()), new Sta(classReg), new Lda(classReg), new Stmodulevar(new Imm(0)), diff --git a/ts2panda/tests/expression/arguments.test.ts b/ts2panda/tests/expression/arguments.test.ts index f509b3966f..60d84a95ab 100644 --- a/ts2panda/tests/expression/arguments.test.ts +++ b/ts2panda/tests/expression/arguments.test.ts @@ -47,7 +47,7 @@ describe("arguments Keyword", function () { new Ldobjbyindex(new Imm(0), new Imm(0)), new Returnundefined() ]; - let functionPg = snippetCompiler.getPandaGenByName("foo"); + let functionPg = snippetCompiler.getPandaGenByName("UnitTest.foo"); let insns = functionPg!.getInsns(); expect(checkInstructions(insns, expected)).to.be.true; @@ -68,7 +68,7 @@ describe("arguments Keyword", function () { new Ldobjbyindex(new Imm(0), new Imm(0)), new Returnundefined() ]; - let functionPg = snippetCompiler.getPandaGenByName("foo"); + let functionPg = snippetCompiler.getPandaGenByName("UnitTest.foo"); let insns = functionPg!.getInsns(); expect(checkInstructions(insns, expected)).to.be.true; diff --git a/ts2panda/tests/expression/commalist.test.ts b/ts2panda/tests/expression/commalist.test.ts index 41d44eb25b..6c00a01211 100644 --- a/ts2panda/tests/expression/commalist.test.ts +++ b/ts2panda/tests/expression/commalist.test.ts @@ -72,7 +72,7 @@ describe("CommaListExpression", function () { let insns = snippetCompiler.getGlobalInsns(); let expected = [ new Mov(new VReg(), new VReg()), - new Defineclasswithbuffer(new Imm(0), "#1#Test", "_0", new Imm(0), new VReg()), + new Defineclasswithbuffer(new Imm(0), "UnitTest.#1#Test", "_0", new Imm(0), new VReg()), new Sta(new VReg()), new Lda(new VReg()), new Sttoglobalrecord(new Imm(1), "Test"), diff --git a/ts2panda/tests/expression/functionExpression.test.ts b/ts2panda/tests/expression/functionExpression.test.ts index d434f440ae..b4cd1c8e7a 100644 --- a/ts2panda/tests/expression/functionExpression.test.ts +++ b/ts2panda/tests/expression/functionExpression.test.ts @@ -71,7 +71,7 @@ describe("compileFunctionExpression", function () { let checkCount = 0; pandaGens.forEach((pg) => { - if (pg.internalName == "test") { + if (pg.internalName == "UnitTest.test") { expect(checkInstructions(pg.getInsns(), expected_func), "check func insns").to.be.true; checkCount++; } @@ -89,15 +89,15 @@ describe("compileFunctionExpression", function () { let checkCount = 0; pandaGens.forEach((pg) => { - if (pg.internalName == "a") { + if (pg.internalName == "UnitTest.a") { checkCount++; } - if (pg.internalName == "func_main_0") { + if (pg.internalName == "UnitTest.func_main_0") { pg.getInsns().forEach((insns) => { if (insns instanceof Definefunc) { - expect(insns.operands[1]).to.equal('a'); + expect(insns.operands[1]).to.equal('UnitTest.a'); checkCount++; } }); @@ -117,15 +117,15 @@ describe("compileFunctionExpression", function () { let checkCount = 0; pandaGens.forEach((pg) => { - if (pg.internalName == "a") { + if (pg.internalName == "UnitTest.a") { checkCount++; } - if (pg.internalName == "func_main_0") { + if (pg.internalName == "UnitTest.func_main_0") { pg.getInsns().forEach((insns) => { if (insns instanceof Definefunc) { - expect(insns.operands[1]).to.equal('a'); + expect(insns.operands[1]).to.equal('UnitTest.a'); checkCount++; } }); @@ -146,15 +146,15 @@ describe("compileFunctionExpression", function () { let checkCount = 0; pandaGens.forEach((pg) => { - if (pg.internalName == "a") { + if (pg.internalName == "UnitTest.a") { checkCount++; } - if (pg.internalName == "func_main_0") { + if (pg.internalName == "UnitTest.func_main_0") { pg.getInsns().forEach((insns) => { if (insns instanceof Definefunc) { - expect(insns.operands[1]).to.equal('a'); + expect(insns.operands[1]).to.equal('UnitTest.a'); checkCount++; } }); @@ -183,16 +183,16 @@ describe("compileFunctionExpression", function () { ]; pandaGens.forEach((pg) => { - if (pg.internalName == "p") { + if (pg.internalName == "UnitTest.p") { expect(checkInstructions(pg.getInsns(), expected_func), "check arrow func insns").to.be.true; checkCount++; } - if (pg.internalName == "func_main_0") { + if (pg.internalName == "UnitTest.func_main_0") { pg.getInsns().forEach((insns) => { if (insns instanceof Definefunc) { - expect(insns.operands[1]).to.equal('p'); + expect(insns.operands[1]).to.equal('UnitTest.p'); checkCount++; } }); @@ -289,15 +289,15 @@ describe("compileFunctionExpression", function () { let checkCount = 0; pandaGens.forEach((pg) => { - if (pg.internalName == "a") { + if (pg.internalName == "UnitTest.a") { expect(checkInstructions(pg.getInsns(), expected_func), "check generator func insns").to.be.true; checkCount++; } - if (pg.internalName == "func_main_0") { + if (pg.internalName == "UnitTest.func_main_0") { pg.getInsns().forEach((insns) => { if (insns instanceof Definefunc) { - expect(insns.operands[1]).to.equal('a'); + expect(insns.operands[1]).to.equal('UnitTest.a'); checkCount++; } }); @@ -352,15 +352,15 @@ describe("compileFunctionExpression", function () { let checkCount = 0; pandaGens.forEach((pg) => { - if (pg.internalName == "a") { + if (pg.internalName == "UnitTest.a") { expect(checkInstructions(pg.getInsns(), expected_func), "check async func insns").to.be.true; checkCount++; } - if (pg.internalName == "func_main_0") { + if (pg.internalName == "UnitTest.func_main_0") { pg.getInsns().forEach((insns) => { if (insns instanceof Definefunc) { - expect(insns.operands[1]).to.equal('a'); + expect(insns.operands[1]).to.equal('UnitTest.a'); checkCount++; } }); diff --git a/ts2panda/tests/expression/thisKeyWord.test.ts b/ts2panda/tests/expression/thisKeyWord.test.ts index 9762e99121..c1ae227b88 100644 --- a/ts2panda/tests/expression/thisKeyWord.test.ts +++ b/ts2panda/tests/expression/thisKeyWord.test.ts @@ -51,7 +51,7 @@ describe("ThisKeyword", function () { it("this in function scope", function () { let snippetCompiler = new SnippetCompiler(); snippetCompiler.compile("function a() {this}"); - let functionPg = snippetCompiler.getPandaGenByName("a"); + let functionPg = snippetCompiler.getPandaGenByName("UnitTest.a"); let functionScope = functionPg!.getScope(); let insns = compileMainSnippet("this;", pandaGen, functionScope); let expected = [ diff --git a/ts2panda/tests/hoist.test.ts b/ts2panda/tests/hoist.test.ts index 5542972dc6..30c227a420 100644 --- a/ts2panda/tests/hoist.test.ts +++ b/ts2panda/tests/hoist.test.ts @@ -86,7 +86,7 @@ describe("HoistTest", function () { let insns = snippetCompiler.getGlobalInsns(); let expected = [ - new Definefunc(new Imm(0), "a", new Imm(0)), + new Definefunc(new Imm(0), "UnitTest.a", new Imm(0)), new Stglobalvar(new Imm(1), "a"), new Returnundefined() ] @@ -101,7 +101,7 @@ describe("HoistTest", function () { let insns = snippetCompiler.getGlobalInsns(); let expected = [ - new Definefunc(new Imm(0), "#2#a", new Imm(0)), + new Definefunc(new Imm(0), "UnitTest.#2#a", new Imm(0)), new Stglobalvar(new Imm(1), "a"), new Returnundefined() ] @@ -117,7 +117,7 @@ describe("HoistTest", function () { let insns = snippetCompiler.getGlobalInsns(); let expected = [ - new Definefunc(new Imm(0), "a", new Imm(0)), + new Definefunc(new Imm(0), "UnitTest.a", new Imm(0)), new Stglobalvar(new Imm(1), "a"), new Ldai(new Imm(1)), new Stglobalvar(new Imm(2), "a"), @@ -132,7 +132,7 @@ describe("HoistTest", function () { let snippetCompiler = new SnippetCompiler(); snippetCompiler.compile(`function a() {var a = 1;}`); IRNode.pg = new PandaGen("foo", creatAstFromSnippet(`function a() {var a = 1;}`), 0, undefined); - let funcPg = snippetCompiler.getPandaGenByName("a"); + let funcPg = snippetCompiler.getPandaGenByName("UnitTest.a"); let insns = funcPg!.getInsns(); let a = new VReg(); @@ -152,11 +152,11 @@ describe("HoistTest", function () { let snippetCompiler = new SnippetCompiler(); snippetCompiler.compile(`function a() {function b() {}};`); IRNode.pg = new PandaGen("foo", creatAstFromSnippet(`function a() {function b() {}};`), 0, undefined); - let funcPg = snippetCompiler.getPandaGenByName("a"); + let funcPg = snippetCompiler.getPandaGenByName("UnitTest.a"); let insns = funcPg!.getInsns(); let a = new VReg(); let expected = [ - new Definefunc(new Imm(0), "b", new Imm(0)), + new Definefunc(new Imm(0), "UnitTest.b", new Imm(0)), new Sta(a), new Returnundefined() @@ -170,7 +170,7 @@ describe("HoistTest", function () { let snippetCompiler = new SnippetCompiler(); snippetCompiler.compile(`a = 1; let a;`); - let funcPg = snippetCompiler.getPandaGenByName("func_main_0"); + let funcPg = snippetCompiler.getPandaGenByName("UnitTest.func_main_0"); let insns = funcPg!.getInsns(); let idReg = new VReg(); let expected = [ @@ -189,7 +189,7 @@ describe("HoistTest", function () { a = 1; let a; }`); - let funcPg = snippetCompiler.getPandaGenByName("b"); + let funcPg = snippetCompiler.getPandaGenByName("UnitTest.b"); let insns = funcPg!.getInsns(); let idReg = new VReg(); @@ -209,7 +209,7 @@ describe("HoistTest", function () { a = 1; let a; }`); - let funcPg = snippetCompiler.getPandaGenByName("func_main_0"); + let funcPg = snippetCompiler.getPandaGenByName("UnitTest.func_main_0"); let insns = funcPg!.getInsns(); let idReg = new VReg(); diff --git a/ts2panda/tests/lexenv.test.ts b/ts2panda/tests/lexenv.test.ts index 5c52068929..c5d6e49463 100644 --- a/ts2panda/tests/lexenv.test.ts +++ b/ts2panda/tests/lexenv.test.ts @@ -104,7 +104,7 @@ describe("lexenv-compile-testcase in lexenv.test.ts", function () { it("test CompilerDriver.scanFunctions-with-empty", function () { let source: string = ``; let sourceFile = creatAstFromSnippet(source); - let compilerDriver = new CompilerDriver('UnitTest'); + let compilerDriver = new CompilerDriver('UnitTest', 'UnitTest'); let globalScope = new GlobalScope(sourceFile); let recorder = new Recorder(sourceFile, globalScope, compilerDriver, false, false, true); recorder.record(); @@ -132,7 +132,7 @@ describe("lexenv-compile-testcase in lexenv.test.ts", function () { var funcExpression = function() { } `; let sourceFile = creatAstFromSnippet(source); - let compilerDriver = new CompilerDriver('UnitTest'); + let compilerDriver = new CompilerDriver('UnitTest', 'UnitTest'); let globalScope = new GlobalScope(sourceFile); let recorder = new Recorder(sourceFile, globalScope, compilerDriver, false, false, true); recorder.record(); @@ -179,7 +179,7 @@ describe("lexenv-compile-testcase in lexenv.test.ts", function () { let source: string = ` `; let sourceFile = creatAstFromSnippet(source); - let compilerDriver = new CompilerDriver('UnitTest'); + let compilerDriver = new CompilerDriver('UnitTest', 'UnitTest'); let globalScope = new GlobalScope(sourceFile); let recorder = new Recorder(sourceFile, globalScope, compilerDriver, false, false, true); @@ -203,7 +203,7 @@ describe("lexenv-compile-testcase in lexenv.test.ts", function () { var funcExt = function() { } `; let sourceFile = creatAstFromSnippet(source); - let compilerDriver = new CompilerDriver('UnitTest'); + let compilerDriver = new CompilerDriver('UnitTest', 'UnitTest'); let globalScope = new GlobalScope(sourceFile); let recorder = new Recorder(sourceFile, globalScope, compilerDriver, false, false, true); @@ -257,7 +257,7 @@ describe("lexenv-compile-testcase in lexenv.test.ts", function () { }))) `; let sourceFile = creatAstFromSnippet(source); - let compilerDriver = new CompilerDriver('UnitTest'); + let compilerDriver = new CompilerDriver('UnitTest', 'UnitTest'); let globalScope = new GlobalScope(sourceFile); let recorder = new Recorder(sourceFile, globalScope, compilerDriver, false, false, true); @@ -403,7 +403,7 @@ describe("lexenv-compile-testcase in lexenv.test.ts", function () { let expected_main = [ new Lda(new VReg()), new Stglobalvar(new Imm(0), "outer"), - new Definefunc(new Imm(1), "func", new Imm(0)), + new Definefunc(new Imm(1), "UnitTest.func", new Imm(0)), new Stglobalvar(new Imm(2), "func"), new Ldai(new Imm(1)), new Stglobalvar(new Imm(3), "outer"), @@ -417,9 +417,9 @@ describe("lexenv-compile-testcase in lexenv.test.ts", function () { ]; pandaGens.forEach((pg) => { - if (pg.internalName == "func_main_0") { + if (pg.internalName == "UnitTest.func_main_0") { expect(checkInstructions(pg.getInsns(), expected_main)).to.be.true; - } else if (pg.internalName == "func") { + } else if (pg.internalName == "UnitTest.func") { expect(checkInstructions(pg.getInsns(), expected_func)).to.be.true; } }) @@ -438,7 +438,7 @@ describe("lexenv-compile-testcase in lexenv.test.ts", function () { let pandaGens = compileAllSnippet(source, passes); IRNode.pg = new PandaGen("foo", creatAstFromSnippet(`class C {}; export {C}`), 0, undefined); let expected_main = [ - new Definefunc(new Imm(0), "func", new Imm(0)), + new Definefunc(new Imm(0), "UnitTest.func", new Imm(0)), new Stglobalvar(new Imm(1), "func"), // global.func = func_func_1 new Ldai(new Imm(1)), // value = 1 new Sttoglobalrecord(new Imm(2), "outer"), @@ -455,11 +455,11 @@ describe("lexenv-compile-testcase in lexenv.test.ts", function () { pandaGens.forEach((pg) => { let scope = pg.getScope(); - if (pg.internalName == "func_main_0") { + if (pg.internalName == "UnitTest.func_main_0") { expect(checkInstructions(pg.getInsns(), expected_main), "check main insns").to.be.true; expect(scope.getNumLexEnv(), "main scope has 0 lexvar").to.be.equal(0); // expect(scope.hasLexEnv(), "main scope has lexenv").to.be.true; - } else if (pg.internalName == "func") { + } else if (pg.internalName == "UnitTest.func") { expect(checkInstructions(pg.getInsns(), expected_func), "check func insns").to.be.true; expect(scope.getNumLexEnv(), "func scope has 1 lexvar").to.be.equal(0); @@ -500,7 +500,7 @@ describe("lexenv-compile-testcase in lexenv.test.ts", function () { new Lda(new VReg()), new Stlexvar(new Imm(0), new Imm(1)), new Lda(new VReg()), - new Definefunc(new Imm(0), "#1#", new Imm(0)), + new Definefunc(new Imm(0), "UnitTest.#1#", new Imm(0)), // returnStatement new Sta(new VReg()), new Lda(new VReg()), @@ -536,13 +536,13 @@ describe("lexenv-compile-testcase in lexenv.test.ts", function () { snippetCompiler.compile(source, passes); // check compile result! - let outerPg = snippetCompiler.getPandaGenByName("outer"); + let outerPg = snippetCompiler.getPandaGenByName("UnitTest.outer"); let outerScope = outerPg!.getScope(); let outerA = outerScope!.findLocal("a"); expect(outerA instanceof LocalVariable, "a in outer is local variable").to.be.true; // expect((outerScope).hasLexEnv(), "outer scope need to create lex env").to.be.true; expect((outerScope).getNumLexEnv(), "number of lexvar at outer scope").to.be.equal(2); - let anonymousPg = snippetCompiler.getPandaGenByName("#1#"); + let anonymousPg = snippetCompiler.getPandaGenByName("UnitTest.#1#"); let anonymousScope = anonymousPg!.getScope(); let anonymousA = anonymousScope!.findLocal("a"); let searchRlt = anonymousScope!.find("a"); @@ -551,7 +551,7 @@ describe("lexenv-compile-testcase in lexenv.test.ts", function () { expect(anonymousA, "no a in anonymous function").to.be.undefined; // expect((anonymousScope).hasLexEnv(), "anonymous scope had lex env").to.be.true; expect((anonymousScope).getNumLexEnv()).to.be.equal(0); - let globalPg = snippetCompiler.getPandaGenByName("func_main_0"); + let globalPg = snippetCompiler.getPandaGenByName("UnitTest.func_main_0"); let globalScope = globalPg!.getScope(); let globalA = globalScope!.findLocal("a"); expect(globalA instanceof GlobalVariable, "globalA is GlobalVariable").to.be.true; diff --git a/ts2panda/tests/statements/functionDeclaration.test.ts b/ts2panda/tests/statements/functionDeclaration.test.ts index 7c5ef3b078..6405c9cd96 100644 --- a/ts2panda/tests/statements/functionDeclaration.test.ts +++ b/ts2panda/tests/statements/functionDeclaration.test.ts @@ -46,9 +46,10 @@ describe("FunctionDeclarationTest", function () { let snippetCompiler = new SnippetCompiler(); snippetCompiler.compile("function foo() {}"); IRNode.pg = new PandaGen("", creatAstFromSnippet(``), 0, undefined); + let funcInternalName = "UnitTest.foo"; let funcName = "foo"; let expected = [ - new Definefunc(new Imm(0), funcName, new Imm(0)), + new Definefunc(new Imm(0), funcInternalName, new Imm(0)), new Stglobalvar(new Imm(1), funcName), new Returnundefined() ]; @@ -68,7 +69,7 @@ describe("FunctionDeclarationTest", function () { `); IRNode.pg = new PandaGen("", creatAstFromSnippet(``), 0, undefined); let expected = [ - new Definefunc(new Imm(0), "#2#foo", new Imm(0)), + new Definefunc(new Imm(0), "UnitTest.#2#foo", new Imm(0)), new Stglobalvar(new Imm(1), "foo"), new Returnundefined() ]; @@ -86,12 +87,12 @@ describe("FunctionDeclarationTest", function () { IRNode.pg = new PandaGen("", creatAstFromSnippet(``), 0, undefined); let funcReg = new VReg(); let expected = [ - new Definefunc(new Imm(0), "foo", new Imm(0)), + new Definefunc(new Imm(0), "UnitTest.foo", new Imm(0)), new Sta(funcReg), new Returnundefined() ]; - let functionPg = snippetCompiler.getPandaGenByName("out"); + let functionPg = snippetCompiler.getPandaGenByName("UnitTest.out"); let insns = functionPg!.getInsns(); let functionScope = functionPg!.getScope(); @@ -109,7 +110,7 @@ describe("FunctionDeclarationTest", function () { let insns = snippetCompiler.getGlobalInsns(); IRNode.pg = new PandaGen("", creatAstFromSnippet(``), 0, undefined); let expected = [ - new Definefunc(new Imm(0), "foo", new Imm(0)), + new Definefunc(new Imm(0), "UnitTest.foo", new Imm(0)), new Sttoglobalrecord(new Imm(1), "foo"), new Returnundefined() ]; @@ -124,7 +125,7 @@ describe("FunctionDeclarationTest", function () { IRNode.pg = new PandaGen("", creatAstFromSnippet(``), 0, undefined); let expected_main = [ - new Definefunc(new Imm(0), "test", new Imm(1)), + new Definefunc(new Imm(0), "UnitTest.test", new Imm(1)), new Stglobalvar(new Imm(1), "test"), new Returnundefined() ]; @@ -142,10 +143,10 @@ describe("FunctionDeclarationTest", function () { ]; compilerunit.forEach(element => { - if (element.internalName == "func_main_0") { + if (element.internalName == "UnitTest.func_main_0") { let insns = element.getInsns(); expect(checkInstructions(insns, expected_main)).to.be.true; - } else if (element.internalName == "test") { + } else if (element.internalName == "UnitTest.test") { let insns = element.getInsns(); expect(checkInstructions(insns, expected_func)).to.be.true; let parameterLength = element.getParameterLength(); @@ -168,7 +169,7 @@ describe("FunctionDeclarationTest", function () { new Returnundefined(), ]; - let functionPg = snippetCompiler.getPandaGenByName("test"); + let functionPg = snippetCompiler.getPandaGenByName("UnitTest.test"); let insns = functionPg!.getInsns(); expect(checkInstructions(insns, expected_func)).to.be.true; diff --git a/ts2panda/tests/statements/variableDeclaration.test.ts b/ts2panda/tests/statements/variableDeclaration.test.ts index 95d5bbb47a..88db2c51f3 100644 --- a/ts2panda/tests/statements/variableDeclaration.test.ts +++ b/ts2panda/tests/statements/variableDeclaration.test.ts @@ -165,7 +165,7 @@ describe("VariableDeclarationTest", function () { let snippetCompiler = new SnippetCompiler(); snippetCompiler.compile("function a() {var i;}"); IRNode.pg = new PandaGen("", creatAstFromSnippet(``), 0, undefined); - let funcPg = snippetCompiler.getPandaGenByName("a"); + let funcPg = snippetCompiler.getPandaGenByName("UnitTest.a"); let functionScope = funcPg!.getScope(); let insns = funcPg!.getInsns(); let expected = [ @@ -184,7 +184,7 @@ describe("VariableDeclarationTest", function () { let snippetCompiler = new SnippetCompiler(); snippetCompiler.compile("function a() {let i;}"); IRNode.pg = new PandaGen("", creatAstFromSnippet(``), 0, undefined); - let funcPg = snippetCompiler.getPandaGenByName("a"); + let funcPg = snippetCompiler.getPandaGenByName("UnitTest.a"); let functionScope = funcPg!.getScope(); let insns = funcPg!.getInsns(); let expected = [ @@ -201,7 +201,7 @@ describe("VariableDeclarationTest", function () { let snippetCompiler = new SnippetCompiler(); snippetCompiler.compile("function a() {const i = 5;}"); IRNode.pg = new PandaGen("", creatAstFromSnippet(``), 0, undefined); - let funcPg = snippetCompiler.getPandaGenByName("a"); + let funcPg = snippetCompiler.getPandaGenByName("UnitTest.a"); let functionScope = funcPg!.getScope(); let insns = funcPg!.getInsns(); let expected = [ @@ -217,7 +217,7 @@ describe("VariableDeclarationTest", function () { it('let i in a local scope', function () { let snippetCompiler = new SnippetCompiler(); snippetCompiler.compile("{let i;}"); - let funcPg = snippetCompiler.getPandaGenByName("func_main_0"); + let funcPg = snippetCompiler.getPandaGenByName("UnitTest.func_main_0"); let localScope = funcPg!.getScope(); let insns = funcPg!.getInsns(); diff --git a/ts2panda/tests/types/array.test.ts b/ts2panda/tests/types/array.test.ts index 131bcc2e47..48f8b2db92 100644 --- a/ts2panda/tests/types/array.test.ts +++ b/ts2panda/tests/types/array.test.ts @@ -30,7 +30,7 @@ describe("array tests in array.test.ts", function() { it("test array with primitives", function() { let fileNames = 'tests/types/array/array_primitives.ts'; let result = compileTsWithType(fileNames); - let functionPg = result.snippetCompiler.getPandaGenByName("func_main_0"); + let functionPg = result.snippetCompiler.getPandaGenByName("UnitTest.func_main_0"); let locals = functionPg!.getLocals(); // check vreg let extectedVRegTypePair = [ @@ -75,7 +75,7 @@ describe("array tests in array.test.ts", function() { it("test array with class", function() { let fileNames = 'tests/types/array/array_class.ts'; let result = compileTsWithType(fileNames); - let functionPg = result.snippetCompiler.getPandaGenByName("func_main_0"); + let functionPg = result.snippetCompiler.getPandaGenByName("UnitTest.func_main_0"); let locals = functionPg!.getLocals(); // check vreg let extectedVRegTypePair = [ @@ -108,7 +108,7 @@ describe("array tests in array.test.ts", function() { it("test array with multi same primitive", function() { let fileNames = 'tests/types/array/array_multi_same_primi.ts'; let result = compileTsWithType(fileNames); - let functionPg = result.snippetCompiler.getPandaGenByName("func_main_0"); + let functionPg = result.snippetCompiler.getPandaGenByName("UnitTest.func_main_0"); let locals = functionPg!.getLocals(); // check vreg let extectedVRegTypePair = [ @@ -159,7 +159,7 @@ describe("array tests in array.test.ts", function() { it("test array with multi same class", function() { let fileNames = 'tests/types/array/array_multi_same_class.ts'; let result = compileTsWithType(fileNames); - let functionPg = result.snippetCompiler.getPandaGenByName("func_main_0"); + let functionPg = result.snippetCompiler.getPandaGenByName("UnitTest.func_main_0"); let locals = functionPg!.getLocals(); // check vreg let extectedVRegTypePair = [ @@ -193,7 +193,7 @@ describe("array tests in array.test.ts", function() { it("test array with union", function() { let fileNames = 'tests/types/array/array_union.ts'; let result = compileTsWithType(fileNames); - let functionPg = result.snippetCompiler.getPandaGenByName("func_main_0"); + let functionPg = result.snippetCompiler.getPandaGenByName("UnitTest.func_main_0"); let locals = functionPg!.getLocals(); // check vreg let extectedVRegTypePair = [ @@ -222,7 +222,7 @@ describe("array tests in array.test.ts", function() { it("test array with object", function() { let fileNames = 'tests/types/array/array_object.ts'; let result = compileTsWithType(fileNames); - let functionPg = result.snippetCompiler.getPandaGenByName("func_main_0"); + let functionPg = result.snippetCompiler.getPandaGenByName("UnitTest.func_main_0"); let locals = functionPg!.getLocals(); // check vreg let extectedVRegTypePair = [ diff --git a/ts2panda/tests/types/class.test.ts b/ts2panda/tests/types/class.test.ts index 1a58c70fb9..00247f961d 100644 --- a/ts2panda/tests/types/class.test.ts +++ b/ts2panda/tests/types/class.test.ts @@ -30,7 +30,7 @@ describe("class tests in class.test.ts", function () { it("test class with no parameter in block", function () { let fileNames = 'tests/types/class/class_constr_no_para.ts'; let result = compileTsWithType(fileNames); - let functionPg = result.snippetCompiler.getPandaGenByName("func_main_0"); + let functionPg = result.snippetCompiler.getPandaGenByName("UnitTest.func_main_0"); let locals = functionPg!.getLocals(); // check vreg let extectedVRegTypePair = [ @@ -67,7 +67,7 @@ describe("class tests in class.test.ts", function () { it("test class with parameter in block", function () { let fileNames = 'tests/types/class/class_constr_para.ts'; let result = compileTsWithType(fileNames); - let functionPg = result.snippetCompiler.getPandaGenByName("func_main_0"); + let functionPg = result.snippetCompiler.getPandaGenByName("UnitTest.func_main_0"); let locals = functionPg!.getLocals(); // check vreg let extectedVRegTypePair = [ @@ -103,7 +103,7 @@ describe("class tests in class.test.ts", function () { it("test class fields type", function () { let fileNames = 'tests/types/class/class_fields.ts'; let result = compileTsWithType(fileNames); - let functionPg = result.snippetCompiler.getPandaGenByName("func_main_0"); + let functionPg = result.snippetCompiler.getPandaGenByName("UnitTest.func_main_0"); let locals = functionPg!.getLocals(); // check vreg let extectedVRegTypePair = [ @@ -138,7 +138,7 @@ describe("class tests in class.test.ts", function () { it("test class methods type", function () { let fileNames = 'tests/types/class/class_methods.ts'; let result = compileTsWithType(fileNames); - let functionPg = result.snippetCompiler.getPandaGenByName("func_main_0"); + let functionPg = result.snippetCompiler.getPandaGenByName("UnitTest.func_main_0"); let locals = functionPg!.getLocals(); // check vreg let extectedVRegTypePair = [ @@ -180,7 +180,7 @@ describe("class tests in class.test.ts", function () { it("test class static fields type", function () { let fileNames = 'tests/types/class/class_static_fields.ts'; let result = compileTsWithType(fileNames); - let functionPg = result.snippetCompiler.getPandaGenByName("func_main_0"); + let functionPg = result.snippetCompiler.getPandaGenByName("UnitTest.func_main_0"); let locals = functionPg!.getLocals(); // check vreg let extectedVRegTypePair = [ @@ -215,7 +215,7 @@ describe("class tests in class.test.ts", function () { it("test class static methods type", function () { let fileNames = 'tests/types/class/class_static_methods.ts'; let result = compileTsWithType(fileNames); - let functionPg = result.snippetCompiler.getPandaGenByName("func_main_0"); + let functionPg = result.snippetCompiler.getPandaGenByName("UnitTest.func_main_0"); let locals = functionPg!.getLocals(); // check vreg let extectedVRegTypePair = [ @@ -258,7 +258,7 @@ describe("class tests in class.test.ts", function () { it("test abstract class type", function () { let fileNames = 'tests/types/class/class_abstract.ts'; let result = compileTsWithType(fileNames); - let functionPg = result.snippetCompiler.getPandaGenByName("func_main_0"); + let functionPg = result.snippetCompiler.getPandaGenByName("UnitTest.func_main_0"); let locals = functionPg!.getLocals(); // check vreg let extectedVRegTypePair = [ @@ -303,7 +303,7 @@ describe("class tests in class.test.ts", function () { it("test class implements type", function () { let fileNames = 'tests/types/class/class_implements.ts'; let result = compileTsWithType(fileNames); - let functionPg = result.snippetCompiler.getPandaGenByName("func_main_0"); + let functionPg = result.snippetCompiler.getPandaGenByName("UnitTest.func_main_0"); let locals = functionPg!.getLocals(); // check vreg let extectedVRegTypePair = [ diff --git a/ts2panda/tests/types/function.test.ts b/ts2panda/tests/types/function.test.ts index 5a37e3d989..3003d42926 100644 --- a/ts2panda/tests/types/function.test.ts +++ b/ts2panda/tests/types/function.test.ts @@ -30,7 +30,7 @@ describe("function tests in function.test.ts", function () { it("test function with no parameter", function () { let fileNames = 'tests/types/function/function_no_para.ts'; let result = compileTsWithType(fileNames); - let functionPg = result.snippetCompiler.getPandaGenByName("func_main_0"); + let functionPg = result.snippetCompiler.getPandaGenByName("UnitTest.func_main_0"); let locals = functionPg!.getLocals(); // check vreg let extectedVRegTypePair = [ @@ -60,7 +60,7 @@ describe("function tests in function.test.ts", function () { it("test function with muti parameter", function () { let fileNames = 'tests/types/function/function_multi_para.ts'; let result = compileTsWithType(fileNames); - let functionPg = result.snippetCompiler.getPandaGenByName("func_main_0"); + let functionPg = result.snippetCompiler.getPandaGenByName("UnitTest.func_main_0"); let locals = functionPg!.getLocals(); // check vreg let extectedVRegTypePair = [ @@ -92,7 +92,7 @@ describe("function tests in function.test.ts", function () { it("test function with same type of paras and return", function () { let fileNames = 'tests/types/function/function_same_para_and_return.ts'; let result = compileTsWithType(fileNames); - let functionPg = result.snippetCompiler.getPandaGenByName("func_main_0"); + let functionPg = result.snippetCompiler.getPandaGenByName("UnitTest.func_main_0"); let locals = functionPg!.getLocals(); // check vreg let extectedVRegTypePair = [ @@ -131,7 +131,7 @@ describe("function tests in function.test.ts", function () { it("test function with class as parameter", function () { let fileNames = 'tests/types/function/function_class_para.ts'; let result = compileTsWithType(fileNames); - let functionPg = result.snippetCompiler.getPandaGenByName("func_main_0"); + let functionPg = result.snippetCompiler.getPandaGenByName("UnitTest.func_main_0"); let locals = functionPg!.getLocals(); // check vreg let extectedVRegTypePair = [ @@ -172,7 +172,7 @@ describe("function tests in function.test.ts", function () { it("test function with class as return", function () { let fileNames = 'tests/types/function/function_class_return.ts'; let result = compileTsWithType(fileNames); - let functionPg = result.snippetCompiler.getPandaGenByName("func_main_0"); + let functionPg = result.snippetCompiler.getPandaGenByName("UnitTest.func_main_0"); let locals = functionPg!.getLocals(); // check vreg let extectedVRegTypePair = [ diff --git a/ts2panda/tests/types/object.test.ts b/ts2panda/tests/types/object.test.ts index 9f7446a20a..bfaeef5ae8 100644 --- a/ts2panda/tests/types/object.test.ts +++ b/ts2panda/tests/types/object.test.ts @@ -30,7 +30,7 @@ describe("object tests in object.test.ts", function() { it("test object with primitives", function() { let fileNames = 'tests/types/object/object_primi.ts'; let result = compileTsWithType(fileNames); - let functionPg = result.snippetCompiler.getPandaGenByName("func_main_0"); + let functionPg = result.snippetCompiler.getPandaGenByName("UnitTest.func_main_0"); let locals = functionPg!.getLocals(); // check vreg let extectedVRegTypePair = [ @@ -56,7 +56,7 @@ describe("object tests in object.test.ts", function() { it("test object with user defined type", function() { let fileNames = 'tests/types/object/object_class.ts'; let result = compileTsWithType(fileNames); - let functionPg = result.snippetCompiler.getPandaGenByName("func_main_0"); + let functionPg = result.snippetCompiler.getPandaGenByName("UnitTest.func_main_0"); let locals = functionPg!.getLocals(); // check vreg let extectedVRegTypePair = [ diff --git a/ts2panda/tests/types/primitives.test.ts b/ts2panda/tests/types/primitives.test.ts index 0f726cd7fc..3603a83536 100644 --- a/ts2panda/tests/types/primitives.test.ts +++ b/ts2panda/tests/types/primitives.test.ts @@ -30,7 +30,7 @@ describe("primitives tests in primitives.test.ts", function() { it("test primitives in block", function() { let fileNames = 'tests/types/primitives/primitives_in_block.ts'; let result = compileTsWithType(fileNames); - let functionPg = result.snippetCompiler.getPandaGenByName("func_main_0"); + let functionPg = result.snippetCompiler.getPandaGenByName("UnitTest.func_main_0"); let locals = functionPg!.getLocals(); // check vreg let extectedVRegTypePair = [ @@ -59,18 +59,18 @@ describe("primitives tests in primitives.test.ts", function() { it("test number in function", function() { let fileNames = 'tests/types/primitives/primitives_in_function.ts'; let result = compileTsWithType(fileNames); - let functionPg = result.snippetCompiler.getPandaGenByName("numberFunc"); + let functionPg = result.snippetCompiler.getPandaGenByName("UnitTest.numberFunc"); let locals = functionPg!.getLocals(); // check vreg let extectedVRegTypePair = [ - ["#0#input", 1], - ["#1#num", 1], - ["#2#bool", 2], - ["#3#str", 4], - ["#4#sym", 5], - ["#5#nu", 6], - ["#6#und", 7], - ["#7#vd", 3], + ["#3#input", 1], + ["#4#num", 1], + ["#5#bool", 2], + ["#6#str", 4], + ["#7#sym", 5], + ["#8#nu", 6], + ["#9#und", 7], + ["#10#vd", 3], ] let vreg2TypeMap = createVRegTypePair(extectedVRegTypePair); expect(compareVReg2Type(vreg2TypeMap, locals), "check vreg typeInfo").to.be.true; @@ -99,7 +99,7 @@ describe("primitives tests in primitives.test.ts", function() { it("test primitives in for", function() { let fileNames = 'tests/types/primitives/primitives_in_for.ts'; let result = compileTsWithType(fileNames); - let functionPg = result.snippetCompiler.getPandaGenByName("func_main_0"); + let functionPg = result.snippetCompiler.getPandaGenByName("UnitTest.func_main_0"); let locals = functionPg!.getLocals(); // check vreg let extectedVRegTypePair = [ @@ -129,7 +129,7 @@ describe("primitives tests in primitives.test.ts", function() { it("test primitives in if", function() { let fileNames = 'tests/types/primitives/primitives_in_if.ts'; let result = compileTsWithType(fileNames); - let functionPg = result.snippetCompiler.getPandaGenByName("func_main_0"); + let functionPg = result.snippetCompiler.getPandaGenByName("UnitTest.func_main_0"); let locals = functionPg!.getLocals(); // check vreg let extectedVRegTypePair = [ @@ -158,7 +158,7 @@ describe("primitives tests in primitives.test.ts", function() { it("test primitives in class", function() { let fileNames = 'tests/types/primitives/primitives_in_class.ts'; let result = compileTsWithType(fileNames); - let functionPg = result.snippetCompiler.getPandaGenByName("func_main_0"); + let functionPg = result.snippetCompiler.getPandaGenByName("UnitTest.func_main_0"); let locals = functionPg!.getLocals(); // check vreg let extectedVRegTypePair = [ @@ -196,7 +196,7 @@ describe("primitives tests in primitives.test.ts", function() { it("test primitives with only type annotations", function() { let fileNames = 'tests/types/primitives/primitives_only_type_annotation.ts'; let result = compileTsWithType(fileNames); - let functionPg = result.snippetCompiler.getPandaGenByName("func_main_0"); + let functionPg = result.snippetCompiler.getPandaGenByName("UnitTest.func_main_0"); let locals = functionPg!.getLocals(); // check vreg let extectedVRegTypePair = [ @@ -224,7 +224,7 @@ describe("primitives tests in primitives.test.ts", function() { it("test primitives without type annotations", function() { let fileNames = 'tests/types/primitives/primitives_no_type_annotation.ts'; let result = compileTsWithType(fileNames); - let functionPg = result.snippetCompiler.getPandaGenByName("func_main_0"); + let functionPg = result.snippetCompiler.getPandaGenByName("UnitTest.func_main_0"); let locals = functionPg!.getLocals(); // check vreg let extectedVRegTypePair = [ diff --git a/ts2panda/tests/types/union.test.ts b/ts2panda/tests/types/union.test.ts index 299d54a28b..4d97791ae0 100644 --- a/ts2panda/tests/types/union.test.ts +++ b/ts2panda/tests/types/union.test.ts @@ -30,7 +30,7 @@ describe("union tests in union.test.ts", function () { it("test union with primitives", function () { let fileNames = 'tests/types/union/union_primitives.ts'; let result = compileTsWithType(fileNames); - let functionPg = result.snippetCompiler.getPandaGenByName("func_main_0"); + let functionPg = result.snippetCompiler.getPandaGenByName("UnitTest.func_main_0"); let locals = functionPg!.getLocals(); // check vreg let extectedVRegTypePair = [ @@ -68,7 +68,7 @@ describe("union tests in union.test.ts", function () { it("test union with user defined type", function () { let fileNames = 'tests/types/union/union_userDefinedType.ts'; let result = compileTsWithType(fileNames); - let functionPg = result.snippetCompiler.getPandaGenByName("func_main_0"); + let functionPg = result.snippetCompiler.getPandaGenByName("UnitTest.func_main_0"); let locals = functionPg!.getLocals(); // check vreg let extectedVRegTypePair = [ @@ -104,7 +104,7 @@ describe("union tests in union.test.ts", function () { it("test union with multi same primitives", function () { let fileNames = 'tests/types/union/union_multi_same_primi.ts'; let result = compileTsWithType(fileNames); - let functionPg = result.snippetCompiler.getPandaGenByName("func_main_0"); + let functionPg = result.snippetCompiler.getPandaGenByName("UnitTest.func_main_0"); let locals = functionPg!.getLocals(); // check vreg let extectedVRegTypePair = [ @@ -130,7 +130,7 @@ describe("union tests in union.test.ts", function () { it("test union with multi same user defined type", function () { let fileNames = 'tests/types/union/union_multi_userDefinedType.ts'; let result = compileTsWithType(fileNames); - let functionPg = result.snippetCompiler.getPandaGenByName("func_main_0"); + let functionPg = result.snippetCompiler.getPandaGenByName("UnitTest.func_main_0"); let locals = functionPg!.getLocals(); // check vreg let extectedVRegTypePair = [ diff --git a/ts2panda/tests/utils/base.ts b/ts2panda/tests/utils/base.ts index 2d9f7ed318..49c7c5b52d 100644 --- a/ts2panda/tests/utils/base.ts +++ b/ts2panda/tests/utils/base.ts @@ -146,7 +146,7 @@ export function compileAllSnippet(snippet: string, passes?: Pass[], literalBuffe jshelpers.bindSourceFile(sourceFile, {}); CmdOptions.isWatchEvaluateExpressionMode() ? setGlobalStrict(true) : setGlobalStrict(jshelpers.isEffectiveStrictModeSourceFile(sourceFile, compileOptions)); - let compilerDriver = new CompilerDriver('UnitTest'); + let compilerDriver = new CompilerDriver('UnitTest', 'UnitTest'); if (!passes) { passes = []; @@ -166,7 +166,7 @@ export function compileMainSnippet(snippet: string, pandaGen?: PandaGen, scope?: // only return main function if (compileFunc) { compileUnits.filter((pg) => { - return (pg.internalName == "func_main_0"); + return (pg.internalName == "UnitTest.func_main_0"); }) } @@ -191,7 +191,7 @@ export function compileAfterSnippet(snippet: string, name:string, isCommonJs: bo } jshelpers.bindSourceFile(sourceFile, {}); setGlobalStrict(jshelpers.isEffectiveStrictModeSourceFile(sourceFile, compileOptions)); - let compilerDriver = new CompilerDriver('UnitTest'); + let compilerDriver = new CompilerDriver('UnitTest', 'UnitTest'); compilerDriver.setCustomPasses([]); compilerDriver.compileUnitTest(sourceFile, []); compileUnits = compilerDriver.getCompilationUnits(); @@ -228,7 +228,7 @@ export class SnippetCompiler { } getGlobalInsns(): IRNode[] { - let root = this.getPandaGenByName("func_main_0"); + let root = this.getPandaGenByName("UnitTest.func_main_0"); if (root) { return root.getInsns(); } else { @@ -237,7 +237,7 @@ export class SnippetCompiler { } getGlobalScope(): Scope | undefined { - let globalPandaGen = this.getPandaGenByName("func_main_0"); + let globalPandaGen = this.getPandaGenByName("UnitTest.func_main_0"); return globalPandaGen ? globalPandaGen.getScope()!.getNearestVariableScope() : undefined; } diff --git a/ts2panda/ts2abc/ts2abc.cpp b/ts2panda/ts2abc/ts2abc.cpp index 57c350067e..251750154d 100644 --- a/ts2panda/ts2abc/ts2abc.cpp +++ b/ts2panda/ts2abc/ts2abc.cpp @@ -58,6 +58,7 @@ constexpr std::size_t BOUND_RIGHT = 0; constexpr std::size_t LINE_NUMBER = 0; constexpr bool IS_DEFINED = true; int g_opCodeIndex = 0; +std::string g_recordName = ""; std::unordered_map g_opcodeMap = { #define OPLIST(opcode, name, optype, width, flags, def_idx, use_idxs) {g_opCodeIndex++, panda::pandasm::Opcode::opcode}, PANDA_INSTRUCTION_LIST(OPLIST) @@ -69,7 +70,6 @@ std::unordered_map g_opcodeMap = { static panda::pandasm::Record MakeRecordDefinition(const std::string &name) { auto record = panda::pandasm::Record(name, LANG_EXT); - return record; } @@ -879,35 +879,27 @@ static void GenerateESTypeAnnotationRecord(panda::pandasm::Program &prog) prog.record_table.emplace(tsTypeAnnotationRecord.name, std::move(tsTypeAnnotationRecord)); } -static void GenerateCommonJsRecord(panda::pandasm::Program &prog, bool isCommonJs) -{ - // when multi-abc file get merged, field should be inserted in abc's own record - auto commonjsRecord = panda::pandasm::Record("_CommonJsRecord", LANG_EXT); - commonjsRecord.metadata->SetAccessFlags(panda::ACC_PUBLIC); - auto isCommonJsField = panda::pandasm::Field(LANG_EXT); - isCommonJsField.name = "isCommonJs"; - isCommonJsField.type = panda::pandasm::Type("u8", 0); - isCommonJsField.metadata->SetValue(panda::pandasm::ScalarValue::Create( - static_cast(isCommonJs))); - commonjsRecord.field_list.emplace_back(std::move(isCommonJsField)); - - prog.record_table.emplace(commonjsRecord.name, std::move(commonjsRecord)); -} - -static void GenerateESModuleRecord(panda::pandasm::Program &prog) +static void SetCommonjsField(panda::pandasm::Program &prog, bool isCommonjs) { - auto ecmaModuleRecord = panda::pandasm::Record("_ESModuleRecord", LANG_EXT); - ecmaModuleRecord.metadata->SetAccessFlags(panda::ACC_PUBLIC); - prog.record_table.emplace(ecmaModuleRecord.name, std::move(ecmaModuleRecord)); + auto iter = prog.record_table.find(g_recordName); + if (iter != prog.record_table.end()) { + auto &rec = iter->second; + auto isCommonJsField = panda::pandasm::Field(LANG_EXT); + isCommonJsField.name = "isCommonjs"; + isCommonJsField.type = panda::pandasm::Type("u8", 0); + isCommonJsField.metadata->SetValue( + panda::pandasm::ScalarValue::Create(static_cast(isCommonjs))); + rec.field_list.emplace_back(std::move(isCommonJsField)); + } } static void AddModuleRecord(panda::pandasm::Program &prog, const std::string &moduleName) { - auto iter = prog.record_table.find("_ESModuleRecord"); + auto iter = prog.record_table.find(g_recordName); if (iter != prog.record_table.end()) { auto &rec = iter->second; auto moduleIdxField = panda::pandasm::Field(LANG_EXT); - moduleIdxField.name = moduleName; + moduleIdxField.name = "moduleRecordIdx"; moduleIdxField.type = panda::pandasm::Type("u32", 0); std::string moduleId = GetLiteralId(g_newLiteralArrayIndex); moduleIdxField.metadata->SetValue( @@ -937,23 +929,11 @@ int ParseJson(const std::string &data, Json::Value &rootValue) return RETURN_SUCCESS; } -static void ParseModuleMode(const Json::Value &rootValue, panda::pandasm::Program &prog) -{ - Logd("----------------parse module_mode-----------------"); - if (rootValue.isMember("module_mode") && rootValue["module_mode"].isBool()) { - if (rootValue["module_mode"].asBool()) { - GenerateESModuleRecord(prog); - } - } -} - -static void ParseCommonJsModuleMode(const Json::Value &rootValue, panda::pandasm::Program &prog) +static void SetCommonJsModuleMode(const Json::Value &rootValue, panda::pandasm::Program &prog) { Logd("------------parse commonjs_module_mode-------------"); if (rootValue.isMember("commonjs_module") && rootValue["commonjs_module"].isBool()) { - if (rootValue["commonjs_module"].asBool()) { - GenerateCommonJsRecord(prog, true); - } + SetCommonjsField(prog, rootValue["commonjs_module"].asBool()); } } @@ -1037,8 +1017,7 @@ static void ParseOptions(const Json::Value &rootValue, panda::pandasm::Program & { GenerateESCallTypeAnnotationRecord(prog); GenerateESTypeAnnotationRecord(prog); - ParseModuleMode(rootValue, prog); - ParseCommonJsModuleMode(rootValue, prog); + SetCommonJsModuleMode(rootValue, prog); ParseLogEnable(rootValue); ParseDebugMode(rootValue); ParseOptLevel(rootValue); @@ -1055,9 +1034,10 @@ static void ParseSingleFunc(const Json::Value &rootValue, panda::pandasm::Progra prog.function_table.emplace(function.name.c_str(), std::move(function)); } -static void ParseSingleRec(const Json::Value &rootValue, panda::pandasm::Program &prog) +static void ParseRec(const Json::Value &rootValue, panda::pandasm::Program &prog) { auto record = ParseRecord(rootValue["rb"]); + g_recordName = record.name; prog.record_table.emplace(record.name.c_str(), std::move(record)); } @@ -1255,7 +1235,7 @@ static int ParseSmallPieceJson(const std::string &subJson, panda::pandasm::Progr } case static_cast(JsonType::RECORD): { if (rootValue.isMember("rb") && rootValue["rb"].isObject()) { - ParseSingleRec(rootValue, prog); + ParseRec(rootValue, prog); } break; } diff --git a/ts2panda/ts2abc/ts2abc_options.h b/ts2panda/ts2abc/ts2abc_options.h index 76f326fe25..03d56e78e9 100755 --- a/ts2panda/ts2abc/ts2abc_options.h +++ b/ts2panda/ts2abc/ts2abc_options.h @@ -224,7 +224,7 @@ namespace panda::ts2abc { panda::PandArg compile_by_pipe_arg_{ "compile-by-pipe", false, R"(Compile a json file that is passed by pipe)"}; panda::PandArg compiler_output_proto_{ "output-proto", "", - R"(compiler proto serialize binary output (.proto))"}; + R"(Specify the output name for serializd protobuf file (.protoBin))"}; panda::PandArg Tail_Arg1_arg_{ "ARG_1", "", R"(Path to input(json file) or path to output(ark bytecode)" " when 'compile-by-pipe' enabled)"}; -- Gitee From ebefdabcd6e4f499c27a83610d19cf65efd14f98 Mon Sep 17 00:00:00 2001 From: zhangrengao Date: Thu, 20 Oct 2022 14:38:22 +0800 Subject: [PATCH 3/7] Remove call type optimization of ts file Signed-off-by: zhangrengao Change-Id: Ic8f8af8eacdcfc275e6f6565131fdbd2fd0c1835 --- ts2panda/src/compiler.ts | 67 ------------------ ts2panda/src/compilerDriver.ts | 1 + ts2panda/src/expression/metaProperty.ts | 2 - ts2panda/src/lexenv.ts | 6 -- ts2panda/src/scope.ts | 21 ------ ts2panda/src/statement/classStatement.ts | 6 -- ts2panda/ts2abc/ts2abc.cpp | 86 +++++++++--------------- 7 files changed, 33 insertions(+), 156 deletions(-) diff --git a/ts2panda/src/compiler.ts b/ts2panda/src/compiler.ts index d15844a000..a4027cacb9 100644 --- a/ts2panda/src/compiler.ts +++ b/ts2panda/src/compiler.ts @@ -164,7 +164,6 @@ export class Compiler { this.compileSourceFileOrBlock(this.rootNode); } else { this.compileFunctionLikeDeclaration(this.rootNode); - this.callOpt(); } } @@ -180,57 +179,6 @@ export class Compiler { return this.envUnion[this.envUnion.length - 1]; } - private callOpt() { - if (CmdOptions.isDebugMode()) { - return; - } - let CallMap: Map = new Map([ - ["this", 1], - ["4newTarget", 2], - ["0newTarget", 2], - ["argumentsOrRestargs", 4], - ["4funcObj", 8] - ]); - let callType = 0; - let scope = this.pandaGen.getScope(); - - if (scope instanceof FunctionScope) { - let tempLocals: VReg[] = []; - let tempNames: Set = new Set(); - let count = 0; - // 4funcObj/newTarget/this - for (let i = 0; i < 3; i++) { - if (scope.getCallOpt().has(scope.getParameters()[i].getName())) { - tempLocals.push(this.pandaGen.getLocals()[i]); - callType += CallMap.get(scope.getParameters()[i].getName()) ?? 0; - } else { - tempNames.add(scope.getParameters()[i].getName()); - count++; - } - } - // actual parameters - for (let i = 3; i < this.pandaGen.getLocals().length; i++) { - tempLocals.push(this.pandaGen.getLocals()[i]); - } - let name2variable = scope.getName2variable(); - // @ts-ignore - name2variable.forEach((value, key) => { - if (tempNames.has(key)) { - name2variable.delete(key) - } - }) - - this.pandaGen.setLocals(tempLocals); - this.pandaGen.setParametersCount(this.pandaGen.getParametersCount() - count); - - if (scope.getArgumentsOrRestargs()) { - callType += CallMap.get("argumentsOrRestargs") ?? 0; - } - - this.pandaGen.setCallType(callType); - } - } - private storeFuncObj2LexEnvIfNeeded() { let rootNode = this.rootNode; if (!ts.isFunctionExpression(rootNode) && !ts.isMethodDeclaration(rootNode)) { @@ -288,9 +236,6 @@ export class Compiler { pandaGen.getVregForVariable(variableInfo.v)); } else { if (v && v.isLexVar) { - if ((arg === "this" || arg === "4newTarget") && variableInfo.scope instanceof FunctionScope) { - variableInfo.scope.setCallOpt(arg); - } if (arg === "arguments" && variableInfo.scope instanceof FunctionScope) { variableInfo.scope.setArgumentsOrRestargs(); } @@ -1062,8 +1007,6 @@ export class Compiler { let { scope, level, v } = this.scope.find("this"); - this.setCallOpt(scope, "this") - if (!v) { throw new Error("\"this\" not found"); } @@ -1467,8 +1410,6 @@ export class Compiler { let level = thisInfo.level; let v = thisInfo.v; - this.setCallOpt(scope, "this") - if (scope && level >= 0) { let needSetLexVar: boolean = false; while (curScope != scope) { @@ -1497,8 +1438,6 @@ export class Compiler { let pandaGen = this.pandaGen; let thisInfo = this.getCurrentScope().find("this"); - this.setCallOpt(thisInfo.scope, "this") - if (thisInfo.v!.isLexVar) { let slot = (thisInfo.v).idxLex; let value = pandaGen.getTemp(); @@ -1510,12 +1449,6 @@ export class Compiler { } } - setCallOpt(scope: Scope | undefined, callOptStr: String) { - if (scope instanceof FunctionScope) { - scope.setCallOpt(callOptStr); - } - } - getPandaGen() { return this.pandaGen; } diff --git a/ts2panda/src/compilerDriver.ts b/ts2panda/src/compilerDriver.ts index 2897861533..ce216975fb 100644 --- a/ts2panda/src/compilerDriver.ts +++ b/ts2panda/src/compilerDriver.ts @@ -186,6 +186,7 @@ export class CompilerDriver { listenErrorEvent(ts2abcProc); try { + // must keep [dumpRecord] at first Ts2Panda.dumpRecord(ts2abcProc, this.recordName); Ts2Panda.dumpCmdOptions(ts2abcProc); Ts2Panda.dumpRecordName(ts2abcProc, getRecordName(CompilerDriver.srcNode)); diff --git a/ts2panda/src/expression/metaProperty.ts b/ts2panda/src/expression/metaProperty.ts index eadef5cdee..de0500b305 100644 --- a/ts2panda/src/expression/metaProperty.ts +++ b/ts2panda/src/expression/metaProperty.ts @@ -23,8 +23,6 @@ export function compileMetaProperty(expr: ts.MetaProperty, compiler: Compiler) { if (id == "target") { let { scope, level, v } = curScope.find("4newTarget"); - compiler.setCallOpt(scope, "4newTarget"); - if (!v) { throw new Error("fail to access new.target"); } else { diff --git a/ts2panda/src/lexenv.ts b/ts2panda/src/lexenv.ts index ee896e07f6..aba261946a 100644 --- a/ts2panda/src/lexenv.ts +++ b/ts2panda/src/lexenv.ts @@ -91,9 +91,6 @@ export class VariableAccessLoad extends VariableAccessBase { pandaGen.freeTemps(holeReg); return insns; } - if (v.getName() === "4funcObj") { - this.scope.setCallOpt("4funcObj") - } insns.push(loadAccumulator(bindVreg)); return insns; @@ -160,9 +157,6 @@ export class VariableAcessStore extends VariableAccessBase { checkConstAssignment(pandaGen, v, insns, this.node); } - if (v.getName() === "4funcObj") { - this.scope.setCallOpt("4funcObj") - } insns.push(storeAccumulator(bindVreg)); return insns; diff --git a/ts2panda/src/scope.ts b/ts2panda/src/scope.ts index 3c8b01a1c5..637dc19b6c 100644 --- a/ts2panda/src/scope.ts +++ b/ts2panda/src/scope.ts @@ -94,7 +94,6 @@ export abstract class Scope { // for debuginfo protected startInsIdx: number | undefined; protected endInsIdx: number | undefined; - private callOpt: Set = new Set(); private isArgumentsOrRestargs: boolean = false; constructor() { } @@ -259,26 +258,6 @@ export abstract class Scope { return this.decls; } - public getCallOpt() { - return this.callOpt; - } - - public setCallOpt(key: String) { - if (this instanceof FunctionScope) { - this.callOpt.add(key); - } else { - let parent = this.parent; - while (parent != undefined) { - if (parent instanceof FunctionScope) { - parent.callOpt.add(key); - break; - } else { - parent = parent.parent; - } - } - } - } - public setArgumentsOrRestargs() { this.isArgumentsOrRestargs = true; } diff --git a/ts2panda/src/statement/classStatement.ts b/ts2panda/src/statement/classStatement.ts index 56a29cbcae..3b4368dbcf 100644 --- a/ts2panda/src/statement/classStatement.ts +++ b/ts2panda/src/statement/classStatement.ts @@ -364,9 +364,6 @@ export function compileSuperCall(compiler: Compiler, node: ts.CallExpression, ar let curScope = compiler.getCurrentScope(); let { scope, level, v } = curScope.find("this"); - compiler.setCallOpt(scope, "this"); - compiler.setCallOpt(scope, "4newTarget"); - if (scope && level >= 0) { let tmpScope = curScope; let needSetLexVar: boolean = false; @@ -381,9 +378,6 @@ export function compileSuperCall(compiler: Compiler, node: ts.CallExpression, ar if (needSetLexVar) { scope.setLexVar(v, curScope); } - if (needSetLexVar && curScope instanceof FunctionScope) { - curScope.setCallOpt("0newTarget"); - } } if (hasSpread) { diff --git a/ts2panda/ts2abc/ts2abc.cpp b/ts2panda/ts2abc/ts2abc.cpp index 251750154d..1cba8c9cb7 100644 --- a/ts2panda/ts2abc/ts2abc.cpp +++ b/ts2panda/ts2abc/ts2abc.cpp @@ -177,6 +177,11 @@ static std::string GetLiteralId(int64_t index) return g_recordName + "_" + std::to_string(index); } +static bool IsFuncMain0(std::string funcName) { + std::string expectedName = g_recordName + ".func_main_0"; + return funcName == expectedName; +} + static std::string ParseUnicodeEscapeString(const std::string &data) { const int unicodeEscapeSymbolLen = 2; @@ -591,34 +596,6 @@ static void ParseFunctionCatchTables(const Json::Value &function, panda::pandasm } } -static void ParseFunctionCallType(const Json::Value &function, panda::pandasm::Function &pandaFunc) -{ - if (g_debugModeEnabled) { - return; - } - - std::string funcName = ""; - if (function.isMember("n") && function["n"].isString()) { - funcName = function["n"].asString(); - } - if (funcName == "func_main_0") { - return; - } - - uint32_t callType = 0; - if (function.isMember("ct") && function["ct"].isInt()) { - callType = function["ct"].asUInt(); - } - panda::pandasm::AnnotationData callTypeAnnotation("_ESCallTypeAnnotation"); - std::string annotationName = "callType"; - panda::pandasm::AnnotationElement callTypeAnnotationElement( - annotationName, std::make_unique( - panda::pandasm::ScalarValue::Create(callType))); - callTypeAnnotation.AddElement(std::move(callTypeAnnotationElement)); - const_cast&>( - pandaFunc.metadata->GetAnnotations()).push_back(std::move(callTypeAnnotation)); -} - static std::vector> GetInstTypeMap(const Json::Value &function, panda::pandasm::Function &pandaFunc) { @@ -778,7 +755,7 @@ static void ParseFunctionExportedType(const Json::Value &function, panda::pandas std::string funcName = ""; if (function.isMember("n") && function["n"].isString()) { funcName = function["n"].asString(); - if (funcName != "func_main_0") { + if (!IsFuncMain0(funcName)) { return; } } @@ -805,7 +782,7 @@ static void ParseFunctionDeclaredType(const Json::Value &function, panda::pandas std::string funcName = ""; if (function.isMember("n") && function["n"].isString()) { funcName = function["n"].asString(); - if (funcName != "func_main_0") { + if (!IsFuncMain0(funcName)) { return; } } @@ -857,7 +834,7 @@ static panda::pandasm::Function ParseFunction(const Json::Value &function, panda ParseFunctionKind(function, pandaFunc); ParseFunctionIcSize(function, pandaFunc); - if (g_isDtsFile && pandaFunc.name != "func_main_0") { + if (g_isDtsFile && !IsFuncMain0(pandaFunc.name)) { pandaFunc.metadata->SetAttribute("external"); } @@ -1190,29 +1167,30 @@ static void ParseSingleModule(const Json::Value &rootValue, panda::pandasm::Prog static void ParseSingleTypeInfo(const Json::Value &rootValue, panda::pandasm::Program &prog) { - auto typeInfoRecord = rootValue["ti"]; - auto typeFlag = typeInfoRecord["tf"].asBool(); - auto typeSummaryIndex = typeInfoRecord["tsi"].asString(); - auto ecmaTypeInfoRecord = panda::pandasm::Record("_ESTypeInfoRecord", LANG_EXT); - ecmaTypeInfoRecord.metadata->SetAccessFlags(panda::ACC_PUBLIC); - - auto typeFlagField = panda::pandasm::Field(LANG_EXT); - typeFlagField.name = "typeFlag"; - typeFlagField.type = panda::pandasm::Type("u8", 0); - typeFlagField.metadata->SetValue(panda::pandasm::ScalarValue::Create( - static_cast(typeFlag))); - ecmaTypeInfoRecord.field_list.emplace_back(std::move(typeFlagField)); - - if (g_enableTypeinfo) { - auto typeSummaryIndexField = panda::pandasm::Field(LANG_EXT); - typeSummaryIndexField.name = "typeSummaryOffset"; - typeSummaryIndexField.type = panda::pandasm::Type("u32", 0); - typeSummaryIndexField.metadata->SetValue( - panda::pandasm::ScalarValue::Create(typeSummaryIndex)); - ecmaTypeInfoRecord.field_list.emplace_back(std::move(typeSummaryIndexField)); - } - - prog.record_table.emplace(ecmaTypeInfoRecord.name, std::move(ecmaTypeInfoRecord)); + auto iter = prog.record_table.find(g_recordName); + if (iter != prog.record_table.end()) { + auto &rec = iter->second; + + auto typeInfoRecord = rootValue["ti"]; + auto typeFlag = typeInfoRecord["tf"].asBool(); + auto typeSummaryIndex = typeInfoRecord["tsi"].asUInt(); + + auto typeFlagField = panda::pandasm::Field(LANG_EXT); + typeFlagField.name = "typeFlag"; + typeFlagField.type = panda::pandasm::Type("u8", 0); + typeFlagField.metadata->SetValue(panda::pandasm::ScalarValue::Create( + static_cast(typeFlag))); + rec.field_list.emplace_back(std::move(typeFlagField)); + + if (g_enableTypeinfo) { + auto typeSummaryIndexField = panda::pandasm::Field(LANG_EXT); + typeSummaryIndexField.name = "typeSummaryOffset"; + typeSummaryIndexField.type = panda::pandasm::Type("u32", 0); + typeSummaryIndexField.metadata->SetValue( + panda::pandasm::ScalarValue::Create(typeSummaryIndex)); + rec.field_list.emplace_back(std::move(typeSummaryIndexField)); + } + } } static int ParseSmallPieceJson(const std::string &subJson, panda::pandasm::Program &prog) -- Gitee From 80c1943e82ed2f44a157f28dd9164a11b4cfcc3e Mon Sep 17 00:00:00 2001 From: gavin1012_hw Date: Mon, 26 Sep 2022 10:22:31 +0800 Subject: [PATCH 4/7] Support ts2abc && es2abc && aot test262 cases in merged style Signed-off-by: gavin1012_hw Change-Id: I4e750e9ad20d9a0ea10c585176e3fe6145449f39 --- merge_abc/src/options.h | 2 +- test262/run_sunspider.py | 96 +++++++++++++------ ts2panda/src/base/bcGenUtil.ts | 9 +- ts2panda/src/base/lexEnv.ts | 6 +- ts2panda/src/base/util.ts | 24 ++++- ts2panda/src/cmdOptions.ts | 15 ++- ts2panda/src/compilerDriver.ts | 1 - ts2panda/src/index.ts | 43 +++------ ts2panda/src/pandagen.ts | 15 ++- ts2panda/src/pandasm.ts | 2 - ts2panda/src/ts2panda.ts | 14 --- ts2panda/tests/esmodule.test.ts | 3 +- ts2panda/tests/expression/call.test.ts | 4 +- ts2panda/tests/expression/commalist.test.ts | 4 +- ts2panda/tests/expression/literal.test.ts | 27 ++++-- ts2panda/tests/statements/switch.test.ts | 2 +- ts2panda/tests/types/array.test.ts | 24 ++--- ts2panda/tests/types/class.test.ts | 52 +++++----- ts2panda/tests/types/function.test.ts | 18 ++-- ts2panda/tests/types/object.test.ts | 8 +- ts2panda/tests/types/primitives.test.ts | 6 +- ts2panda/tests/types/union.test.ts | 16 ++-- ts2panda/tests/utils/base.ts | 2 + .../tests/watch_expression/addWatch.test.ts | 6 +- ts2panda/ts2abc/main.cpp | 32 +++++++ ts2panda/ts2abc/ts2abc.cpp | 70 ++++++++++++-- ts2panda/ts2abc/ts2abc.h | 1 + ts2panda/ts2abc/ts2abc_options.h | 44 ++++++++- 28 files changed, 359 insertions(+), 187 deletions(-) diff --git a/merge_abc/src/options.h b/merge_abc/src/options.h index e1c76e1702..8475ab1d20 100644 --- a/merge_abc/src/options.h +++ b/merge_abc/src/options.h @@ -58,7 +58,7 @@ public: private: panda::PandArgParser *argparser_; std::string errorMsg_; - std::string protoBinSuffix_ {"bin"}; + std::string protoBinSuffix_ {"protoBin"}; std::string protoPathInput_; std::string outputFileName_ {"modules.abc"}; std::string outputFilePath_; diff --git a/test262/run_sunspider.py b/test262/run_sunspider.py index 30dbaca4bd..cc3b9bd3b4 100755 --- a/test262/run_sunspider.py +++ b/test262/run_sunspider.py @@ -97,6 +97,7 @@ ARK_AOT_TOOL = DEFAULT_ARK_AOT_TOOL ARK_FRONTEND = DEFAULT_ARK_FRONTEND ARK_FRONTEND_BINARY = DEFAULT_ARK_FRONTEND_BINARY ARK_ARCH = DEFAULT_ARK_ARCH +PROTO_BIN_SUFFIX = "protoBin" def output(retcode, msg): @@ -230,77 +231,114 @@ class ArkProgram(): output_file = os.path.splitext(os.path.join(BASE_OUT_DIR, os.path.split(dependency)[1]))[0] output_abc = f"{output_file}.abc" - proto_bin_file = f"{output_file}.bin" - output_abc_name = os.path.basename(output_abc) - frontend_tool = self.ark_frontend_binary merge_abc_binary = self.args.merge_abc_binary merge_abc_mode = self.merge_abc_mode if merge_abc_mode != "0": + proto_bin_file = output_file + "." + PROTO_BIN_SUFFIX cmd_args = [frontend_tool, dependency, '--outputProto', proto_bin_file, '--module', '--merge-abc'] - proc = subprocess.call(cmd_args) - cmd_args = [merge_abc_binary, '--input', proto_bin_file, '--suffix', - "bin", '--outputFilePath', BASE_OUT_DIR, '--output', - output_abc_name] else: cmd_args = [frontend_tool, dependency, '--output', output_abc, '--module', '--merge-abc'] proc = subprocess.Popen(cmd_args) proc.wait() + def gen_merged_abc(self, dependencies, file_name_pre, proto_bin_file, retcode): + merge_abc_binary = self.args.merge_abc_binary + file_dir = os.path.split(self.js_file)[0] + proto_abc_file = ".".join([os.path.splitext(os.path.basename(self.js_file))[0], "abc"]) + generate_merged_abc = True + # collect protoBin file into new-made testcase dir + if (len(dependencies) != 0): + if os.path.exists(file_name_pre): + subprocess.run(['rm', '-rf', file_name_pre]) + subprocess.run(['mkdir', file_name_pre]) + + for dependency in list(set(dependencies)): + dependency_file_prefix = os.path.basename(dependency)[:-3] + dependency_bin_file = file_dir + "/" + \ + ".".join([dependency_file_prefix, + PROTO_BIN_SUFFIX]) + # test262 report syntax error cases + if not os.path.exists(dependency_bin_file): + generate_merged_abc = False + else: + subprocess.run(['cp', dependency_bin_file, file_name_pre]) + + if not os.path.exists(proto_bin_file): + generate_merged_abc = False + else: + subprocess.run(['cp', proto_bin_file, file_name_pre]) + + if (len(dependencies) != 0) and generate_merged_abc: + # module test262 cases + cmd_args = [merge_abc_binary, '--input', file_name_pre, + '--suffix', PROTO_BIN_SUFFIX, '--outputFilePath', + file_dir, '--output', proto_abc_file] + self.abc_file = f'{file_name_pre}.abc' + retcode = exec_command(cmd_args) + elif os.path.exists(proto_bin_file): + cmd_args = [merge_abc_binary, '--input', proto_bin_file, + '--suffix', PROTO_BIN_SUFFIX, '--outputFilePath', + file_dir, '--output', proto_abc_file] + self.abc_file = f'{file_name_pre}.abc' + retcode = exec_command(cmd_args) + return retcode + def gen_abc(self): js_file = self.js_file file_name_pre = os.path.splitext(js_file)[0] file_name = os.path.basename(js_file) - file_dir = os.path.split(js_file)[0] out_file = f"{file_name_pre}.abc" - proto_bin_file = f"{file_name_pre}.bin" - proto_abc_file = ".".join([os.path.splitext(file_name)[0], "abc"]) + proto_bin_file = file_name_pre + "." + PROTO_BIN_SUFFIX self.abc_file = out_file mod_opt_index = 0 cmd_args = [] + dependency_cmd_args= [] frontend_tool = self.ark_frontend_binary - merge_abc_binary = self.args.merge_abc_binary merge_abc_mode = self.merge_abc_mode + dependencies = [] # pre-generate the dependencies' abc when ark_frontend is [es2panda] - if (file_name in self.module_list or file_name in self.dynamicImport_list) and \ - self.ark_frontend == ARK_FRONTEND_LIST[1]: + if (file_name in self.module_list or file_name in self.dynamicImport_list): search_dir = "language/module-code" if file_name in self.module_list \ else "language/expressions/dynamic-import" dependencies = collect_module_dependencies(js_file, os.path.join(TEST_FULL_DIR, search_dir), []) - for dependency in list(set(dependencies)): - self.gen_dependency_abc(dependency) + if (self.ark_frontend == ARK_FRONTEND_LIST[1]): + for dependency in list(set(dependencies)): + self.gen_dependency_abc(dependency) if self.ark_frontend == ARK_FRONTEND_LIST[0]: mod_opt_index = 3 if merge_abc_mode != "0": - # '--opt-level=0' is added due to failure in optimizer, should be removed later cmd_args = ['node', '--expose-gc', frontend_tool, js_file, - '--output-proto', proto_bin_file, '--opt-level=0'] + '--output-proto', '--merge-abc'] else: cmd_args = ['node', '--expose-gc', frontend_tool, - js_file, '-o', out_file] + js_file, '-o', out_file, '--merge-abc'] if file_name in self.module_list: cmd_args.insert(mod_opt_index, "-m") self.module = True elif self.ark_frontend == ARK_FRONTEND_LIST[1]: mod_opt_index = 1 if merge_abc_mode != "0": - cmd_args = [frontend_tool, '--outputProto', + # '--merge-abc' is added due to 'merge-abc' is not opened as default in es2abc, should be removed later + cmd_args = [frontend_tool, '--function-threads=' + + str(self.es2abc_thread_count), '--outputProto', proto_bin_file, js_file, '--merge-abc'] else: + # '--merge-abc' should be removed when record-name is set as default in es2panda cmd_args = [frontend_tool, '--opt-level=' + str(self.opt_level), '--function-threads=' + str(self.es2abc_thread_count), '--output', - out_file, js_file] + out_file, js_file, '--merge-abc'] if file_name in self.module_list: cmd_args.insert(mod_opt_index, "--module") self.module = True # get abc file list from import statement - if self.ark_aot and self.module: + if merge_abc_mode == "0" and self.ark_aot and self.module: self.abc_file = os.path.abspath(out_file) js_dir = os.path.dirname(js_file) for line in fileinput.input(js_file): @@ -312,15 +350,14 @@ class ArkProgram(): abc_file = os.path.abspath(f'{js_dir}/{abc_file}') if self.abc_file.find(abc_file) < 0: self.abc_file += f':{abc_file}' + + retcode = exec_command(cmd_args) self.abc_cmd = cmd_args + if merge_abc_mode != "0": - proc = subprocess.call(cmd_args) - cmd_args = [merge_abc_binary, '--input', proto_bin_file, - '--suffix', "bin", '--outputFilePath', - file_dir, '--output', proto_abc_file] - retcode = exec_command(cmd_args) - else: - retcode = exec_command(cmd_args) + retcode = self.gen_merged_abc(dependencies, file_name_pre, + proto_bin_file, retcode) + return retcode def compile_aot(self): @@ -356,7 +393,6 @@ class ArkProgram(): qemu_arg2 = self.arch_root cmd_args = [qemu_tool, qemu_arg1, qemu_arg2, self.ark_tool, ICU_PATH, - '--asm-interpreter=1', f'--aot-file={file_name_pre}', f'{file_name_pre}.abc'] elif self.arch == ARK_ARCH_LIST[2]: @@ -365,12 +401,10 @@ class ArkProgram(): qemu_arg2 = self.arch_root cmd_args = [qemu_tool, qemu_arg1, qemu_arg2, self.ark_tool, ICU_PATH, - '--asm-interpreter=1', f'--aot-file={file_name_pre}', f'{file_name_pre}.abc'] elif self.arch == ARK_ARCH_LIST[0]: cmd_args = [self.ark_tool, ICU_PATH, - '--asm-interpreter=1', f'--aot-file={file_name_pre}', f'{file_name_pre}.abc'] diff --git a/ts2panda/src/base/bcGenUtil.ts b/ts2panda/src/base/bcGenUtil.ts index 4be0a9afa6..7f87a6533d 100644 --- a/ts2panda/src/base/bcGenUtil.ts +++ b/ts2panda/src/base/bcGenUtil.ts @@ -177,14 +177,13 @@ export function throwDeleteSuperProperty() { return new ThrowDeletesuperproperty(); } -export function newLexicalEnv(numVars: number, scopeInfoIdx: number | undefined) { - if (scopeInfoIdx == undefined) { +export function newLexicalEnv(numVars: number, scopeInfoId: string | undefined) { + if (scopeInfoId == undefined) { return numVars <= MAX_INT8 ? new Newlexenv(new Imm(numVars)) : new WideNewlexenv(new Imm(numVars)); } - let litId: string = scopeInfoIdx.toString() - return numVars <= MAX_INT8 ? new Newlexenvwithname(new Imm(numVars), litId) : - new WideNewlexenvwithname(new Imm(numVars), litId); + return numVars <= MAX_INT8 ? new Newlexenvwithname(new Imm(numVars), scopeInfoId) : + new WideNewlexenvwithname(new Imm(numVars), scopeInfoId); } export function popLexicalEnv() { diff --git a/ts2panda/src/base/lexEnv.ts b/ts2panda/src/base/lexEnv.ts index a6e91703c4..5393dbd8b1 100644 --- a/ts2panda/src/base/lexEnv.ts +++ b/ts2panda/src/base/lexEnv.ts @@ -28,14 +28,14 @@ import { CacheList, getVregisterCache } from "./vregisterCache"; function createLexEnv(pandaGen: PandaGen, scope: VariableScope): IRNode[] { let lexEnvVars = scope.getNumLexEnv(); let insns: IRNode[] = []; - let scopeInfoIdx: number | undefined = undefined; + let scopeInfoId: string | undefined = undefined; let lexVarInfo = scope.getLexVarInfo(); if (CmdOptions.isDebugMode()) { - scopeInfoIdx = pandaGen.appendScopeInfo(lexVarInfo); + scopeInfoId = pandaGen.appendScopeInfo(lexVarInfo); } insns.push( - newLexicalEnv(lexEnvVars, scopeInfoIdx), + newLexicalEnv(lexEnvVars, scopeInfoId), storeAccumulator(getVregisterCache(pandaGen, CacheList.LexEnv)) ); diff --git a/ts2panda/src/base/util.ts b/ts2panda/src/base/util.ts index 9b60cb6d45..25bf68deee 100644 --- a/ts2panda/src/base/util.ts +++ b/ts2panda/src/base/util.ts @@ -392,8 +392,30 @@ export function hasAbstractModifier(node: ts.Node): boolean { export const MAX_INT8 = 127; export const MAX_INT16 = 32767; +export function getOutputBinName(node: ts.SourceFile) { + let outputBinName = CmdOptions.getOutputBinName(); + let fileName = node.fileName.substring(0, node.fileName.lastIndexOf('.')); + let inputFileName = CmdOptions.getInputFileName(); + if (/^win/.test(require('os').platform())) { + var inputFileTmps = inputFileName.split(path.sep); + inputFileName = path.posix.join(...inputFileTmps); + } + + if (fileName != inputFileName) { + outputBinName = fileName + ".abc"; + } + return outputBinName; +} + export function getRecordName(node: ts.SourceFile): string { - return ""; // need to be fixed later + let recordName = CmdOptions.getRecordName(); + + if (recordName == "") { + let outputBinName = getOutputBinName(node); + recordName = path.basename(outputBinName, path.extname(outputBinName)); + } + + return recordName; } export function getLiteralKey(node: ts.SourceFile, idx:number): string { diff --git a/ts2panda/src/cmdOptions.ts b/ts2panda/src/cmdOptions.ts index 94b151eaff..b746fdf986 100644 --- a/ts2panda/src/cmdOptions.ts +++ b/ts2panda/src/cmdOptions.ts @@ -52,7 +52,8 @@ const ts2pandaOptions = [ { name: 'source-file', type: String, defaultValue: "", description: "specify the file path info recorded in generated abc" }, { name: 'generate-tmp-file', type: Boolean, defaultValue: false, description: "whether to generate intermediate temporary files"}, { name: 'record-name', type: String, defaultValue: "", description: "specify the record name." }, - { name: 'output-proto', type: String, defaultValue: "", description: "specify the output name for serializd protobuf file (.protoBin)" }, + { name: 'output-proto', type: Boolean, defaultValue: false, description: "Output protoBin file. Default: false" }, + { name: 'proto-name', type: String, defaultValue: "", description: "specify the output name for serializd protobuf file (.protoBin)" }, ] @@ -324,10 +325,20 @@ export class CmdOptions { return this.options["generate-tmp-file"]; } - static getOutputproto(): string { + static isOutputproto(): boolean { + if (!this.options) { + return false; + } return this.options["output-proto"]; } + static getProtoName(): string { + if (!this.options) { + return ""; + } + return this.options["proto-name"]; + } + // @ts-ignore static parseUserCmd(args: string[]): ts.ParsedCommandLine | undefined { this.options = commandLineArgs(ts2pandaOptions, { partial: true }); diff --git a/ts2panda/src/compilerDriver.ts b/ts2panda/src/compilerDriver.ts index ce216975fb..00164490d6 100644 --- a/ts2panda/src/compilerDriver.ts +++ b/ts2panda/src/compilerDriver.ts @@ -189,7 +189,6 @@ export class CompilerDriver { // must keep [dumpRecord] at first Ts2Panda.dumpRecord(ts2abcProc, this.recordName); Ts2Panda.dumpCmdOptions(ts2abcProc); - Ts2Panda.dumpRecordName(ts2abcProc, getRecordName(CompilerDriver.srcNode)); for (let i = 0; i < this.pendingCompilationUnits.length; i++) { let unit: PendingCompilationUnit = this.pendingCompilationUnits[i]; diff --git a/ts2panda/src/index.ts b/ts2panda/src/index.ts index 26eb031a6d..61f2dbfed0 100644 --- a/ts2panda/src/index.ts +++ b/ts2panda/src/index.ts @@ -21,10 +21,19 @@ import { CompilerDriver } from "./compilerDriver"; import * as diag from "./diagnostic"; import * as jshelpers from "./jshelpers"; import { LOGE } from "./log"; -import { setGlobalDeclare, setGlobalStrict } from "./strictMode"; +import { + setGlobalDeclare, + setGlobalStrict +} from "./strictMode"; import { TypeChecker } from "./typeChecker"; -import { setPos, isBase64Str, transformCommonjsModule } from "./base/util"; -import { IGNORE_ERROR_CODE } from './ignoreSyntaxError' +import { IGNORE_ERROR_CODE } from './ignoreSyntaxError'; +import { + setPos, + isBase64Str, + transformCommonjsModule, + getRecordName, + getOutputBinName +} from "./base/util"; function checkIsGlobalDeclaration(sourceFile: ts.SourceFile) { for (let statement of sourceFile.statements) { @@ -46,6 +55,7 @@ function checkIsGlobalDeclaration(sourceFile: ts.SourceFile) { function generateDTs(node: ts.SourceFile, options: ts.CompilerOptions) { let outputBinName = getOutputBinName(node); let compilerDriver = new CompilerDriver(outputBinName, getRecordName(node)); + CompilerDriver.srcNode = node; setGlobalStrict(jshelpers.isEffectiveStrictModeSourceFile(node, options)); compilerDriver.compile(node); compilerDriver.showStatistics(); @@ -143,21 +153,6 @@ function main(fileNames: string[], options: ts.CompilerOptions) { }); } -function getOutputBinName(node: ts.SourceFile) { - let outputBinName = CmdOptions.getOutputBinName(); - let fileName = node.fileName.substring(0, node.fileName.lastIndexOf('.')); - let inputFileName = CmdOptions.getInputFileName(); - if (/^win/.test(require('os').platform())) { - var inputFileTmps = inputFileName.split(path.sep); - inputFileName = path.posix.join(...inputFileTmps); - } - - if (fileName != inputFileName) { - outputBinName = fileName + ".abc"; - } - return outputBinName; -} - function getDtsFiles(libDir: string): string[] { let dtsFiles:string[] = []; function finDtsFile(dir){ @@ -177,17 +172,6 @@ function getDtsFiles(libDir: string): string[] { return dtsFiles; } -function getRecordName(node: ts.SourceFile): string { - let recordName = CmdOptions.getRecordName(); - - if (recordName == "") { - let outputBinName = getOutputBinName(node); - recordName = path.basename(outputBinName, path.extname(outputBinName)); - } - - return recordName; -} - function specifyCustomLib(customLib) { Compiler.Options.Default["lib"] = customLib; let curFiles = fs.readdirSync(__dirname); @@ -345,6 +329,7 @@ function compileWatchExpression(jsFileName: string, errorMsgFileName: string, op } let outputBinName = getOutputBinName(node); let compilerDriver = new CompilerDriver(outputBinName, watchOutputFileName); + CompilerDriver.srcNode = node; setGlobalStrict(jshelpers.isEffectiveStrictModeSourceFile(node, options)); compilerDriver.compile(node); return node; diff --git a/ts2panda/src/pandagen.ts b/ts2panda/src/pandagen.ts index 2ffc0c0c2a..b168d00156 100644 --- a/ts2panda/src/pandagen.ts +++ b/ts2panda/src/pandagen.ts @@ -235,13 +235,12 @@ export class PandaGen { this.setFunctionKind(node); } - public appendScopeInfo(lexVarInfo: Map): number | undefined { + public appendScopeInfo(lexVarInfo: Map): string | undefined { if (lexVarInfo.size == 0) { return undefined; } - let scopeInfoIdx: number | undefined = undefined; - scopeInfoIdx = PandaGen.getLiteralArrayBuffer().length; + let scopeInfoId: string | undefined = undefined; let scopeInfo = new LiteralBuffer(); let scopeInfoLiterals = new Array(); scopeInfoLiterals.push(new Literal(LiteralTag.INTEGER, lexVarInfo.size)); @@ -250,8 +249,8 @@ export class PandaGen { scopeInfoLiterals.push(new Literal(LiteralTag.INTEGER, slot)); }); scopeInfo.addLiterals(...scopeInfoLiterals); - PandaGen.getLiteralArrayBuffer().push(scopeInfo); - return scopeInfoIdx; + scopeInfoId = PandaGen.appendLiteralArrayBuffer(scopeInfo); + return scopeInfoId; } public setFunctionKind(node: ts.SourceFile | ts.FunctionLikeDeclaration) { @@ -534,15 +533,15 @@ export class PandaGen { createLexEnv(node: ts.Node, scope: VariableScope | LoopScope) { let numVars = scope.getNumLexEnv(); - let scopeInfoIdx: number | undefined = undefined; + let scopeInfoId: string | undefined = undefined; let lexVarInfo = scope.getLexVarInfo(); if (CmdOptions.isDebugMode()) { - scopeInfoIdx = this.appendScopeInfo(lexVarInfo); + scopeInfoId = this.appendScopeInfo(lexVarInfo); } this.add( node, - newLexicalEnv(numVars, scopeInfoIdx), + newLexicalEnv(numVars, scopeInfoId), ) } diff --git a/ts2panda/src/pandasm.ts b/ts2panda/src/pandasm.ts index bc12caea96..236085d112 100644 --- a/ts2panda/src/pandasm.ts +++ b/ts2panda/src/pandasm.ts @@ -115,11 +115,9 @@ export class Function { export class Record { public name: string; - public metadata: Metadata; constructor(name: string) { this.name = name; - this.metadata = new Metadata(); } } diff --git a/ts2panda/src/ts2panda.ts b/ts2panda/src/ts2panda.ts index 271a015000..05546247ab 100644 --- a/ts2panda/src/ts2panda.ts +++ b/ts2panda/src/ts2panda.ts @@ -212,20 +212,6 @@ export class Ts2Panda { }); } - static dumpRecordName(ts2abc: any, recordName: string) { - let recordNameObject = { - "t": JsonType.record_name, - "rn": recordName - } - - let jsonRecordName = escapeUnicode(JSON.stringify(recordNameObject, null, 2)); - jsonRecordName = "$" + jsonRecordName.replace(dollarSign, '#$') + "$"; - if (CmdOptions.isEnableDebugLog()) { - Ts2Panda.jsonString += jsonRecordName; - } - ts2abc.stdio[3].write(jsonRecordName + '\n'); - } - static dumpCmdOptions(ts2abc: any): void { let enableRecordType: boolean = CmdOptions.needRecordType() && CompilerDriver.isTsFile; let options = { diff --git a/ts2panda/tests/esmodule.test.ts b/ts2panda/tests/esmodule.test.ts index e73c64d565..9c8985d79b 100644 --- a/ts2panda/tests/esmodule.test.ts +++ b/ts2panda/tests/esmodule.test.ts @@ -41,6 +41,7 @@ describe("ExportDeclaration", function () { it("exportClassTest ", function() { CmdOptions.isModules = () => {return true}; + CmdOptions.parseUserCmd([""]); let snippetCompiler = new SnippetCompiler(); snippetCompiler.compile(`class C {}; export {C}`); IRNode.pg = new PandaGen("foo", creatAstFromSnippet(`class C {}; export {C}`), 0, undefined); @@ -49,7 +50,7 @@ describe("ExportDeclaration", function () { let classReg = new VReg(); let expected = [ new Mov(new VReg(), new VReg()), - new Defineclasswithbuffer(new Imm(0), "UnitTest.#1#C", "_0", new Imm(0), new VReg()), + new Defineclasswithbuffer(new Imm(0), "UnitTest.#1#C", "snippet_1", new Imm(0), new VReg()), new Sta(classReg), new Lda(classReg), new Stmodulevar(new Imm(0)), diff --git a/ts2panda/tests/expression/call.test.ts b/ts2panda/tests/expression/call.test.ts index a2b6f7bb1d..6e82a070e0 100644 --- a/ts2panda/tests/expression/call.test.ts +++ b/ts2panda/tests/expression/call.test.ts @@ -17,6 +17,7 @@ import { expect } from 'chai'; import 'mocha'; +import { CmdOptions } from '../../src/cmdOptions'; import { Dynamicimport, Callarg0, @@ -102,6 +103,7 @@ describe("CallTest", function () { }); it("spread element call of a global standalone function", function () { + CmdOptions.parseUserCmd([""]); let insns = compileMainSnippet(` const args = [1, 2]; myFunction(...args); @@ -113,7 +115,7 @@ describe("CallTest", function () { let arrayInstance = new VReg(); let expected = [ - new Createarraywithbuffer(new Imm(0), "_0"), + new Createarraywithbuffer(new Imm(0), "snippet_1"), new Sta(arrayInstance), new Lda(arrayInstance), new Stconsttoglobalrecord(new Imm(1), 'args'), diff --git a/ts2panda/tests/expression/commalist.test.ts b/ts2panda/tests/expression/commalist.test.ts index 6c00a01211..20b13a70a7 100644 --- a/ts2panda/tests/expression/commalist.test.ts +++ b/ts2panda/tests/expression/commalist.test.ts @@ -17,6 +17,7 @@ import { expect } from 'chai'; import 'mocha'; +import { CmdOptions } from '../../src/cmdOptions'; import { Returnundefined, Stglobalvar, @@ -37,6 +38,7 @@ import { PandaGen } from '../../src/pandagen'; describe("CommaListExpression", function () { it("computedPropertyName", function () { + CmdOptions.parseUserCmd([""]); let snippetCompiler = new SnippetCompiler(); snippetCompiler.compileAfter(" \ class Test { \ @@ -72,7 +74,7 @@ describe("CommaListExpression", function () { let insns = snippetCompiler.getGlobalInsns(); let expected = [ new Mov(new VReg(), new VReg()), - new Defineclasswithbuffer(new Imm(0), "UnitTest.#1#Test", "_0", new Imm(0), new VReg()), + new Defineclasswithbuffer(new Imm(0), "UnitTest.#1#Test", "test_1", new Imm(0), new VReg()), new Sta(new VReg()), new Lda(new VReg()), new Sttoglobalrecord(new Imm(1), "Test"), diff --git a/ts2panda/tests/expression/literal.test.ts b/ts2panda/tests/expression/literal.test.ts index 832ba0b657..74ea3b3ffe 100644 --- a/ts2panda/tests/expression/literal.test.ts +++ b/ts2panda/tests/expression/literal.test.ts @@ -17,6 +17,7 @@ import { expect } from 'chai'; import 'mocha'; +import { CmdOptions } from '../../src/cmdOptions'; import { DiagnosticCode, DiagnosticError } from '../../src/diagnostic'; import { creatAstFromSnippet } from "../utils/asthelper" import { PandaGen } from '../../src/pandagen'; @@ -91,12 +92,13 @@ describe("LiteralTest", function () { }); it("let arr = [1]", function () { + CmdOptions.parseUserCmd([""]); let insns = compileMainSnippet("let arr = [1]"); IRNode.pg = new PandaGen("", creatAstFromSnippet(``), 0, undefined); let arrayInstance = new VReg(); let expected = [ - new Createarraywithbuffer(new Imm(0), "_0"), + new Createarraywithbuffer(new Imm(0), "snippet_1"), new Sta(arrayInstance), new Lda(arrayInstance), new Sttoglobalrecord(new Imm(1), 'arr'), @@ -120,12 +122,13 @@ describe("LiteralTest", function () { }); it("let arr = [1, 2]", function () { + CmdOptions.parseUserCmd([""]); let insns = compileMainSnippet("let arr = [1, 2]"); IRNode.pg = new PandaGen("", creatAstFromSnippet(``), 0, undefined); let arrayInstance = new VReg(); let expected = [ - new Createarraywithbuffer(new Imm(0), "_0"), + new Createarraywithbuffer(new Imm(0), "snippet_1"), new Sta(arrayInstance), new Lda(arrayInstance), new Sttoglobalrecord(new Imm(1), 'arr'), @@ -154,12 +157,13 @@ describe("LiteralTest", function () { }); it("let arr = [1, , 3]", function () { + CmdOptions.parseUserCmd([""]); let insns = compileMainSnippet("let arr = [1,, 3]"); IRNode.pg = new PandaGen("", creatAstFromSnippet(``), 0, undefined); let arrayInstance = new VReg(); let expected = [ - new Createarraywithbuffer(new Imm(0), "_0"), + new Createarraywithbuffer(new Imm(0), "snippet_1"), new Sta(arrayInstance), new Ldai(new Imm(3)), new Stownbyindex(new Imm(1), arrayInstance, new Imm(2)), @@ -173,6 +177,7 @@ describe("LiteralTest", function () { }); it("let arr = [1, ...arr1, 3]", function () { + CmdOptions.parseUserCmd([""]); let insns = compileMainSnippet(`let arr1 = [1, 2]; let arr = [1, ...arr1, 3]`); IRNode.pg = new PandaGen("", creatAstFromSnippet(``), 0, undefined); @@ -180,12 +185,12 @@ describe("LiteralTest", function () { let arrayInstance = new VReg(); let expected = [ - new Createarraywithbuffer(new Imm(0), "_0"), + new Createarraywithbuffer(new Imm(0), "snippet_1"), new Sta(arrayInstance), new Lda(arrayInstance), new Sttoglobalrecord(new Imm(1), 'arr1'), - new Createarraywithbuffer(new Imm(2), "_1"), + new Createarraywithbuffer(new Imm(2), "snippet_2"), new Sta(arrayInstance), new Ldai(new Imm(1)), new Sta(elemIdxReg), @@ -220,11 +225,12 @@ describe("LiteralTest", function () { }); it("let obj = {a: 1}", function () { + CmdOptions.parseUserCmd([""]); let insns = compileMainSnippet("let obj = {a: 1}"); IRNode.pg = new PandaGen("", creatAstFromSnippet(``), 0, undefined); let objInstance = new VReg(); let expected = [ - new Createobjectwithbuffer(new Imm(0), "_0"), + new Createobjectwithbuffer(new Imm(0), "snippet_1"), new Sta(objInstance), new Lda(objInstance), new Sttoglobalrecord(new Imm(1), 'obj'), @@ -234,13 +240,14 @@ describe("LiteralTest", function () { }); it("let obj = {0: 1 + 2}", function () { + CmdOptions.parseUserCmd([""]); let insns = compileMainSnippet("let obj = {0: 1 + 2}"); IRNode.pg = new PandaGen("", creatAstFromSnippet(``), 0, undefined); let objInstance = new VReg(); let lhs = new VReg(); let expected = [ - new Createobjectwithbuffer(new Imm(0), "_0"), + new Createobjectwithbuffer(new Imm(0), "snippet_1"), new Sta(objInstance), new Ldai(new Imm(1)), new Sta(lhs), @@ -255,12 +262,13 @@ describe("LiteralTest", function () { }); it("let obj = {\"str\": 1}", function () { + CmdOptions.parseUserCmd([""]); let insns = compileMainSnippet("let obj = {\"str\": 1}"); IRNode.pg = new PandaGen("", creatAstFromSnippet(``), 0, undefined); let objInstance = new VReg(); let expected = [ - new Createobjectwithbuffer(new Imm(0), "_0"), + new Createobjectwithbuffer(new Imm(0), "snippet_1"), new Sta(objInstance), new Lda(objInstance), new Sttoglobalrecord(new Imm(1), 'obj'), @@ -270,13 +278,14 @@ describe("LiteralTest", function () { }); it("let a; let obj = {a}", function () { + CmdOptions.parseUserCmd([""]); let insns = compileMainSnippet("let a; let obj = {a}"); IRNode.pg = new PandaGen("", creatAstFromSnippet(``), 0, undefined); ((IRNode.pg)).updateIcSize(1); let objInstance = new VReg(); let expected = [ - new Createobjectwithbuffer(new Imm(0), "_0"), + new Createobjectwithbuffer(new Imm(0), "snippet_1"), new Sta(objInstance), new Tryldglobalbyname(new Imm(1), 'a'), new Stownbyname(new Imm(2), "a", objInstance), diff --git a/ts2panda/tests/statements/switch.test.ts b/ts2panda/tests/statements/switch.test.ts index f09bb9bce2..c50027d688 100644 --- a/ts2panda/tests/statements/switch.test.ts +++ b/ts2panda/tests/statements/switch.test.ts @@ -249,7 +249,7 @@ describe("switchTest", function () { switchEndLabel, new Returnundefined() ]; - let functionPg = snippetCompiler.getPandaGenByName("test"); + let functionPg = snippetCompiler.getPandaGenByName("UnitTest.test"); let insns = functionPg!.getInsns(); expect(checkInstructions(insns, expected)).to.be.true; diff --git a/ts2panda/tests/types/array.test.ts b/ts2panda/tests/types/array.test.ts index 48f8b2db92..f671983ef1 100644 --- a/ts2panda/tests/types/array.test.ts +++ b/ts2panda/tests/types/array.test.ts @@ -47,7 +47,7 @@ describe("array tests in array.test.ts", function() { // check liberalBuffer let expectedBuffValues = [ [ - [2, 6], [24, "_1"], [24, "_2"], [24, "_3"], [24, "_4"], [24, "_5"], [24, "_6"], [2, 0] + [2, 6], [24, "snippet_1"], [24, "snippet_2"], [24, "snippet_3"], [24, "snippet_4"], [24, "snippet_5"], [24, "snippet_6"], [2, 0] ], [ [2, 5], [25, 1] @@ -88,17 +88,17 @@ describe("array tests in array.test.ts", function() { // check liberalBuffer let expectedBuffValues = [ [ - [2, 3], [24, "_1"], [24, "_2"], [24, "_3"], [2, 0] + [2, 3], [24, "snippet_1"], [24, "snippet_2"], [24, "snippet_3"], [2, 0] ], [ [2, 1], [2, 0], [25, 0], [2, 0], [2, 0], [2, 0], [2, 0], [2, 0] ], [ - [2, 2], [24, "_1"] + [2, 2], [24, "snippet_1"] ], [ - [2, 5], [24, "_2"] + [2, 5], [24, "snippet_2"] ] ] let buff = createLiteralBufferArray(expectedBuffValues); @@ -131,7 +131,7 @@ describe("array tests in array.test.ts", function() { // check liberalBuffer let expectedBuffValues = [ [ - [2, 6], [24, "_1"], [24, "_2"], [24, "_3"], [24, "_4"], [24, "_5"], [24, "_6"], [2, 0] + [2, 6], [24, "snippet_1"], [24, "snippet_2"], [24, "snippet_3"], [24, "snippet_4"], [24, "snippet_5"], [24, "snippet_6"], [2, 0] ], [ [2, 5], [25, 1] @@ -173,17 +173,17 @@ describe("array tests in array.test.ts", function() { // check liberalBuffer let expectedBuffValues = [ [ - [2, 3], [24, "_1"], [24, "_2"], [24, "_3"], [2, 0] + [2, 3], [24, "snippet_1"], [24, "snippet_2"], [24, "snippet_3"], [2, 0] ], [ [2, 1], [2, 0], [25, 0], [2, 0], [2, 0], [2, 0], [2, 0], [2, 0] ], [ - [2, 2], [24, "_1"] + [2, 2], [24, "snippet_1"] ], [ - [2, 5], [24, "_2"] + [2, 5], [24, "snippet_2"] ] ] let buff = createLiteralBufferArray(expectedBuffValues); @@ -206,13 +206,13 @@ describe("array tests in array.test.ts", function() { // check liberalBuffer let expectedBuffValues = [ [ - [2, 2], [24, "_1"], [24, "_2"], [2, 0] + [2, 2], [24, "snippet_1"], [24, "snippet_2"], [2, 0] ], [ [2, 4], [2, 2], [25, 4], [25, 1], ], [ - [2, 5], [24, "_1"] + [2, 5], [24, "snippet_1"] ] ] let buff = createLiteralBufferArray(expectedBuffValues); @@ -234,14 +234,14 @@ describe("array tests in array.test.ts", function() { // check liberalBuffer let expectedBuffValues = [ [ - [2, 2], [24, "_1"], [24, "_2"], [2, 0] + [2, 2], [24, "snippet_1"], [24, "snippet_2"], [2, 0] ], [ [2, 6], [2, 2], [5, "element1"], [25, 1], [5, "element2"], [25, 4] ], [ - [2, 5], [24, "_1"] + [2, 5], [24, "snippet_1"] ] ] let buff = createLiteralBufferArray(expectedBuffValues); diff --git a/ts2panda/tests/types/class.test.ts b/ts2panda/tests/types/class.test.ts index 00247f961d..0ee5e903a6 100644 --- a/ts2panda/tests/types/class.test.ts +++ b/ts2panda/tests/types/class.test.ts @@ -43,13 +43,13 @@ describe("class tests in class.test.ts", function () { // check liberalBuffer let expectedBuffValues = [ [ - [2, 3], [24, "_1"], [24, "_2"], [24, "_3"], [2, 0] + [2, 3], [24, "snippet_1"], [24, "snippet_2"], [24, "snippet_3"], [2, 0] ], [ [2, 1], [2, 0], [25, 0], [2, 0], [2, 1], [5, "num"], [25, 1], [2, 0], [2, 0], [2, 1], [5, "constructor"], - [24, "_2"], [2, 0], [2, 0] + [24, "snippet_2"], [2, 0], [2, 0] ], [ [2, 3], [2, 0], @@ -57,7 +57,7 @@ describe("class tests in class.test.ts", function () { [2, 0], [25, 0] ], [ - [2, 2], [24, "_1"] + [2, 2], [24, "snippet_1"] ] ] let buff = createLiteralBufferArray(expectedBuffValues); @@ -80,20 +80,20 @@ describe("class tests in class.test.ts", function () { // check liberalBuffer let expectedBuffValues = [ [ - [2, 3], [24, "_1"], [24, "_2"], [24, "_3"], [2, 0] + [2, 3], [24, "snippet_1"], [24, "snippet_2"], [24, "snippet_3"], [2, 0] ], [ [2, 1], [2, 0], [25, 0], [2, 0], [2, 1], [5, "num"], [25, 1], [2, 0], [2, 0], [2, 1], [5, "constructor"], - [24, "_2"], [2, 0], [2, 0] + [24, "snippet_2"], [2, 0], [2, 0] ], [ [2, 3], [2, 0], [5, "constructor"], [2, 0], [2, 1], [25, 1], [25, 0] ], [ - [2, 2], [24, "_1"] + [2, 2], [24, "snippet_1"] ] ] let buff = createLiteralBufferArray(expectedBuffValues); @@ -116,7 +116,7 @@ describe("class tests in class.test.ts", function () { // check liberalBuffer let expectedBuffValues = [ [ - [2, 2], [24, "_1"], [24, "_2"], [2, 0] + [2, 2], [24, "snippet_1"], [24, "snippet_2"], [2, 0] ], [ [2, 1], [2, 0], [25, 0], [2, 0], @@ -128,7 +128,7 @@ describe("class tests in class.test.ts", function () { [2, 0], [2, 1], [2, 0], [2, 0], [2, 0] ], [ - [2, 2], [24, "_1"] + [2, 2], [24, "snippet_1"] ] ] let buff = createLiteralBufferArray(expectedBuffValues); @@ -151,14 +151,14 @@ describe("class tests in class.test.ts", function () { // check liberalBuffer let expectedBuffValues = [ [ - [2, 4], [24, "_1"], [24, "_2"], [24, "_3"], [24, "_4"], [2, 0] + [2, 4], [24, "snippet_1"], [24, "snippet_2"], [24, "snippet_3"], [24, "snippet_4"], [2, 0] ], [ [2, 1], [2, 0], [25, 0], [2, 0], [2, 1], [5, "val"], [25, 1], [2, 0], [2, 0], [2, 2], - [5, "setVal"], [24, "_2"], - [5, "getValStr"], [24, "_3"], + [5, "setVal"], [24, "snippet_2"], + [5, "getValStr"], [24, "snippet_3"], [2, 0], [2, 0], ], [ @@ -170,7 +170,7 @@ describe("class tests in class.test.ts", function () { [2, 0], [2, 0], [25, 4] ], [ - [2, 2], [24, "_1"] + [2, 2], [24, "snippet_1"] ] ] let buff = createLiteralBufferArray(expectedBuffValues); @@ -193,7 +193,7 @@ describe("class tests in class.test.ts", function () { // check liberalBuffer let expectedBuffValues = [ [ - [2, 2], [24, "_1"], [24, "_2"], [2, 0] + [2, 2], [24, "snippet_1"], [24, "snippet_2"], [2, 0] ], [ [2, 1], [2, 0], [25, 0], [2, 0], @@ -205,7 +205,7 @@ describe("class tests in class.test.ts", function () { [25, 4], [2, 0], [2, 0], [2, 0] ], [ - [2, 2], [24, "_1"] + [2, 2], [24, "snippet_1"] ] ] let buff = createLiteralBufferArray(expectedBuffValues); @@ -229,15 +229,15 @@ describe("class tests in class.test.ts", function () { // check liberalBuffer let expectedBuffValues = [ [ - [2, 4], [24, "_1"], [24, "_2"], [24, "_3"], [24, "_4"], [2, 0] + [2, 4], [24, "snippet_1"], [24, "snippet_2"], [24, "snippet_3"], [24, "snippet_4"], [2, 0] ], [ [2, 1], [2, 0], [25, 0], [2, 0], [2, 1], [5, "val"], [25, 1], [2, 0], [2, 0], [2, 1], [5, "setVal"], - [24, "_2"], [2, 1], [5, "str"], + [24, "snippet_2"], [2, 1], [5, "str"], [25, 4], [2, 0], [2, 0], [2, 1], - [5, "getStr"], [24, "_3"] + [5, "getStr"], [24, "snippet_3"] ], [ [2, 3], [2, 0], [5, "setVal"], @@ -248,7 +248,7 @@ describe("class tests in class.test.ts", function () { [2, 0], [2, 0], [25, 4] ], [ - [2, 2], [24, "_1"] + [2, 2], [24, "snippet_1"] ] ] let buff = createLiteralBufferArray(expectedBuffValues); @@ -272,11 +272,11 @@ describe("class tests in class.test.ts", function () { // check liberalBuffer let expectedBuffValues = [ [ - [2, 5], [24, "_1"], [24, "_2"], [24, "_3"], [24, "_4"], [24, "_5"], [2, 0] + [2, 5], [24, "snippet_1"], [24, "snippet_2"], [24, "snippet_3"], [24, "snippet_4"], [24, "snippet_5"], [2, 0] ], [ [2, 1], [2, 1], [25, 0], [2, 0], - [2, 0], [2, 1], [5, "eat"], [24, "_2"], + [2, 0], [2, 1], [5, "eat"], [24, "snippet_2"], [2, 0], [2, 0] ], [ @@ -284,16 +284,16 @@ describe("class tests in class.test.ts", function () { [2, 0], [2, 0], [25, 0] ], [ - [2, 1], [2, 0], [24, "_1"], + [2, 1], [2, 0], [24, "snippet_1"], [2, 0], [2, 0], [2, 1], [5, "constructor"], - [24, "_4"], [2, 0], [2, 0] + [24, "snippet_4"], [2, 0], [2, 0] ], [ [2, 3], [2, 0], [5, "constructor"], [2, 0], [2, 0], [25, 0] ], [ - [2, 2], [24, "_3"] + [2, 2], [24, "snippet_3"] ] ] let buff = createLiteralBufferArray(expectedBuffValues); @@ -318,7 +318,7 @@ describe("class tests in class.test.ts", function () { // check liberalBuffer let expectedBuffValues = [ [ - [2, 4], [24, "_1"], [24, "_2"], [24, "_3"], [24, "_4"], [2, 0] + [2, 4], [24, "snippet_1"], [24, "snippet_2"], [24, "snippet_3"], [24, "snippet_4"], [2, 0] ], [ [2, 1], [2, 0], [25, 0], [2, 0], @@ -330,11 +330,11 @@ describe("class tests in class.test.ts", function () { ], [ [2, 1], [2, 0], [25, 0], [2, 2], - [24, "_1"], [24, "_2"], [2, 0], [2, 0], + [24, "snippet_1"], [24, "snippet_2"], [2, 0], [2, 0], [2, 0], [2, 0] ], [ - [2, 2], [24, "_3"] + [2, 2], [24, "snippet_3"] ] ] let buff = createLiteralBufferArray(expectedBuffValues); diff --git a/ts2panda/tests/types/function.test.ts b/ts2panda/tests/types/function.test.ts index 3003d42926..b6b640efcd 100644 --- a/ts2panda/tests/types/function.test.ts +++ b/ts2panda/tests/types/function.test.ts @@ -42,7 +42,7 @@ describe("function tests in function.test.ts", function () { // check liberalBuffer let expectedBuffValues = [ [ - [2, 2], [24, "_1"], [24, "_2"], [2, 0] + [2, 2], [24, "snippet_1"], [24, "snippet_2"], [2, 0] ], [ [2, 3], [2, 0], [5, "local"], @@ -74,7 +74,7 @@ describe("function tests in function.test.ts", function () { // check liberalBuffer let expectedBuffValues = [ [ - [2, 2], [24, "_1"], [24, "_2"], [2, 0] + [2, 2], [24, "snippet_1"], [24, "snippet_2"], [2, 0] ], [ [2, 3], [2, 0], [5, "multi_local"], @@ -109,7 +109,7 @@ describe("function tests in function.test.ts", function () { // check liberalBuffer let expectedBuffValues = [ [ - [2, 3], [24, "_1"], [24, "_2"], [24, "_3"], [2, 0] + [2, 3], [24, "snippet_1"], [24, "snippet_2"], [24, "snippet_3"], [2, 0] ], [ [2, 3], [2, 0], [5, "twoFunctions"], @@ -146,7 +146,7 @@ describe("function tests in function.test.ts", function () { // check liberalBuffer let expectedBuffValues = [ [ - [2, 4], [24, "_1"], [24, "_2"], [24, "_3"], [24, "_4"], [2, 0] + [2, 4], [24, "snippet_1"], [24, "snippet_2"], [24, "snippet_3"], [24, "snippet_4"], [2, 0] ], [ [2, 3], [2, 0], [5, "localClass"], @@ -159,10 +159,10 @@ describe("function tests in function.test.ts", function () { [ [2, 3], [2, 0], [5, "foo"], [2, 0], - [2, 2], [25, 1], [24, "_4"], [25, 0] + [2, 2], [25, 1], [24, "snippet_4"], [25, 0] ], [ - [2, 2], [24, "_2"] + [2, 2], [24, "snippet_2"] ] ] let buff = createLiteralBufferArray(expectedBuffValues); @@ -184,7 +184,7 @@ describe("function tests in function.test.ts", function () { // check liberalBuffer let expectedBuffValues = [ [ - [2, 4], [24, "_1"], [24, "_2"], [24, "_3"], [24, "_4"], [2, 0] + [2, 4], [24, "snippet_1"], [24, "snippet_2"], [24, "snippet_3"], [24, "snippet_4"], [2, 0] ], [ [2, 3], [2, 0], [5, "localClassRet"], @@ -197,10 +197,10 @@ describe("function tests in function.test.ts", function () { ], [ [2, 3], [2, 0], [5, "foo"], - [2, 0], [2, 0], [24, "_4"] + [2, 0], [2, 0], [24, "snippet_4"] ], [ - [2, 2], [24, "_2"] + [2, 2], [24, "snippet_2"] ] ] let buff = createLiteralBufferArray(expectedBuffValues); diff --git a/ts2panda/tests/types/object.test.ts b/ts2panda/tests/types/object.test.ts index bfaeef5ae8..600f68aa49 100644 --- a/ts2panda/tests/types/object.test.ts +++ b/ts2panda/tests/types/object.test.ts @@ -42,7 +42,7 @@ describe("object tests in object.test.ts", function() { // check liberalBuffer let expectedBuffValues = [ [ - [2, 1], [24, "_1"], [2, 0] + [2, 1], [24, "snippet_1"], [2, 0] ], [ [2, 6], [2, 2], [5, "a"], @@ -69,7 +69,7 @@ describe("object tests in object.test.ts", function() { // check liberalBuffer let expectedBuffValues = [ [ - [2, 4], [24, "_1"], [24, "_2"], [24, "_3"], [24, "_4"], [2, 0] + [2, 4], [24, "snippet_1"], [24, "snippet_2"], [24, "snippet_3"], [24, "snippet_4"], [2, 0] ], [ [2, 1], [2, 0], [25, 0], [2, 0], @@ -77,10 +77,10 @@ describe("object tests in object.test.ts", function() { ], [ [2, 6], [2, 2], [5, "a"], - [24, "_3"], [5, "b"], [24, "_4"] + [24, "snippet_3"], [5, "b"], [24, "snippet_4"] ], [ - [2, 2], [24, "_1"] + [2, 2], [24, "snippet_1"] ], [ [2, 4], [2, 2], [25, 4], [25, 1] diff --git a/ts2panda/tests/types/primitives.test.ts b/ts2panda/tests/types/primitives.test.ts index 3603a83536..d7417cea10 100644 --- a/ts2panda/tests/types/primitives.test.ts +++ b/ts2panda/tests/types/primitives.test.ts @@ -79,7 +79,7 @@ describe("primitives tests in primitives.test.ts", function() { let expectedBuffValues = [ [ [2, 1], - [24, "_1"], + [24, "snippet_1"], [2, 0] ], [ @@ -171,7 +171,7 @@ describe("primitives tests in primitives.test.ts", function() { // check liberalBuffer let expectedBuffValues = [ [ - [2, 2], [24, "_1"], [24, "_2"], [2, 0] + [2, 2], [24, "snippet_1"], [24, "snippet_2"], [2, 0] ], [ [2, 1], [2, 0], [25, 0], [2, 0], @@ -186,7 +186,7 @@ describe("primitives tests in primitives.test.ts", function() { [2, 0], [2, 0], [2, 0] ], [ - [2, 2], [24, "_1"] + [2, 2], [24, "snippet_1"] ] ] let buff = createLiteralBufferArray(expectedBuffValues); diff --git a/ts2panda/tests/types/union.test.ts b/ts2panda/tests/types/union.test.ts index 4d97791ae0..7b0be9553f 100644 --- a/ts2panda/tests/types/union.test.ts +++ b/ts2panda/tests/types/union.test.ts @@ -45,7 +45,7 @@ describe("union tests in union.test.ts", function () { // check liberalBuffer let expectedBuffValues = [ [ - [2, 4], [24, "_1"], [24, "_2"], [24, "_3"], [24, "_4"], [2, 0] + [2, 4], [24, "snippet_1"], [24, "snippet_2"], [24, "snippet_3"], [24, "snippet_4"], [2, 0] ], [ [2, 4], [2, 2], [25, 1], [25, 2] @@ -81,17 +81,17 @@ describe("union tests in union.test.ts", function () { // check liberalBuffer let expectedBuffValues = [ [ - [2, 4], [24, "_1"], [24, "_2"], [24, "_3"], [24, "_4"], [2, 0] + [2, 4], [24, "snippet_1"], [24, "snippet_2"], [24, "snippet_3"], [24, "snippet_4"], [2, 0] ], [ [2, 1], [2, 0], [25, 0], [2, 0], [2, 0], [2, 0], [2, 0], [2, 0] ], [ - [2, 4], [2, 2], [24, "_3"], [24, "_4"] + [2, 4], [2, 2], [24, "snippet_3"], [24, "snippet_4"] ], [ - [2, 2], [24, "_1"] + [2, 2], [24, "snippet_1"] ], [ [2, 5], [25, 1] @@ -117,7 +117,7 @@ describe("union tests in union.test.ts", function () { // check liberalBuffer let expectedBuffValues = [ [ - [2, 1], [24, "_1"], [2, 0] + [2, 1], [24, "snippet_1"], [2, 0] ], [ [2, 4], [2, 2], [25, 1], [25, 2] @@ -144,17 +144,17 @@ describe("union tests in union.test.ts", function () { // check liberalBuffer let expectedBuffValues = [ [ - [2, 4], [24, "_1"], [24, "_2"], [24, "_3"], [24, "_4"], [2, 0] + [2, 4], [24, "snippet_1"], [24, "snippet_2"], [24, "snippet_3"], [24, "snippet_4"], [2, 0] ], [ [2, 1], [2, 0], [25, 0], [2, 0], [2, 0], [2, 0], [2, 0], [2, 0] ], [ - [2, 4], [2, 2], [24, "_3"], [24, "_4"] + [2, 4], [2, 2], [24, "snippet_3"], [24, "snippet_4"] ], [ - [2, 2], [24, "_1"] + [2, 2], [24, "snippet_1"] ], [ [2, 5], [25, 1] diff --git a/ts2panda/tests/utils/base.ts b/ts2panda/tests/utils/base.ts index 49c7c5b52d..201173ffd4 100644 --- a/ts2panda/tests/utils/base.ts +++ b/ts2panda/tests/utils/base.ts @@ -147,6 +147,7 @@ export function compileAllSnippet(snippet: string, passes?: Pass[], literalBuffe CmdOptions.isWatchEvaluateExpressionMode() ? setGlobalStrict(true) : setGlobalStrict(jshelpers.isEffectiveStrictModeSourceFile(sourceFile, compileOptions)); let compilerDriver = new CompilerDriver('UnitTest', 'UnitTest'); + CompilerDriver.srcNode = sourceFile; if (!passes) { passes = []; @@ -192,6 +193,7 @@ export function compileAfterSnippet(snippet: string, name:string, isCommonJs: bo jshelpers.bindSourceFile(sourceFile, {}); setGlobalStrict(jshelpers.isEffectiveStrictModeSourceFile(sourceFile, compileOptions)); let compilerDriver = new CompilerDriver('UnitTest', 'UnitTest'); + CompilerDriver.srcNode = sourceFile; compilerDriver.setCustomPasses([]); compilerDriver.compileUnitTest(sourceFile, []); compileUnits = compilerDriver.getCompilationUnits(); diff --git a/ts2panda/tests/watch_expression/addWatch.test.ts b/ts2panda/tests/watch_expression/addWatch.test.ts index 7d00f48a70..6de1d64069 100644 --- a/ts2panda/tests/watch_expression/addWatch.test.ts +++ b/ts2panda/tests/watch_expression/addWatch.test.ts @@ -370,7 +370,7 @@ describe("WatchExpressions", function () { IRNode.pg = new PandaGen("", creatAstFromSnippet(``), 0, undefined); let expected = [ - new Createarraywithbuffer(new Imm(0), "_1"), + new Createarraywithbuffer(new Imm(0), "snippet_1"), new Sta(new VReg()), new Lda(new VReg()), @@ -388,7 +388,7 @@ describe("WatchExpressions", function () { IRNode.pg = new PandaGen("", creatAstFromSnippet(``), 0, undefined); let expected = [ - new Createobjectwithbuffer(new Imm(0), "_1"), + new Createobjectwithbuffer(new Imm(0), "snippet_1"), new Sta(new VReg()), new Lda(new VReg()), new Sta(new VReg()), @@ -946,7 +946,7 @@ describe("WatchExpressions", function () { let expected = [ new Mov(new VReg(), new VReg()), - new Defineclasswithbuffer(new Imm(0), "#1#", "_1", new Imm(0), new VReg()), + new Defineclasswithbuffer(new Imm(0), "#1#", "snippet_1", new Imm(0), new VReg()), new Sta(new VReg()), new Lda(new VReg()), new Sta(new VReg()), diff --git a/ts2panda/ts2abc/main.cpp b/ts2panda/ts2abc/main.cpp index c284060058..7e315e564c 100644 --- a/ts2panda/ts2abc/main.cpp +++ b/ts2panda/ts2abc/main.cpp @@ -49,6 +49,30 @@ int Preprocess(const panda::ts2abc::Options &options, const panda::PandArgParser return panda::ts2abc::RETURN_SUCCESS; } +bool HandleNpmEntries(const panda::ts2abc::Options &options, const panda::PandArgParser &argParser, + const std::string &usage) +{ + std::string input = options.GetTailArg1(); + std::string output = options.GetTailArg2(); + if (options.GetCompileByPipeArg() || input.empty() || output.empty()) { + if (options.GetCompileByPipeArg()) { + std::cerr << "[compile-npm-entries] and [compile-by-pipe] can not be used simultaneously" << std::endl; + } else { + std::cerr << "Incorrect args number" << std::endl; + } + std::cerr << "Usage example: js2abc --compile-npm-entries npm_entries.txt npm_entries.abc"<< std::endl; + std::cerr << usage << std::endl; + std::cerr << argParser.GetHelpString(); + return false; + } + + if (!panda::ts2abc::CompileNpmEntries(input, output)) { + return false; + } + + return true; +} + int main(int argc, const char *argv[]) { panda::PandArgParser argParser; @@ -76,6 +100,14 @@ int main(int argc, const char *argv[]) return panda::ts2abc::RETURN_SUCCESS; } + if (options.GetCompileNpmEntries()) { + if (!HandleNpmEntries(options, argParser, usage)) { + return panda::ts2abc::RETURN_FAILED; + } + return panda::ts2abc::RETURN_SUCCESS; + } + + if ((options.GetOptLevelArg() < static_cast(panda::ts2abc::OptLevel::O_LEVEL0)) || (options.GetOptLevelArg() > static_cast(panda::ts2abc::OptLevel::O_LEVEL2))) { std::cerr << "Incorrect optimization level value" << std::endl; diff --git a/ts2panda/ts2abc/ts2abc.cpp b/ts2panda/ts2abc/ts2abc.cpp index 1cba8c9cb7..7df81efe62 100644 --- a/ts2panda/ts2abc/ts2abc.cpp +++ b/ts2panda/ts2abc/ts2abc.cpp @@ -52,13 +52,14 @@ std::string g_compilerOutputProto = ""; std::string g_recordName = ""; constexpr uint32_t LITERALBUFFERINDEXOFFSET = 100; uint32_t MAX_UINT8 = static_cast(std::numeric_limits::max()); +bool g_isOutputProto = false; +static constexpr const char* PROTO_BIN_SUFFIX = "protoBin"; constexpr std::size_t BOUND_LEFT = 0; constexpr std::size_t BOUND_RIGHT = 0; constexpr std::size_t LINE_NUMBER = 0; constexpr bool IS_DEFINED = true; int g_opCodeIndex = 0; -std::string g_recordName = ""; std::unordered_map g_opcodeMap = { #define OPLIST(opcode, name, optype, width, flags, def_idx, use_idxs) {g_opCodeIndex++, panda::pandasm::Opcode::opcode}, PANDA_INSTRUCTION_LIST(OPLIST) @@ -826,8 +827,6 @@ static panda::pandasm::Function ParseFunction(const Json::Value &function, panda ParseSourceFileInfo(function, pandaFunc); ParseFunctionLabels(function, pandaFunc); ParseFunctionCatchTables(function, pandaFunc); - // parsing call opt type - ParseFunctionCallType(function, pandaFunc); ParseFunctionTypeInfo(function, pandaFunc, prog); ParseFunctionExportedType(function, pandaFunc, prog); ParseFunctionDeclaredType(function, pandaFunc, prog); @@ -975,10 +974,14 @@ static void ParseEnableTypeInfo(const Json::Value &rootValue) static void ParseCompilerOutputProto(const Json::Value &rootValue) { Logd("-----------------parse compiler output proto-----------------"); - if (rootValue.isMember("output-proto") && rootValue["output-proto"].isString()) { - g_compilerOutputProto = rootValue["output-proto"].asString(); + if (rootValue.isMember("output-proto") && rootValue["output-proto"].isBool()) { + g_isOutputProto = rootValue["output-proto"].asBool(); + } + if (rootValue.isMember("proto-name") && rootValue["proto-name"].isString()) { + g_compilerOutputProto = rootValue["proto-name"].asString(); } } + static void ReplaceAllDistinct(std::string &str, const std::string &oldValue, const std::string &newValue) { for (std::string::size_type pos(0); pos != std::string::npos; pos += newValue.length()) { @@ -1173,7 +1176,7 @@ static void ParseSingleTypeInfo(const Json::Value &rootValue, panda::pandasm::Pr auto typeInfoRecord = rootValue["ti"]; auto typeFlag = typeInfoRecord["tf"].asBool(); - auto typeSummaryIndex = typeInfoRecord["tsi"].asUInt(); + auto typeSummaryIndex = typeInfoRecord["tsi"].asString(); auto typeFlagField = panda::pandasm::Field(LANG_EXT); typeFlagField.name = "typeFlag"; @@ -1390,9 +1393,14 @@ bool GenerateProgram([[maybe_unused]] const std::string &data, const std::string Logd("parsing done, calling pandasm\n"); - std::string compilerOutputProto = g_compilerOutputProto; if (options.GetCompilerOutputProto().size() > 0) { - compilerOutputProto = options.GetCompilerOutputProto(); + g_compilerOutputProto = options.GetCompilerOutputProto(); + } + + std::string compilerOutputProto = g_compilerOutputProto; + + if (compilerOutputProto.size() == 0 && g_isOutputProto) { + compilerOutputProto = output.substr(0, output.find_last_of(".") + 1).append(PROTO_BIN_SUFFIX); } #ifdef ENABLE_BYTECODE_OPT @@ -1446,6 +1454,52 @@ bool GenerateProgram([[maybe_unused]] const std::string &data, const std::string return true; } +bool CompileNpmEntries(const std::string &input, const std::string &output) +{ + auto inputAbs = panda::os::file::File::GetAbsolutePath(input); + if (!inputAbs) { + std::cerr << "Input file does not exist" << std::endl; + return false; + } + auto fpath = inputAbs.Value(); + if (panda::os::file::File::IsRegularFile(fpath) == false) { + std::cerr << "Input must be either a regular file or a directory" << std::endl; + return false; + } + + std::stringstream ss; + std::ifstream inputStream(input); + if (inputStream.fail()) { + std::cerr << "Failed to read file to buffer: " << input << std::endl; + return false; + } + ss << inputStream.rdbuf(); + + panda::pandasm::Program prog = panda::pandasm::Program(); + prog.lang = LANG_EXT; + + std::string line; + while (getline(ss, line)) { + std::size_t pos = line.find(":"); + std::string recordName = line.substr(0, pos); + std::string field = line.substr(pos + 1); + + auto langExt = LANG_EXT; + auto entryNameField = panda::pandasm::Field(langExt); + entryNameField.name = field; + entryNameField.type = panda::pandasm::Type("u8", 0); + entryNameField.metadata->SetValue(panda::pandasm::ScalarValue::Create( + static_cast(0))); + + panda::pandasm::Record entryRecord = panda::pandasm::Record(recordName, langExt); + entryRecord.field_list.emplace_back(std::move(entryNameField)); + prog.record_table.emplace(recordName, std::move(entryRecord)); + } + + panda::proto::ProtobufSnapshotGenerator::GenerateSnapshot(prog, output); + return true; +} + bool HandleJsonFile(const std::string &input, std::string &data) { auto inputAbs = panda::os::file::File::GetAbsolutePath(input); diff --git a/ts2panda/ts2abc/ts2abc.h b/ts2panda/ts2abc/ts2abc.h index 4b4658dfdb..9288b91c27 100644 --- a/ts2panda/ts2abc/ts2abc.h +++ b/ts2panda/ts2abc/ts2abc.h @@ -51,6 +51,7 @@ enum class OptLevel { bool HandleJsonFile(const std::string &input, std::string &data); bool GenerateProgram(const std::string &data, const std::string &output, panda::ts2abc::Options options); +bool CompileNpmEntries(const std::string &input, const std::string &output); bool GetDebugLog(); void ParseLogEnable(const Json::Value &rootValue); bool GetDebugModeEnabled(); diff --git a/ts2panda/ts2abc/ts2abc_options.h b/ts2panda/ts2abc/ts2abc_options.h index 03d56e78e9..d4cfb330b5 100755 --- a/ts2panda/ts2abc/ts2abc_options.h +++ b/ts2panda/ts2abc/ts2abc_options.h @@ -39,7 +39,9 @@ namespace panda::ts2abc { parser->Add(&bc_version_arg_); parser->Add(&bc_min_version_arg_); parser->Add(&compile_by_pipe_arg_); + parser->Add(&compile_npm_entries_); parser->Add(&compiler_output_proto_); + parser->Add(&output_proto_name_); parser->EnableTail(); parser->PushBackTail(&Tail_Arg1_arg_); parser->PushBackTail(&Tail_Arg2_arg_); @@ -150,21 +152,51 @@ namespace panda::ts2abc { return compile_by_pipe_arg_.WasSet(); } - std::string GetCompilerOutputProto() const + bool GetCompileNpmEntries() const + { + return compile_npm_entries_.GetValue(); + } + + void SetCompileNpmEntries(bool value) + { + compile_npm_entries_.SetValue(value); + } + + bool WasSetCompileNpmEntries() const + { + return compile_npm_entries_.WasSet(); + } + + bool IsOutputProto() const { return compiler_output_proto_.GetValue(); } - void SetCompilerOutputProto(std::string value) + void SetOutputProto(bool value) { compiler_output_proto_.SetValue(value); } - bool WasSetCompilerOutputProto() const + bool WasSetOutputProto() const { return compiler_output_proto_.WasSet(); } + std::string GetCompilerOutputProto() const + { + return output_proto_name_.GetValue(); + } + + void SetCompilerOutputProto(std::string value) + { + output_proto_name_.SetValue(value); + } + + bool WasSetCompilerOutputProto() const + { + return output_proto_name_.WasSet(); + } + std::string GetTailArg1() const { return Tail_Arg1_arg_.GetValue(); @@ -223,7 +255,11 @@ namespace panda::ts2abc { R"(Print ark bytecode minimum supported version)"}; panda::PandArg compile_by_pipe_arg_{ "compile-by-pipe", false, R"(Compile a json file that is passed by pipe)"}; - panda::PandArg compiler_output_proto_{ "output-proto", "", + panda::PandArg compile_npm_entries_{ "compile-npm-entries", false, + R"(Compile npm entries info into an abc file)"}; + panda::PandArg compiler_output_proto_{ "output-proto", false, + R"(Output protoBin file)"}; + panda::PandArg output_proto_name_{ "proto-name", "", R"(Specify the output name for serializd protobuf file (.protoBin))"}; panda::PandArg Tail_Arg1_arg_{ "ARG_1", "", R"(Path to input(json file) or path to output(ark bytecode)" -- Gitee From d0ee41a3cd309c873a3936ae51ad1a4535e7add6 Mon Sep 17 00:00:00 2001 From: hufeng Date: Sat, 15 Oct 2022 20:43:22 +0800 Subject: [PATCH 5/7] Support merge-abc option in ts2abc Signed-off-by: hufeng Change-Id: Icfed901ec2defa044a512735dcc5e17a68afa1ba --- test262/run_sunspider.py | 12 +- ts2panda/scripts/generate_js_bytecode.py | 4 + ts2panda/src/base/util.ts | 2 +- ts2panda/src/cmdOptions.ts | 22 +++- ts2panda/src/compilerDriver.ts | 24 ++-- ts2panda/src/recorder.ts | 8 +- ts2panda/src/ts2panda.ts | 1 + ts2panda/tests/utils/base.ts | 15 ++- .../tests/watch_expression/addWatch.test.ts | 113 +++++------------- ts2panda/ts2abc/ts2abc.cpp | 110 ++++++++++++++--- 10 files changed, 189 insertions(+), 122 deletions(-) diff --git a/test262/run_sunspider.py b/test262/run_sunspider.py index cc3b9bd3b4..ce5bce3555 100755 --- a/test262/run_sunspider.py +++ b/test262/run_sunspider.py @@ -240,8 +240,9 @@ class ArkProgram(): cmd_args = [frontend_tool, dependency, '--outputProto', proto_bin_file, '--module', '--merge-abc'] else: + # for testing no-record-name abc cmd_args = [frontend_tool, dependency, '--output', output_abc, - '--module', '--merge-abc'] + '--module'] proc = subprocess.Popen(cmd_args) proc.wait() @@ -296,7 +297,7 @@ class ArkProgram(): self.abc_file = out_file mod_opt_index = 0 cmd_args = [] - dependency_cmd_args= [] + dependency_cmd_args = [] frontend_tool = self.ark_frontend_binary merge_abc_mode = self.merge_abc_mode dependencies = [] @@ -316,8 +317,9 @@ class ArkProgram(): cmd_args = ['node', '--expose-gc', frontend_tool, js_file, '--output-proto', '--merge-abc'] else: + # for testing no-record-name abc cmd_args = ['node', '--expose-gc', frontend_tool, - js_file, '-o', out_file, '--merge-abc'] + js_file, '-o', out_file] if file_name in self.module_list: cmd_args.insert(mod_opt_index, "-m") self.module = True @@ -329,11 +331,11 @@ class ArkProgram(): str(self.es2abc_thread_count), '--outputProto', proto_bin_file, js_file, '--merge-abc'] else: - # '--merge-abc' should be removed when record-name is set as default in es2panda + # for testing no-record-name abc cmd_args = [frontend_tool, '--opt-level=' + str(self.opt_level), '--function-threads=' + str(self.es2abc_thread_count), '--output', - out_file, js_file, '--merge-abc'] + out_file, js_file] if file_name in self.module_list: cmd_args.insert(mod_opt_index, "--module") self.module = True diff --git a/ts2panda/scripts/generate_js_bytecode.py b/ts2panda/scripts/generate_js_bytecode.py index 2e7949cda3..0f4aca8823 100755 --- a/ts2panda/scripts/generate_js_bytecode.py +++ b/ts2panda/scripts/generate_js_bytecode.py @@ -48,6 +48,8 @@ def parse_args(): help='enable builtin types recognition for .d.ts files') parser.add_argument("--functionSourceCode", action='store_true', help='compile abc with function sourcecode info') + parser.add_argument("--merge-abc", action='store_true', + help='Compile as merge abc') arguments = parser.parse_args() return arguments @@ -100,6 +102,8 @@ def gen_abc_info(input_arguments): cmd.insert(7, '-b') if input_arguments.functionSourceCode: cmd.insert(8, '--function-sourcecode') + if input_arguments.merge_abc: + cmd.insert(9, '--merge-abc') run_command(cmd, path) diff --git a/ts2panda/src/base/util.ts b/ts2panda/src/base/util.ts index 25bf68deee..2453424609 100644 --- a/ts2panda/src/base/util.ts +++ b/ts2panda/src/base/util.ts @@ -410,7 +410,7 @@ export function getOutputBinName(node: ts.SourceFile) { export function getRecordName(node: ts.SourceFile): string { let recordName = CmdOptions.getRecordName(); - if (recordName == "") { + if (recordName == "" && CmdOptions.isMergeAbc()) { let outputBinName = getOutputBinName(node); recordName = path.basename(outputBinName, path.extname(outputBinName)); } diff --git a/ts2panda/src/cmdOptions.ts b/ts2panda/src/cmdOptions.ts index b746fdf986..32829c8d0a 100644 --- a/ts2panda/src/cmdOptions.ts +++ b/ts2panda/src/cmdOptions.ts @@ -51,9 +51,10 @@ const ts2pandaOptions = [ { name: 'expression-watch-toolchain', type: String, defaultValue: "es2panda", description: "Specify the tool chain used to transform the expression" }, { name: 'source-file', type: String, defaultValue: "", description: "specify the file path info recorded in generated abc" }, { name: 'generate-tmp-file', type: Boolean, defaultValue: false, description: "whether to generate intermediate temporary files"}, - { name: 'record-name', type: String, defaultValue: "", description: "specify the record name." }, + { name: 'record-name', type: String, defaultValue: "", description: "specify the record name, this option can only be used when [merge-abc] is enabled." }, { name: 'output-proto', type: Boolean, defaultValue: false, description: "Output protoBin file. Default: false" }, { name: 'proto-name', type: String, defaultValue: "", description: "specify the output name for serializd protobuf file (.protoBin)" }, + { name: 'merge-abc', type: Boolean, defaultValue: false, description: "Compile as merge abc" }, ] @@ -212,10 +213,22 @@ export class CmdOptions { return outputFile; } + static setMergeAbc(mergeAbcMode: Boolean): void { + if (!this.options) { + return; + } + this.options["merge-abc"] = mergeAbcMode; + } + static getRecordName(): string { if (!this.options) { return ""; } + + if (!this.options["merge-abc"]) { + return ""; + } + return this.options["record-name"]; } @@ -339,6 +352,13 @@ export class CmdOptions { return this.options["proto-name"]; } + static isMergeAbc(): boolean { + if (!this.options) { + return false; + } + return this.options["merge-abc"] + } + // @ts-ignore static parseUserCmd(args: string[]): ts.ParsedCommandLine | undefined { this.options = commandLineArgs(ts2pandaOptions, { partial: true }); diff --git a/ts2panda/src/compilerDriver.ts b/ts2panda/src/compilerDriver.ts index 00164490d6..8409b71ab9 100644 --- a/ts2panda/src/compilerDriver.ts +++ b/ts2panda/src/compilerDriver.ts @@ -186,8 +186,10 @@ export class CompilerDriver { listenErrorEvent(ts2abcProc); try { - // must keep [dumpRecord] at first - Ts2Panda.dumpRecord(ts2abcProc, this.recordName); + if (CmdOptions.isMergeAbc()) { + // must keep [dumpRecord] at first + Ts2Panda.dumpRecord(ts2abcProc, this.recordName); + } Ts2Panda.dumpCmdOptions(ts2abcProc); for (let i = 0; i < this.pendingCompilationUnits.length; i++) { @@ -360,6 +362,14 @@ export class CompilerDriver { return idx; } + getFormatedRecordName() { + let formatedRecordName: string = ''; + if (CmdOptions.isMergeAbc()) { + formatedRecordName = this.recordName + '.'; + } + return formatedRecordName; + } + /** * Internal name is used to indentify a function in panda file * Runtime uses this name to bind code and a Function object @@ -377,13 +387,13 @@ export class CompilerDriver { if (name == '') { if ((ts.isFunctionDeclaration(node) && hasExportKeywordModifier(node) && hasDefaultKeywordModifier(node)) || ts.isExportAssignment(findOuterNodeOfParenthesis(node))) { - return `${this.recordName}.default`; + return `${this.getFormatedRecordName()}default`; } - return `${this.recordName}.#${this.getFuncId(funcNode)}#`; + return `${this.getFormatedRecordName()}#${this.getFuncId(funcNode)}#`; } if (name == "func_main_0") { - return `${this.recordName}.#${this.getFuncId(funcNode)}#${name}`; + return `${this.getFormatedRecordName()}#${this.getFuncId(funcNode)}#${name}`; } let funcNameMap = recorder.getFuncNameMap(); @@ -400,7 +410,7 @@ export class CompilerDriver { name = `#${this.getFuncId(funcNode)}#` } } - return `${this.recordName}.${name}`; + return `${this.getFormatedRecordName()}${name}`; } getInternalNameForCtor(node: ts.ClassLikeDeclaration, ctor: ts.ConstructorDeclaration) { @@ -409,7 +419,7 @@ export class CompilerDriver { if (name.lastIndexOf(".") != -1) { name = `#${this.getFuncId(ctor)}#` } - return `${this.recordName}.${name}`; + return `${this.getFormatedRecordName()}${name}`; } writeBinaryFile(pandaGen: PandaGen) { diff --git a/ts2panda/src/recorder.ts b/ts2panda/src/recorder.ts index 866ed784d9..2f3881b13d 100644 --- a/ts2panda/src/recorder.ts +++ b/ts2panda/src/recorder.ts @@ -458,11 +458,11 @@ export class Recorder { return exportStmt; } - private getNormalizeModuleSpecifier(moduleSpecifier: ts.Expression): string { + private getModuleSpecifier(moduleSpecifier: ts.Expression): string { if (!ts.isStringLiteral(moduleSpecifier)) { throw new Error("moduleSpecifier must be a stringLiteral"); } - return path.normalize(jshelpers.getTextOfIdentifierOrLiteral(moduleSpecifier)); + return jshelpers.getTextOfIdentifierOrLiteral(moduleSpecifier); } private recordEcmaNamedBindings(namedBindings: ts.NamedImportBindings, scope: ModuleScope, moduleRequest: string) { @@ -506,7 +506,7 @@ export class Recorder { return; } - let moduleRequest: string = this.getNormalizeModuleSpecifier(node.moduleSpecifier); + let moduleRequest: string = this.getModuleSpecifier(node.moduleSpecifier); if (node.importClause) { let importClause: ts.ImportClause = node.importClause; @@ -519,7 +519,7 @@ export class Recorder { private recordEcmaExportDecl(node: ts.ExportDeclaration, scope: ModuleScope) { if (node.moduleSpecifier) { - let moduleRequest: string = this.getNormalizeModuleSpecifier(node.moduleSpecifier); + let moduleRequest: string = this.getModuleSpecifier(node.moduleSpecifier); if (node.exportClause) { let namedBindings: ts.NamedExportBindings = node.exportClause; diff --git a/ts2panda/src/ts2panda.ts b/ts2panda/src/ts2panda.ts index 05546247ab..8f1e9dfbcc 100644 --- a/ts2panda/src/ts2panda.ts +++ b/ts2panda/src/ts2panda.ts @@ -216,6 +216,7 @@ export class Ts2Panda { let enableRecordType: boolean = CmdOptions.needRecordType() && CompilerDriver.isTsFile; let options = { "t": JsonType.options, + "merge_abc": CmdOptions.isMergeAbc(), "module_mode": CmdOptions.isModules(), "commonjs_module": CmdOptions.isCommonJs(), "debug_mode": CmdOptions.isDebugMode(), diff --git a/ts2panda/tests/utils/base.ts b/ts2panda/tests/utils/base.ts index 201173ffd4..31017db4ad 100644 --- a/ts2panda/tests/utils/base.ts +++ b/ts2panda/tests/utils/base.ts @@ -141,9 +141,15 @@ export function checkInstructions(actual: IRNode[], expected: IRNode[], checkFn? return true; } -export function compileAllSnippet(snippet: string, passes?: Pass[], literalBufferArray?: Array): PandaGen[] { +export function compileAllSnippet(snippet: string, passes?: Pass[], literalBufferArray?: Array, + isWatchEvaluateExpressionMode?: boolean): PandaGen[] { let sourceFile = creatAstFromSnippet(snippet); jshelpers.bindSourceFile(sourceFile, {}); + CmdOptions.parseUserCmd([""]); + if (isWatchEvaluateExpressionMode) { + CmdOptions.setWatchEvaluateExpressionArgs(['','']); + } + CmdOptions.setMergeAbc(true); CmdOptions.isWatchEvaluateExpressionMode() ? setGlobalStrict(true) : setGlobalStrict(jshelpers.isEffectiveStrictModeSourceFile(sourceFile, compileOptions)); let compilerDriver = new CompilerDriver('UnitTest', 'UnitTest'); @@ -157,8 +163,9 @@ export function compileAllSnippet(snippet: string, passes?: Pass[], literalBuffe return compilerDriver.getCompilationUnits(); } -export function compileMainSnippet(snippet: string, pandaGen?: PandaGen, scope?: Scope, passes?: Pass[], compileFunc?: boolean): IRNode[] { - let compileUnits = compileAllSnippet(snippet, passes); +export function compileMainSnippet(snippet: string, pandaGen?: PandaGen, scope?: Scope, passes?: Pass[], + compileFunc?: boolean, isWatchEvaluateExpressionMode?: boolean): IRNode[] { + let compileUnits = compileAllSnippet(snippet, passes, undefined, isWatchEvaluateExpressionMode); if (compileUnits.length != 1 && !compileFunc) { throw new Error("Error: please use compileMainSnippet1 for multi function compile"); @@ -176,6 +183,8 @@ export function compileMainSnippet(snippet: string, pandaGen?: PandaGen, scope?: export function compileAfterSnippet(snippet: string, name:string, isCommonJs: boolean = false) { let compileUnits = null; + CmdOptions.parseUserCmd([""]); + CmdOptions.setMergeAbc(true); ts.transpileModule( snippet, { diff --git a/ts2panda/tests/watch_expression/addWatch.test.ts b/ts2panda/tests/watch_expression/addWatch.test.ts index 6de1d64069..586e49acf2 100644 --- a/ts2panda/tests/watch_expression/addWatch.test.ts +++ b/ts2panda/tests/watch_expression/addWatch.test.ts @@ -70,11 +70,9 @@ import { checkInstructions, compileMainSnippet, compileAllSnippet } from "../uti describe("WatchExpressions", function () { it("watch NumericLiteral", function () { - CmdOptions.parseUserCmd([""]); - CmdOptions.setWatchEvaluateExpressionArgs(['','']); let insns = compileMainSnippet(` a=-123.212 - `); + `, undefined, undefined, undefined, undefined, true); IRNode.pg = new PandaGen("", creatAstFromSnippet(``), 0, undefined); let expected = [ @@ -98,11 +96,9 @@ describe("WatchExpressions", function () { }); it("watch StringLiteral", function () { - CmdOptions.parseUserCmd([""]); - CmdOptions.setWatchEvaluateExpressionArgs(['','']); let insns = compileMainSnippet(` y = 'He is called \'Johnny\'' - `); + `, undefined, undefined, undefined, undefined, true); IRNode.pg = new PandaGen("", creatAstFromSnippet(``), 0, undefined); let expected = [ @@ -131,11 +127,9 @@ describe("WatchExpressions", function () { }); it("watch RegularExpressionLiteral", function () { - CmdOptions.parseUserCmd([""]); - CmdOptions.setWatchEvaluateExpressionArgs(['','']); let insns = compileMainSnippet(` a = /abc/ - `); + `, undefined, undefined, undefined, undefined, true); IRNode.pg = new PandaGen("", creatAstFromSnippet(``), 0, undefined); let expected = [ @@ -155,11 +149,9 @@ describe("WatchExpressions", function () { }); it("watch Identifier", function () { - CmdOptions.parseUserCmd([""]); - CmdOptions.setWatchEvaluateExpressionArgs(['','']); let insns = compileMainSnippet(` _awef - `); + `, undefined, undefined, undefined, undefined, true); IRNode.pg = new PandaGen("", creatAstFromSnippet(``), 0, undefined); let expected = [ @@ -178,11 +170,9 @@ describe("WatchExpressions", function () { }); it("watch TrueKeyword", function () { - CmdOptions.parseUserCmd([""]); - CmdOptions.setWatchEvaluateExpressionArgs(['','']); let insns = compileMainSnippet(` b === true - `); + `, undefined, undefined, undefined, undefined, true); IRNode.pg = new PandaGen("", creatAstFromSnippet(``), 0, undefined); let isTrueLabel = new Label(); @@ -212,11 +202,9 @@ describe("WatchExpressions", function () { }); it("watch FalseKeyword", function () { - CmdOptions.parseUserCmd([""]); - CmdOptions.setWatchEvaluateExpressionArgs(['','']); let insns = compileMainSnippet(` b === false - `); + `, undefined, undefined, undefined, undefined, true); IRNode.pg = new PandaGen("", creatAstFromSnippet(``), 0, undefined); let ifFalseLabel = new Label(); //lable0 @@ -247,11 +235,9 @@ describe("WatchExpressions", function () { }); it("watch CallExpression", function () { - CmdOptions.parseUserCmd([""]); - CmdOptions.setWatchEvaluateExpressionArgs(['','']); let insns = compileMainSnippet(` BigInt(10.2) - `); + `, undefined, undefined, undefined, undefined, true); IRNode.pg = new PandaGen("", creatAstFromSnippet(``), 0, undefined); let expected = [ @@ -275,11 +261,9 @@ describe("WatchExpressions", function () { }); it("watch NullKeyword", function () { - CmdOptions.parseUserCmd([""]); - CmdOptions.setWatchEvaluateExpressionArgs(['','']); let insns = compileMainSnippet(` b === null - `); + `, undefined, undefined, undefined, undefined, true); IRNode.pg = new PandaGen("", creatAstFromSnippet(``), 0, undefined); let isTrueLabel = new Label(); @@ -309,11 +293,9 @@ describe("WatchExpressions", function () { }); it("watch ThisKeyword", function () { - CmdOptions.parseUserCmd([""]); - CmdOptions.setWatchEvaluateExpressionArgs(['','']); let insns = compileMainSnippet(` this - `); + `, undefined, undefined, undefined, undefined, true); IRNode.pg = new PandaGen("", creatAstFromSnippet(``), 0, undefined); let expected = [ @@ -332,13 +314,11 @@ describe("WatchExpressions", function () { }); it("watch MetaProperty", function () { - CmdOptions.parseUserCmd([""]); - CmdOptions.setWatchEvaluateExpressionArgs(['','']); let pandaGens = compileAllSnippet(` function (){ b = new.target; } - `); + `, undefined, undefined, true); IRNode.pg = new PandaGen("", creatAstFromSnippet(``), 0, undefined); let expected = [ @@ -362,11 +342,9 @@ describe("WatchExpressions", function () { }); it("watch ArrayLiteralExpression", function () { - CmdOptions.parseUserCmd([""]); - CmdOptions.setWatchEvaluateExpressionArgs(['','']); let insns = compileMainSnippet(` [1,2] - `); + `, undefined, undefined, undefined, undefined, true); IRNode.pg = new PandaGen("", creatAstFromSnippet(``), 0, undefined); let expected = [ @@ -380,11 +358,9 @@ describe("WatchExpressions", function () { }); it("watch ObjectLiteralExpression", function () { - CmdOptions.parseUserCmd([""]); - CmdOptions.setWatchEvaluateExpressionArgs(['','']); let insns = compileMainSnippet(` a = {key:1,value:1} - `); + `, undefined, undefined, undefined, undefined, true); IRNode.pg = new PandaGen("", creatAstFromSnippet(``), 0, undefined); let expected = [ @@ -406,11 +382,9 @@ describe("WatchExpressions", function () { }); it("watch PropertyAccessExpression", function () { - CmdOptions.parseUserCmd([""]); - CmdOptions.setWatchEvaluateExpressionArgs(['','']); let insns = compileMainSnippet(` a.b - `); + `, undefined, undefined, undefined, undefined, true); IRNode.pg = new PandaGen("", creatAstFromSnippet(``), 0, undefined); let expected = [ @@ -432,11 +406,9 @@ describe("WatchExpressions", function () { }); it("watch ElementAccessExpression", function () { - CmdOptions.parseUserCmd([""]); - CmdOptions.setWatchEvaluateExpressionArgs(['','']); let insns = compileMainSnippet(` a[0] - `); + `, undefined, undefined, undefined, undefined, true); IRNode.pg = new PandaGen("", creatAstFromSnippet(``), 0, undefined); let expected = [ @@ -458,11 +430,9 @@ describe("WatchExpressions", function () { }); it("watch NewExpression", function () { - CmdOptions.parseUserCmd([""]); - CmdOptions.setWatchEvaluateExpressionArgs(['','']); let insns = compileMainSnippet(` new Function() - `); + `, undefined, undefined, undefined, undefined, true); IRNode.pg = new PandaGen("", creatAstFromSnippet(``), 0, undefined); let expected = [ @@ -483,11 +453,9 @@ describe("WatchExpressions", function () { }); it("watch ParenthesizedExpression", function () { - CmdOptions.parseUserCmd([""]); - CmdOptions.setWatchEvaluateExpressionArgs(['','']); let insns = compileMainSnippet(` (a,b,c) - `); + `, undefined, undefined, undefined, undefined, true); IRNode.pg = new PandaGen("", creatAstFromSnippet(``), 0, undefined); let expected = [ @@ -524,11 +492,9 @@ describe("WatchExpressions", function () { }); it("watch FunctionExpression", function () { - CmdOptions.parseUserCmd([""]); - CmdOptions.setWatchEvaluateExpressionArgs(['','']); let pandaGens = compileAllSnippet(` a = function () {} - `); + `, undefined, undefined, true); IRNode.pg = new PandaGen("", creatAstFromSnippet(``), 0, undefined); let expected = [ @@ -552,11 +518,9 @@ describe("WatchExpressions", function () { }); it("watch DeleteExpression", function () { - CmdOptions.parseUserCmd([""]); - CmdOptions.setWatchEvaluateExpressionArgs(['','']); let insns = compileMainSnippet(` delete[abc] - `); + `, undefined, undefined, undefined, undefined, true); IRNode.pg = new PandaGen("", creatAstFromSnippet(``), 0, undefined); let expected = [ @@ -580,11 +544,9 @@ describe("WatchExpressions", function () { }); it("watch TypeOfExpression", function () { - CmdOptions.parseUserCmd([""]); - CmdOptions.setWatchEvaluateExpressionArgs(['','']); let insns = compileMainSnippet(` typeof(a) - `); + `, undefined, undefined, undefined, undefined, true); IRNode.pg = new PandaGen("", creatAstFromSnippet(``), 0, undefined); let expected = [ @@ -604,11 +566,9 @@ describe("WatchExpressions", function () { }); it("watch VoidExpression", function () { - CmdOptions.parseUserCmd([""]); - CmdOptions.setWatchEvaluateExpressionArgs(['','']); let insns = compileMainSnippet(` void doSomething() - `); + `, undefined, undefined, undefined, undefined, true); IRNode.pg = new PandaGen("", creatAstFromSnippet(``), 0, undefined); let expected = [ @@ -631,13 +591,10 @@ describe("WatchExpressions", function () { }); it("watch AwaitExpression", function () { - CmdOptions.parseUserCmd([""]); - CmdOptions.setWatchEvaluateExpressionArgs(['','']); let pandaGens = compileAllSnippet( `async function a(){ await abc; - }` - ); + }`, undefined, undefined, true); IRNode.pg = new PandaGen("", creatAstFromSnippet(``), 0, undefined); let beginLabel = new Label(); @@ -689,11 +646,9 @@ describe("WatchExpressions", function () { }); it("watch PrefixUnaryExpression", function () { - CmdOptions.parseUserCmd([""]); - CmdOptions.setWatchEvaluateExpressionArgs(['','']); let insns = compileMainSnippet(` --a - `); + `, undefined, undefined, undefined, undefined, true); IRNode.pg = new PandaGen("", creatAstFromSnippet(``), 0, undefined); let expected = [ @@ -723,11 +678,9 @@ describe("WatchExpressions", function () { }); it("watch PostfixUnaryExpression", function () { - CmdOptions.parseUserCmd([""]); - CmdOptions.setWatchEvaluateExpressionArgs(['','']); let insns = compileMainSnippet(` a-- - `); + `, undefined, undefined, undefined, undefined, true); IRNode.pg = new PandaGen("", creatAstFromSnippet(``), 0, undefined); let expected = [ @@ -759,11 +712,9 @@ describe("WatchExpressions", function () { }); it("watch BinaryExpression", function () { - CmdOptions.parseUserCmd([""]); - CmdOptions.setWatchEvaluateExpressionArgs(['','']); let insns = compileMainSnippet(` a+b - `); + `, undefined, undefined, undefined, undefined, true); IRNode.pg = new PandaGen("", creatAstFromSnippet(``), 0, undefined); let expected = [ @@ -792,11 +743,9 @@ describe("WatchExpressions", function () { }); it("watch ConditionalExpression", function () { - CmdOptions.parseUserCmd([""]); - CmdOptions.setWatchEvaluateExpressionArgs(['','']); let insns = compileMainSnippet(` a?4:2 - `); + `, undefined, undefined, undefined, undefined, true); IRNode.pg = new PandaGen("", creatAstFromSnippet(``), 0, undefined); let ifTrueLabel = new Label(); @@ -825,12 +774,10 @@ describe("WatchExpressions", function () { }); it("watch YieldExpression", function () { - CmdOptions.parseUserCmd([""]); - CmdOptions.setWatchEvaluateExpressionArgs(['','']); let pandaGens = compileAllSnippet(` function* func(){ yield a; - }`); + }`, undefined, undefined, true); IRNode.pg = new PandaGen("", creatAstFromSnippet(``), 0, undefined); let startLabel = new Label(); @@ -904,11 +851,9 @@ describe("WatchExpressions", function () { }); it("watch ArrowFunction", function () { - CmdOptions.parseUserCmd([""]); - CmdOptions.setWatchEvaluateExpressionArgs(['','']); let pandaGens = compileAllSnippet(` a => b.length - `); + `, undefined, undefined, true); IRNode.pg = new PandaGen("", creatAstFromSnippet(``), 0, undefined); let expected = [ @@ -937,11 +882,9 @@ describe("WatchExpressions", function () { }); it("watch ClassExpression", function () { - CmdOptions.parseUserCmd([""]); - CmdOptions.setWatchEvaluateExpressionArgs(['','']); let pandaGens = compileAllSnippet(` a = new class{}; - `); + `, undefined, undefined, true); IRNode.pg = new PandaGen("", creatAstFromSnippet(``), 0, undefined); let expected = [ diff --git a/ts2panda/ts2abc/ts2abc.cpp b/ts2panda/ts2abc/ts2abc.cpp index 7df81efe62..073db29293 100644 --- a/ts2panda/ts2abc/ts2abc.cpp +++ b/ts2panda/ts2abc/ts2abc.cpp @@ -37,6 +37,7 @@ namespace panda::ts2abc { // pandasm definitions constexpr const auto LANG_EXT = panda::pandasm::extensions::Language::ECMASCRIPT; const std::string WHOLE_LINE; +bool g_isMergeAbc = false; bool g_debugModeEnabled = false; bool g_debugLogEnabled = false; int g_optLevel = 0; @@ -178,8 +179,12 @@ static std::string GetLiteralId(int64_t index) return g_recordName + "_" + std::to_string(index); } -static bool IsFuncMain0(std::string funcName) { - std::string expectedName = g_recordName + ".func_main_0"; +static bool IsFuncMain0(std::string funcName) +{ + std::string expectedName = "func_main_0"; + if (g_isMergeAbc) { + expectedName = g_recordName + "." + expectedName; + } return funcName == expectedName; } @@ -855,6 +860,28 @@ static void GenerateESTypeAnnotationRecord(panda::pandasm::Program &prog) prog.record_table.emplace(tsTypeAnnotationRecord.name, std::move(tsTypeAnnotationRecord)); } +static void GenerateESModuleRecord(panda::pandasm::Program &prog) +{ + auto ecmaModuleRecord = panda::pandasm::Record("_ESModuleRecord", LANG_EXT); + ecmaModuleRecord.metadata->SetAccessFlags(panda::ACC_PUBLIC); + prog.record_table.emplace(ecmaModuleRecord.name, std::move(ecmaModuleRecord)); +} + +static void GenerateCommonJsRecord(panda::pandasm::Program &prog, bool isCommonJs) +{ + // when multi-abc file get merged, field should be inserted in abc's own record + auto commonjsRecord = panda::pandasm::Record("_CommonJsRecord", LANG_EXT); + commonjsRecord.metadata->SetAccessFlags(panda::ACC_PUBLIC); + auto isCommonJsField = panda::pandasm::Field(LANG_EXT); + isCommonJsField.name = "isCommonJs"; + isCommonJsField.type = panda::pandasm::Type("u8", 0); + isCommonJsField.metadata->SetValue(panda::pandasm::ScalarValue::Create( + static_cast(isCommonJs))); + commonjsRecord.field_list.emplace_back(std::move(isCommonJsField)); + + prog.record_table.emplace(commonjsRecord.name, std::move(commonjsRecord)); +} + static void SetCommonjsField(panda::pandasm::Program &prog, bool isCommonjs) { auto iter = prog.record_table.find(g_recordName); @@ -871,11 +898,13 @@ static void SetCommonjsField(panda::pandasm::Program &prog, bool isCommonjs) static void AddModuleRecord(panda::pandasm::Program &prog, const std::string &moduleName) { - auto iter = prog.record_table.find(g_recordName); + std::string moduleRecordName = g_isMergeAbc ? g_recordName : "_ESModuleRecord"; + std::string fieldName = g_isMergeAbc ? "moduleRecordIdx" : moduleName; + auto iter = prog.record_table.find(moduleRecordName); if (iter != prog.record_table.end()) { auto &rec = iter->second; auto moduleIdxField = panda::pandasm::Field(LANG_EXT); - moduleIdxField.name = "moduleRecordIdx"; + moduleIdxField.name = fieldName; moduleIdxField.type = panda::pandasm::Type("u32", 0); std::string moduleId = GetLiteralId(g_newLiteralArrayIndex); moduleIdxField.metadata->SetValue( @@ -905,11 +934,35 @@ int ParseJson(const std::string &data, Json::Value &rootValue) return RETURN_SUCCESS; } -static void SetCommonJsModuleMode(const Json::Value &rootValue, panda::pandasm::Program &prog) +static void ParseMergeAbcMode(const Json::Value &rootValue) +{ + Logd("---------------parse is_merge_abc----------------"); + if (rootValue.isMember("merge_abc") && rootValue["merge_abc"].isBool()) { + g_isMergeAbc = rootValue["merge_abc"].asBool(); + } +} + +static void ParseModuleMode(const Json::Value &rootValue, panda::pandasm::Program &prog) +{ + Logd("----------------parse module_mode-----------------"); + if (rootValue.isMember("module_mode") && rootValue["module_mode"].isBool()) { + if (rootValue["module_mode"].asBool() && !g_isMergeAbc) { + GenerateESModuleRecord(prog); + } + } +} + +static void ParseCommonJsModuleMode(const Json::Value &rootValue, panda::pandasm::Program &prog) { Logd("------------parse commonjs_module_mode-------------"); if (rootValue.isMember("commonjs_module") && rootValue["commonjs_module"].isBool()) { - SetCommonjsField(prog, rootValue["commonjs_module"].asBool()); + if (g_isMergeAbc) { + SetCommonjsField(prog, rootValue["commonjs_module"].asBool()); + } else { + if (rootValue["commonjs_module"].asBool()) { + GenerateCommonJsRecord(prog, true); + } + } } } @@ -997,7 +1050,9 @@ static void ParseOptions(const Json::Value &rootValue, panda::pandasm::Program & { GenerateESCallTypeAnnotationRecord(prog); GenerateESTypeAnnotationRecord(prog); - SetCommonJsModuleMode(rootValue, prog); + ParseMergeAbcMode(rootValue); + ParseModuleMode(rootValue, prog); + ParseCommonJsModuleMode(rootValue, prog); ParseLogEnable(rootValue); ParseDebugMode(rootValue); ParseOptLevel(rootValue); @@ -1170,20 +1225,41 @@ static void ParseSingleModule(const Json::Value &rootValue, panda::pandasm::Prog static void ParseSingleTypeInfo(const Json::Value &rootValue, panda::pandasm::Program &prog) { - auto iter = prog.record_table.find(g_recordName); - if (iter != prog.record_table.end()) { - auto &rec = iter->second; - - auto typeInfoRecord = rootValue["ti"]; - auto typeFlag = typeInfoRecord["tf"].asBool(); - auto typeSummaryIndex = typeInfoRecord["tsi"].asString(); + auto typeInfoRecord = rootValue["ti"]; + auto typeFlag = typeInfoRecord["tf"].asBool(); + auto typeSummaryIndex = typeInfoRecord["tsi"].asString(); + + if (g_isMergeAbc) { + auto iter = prog.record_table.find(g_recordName); + if (iter != prog.record_table.end()) { + auto &rec = iter->second; + + auto typeFlagField = panda::pandasm::Field(LANG_EXT); + typeFlagField.name = "typeFlag"; + typeFlagField.type = panda::pandasm::Type("u8", 0); + typeFlagField.metadata->SetValue(panda::pandasm::ScalarValue::Create( + static_cast(typeFlag))); + rec.field_list.emplace_back(std::move(typeFlagField)); + + if (g_enableTypeinfo) { + auto typeSummaryIndexField = panda::pandasm::Field(LANG_EXT); + typeSummaryIndexField.name = "typeSummaryOffset"; + typeSummaryIndexField.type = panda::pandasm::Type("u32", 0); + typeSummaryIndexField.metadata->SetValue( + panda::pandasm::ScalarValue::Create(typeSummaryIndex)); + rec.field_list.emplace_back(std::move(typeSummaryIndexField)); + } + } + } else { + auto ecmaTypeInfoRecord = panda::pandasm::Record("_ESTypeInfoRecord", LANG_EXT); + ecmaTypeInfoRecord.metadata->SetAccessFlags(panda::ACC_PUBLIC); auto typeFlagField = panda::pandasm::Field(LANG_EXT); typeFlagField.name = "typeFlag"; typeFlagField.type = panda::pandasm::Type("u8", 0); typeFlagField.metadata->SetValue(panda::pandasm::ScalarValue::Create( static_cast(typeFlag))); - rec.field_list.emplace_back(std::move(typeFlagField)); + ecmaTypeInfoRecord.field_list.emplace_back(std::move(typeFlagField)); if (g_enableTypeinfo) { auto typeSummaryIndexField = panda::pandasm::Field(LANG_EXT); @@ -1191,8 +1267,10 @@ static void ParseSingleTypeInfo(const Json::Value &rootValue, panda::pandasm::Pr typeSummaryIndexField.type = panda::pandasm::Type("u32", 0); typeSummaryIndexField.metadata->SetValue( panda::pandasm::ScalarValue::Create(typeSummaryIndex)); - rec.field_list.emplace_back(std::move(typeSummaryIndexField)); + ecmaTypeInfoRecord.field_list.emplace_back(std::move(typeSummaryIndexField)); } + + prog.record_table.emplace(ecmaTypeInfoRecord.name, std::move(ecmaTypeInfoRecord)); } } -- Gitee From afaf8602d0faf5b987fba280d1445ba530119682 Mon Sep 17 00:00:00 2001 From: gavin1012_hw Date: Thu, 20 Oct 2022 18:45:31 +0800 Subject: [PATCH 6/7] Fix comments Signed-off-by: gavin1012_hw Change-Id: I57434eab0b437086f7e4f167137a2710ffffc903 --- ts2panda/src/cmdOptions.ts | 8 ----- ts2panda/src/ts2panda.ts | 1 - ts2panda/ts2abc/ts2abc.cpp | 61 ++++++++++++++------------------ ts2panda/ts2abc/ts2abc_options.h | 18 ---------- 4 files changed, 26 insertions(+), 62 deletions(-) diff --git a/ts2panda/src/cmdOptions.ts b/ts2panda/src/cmdOptions.ts index 32829c8d0a..99a1539d77 100644 --- a/ts2panda/src/cmdOptions.ts +++ b/ts2panda/src/cmdOptions.ts @@ -53,7 +53,6 @@ const ts2pandaOptions = [ { name: 'generate-tmp-file', type: Boolean, defaultValue: false, description: "whether to generate intermediate temporary files"}, { name: 'record-name', type: String, defaultValue: "", description: "specify the record name, this option can only be used when [merge-abc] is enabled." }, { name: 'output-proto', type: Boolean, defaultValue: false, description: "Output protoBin file. Default: false" }, - { name: 'proto-name', type: String, defaultValue: "", description: "specify the output name for serializd protobuf file (.protoBin)" }, { name: 'merge-abc', type: Boolean, defaultValue: false, description: "Compile as merge abc" }, ] @@ -345,13 +344,6 @@ export class CmdOptions { return this.options["output-proto"]; } - static getProtoName(): string { - if (!this.options) { - return ""; - } - return this.options["proto-name"]; - } - static isMergeAbc(): boolean { if (!this.options) { return false; diff --git a/ts2panda/src/ts2panda.ts b/ts2panda/src/ts2panda.ts index 8f1e9dfbcc..629511fd0e 100644 --- a/ts2panda/src/ts2panda.ts +++ b/ts2panda/src/ts2panda.ts @@ -226,7 +226,6 @@ export class Ts2Panda { "display_typeinfo": CmdOptions.getDisplayTypeinfo(), "is_dts_file": isGlobalDeclare(), "output-proto": CmdOptions.isOutputproto(), - "proto-name": CmdOptions.getProtoName(), "record_type": enableRecordType }; let jsonOpt = JSON.stringify(options, null, 2); diff --git a/ts2panda/ts2abc/ts2abc.cpp b/ts2panda/ts2abc/ts2abc.cpp index 073db29293..2e564efc01 100644 --- a/ts2panda/ts2abc/ts2abc.cpp +++ b/ts2panda/ts2abc/ts2abc.cpp @@ -1030,9 +1030,6 @@ static void ParseCompilerOutputProto(const Json::Value &rootValue) if (rootValue.isMember("output-proto") && rootValue["output-proto"].isBool()) { g_isOutputProto = rootValue["output-proto"].asBool(); } - if (rootValue.isMember("proto-name") && rootValue["proto-name"].isString()) { - g_compilerOutputProto = rootValue["proto-name"].asString(); - } } static void ReplaceAllDistinct(std::string &str, const std::string &oldValue, const std::string &newValue) @@ -1250,28 +1247,28 @@ static void ParseSingleTypeInfo(const Json::Value &rootValue, panda::pandasm::Pr rec.field_list.emplace_back(std::move(typeSummaryIndexField)); } } - } else { - auto ecmaTypeInfoRecord = panda::pandasm::Record("_ESTypeInfoRecord", LANG_EXT); - ecmaTypeInfoRecord.metadata->SetAccessFlags(panda::ACC_PUBLIC); - - auto typeFlagField = panda::pandasm::Field(LANG_EXT); - typeFlagField.name = "typeFlag"; - typeFlagField.type = panda::pandasm::Type("u8", 0); - typeFlagField.metadata->SetValue(panda::pandasm::ScalarValue::Create( - static_cast(typeFlag))); - ecmaTypeInfoRecord.field_list.emplace_back(std::move(typeFlagField)); - - if (g_enableTypeinfo) { - auto typeSummaryIndexField = panda::pandasm::Field(LANG_EXT); - typeSummaryIndexField.name = "typeSummaryOffset"; - typeSummaryIndexField.type = panda::pandasm::Type("u32", 0); - typeSummaryIndexField.metadata->SetValue( - panda::pandasm::ScalarValue::Create(typeSummaryIndex)); - ecmaTypeInfoRecord.field_list.emplace_back(std::move(typeSummaryIndexField)); - } + return; + } + auto ecmaTypeInfoRecord = panda::pandasm::Record("_ESTypeInfoRecord", LANG_EXT); + ecmaTypeInfoRecord.metadata->SetAccessFlags(panda::ACC_PUBLIC); + + auto typeFlagField = panda::pandasm::Field(LANG_EXT); + typeFlagField.name = "typeFlag"; + typeFlagField.type = panda::pandasm::Type("u8", 0); + typeFlagField.metadata->SetValue(panda::pandasm::ScalarValue::Create( + static_cast(typeFlag))); + ecmaTypeInfoRecord.field_list.emplace_back(std::move(typeFlagField)); - prog.record_table.emplace(ecmaTypeInfoRecord.name, std::move(ecmaTypeInfoRecord)); + if (g_enableTypeinfo) { + auto typeSummaryIndexField = panda::pandasm::Field(LANG_EXT); + typeSummaryIndexField.name = "typeSummaryOffset"; + typeSummaryIndexField.type = panda::pandasm::Type("u32", 0); + typeSummaryIndexField.metadata->SetValue( + panda::pandasm::ScalarValue::Create(typeSummaryIndex)); + ecmaTypeInfoRecord.field_list.emplace_back(std::move(typeSummaryIndexField)); } + + prog.record_table.emplace(ecmaTypeInfoRecord.name, std::move(ecmaTypeInfoRecord)); } static int ParseSmallPieceJson(const std::string &subJson, panda::pandasm::Program &prog) @@ -1471,14 +1468,8 @@ bool GenerateProgram([[maybe_unused]] const std::string &data, const std::string Logd("parsing done, calling pandasm\n"); - if (options.GetCompilerOutputProto().size() > 0) { - g_compilerOutputProto = options.GetCompilerOutputProto(); - } - - std::string compilerOutputProto = g_compilerOutputProto; - - if (compilerOutputProto.size() == 0 && g_isOutputProto) { - compilerOutputProto = output.substr(0, output.find_last_of(".") + 1).append(PROTO_BIN_SUFFIX); + if (g_isOutputProto) { + g_compilerOutputProto = output.substr(0, output.find_last_of(".") + 1).append(PROTO_BIN_SUFFIX); } #ifdef ENABLE_BYTECODE_OPT @@ -1506,8 +1497,8 @@ bool GenerateProgram([[maybe_unused]] const std::string &data, const std::string panda::bytecodeopt::OptimizeBytecode(&prog, mapsp, output.c_str(), true); - if (compilerOutputProto.size() > 0) { - panda::proto::ProtobufSnapshotGenerator::GenerateSnapshot(prog, compilerOutputProto); + if (g_compilerOutputProto.size() > 0) { + panda::proto::ProtobufSnapshotGenerator::GenerateSnapshot(prog, g_compilerOutputProto); return true; } @@ -1518,8 +1509,8 @@ bool GenerateProgram([[maybe_unused]] const std::string &data, const std::string return true; } #endif - if (compilerOutputProto.size() > 0) { - panda::proto::ProtobufSnapshotGenerator::GenerateSnapshot(prog, compilerOutputProto); + if (g_compilerOutputProto.size() > 0) { + panda::proto::ProtobufSnapshotGenerator::GenerateSnapshot(prog, g_compilerOutputProto); return true; } diff --git a/ts2panda/ts2abc/ts2abc_options.h b/ts2panda/ts2abc/ts2abc_options.h index d4cfb330b5..41dafe7c45 100755 --- a/ts2panda/ts2abc/ts2abc_options.h +++ b/ts2panda/ts2abc/ts2abc_options.h @@ -41,7 +41,6 @@ namespace panda::ts2abc { parser->Add(&compile_by_pipe_arg_); parser->Add(&compile_npm_entries_); parser->Add(&compiler_output_proto_); - parser->Add(&output_proto_name_); parser->EnableTail(); parser->PushBackTail(&Tail_Arg1_arg_); parser->PushBackTail(&Tail_Arg2_arg_); @@ -182,21 +181,6 @@ namespace panda::ts2abc { return compiler_output_proto_.WasSet(); } - std::string GetCompilerOutputProto() const - { - return output_proto_name_.GetValue(); - } - - void SetCompilerOutputProto(std::string value) - { - output_proto_name_.SetValue(value); - } - - bool WasSetCompilerOutputProto() const - { - return output_proto_name_.WasSet(); - } - std::string GetTailArg1() const { return Tail_Arg1_arg_.GetValue(); @@ -259,8 +243,6 @@ namespace panda::ts2abc { R"(Compile npm entries info into an abc file)"}; panda::PandArg compiler_output_proto_{ "output-proto", false, R"(Output protoBin file)"}; - panda::PandArg output_proto_name_{ "proto-name", "", - R"(Specify the output name for serializd protobuf file (.protoBin))"}; panda::PandArg Tail_Arg1_arg_{ "ARG_1", "", R"(Path to input(json file) or path to output(ark bytecode)" " when 'compile-by-pipe' enabled)"}; -- Gitee From d8a79119502f5bf9eb93ec6cdf65a02e91cda878 Mon Sep 17 00:00:00 2001 From: gavin1012_hw Date: Mon, 24 Oct 2022 16:11:14 +0800 Subject: [PATCH 7/7] Fix testinstype test Issue: I5XDVD Signed-off-by: gavin1012_hw Change-Id: I48ca1bc2ccf9861cb18fed841a33e5d794c6fe4e --- testTs/instype/recordthis-expected.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/testTs/instype/recordthis-expected.txt b/testTs/instype/recordthis-expected.txt index d1e0c46c2d..fbc6352221 100644 --- a/testTs/instype/recordthis-expected.txt +++ b/testTs/instype/recordthis-expected.txt @@ -9,7 +9,7 @@ Handle types for function: setName Handle types for function: setId (instruction order, type): (-2, 111), (-1, 105), Handle types for function: dump -(instruction order, type): (-2, 111), (-1, 107), (14, 4), +(instruction order, type): (-2, 111), (-1, 107), (16, 4), Handle types for function: stest (instruction order, type): (-2, 101), (-1, 108), Handle types for function: test @@ -17,6 +17,6 @@ Handle types for function: test Handle types for function: testwiththis (instruction order, type): (-2, 111), (-1, 110), Handle types for function: add -(instruction order, type): (-1, 112), (7, 1), +(instruction order, type): (-1, 112), (9, 1), Handle types for function: func_main_0 (instruction order, type): -- Gitee