diff --git a/es2panda/aot/options.cpp b/es2panda/aot/options.cpp index d581dab53ac1c70e9f9c62cd76feee4c2ce02550..5d189f52032ae35cf67940e65da30efd86459325 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/HowToWriteProtoForAssemblyStuff.md b/merge_abc/HowToWriteProtoForAssemblyStuff.md new file mode 100644 index 0000000000000000000000000000000000000000..83f76ebe34a0002579cc29342f7bb7b908f1a7f3 --- /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; +} +``` diff --git a/merge_abc/src/assemblyFileLocationProto.cpp b/merge_abc/src/assemblyFileLocationProto.cpp index 9f4a0f23bd09b33e9a20c4497a43ff80d3fbb763..e3ef08e9764142893e15997b033ce9207fba1b32 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 83afe39022584f2820b3e615a3714085a5b00be2..2c13264974648c2248d800d34773ade3329be0b7 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 0b56bf70f5bb28ed995a5714db86b2a79bcf7911..f5f9972365d15cf091dae509321871b69c9440c7 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 f355a80490d50fe5e558267315b95a726058d764..63b18cefc1927df9c51b472a40f4b67e395d288e 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 cfd7d34d44076f92dc9c976d744e2f2a04a18040..9409ff12972b829349903b3fe7b4c3b4ef17a8d6 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/merge_abc/src/options.h b/merge_abc/src/options.h index e1c76e170276edaee7d738adce3965c11b57538c..8475ab1d20515beba5af1d11809f3a69c6b172cd 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 0a06caa4bd5197713a7369c648b5331efdeeb267..ce5bce355502f8bd3063a2cfa6b576de7c8660ca 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): @@ -231,48 +232,106 @@ class ArkProgram(): os.path.split(dependency)[1]))[0] output_abc = f"{output_file}.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": + proto_bin_file = output_file + "." + PROTO_BIN_SUFFIX + 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'] 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 - cmd_args = ['node', '--expose-gc', frontend_tool, - js_file, '-o', out_file] + if merge_abc_mode != "0": + 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] 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', - proto_bin_file, js_file] + # '--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: + # for testing no-record-name abc cmd_args = [frontend_tool, '--opt-level=' + str(self.opt_level), '--function-threads=' + str(self.es2abc_thread_count), '--output', @@ -281,7 +340,7 @@ class ArkProgram(): 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): @@ -293,13 +352,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 self.ark_frontend == ARK_FRONTEND_LIST[1] and merge_abc_mode != "0": - cmd_args = [merge_abc_binary, '--input', proto_bin_file, - '--suffix', "bin", '--outputFilePath', - file_dir, '--output', proto_abc_file] - retcode = exec_command(cmd_args) + + if merge_abc_mode != "0": + retcode = self.gen_merged_abc(dependencies, file_name_pre, + proto_bin_file, retcode) + return retcode def compile_aot(self): @@ -335,7 +395,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]: @@ -344,15 +403,15 @@ 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'] + 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 +447,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/scripts/generate_js_bytecode.py b/ts2panda/scripts/generate_js_bytecode.py index 2e7949cda3a523410e4b0d7d8d15d182df4a41f0..0f4aca8823b78f485bb8a4a476a10c631b4d342a 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/bcGenUtil.ts b/ts2panda/src/base/bcGenUtil.ts index 4be0a9afa6cf2f3c9fdab7ce29c460aad7ad202a..7f87a6533d1a667f9c8a34f72577c9192c78a6f1 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 a6e91703c4445ceb6e93702b2020fe6abc3c1b9d..5393dbd8b148e4487e55d9da6196666bb69005e2 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 9b60cb6d457f9cc9de76c546581f8c1dde383345..2453424609fe347aa7ef928b26c18ecd710bbb7c 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 == "" && CmdOptions.isMergeAbc()) { + 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 bf19d72cd51dce6f019b031fb97c0b04d61618c4..99a1539d77ec4346e99a446f8ee39556baa49bd7 100644 --- a/ts2panda/src/cmdOptions.ts +++ b/ts2panda/src/cmdOptions.ts @@ -51,6 +51,9 @@ 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, 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: 'merge-abc', type: Boolean, defaultValue: false, description: "Compile as merge abc" }, ] @@ -209,6 +212,25 @@ 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"]; + } + static getTimeOut(): Number { if (!this.options) { return 0; @@ -315,6 +337,20 @@ export class CmdOptions { return this.options["generate-tmp-file"]; } + static isOutputproto(): boolean { + if (!this.options) { + return false; + } + return this.options["output-proto"]; + } + + 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/compiler.ts b/ts2panda/src/compiler.ts index d15844a0005f46f2c4369740144c0bf31656b52e..a4027cacb97450e3d2eff5e76f4721372e53279d 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 b4c4413c6bc67650755347ae5a4442f53b42923f..8409b71ab9561ca826879f4a95bc4362164abddf 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,8 +186,11 @@ export class CompilerDriver { listenErrorEvent(ts2abcProc); try { + if (CmdOptions.isMergeAbc()) { + // 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]; @@ -357,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 @@ -367,20 +380,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.getFormatedRecordName()}default`; } - return `#${this.getFuncId(funcNode)}#`; + return `${this.getFormatedRecordName()}#${this.getFuncId(funcNode)}#`; } if (name == "func_main_0") { - return `#${this.getFuncId(funcNode)}#${name}`; + return `${this.getFormatedRecordName()}#${this.getFuncId(funcNode)}#${name}`; } let funcNameMap = recorder.getFuncNameMap(); @@ -397,7 +410,7 @@ export class CompilerDriver { name = `#${this.getFuncId(funcNode)}#` } } - return name; + return `${this.getFormatedRecordName()}${name}`; } getInternalNameForCtor(node: ts.ClassLikeDeclaration, ctor: ts.ConstructorDeclaration) { @@ -406,7 +419,7 @@ export class CompilerDriver { if (name.lastIndexOf(".") != -1) { name = `#${this.getFuncId(ctor)}#` } - return name; + return `${this.getFormatedRecordName()}${name}`; } writeBinaryFile(pandaGen: PandaGen) { diff --git a/ts2panda/src/expression/metaProperty.ts b/ts2panda/src/expression/metaProperty.ts index eadef5cdee62d84c92bf3ea6a4da410c4db6ecbd..de0500b3051ae7f37bf677ab3ee0dc292da34912 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/index.ts b/ts2panda/src/index.ts index 62cfa8cbb593828e757da4806b0b51b68f39ecec..61f2dbfed03983b0f4e2496871a577618c034b00 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) { @@ -45,7 +54,8 @@ 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)); + CompilerDriver.srcNode = node; setGlobalStrict(jshelpers.isEffectiveStrictModeSourceFile(node, options)); compilerDriver.compile(node); compilerDriver.showStatistics(); @@ -90,7 +100,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 +128,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); @@ -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){ @@ -203,12 +198,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 +303,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 +328,8 @@ 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); + CompilerDriver.srcNode = node; setGlobalStrict(jshelpers.isEffectiveStrictModeSourceFile(node, options)); compilerDriver.compile(node); return node; @@ -347,10 +345,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/lexenv.ts b/ts2panda/src/lexenv.ts index ee896e07f6d054342b5dc5c3f8ab574faebb616d..aba261946ab94d1da53213d7102dc0a09e828380 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/pandagen.ts b/ts2panda/src/pandagen.ts index 2ffc0c0c2acd551e2c67de4834d981a00edf4aa9..b168d001560945f61ada3ed5885e41f359d9a671 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 50231d927905c22b73a2721ef576b94bf39280b7..236085d1122388770deb4c2bac3be949480d74e4 100644 --- a/ts2panda/src/pandasm.ts +++ b/ts2panda/src/pandasm.ts @@ -115,25 +115,9 @@ 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/recorder.ts b/ts2panda/src/recorder.ts index 866ed784d9dd2361c4f74a2d2bd02fec1222567f..2f3881b13d95af3b0db8d9d9c08dc39193bcf449 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/scope.ts b/ts2panda/src/scope.ts index 3c8b01a1c502da35fbf26e29f44ea11e277d39f5..637dc19b6cb07c071b68b62f40e3179a75d522ff 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 56a29cbcaef00674bcdbcdc86dea44e9092a2f73..3b4368dbcff4b822021647b93817a9f5f4350f81 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/src/ts2panda.ts b/ts2panda/src/ts2panda.ts index a97288f3f3caa47eb141aa30651cb8ae59117080..629511fd0e60fc49fa773cebc8896c3d5f4ed934 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 { @@ -211,24 +212,11 @@ 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 = { "t": JsonType.options, + "merge_abc": CmdOptions.isMergeAbc(), "module_mode": CmdOptions.isModules(), "commonjs_module": CmdOptions.isCommonJs(), "debug_mode": CmdOptions.isDebugMode(), @@ -237,6 +225,7 @@ export class Ts2Panda { "opt_log_level": CmdOptions.getOptLogLevel(), "display_typeinfo": CmdOptions.getDisplayTypeinfo(), "is_dts_file": isGlobalDeclare(), + "output-proto": CmdOptions.isOutputproto(), "record_type": enableRecordType }; let jsonOpt = JSON.stringify(options, null, 2); @@ -247,6 +236,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 +358,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 2ec85828daad71f0df209b090abcc13889319dc0..d17b95e933d6b20600619d5729aa2ceec591681b 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 60c24b23ce02a49a3f57117ba2e8c8ca70fe5ad7..f814112ec480d21082eb8ec814586a1e8b8ba1af 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 ff7e32c2442d3556047e05087f5ba06af9200b6b..9c8985d79b87662b3c0f154bf1c2d576abe9fd3a 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), "#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/arguments.test.ts b/ts2panda/tests/expression/arguments.test.ts index f509b3966fd4b2535d089e8dde107a85177bd70e..60d84a95ab9224b74d92b88f74b51eee1b2dd335 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/call.test.ts b/ts2panda/tests/expression/call.test.ts index a2b6f7bb1d5abc63521941a548025c94af6bf9fe..6e82a070e0e99ebcdfe4fe27cd5692b85b0d94be 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 41d44eb25bcc47960bcc8cb922c2c8c9054f70c8..20b13a70a75f2f6b70b11592660847ba07a7640b 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), "#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/functionExpression.test.ts b/ts2panda/tests/expression/functionExpression.test.ts index d434f440aec0df7be9c9c1f345cc1d48ba22aa9e..b4cd1c8e7a5d034b836bf224a69f5887a8ed0d7e 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/literal.test.ts b/ts2panda/tests/expression/literal.test.ts index 832ba0b657aeb33463c9ff3b9f01686b48f830ee..74ea3b3ffe91e7ab0deb1085fa96b0f8fff5deee 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/expression/thisKeyWord.test.ts b/ts2panda/tests/expression/thisKeyWord.test.ts index 9762e991210e94ef855a059fb240668a41640149..c1ae227b887e73e32300ffdcae2706a3db510845 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 5542972dc66d8ea9898bc0124e9a0e6f8186e8e4..30c227a42039c1f154c8edaab09d94c0eb12c92f 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 5c5206892929565237b45b46f2084004898be458..c5d6e49463c73a6cf4406793606d51bbbb29f4ad 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 7c5ef3b078da143aad91336341fa6aaf5bc0a644..6405c9cd96eb502d1f63fcaafccd9f81b29c368b 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/switch.test.ts b/ts2panda/tests/statements/switch.test.ts index f09bb9bce2bebcd1c7f1ad893ea777ef02a173ac..c50027d68836adbe15938b85f7f7332d04db9ba6 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/statements/variableDeclaration.test.ts b/ts2panda/tests/statements/variableDeclaration.test.ts index 95d5bbb47afb8dcae54889b47695b555518640fd..88db2c51f31051d2e504262752a9692340d51f31 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 131bcc2e47f7531f0977990efd9aace9b649175d..f671983ef1a091cd9081dde22759d3390290c51b 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 = [ @@ -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] @@ -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 = [ @@ -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); @@ -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 = [ @@ -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] @@ -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 = [ @@ -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); @@ -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 = [ @@ -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); @@ -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 = [ @@ -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 1a58c70fb96511d321831c439711666b2fb2e97f..0ee5e903a62d82f7313f36bcfc777ba15c8e72b6 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 = [ @@ -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); @@ -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 = [ @@ -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); @@ -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 = [ @@ -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); @@ -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 = [ @@ -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); @@ -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 = [ @@ -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); @@ -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 = [ @@ -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); @@ -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 = [ @@ -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); @@ -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 = [ @@ -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 5a37e3d989bce5c20a6781e05701ea20dd5b853f..b6b640efcd0c629c8600323c6d8ab52a2a3a392c 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 = [ @@ -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"], @@ -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 = [ @@ -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"], @@ -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 = [ @@ -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"], @@ -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 = [ @@ -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); @@ -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 = [ @@ -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 9f7446a20aac5fea670fe6f05f812f4732548cb4..600f68aa49d7c5799ee1768a2f6d6e21e11a95a6 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 = [ @@ -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"], @@ -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 = [ @@ -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 0f726cd7fcd6bf582d2cf0286237e6d9aaadee7c..d7417cea10fc39eeb060e58c8199a18403252481 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; @@ -79,7 +79,7 @@ describe("primitives tests in primitives.test.ts", function() { let expectedBuffValues = [ [ [2, 1], - [24, "_1"], + [24, "snippet_1"], [2, 0] ], [ @@ -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 = [ @@ -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); @@ -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 299d54a28bce35a16807646f43339004b2f9e6a1..7b0be9553f603c06b52753dc5691dc49aafa03ea 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 = [ @@ -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] @@ -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 = [ @@ -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] @@ -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 = [ @@ -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] @@ -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 = [ @@ -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 2d9f7ed31846e8178766f3856c858f318b605516..31017db4ad7494d8735d56f092c6376065159729 100644 --- a/ts2panda/tests/utils/base.ts +++ b/ts2panda/tests/utils/base.ts @@ -141,12 +141,19 @@ 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'); + let compilerDriver = new CompilerDriver('UnitTest', 'UnitTest'); + CompilerDriver.srcNode = sourceFile; if (!passes) { passes = []; @@ -156,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"); @@ -166,7 +174,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"); }) } @@ -175,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, { @@ -191,7 +201,8 @@ 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.srcNode = sourceFile; compilerDriver.setCustomPasses([]); compilerDriver.compileUnitTest(sourceFile, []); compileUnits = compilerDriver.getCompilationUnits(); @@ -228,7 +239,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 +248,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/tests/watch_expression/addWatch.test.ts b/ts2panda/tests/watch_expression/addWatch.test.ts index 7d00f48a7065d3fe23072c05b09732d5e2eaf564..586e49acf26b4a28429054aebd281dd8f0b3dfce 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,15 +342,13 @@ 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 = [ - new Createarraywithbuffer(new Imm(0), "_1"), + new Createarraywithbuffer(new Imm(0), "snippet_1"), new Sta(new VReg()), new Lda(new VReg()), @@ -380,15 +358,13 @@ 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 = [ - 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()), @@ -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,16 +882,14 @@ 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 = [ 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 c2840600589426893f349ab34431cb1ae148d18f..7e315e564cd9c7c34472fde401210990c1900a7b 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 57c350067eea1a9a4c3b2750f21c54640296a751..2e564efc0198ff25d374382bba5b07f0aee3f872 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; @@ -52,6 +53,8 @@ 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; @@ -69,7 +72,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; } @@ -177,6 +179,15 @@ static std::string GetLiteralId(int64_t index) return g_recordName + "_" + std::to_string(index); } +static bool IsFuncMain0(std::string funcName) +{ + std::string expectedName = "func_main_0"; + if (g_isMergeAbc) { + expectedName = g_recordName + "." + expectedName; + } + return funcName == expectedName; +} + static std::string ParseUnicodeEscapeString(const std::string &data) { const int unicodeEscapeSymbolLen = 2; @@ -591,34 +602,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 +761,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 +788,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; } } @@ -849,15 +832,13 @@ 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); ParseFunctionKind(function, pandaFunc); ParseFunctionIcSize(function, pandaFunc); - if (g_isDtsFile && pandaFunc.name != "func_main_0") { + if (g_isDtsFile && !IsFuncMain0(pandaFunc.name)) { pandaFunc.metadata->SetAttribute("external"); } @@ -879,6 +860,13 @@ 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 @@ -894,20 +882,29 @@ static void GenerateCommonJsRecord(panda::pandasm::Program &prog, bool isCommonJ 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"); + 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 = moduleName; + moduleIdxField.name = fieldName; moduleIdxField.type = panda::pandasm::Type("u32", 0); std::string moduleId = GetLiteralId(g_newLiteralArrayIndex); moduleIdxField.metadata->SetValue( @@ -937,11 +934,19 @@ int ParseJson(const std::string &data, Json::Value &rootValue) return RETURN_SUCCESS; } +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()) { + if (rootValue["module_mode"].asBool() && !g_isMergeAbc) { GenerateESModuleRecord(prog); } } @@ -951,8 +956,12 @@ static void ParseCommonJsModuleMode(const Json::Value &rootValue, panda::pandasm { Logd("------------parse commonjs_module_mode-------------"); if (rootValue.isMember("commonjs_module") && rootValue["commonjs_module"].isBool()) { - if (rootValue["commonjs_module"].asBool()) { - GenerateCommonJsRecord(prog, true); + if (g_isMergeAbc) { + SetCommonjsField(prog, rootValue["commonjs_module"].asBool()); + } else { + if (rootValue["commonjs_module"].asBool()) { + GenerateCommonJsRecord(prog, true); + } } } } @@ -1018,10 +1027,11 @@ 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(); } } + 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()) { @@ -1037,6 +1047,7 @@ static void ParseOptions(const Json::Value &rootValue, panda::pandasm::Program & { GenerateESCallTypeAnnotationRecord(prog); GenerateESTypeAnnotationRecord(prog); + ParseMergeAbcMode(rootValue); ParseModuleMode(rootValue, prog); ParseCommonJsModuleMode(rootValue, prog); ParseLogEnable(rootValue); @@ -1055,9 +1066,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)); } @@ -1213,6 +1225,30 @@ static void ParseSingleTypeInfo(const Json::Value &rootValue, panda::pandasm::Pr 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)); + } + } + return; + } auto ecmaTypeInfoRecord = panda::pandasm::Record("_ESTypeInfoRecord", LANG_EXT); ecmaTypeInfoRecord.metadata->SetAccessFlags(panda::ACC_PUBLIC); @@ -1255,7 +1291,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; } @@ -1432,9 +1468,8 @@ 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(); + if (g_isOutputProto) { + g_compilerOutputProto = output.substr(0, output.find_last_of(".") + 1).append(PROTO_BIN_SUFFIX); } #ifdef ENABLE_BYTECODE_OPT @@ -1462,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; } @@ -1474,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; } @@ -1488,6 +1523,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 4b4658dfdb431b8337ffa9a6a5be827e7d8af10d..9288b91c279c647fcca8c2d927341bcfa4fc5e19 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 76f326fe257cdf811b77e5da75b9b759e2d76843..41dafe7c452c6efedb9b6b0c4f7846025b355193 100755 --- a/ts2panda/ts2abc/ts2abc_options.h +++ b/ts2panda/ts2abc/ts2abc_options.h @@ -39,6 +39,7 @@ 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->EnableTail(); parser->PushBackTail(&Tail_Arg1_arg_); @@ -150,17 +151,32 @@ 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(); } @@ -223,8 +239,10 @@ 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", "", - R"(compiler proto serialize binary 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 Tail_Arg1_arg_{ "ARG_1", "", R"(Path to input(json file) or path to output(ark bytecode)" " when 'compile-by-pipe' enabled)"};