diff --git a/es2panda/aot/options.cpp b/es2panda/aot/options.cpp index d3acf5dcf42c8eaec805d00f0564354e4b55e33e..20b23ce7b3a3cba00951b7e143d300eec5b09ce8 100644 --- a/es2panda/aot/options.cpp +++ b/es2panda/aot/options.cpp @@ -38,11 +38,6 @@ T RemoveExtension(T const &filename) return P > 0 && P != T::npos ? filename.substr(0, P) : filename; } -static std::string FormatRecordName(const std::string &recordName) -{ - return recordName + "."; -} - static std::vector GetStringItems(std::string &input, const std::string &delimiter) { std::vector items; @@ -81,7 +76,7 @@ bool Options::CollectInputFilesFromFileList(const std::string &input) } // itemList: [filePath, recordName, moduleKind, sourceFile] std::string fileName = itemList[0]; - std::string recordName = FormatRecordName(itemList[1]); + std::string recordName = itemList[1]; parser::ScriptKind scriptKind; if (itemList[2] == "script") { scriptKind = parser::ScriptKind::SCRIPT; @@ -278,7 +273,6 @@ bool Options::Parse(int argc, const char **argv) recordName_ = compilerOutput_.empty() ? "Base64Output" : RemoveExtension(util::Helpers::BaseName(compilerOutput_)); } - recordName_ = FormatRecordName(recordName_); } if (!inputIsEmpty) { diff --git a/es2panda/binder/binder.cpp b/es2panda/binder/binder.cpp index 43a98efbaadad7c669278604df5e3d24fc8176da..3216c539cc3a9f087ed41f82d580f2f41a8de9f9 100644 --- a/es2panda/binder/binder.cpp +++ b/es2panda/binder/binder.cpp @@ -202,13 +202,13 @@ void Binder::BuildFunction(FunctionScope *funcScope, util::StringView name) bool funcNameWithoutDot = (name.Find(".") == std::string::npos); bool funcNameWithoutBackslash = (name.Find("\\") == std::string::npos); if (name != ANONYMOUS_FUNC_NAME && funcNameWithoutDot && funcNameWithoutBackslash && !functionNames_.count(name)) { - auto internalName = std::string(program_->RecordName()) + std::string(name); + auto internalName = std::string(program_->FormatedRecordName()) + std::string(name); functionNames_.insert(name); funcScope->BindName(name, util::UString(internalName, Allocator()).View()); return; } std::stringstream ss; - ss << std::string(program_->RecordName()); + ss << std::string(program_->FormatedRecordName()); uint32_t idx = functionNameIndex_++; ss << "#" << std::to_string(idx) << "#"; if (funcNameWithoutDot && funcNameWithoutBackslash) { diff --git a/es2panda/compiler/core/compileQueue.cpp b/es2panda/compiler/core/compileQueue.cpp index f8709aa36dccf91705432f5920f71668ccd9f809..ea11d2bd33e33b34c914a75c9296c6559dc50e12 100644 --- a/es2panda/compiler/core/compileQueue.cpp +++ b/es2panda/compiler/core/compileQueue.cpp @@ -78,7 +78,7 @@ void CompileFunctionJob::Run() FunctionEmitter funcEmitter(&allocator, &pg); funcEmitter.Generate(context_->HotfixHelper()); - context_->GetEmitter()->AddFunction(&funcEmitter); + context_->GetEmitter()->AddFunction(&funcEmitter, context_); if (dependant_) { dependant_->Signal(); diff --git a/es2panda/compiler/core/compilerContext.h b/es2panda/compiler/core/compilerContext.h index 6acc7b83fb53a24cf1004237abdbab7734ca6349..0528705b84f8697c6d6a392f2f4aea0f62537a97 100644 --- a/es2panda/compiler/core/compilerContext.h +++ b/es2panda/compiler/core/compilerContext.h @@ -19,6 +19,7 @@ #include #include #include +#include #include #include diff --git a/es2panda/compiler/core/emitter/emitter.cpp b/es2panda/compiler/core/emitter/emitter.cpp index 7006d4478e9696de8d804453c27c3562d75076dd..1ffd7a46d17e456582088b9098f6cf1498ab2077 100644 --- a/es2panda/compiler/core/emitter/emitter.cpp +++ b/es2panda/compiler/core/emitter/emitter.cpp @@ -343,7 +343,7 @@ Emitter::Emitter(const CompilerContext *context) prog_->lang = LANG_EXT; if (context->IsMergeAbc()) { - auto recordName = context->Binder()->Program()->RecordName().Mutf8(); + auto recordName = context->Binder()->Program()->FormatedRecordName().Mutf8(); rec_ = new panda::pandasm::Record(recordName.substr(0, recordName.find_last_of('.')), LANG_EXT); SetCommonjsField(context->Binder()->Program()->Kind() == parser::ScriptKind::COMMONJS); } else { @@ -359,7 +359,7 @@ Emitter::~Emitter() delete prog_; } -void Emitter::AddFunction(FunctionEmitter *func) +void Emitter::AddFunction(FunctionEmitter *func, CompilerContext *context) { std::lock_guard lock(m_); @@ -369,7 +369,8 @@ void Emitter::AddFunction(FunctionEmitter *func) for (auto &[idx, buf] : func->LiteralBuffers()) { auto literalArrayInstance = panda::pandasm::LiteralArray(std::move(buf)); - prog_->literalarray_table.emplace(std::to_string(idx), std::move(literalArrayInstance)); + auto litId = std::string(context->Binder()->Program()->RecordName()) + "_" + std::to_string(idx); + prog_->literalarray_table.emplace(litId, std::move(literalArrayInstance)); } auto *function = func->Function(); @@ -380,12 +381,13 @@ void Emitter::AddSourceTextModuleRecord(ModuleRecordEmitter *module, CompilerCon { std::lock_guard lock(m_); + auto moduleLiteral = std::string(context->Binder()->Program()->RecordName()) + "_" + std::to_string(module->Index()); if (context->IsMergeAbc()) { auto moduleIdxField = panda::pandasm::Field(LANG_EXT); moduleIdxField.name = "moduleRecordIdx"; moduleIdxField.type = panda::pandasm::Type("u32", 0); - moduleIdxField.metadata->SetValue(panda::pandasm::ScalarValue::Create( - static_cast(module->Index()))); + moduleIdxField.metadata->SetValue(panda::pandasm::ScalarValue::Create( + static_cast(moduleLiteral))); rec_->field_list.emplace_back(std::move(moduleIdxField)); if (context->HotfixHelper()) { @@ -398,8 +400,8 @@ void Emitter::AddSourceTextModuleRecord(ModuleRecordEmitter *module, CompilerCon auto moduleIdxField = panda::pandasm::Field(LANG_EXT); moduleIdxField.name = std::string {context->Binder()->Program()->SourceFile()}; moduleIdxField.type = panda::pandasm::Type("u32", 0); - moduleIdxField.metadata->SetValue(panda::pandasm::ScalarValue::Create( - static_cast(module->Index()))); + moduleIdxField.metadata->SetValue(panda::pandasm::ScalarValue::Create( + static_cast(moduleLiteral))); ecmaModuleRecord.field_list.emplace_back(std::move(moduleIdxField)); if (context->HotfixHelper()) { @@ -409,7 +411,7 @@ void Emitter::AddSourceTextModuleRecord(ModuleRecordEmitter *module, CompilerCon } auto &moduleLiteralsBuffer = module->Buffer(); auto literalArrayInstance = panda::pandasm::LiteralArray(std::move(moduleLiteralsBuffer)); - prog_->literalarray_table.emplace(std::to_string(module->Index()), std::move(literalArrayInstance)); + prog_->literalarray_table.emplace(static_cast(moduleLiteral), std::move(literalArrayInstance)); } void Emitter::DumpAsm(const panda::pandasm::Program *prog) diff --git a/es2panda/compiler/core/emitter/emitter.h b/es2panda/compiler/core/emitter/emitter.h index f689a4e57c80e973f81be76d7c0064134343f076..979356faab3d4654209a431d7d7ad74847f8d631 100644 --- a/es2panda/compiler/core/emitter/emitter.h +++ b/es2panda/compiler/core/emitter/emitter.h @@ -100,7 +100,7 @@ public: NO_COPY_SEMANTIC(Emitter); NO_MOVE_SEMANTIC(Emitter); - void AddFunction(FunctionEmitter *func); + void AddFunction(FunctionEmitter *func, CompilerContext *context); void AddSourceTextModuleRecord(ModuleRecordEmitter *module, CompilerContext *context); static void DumpAsm(const panda::pandasm::Program *prog); panda::pandasm::Program *Finalize(bool dumpDebugInfo, util::Hotfix *hotfixHelper); diff --git a/es2panda/parser/program/program.h b/es2panda/parser/program/program.h index 15cf51474dd0757547aa5da64df1b6964a02f1b7..650ce1978f21870f577caa32a081a93c0b03000c 100644 --- a/es2panda/parser/program/program.h +++ b/es2panda/parser/program/program.h @@ -90,6 +90,11 @@ public: return recordName_.View(); } + util::StringView FormatedRecordName() const + { + return formatedRecordName_.View(); + } + const lexer::LineIndex &GetLineIndex() const { return lineIndex_; @@ -120,6 +125,8 @@ public: void SetRecordName(const std::string &recordName) { recordName_ = util::UString(recordName, Allocator()); + std::string formatedRecordName = recordName + "."; + formatedRecordName_ = util::UString(formatedRecordName, Allocator()); } void AddHotfixHelper(util::Hotfix *hotfixHelper) @@ -142,6 +149,7 @@ private: util::UString sourceCode_ {}; util::UString sourceFile_ {}; util::UString recordName_ {}; + util::UString formatedRecordName_ {}; ScriptKind kind_ {}; ScriptExtension extension_ {}; lexer::LineIndex lineIndex_ {}; diff --git a/ts2panda/src/base/literal.ts b/ts2panda/src/base/literal.ts index 50d7c9d52c9f9d91839eef7a44b90885d4af03f0..2cfb24623694f2d639513a3d2b40c1ad4ee24fe8 100644 --- a/ts2panda/src/base/literal.ts +++ b/ts2panda/src/base/literal.ts @@ -14,59 +14,66 @@ */ export enum LiteralTag { - BOOLEAN = 1, - INTEGER = 2, - DOUBLE = 4, - STRING = 5, - METHOD = 6, - GENERATOR = 7, - ACCESSOR = 8, - METHODAFFILIATE = 9, - // 0x0a - 0x15 for ARRAY_Type - ASYNCGENERATOR = 22, - LITERALBUFFERINDEX = 23, - NULLVALUE = 255 + BOOLEAN = 1, + INTEGER = 2, + DOUBLE = 4, + STRING = 5, + METHOD = 6, + GENERATOR = 7, + ACCESSOR = 8, + METHODAFFILIATE = 9, + // 0x0a - 0x15 for ARRAY_Type + ASYNCGENERATOR = 22, + LITERALBUFFERINDEX = 23, + LITERALARRAY = 24, + BUILTINTYPEINDEX = 25, + NULLVALUE = 255 } export class Literal { - private t: LiteralTag; - private v: any; + private t: LiteralTag; + private v: any; - constructor(t: LiteralTag, v: any) { - this.t = t; - this.v = v; - } + constructor(t: LiteralTag, v: any) { + this.t = t; + this.v = v; + } - getTag() { - return this.t; - } + getTag() { + return this.t; + } - getValue() { - return this.v; - } + getValue() { + return this.v; + } } export class LiteralBuffer { - private lb: Literal[] = []; + private k: string; + private lb: Literal[] = []; - constructor() { }; + constructor() {}; - addLiterals(...literals: Array) { - this.lb.push(...literals); - } + addLiterals(...literals: Array) { + this.lb.push(...literals); + } - getLiterals() { - return this.lb; - } + getLiterals() { + return this.lb; + } - isEmpty() { - return this.lb.length == 0; - } + isEmpty() { + return this.lb.length == 0; + } + + getLiteral(index: number) { + if (index >= this.lb.length || this.lb.length <=0) { + return ; + } + return this.lb[index]; + } - getLiteral(index: number) { - if (index >= this.lb.length || this.lb.length <=0) { - return ; + setKey(key: string) { + this.k = key; } - return this.lb[index]; - } -} \ No newline at end of file +} diff --git a/ts2panda/src/base/typeSystem.ts b/ts2panda/src/base/typeSystem.ts index 43bdf6e64f06046a31eae1783f476faf7d2c5820..898b7f2665c4addc6462fa1fab93271c766e8b09 100644 --- a/ts2panda/src/base/typeSystem.ts +++ b/ts2panda/src/base/typeSystem.ts @@ -26,6 +26,8 @@ import { } from "./literal"; import { hasAbstractModifier } from "./util"; import { CmdOptions } from "../cmdOptions"; +import { getLiteralKey } from "./util"; +import { CompilerDriver } from "../compilerDriver"; export enum PrimitiveType { ANY, @@ -143,7 +145,8 @@ export enum AccessFlag { PROTECTED } -type ClassMemberFunction = ts.MethodDeclaration | ts.ConstructorDeclaration | ts.GetAccessorDeclaration | ts.SetAccessorDeclaration; +type ClassMemberFunction = ts.MethodDeclaration | ts.ConstructorDeclaration | + ts.GetAccessorDeclaration | ts.SetAccessorDeclaration; export abstract class BaseType { @@ -151,6 +154,15 @@ export abstract class BaseType { protected typeChecker = TypeChecker.getInstance(); protected typeRecorder = TypeRecorder.getInstance(); + protected transferType2Literal(type: number, literals: Array) { + if (type >= literalBufferIndexShift) { + let litId = getLiteralKey(CompilerDriver.srcNode, type - literalBufferIndexShift); + literals.push(new Literal(LiteralTag.LITERALARRAY, litId)); + } else { + literals.push(new Literal(LiteralTag.BUILTINTYPEINDEX, type)); + } + } + protected addCurrentType(node: ts.Node, index: number) { this.typeRecorder.addType2Index(node, index); } @@ -233,12 +245,16 @@ export class TypeSummary extends BaseType { transfer2LiteralBuffer(): LiteralBuffer { let countBuf = new LiteralBuffer(); let summaryLiterals: Array = new Array(); - summaryLiterals.push(new Literal(LiteralTag.INTEGER, L2Type._COUNTER)); let definedTypeNum = this.userDefinedClassNum; if (isGlobalDeclare()) { definedTypeNum += userDefinedTypeStartIndex - BuiltinType._HEAD; } summaryLiterals.push(new Literal(LiteralTag.INTEGER, definedTypeNum)); + let literalIdx = PandaGen.getLiteralArrayBuffer.length; + for (let i = 1; i <= definedTypeNum; i++) { + summaryLiterals.push(new Literal(LiteralTag.LITERALARRAY, + getLiteralKey(CompilerDriver.srcNode, literalIdx + i))); + } summaryLiterals.push(new Literal(LiteralTag.INTEGER, this.anonymousRedirect.length)); for (let element of this.anonymousRedirect) { summaryLiterals.push(new Literal(LiteralTag.STRING, element)); @@ -422,10 +438,10 @@ export class ClassType extends BaseType { classTypeLiterals.push(new Literal(LiteralTag.INTEGER, L2Type.CLASS)); classTypeLiterals.push(new Literal(LiteralTag.INTEGER, this.modifier)); - classTypeLiterals.push(new Literal(LiteralTag.INTEGER, this.extendsHeritage)); + this.transferType2Literal(this.extendsHeritage, classTypeLiterals); classTypeLiterals.push(new Literal(LiteralTag.INTEGER, this.implementsHeritages.length)); - this.implementsHeritages.forEach(heritage => { - classTypeLiterals.push(new Literal(LiteralTag.INTEGER, heritage)); + this.implementsHeritages.forEach(heritage => { // heritage types + this.transferType2Literal(heritage, classTypeLiterals); }); // record unstatic fields and methods @@ -446,7 +462,7 @@ export class ClassType extends BaseType { classTypeLiterals.push(new Literal(LiteralTag.INTEGER, transferredTarget.size)); transferredTarget.forEach((typeInfo, name) => { classTypeLiterals.push(new Literal(LiteralTag.STRING, name)); - classTypeLiterals.push(new Literal(LiteralTag.INTEGER, typeInfo[0])); // typeIndex + this.transferType2Literal(typeInfo[0], classTypeLiterals); classTypeLiterals.push(new Literal(LiteralTag.INTEGER, typeInfo[1])); // accessFlag classTypeLiterals.push(new Literal(LiteralTag.INTEGER, typeInfo[2])); // readonly }); @@ -458,7 +474,7 @@ export class ClassType extends BaseType { classTypeLiterals.push(new Literal(LiteralTag.INTEGER, transferredTarget.size)); transferredTarget.forEach((typeInfo, name) => { classTypeLiterals.push(new Literal(LiteralTag.STRING, name)); - classTypeLiterals.push(new Literal(LiteralTag.INTEGER, typeInfo)); + this.transferType2Literal(typeInfo, classTypeLiterals); }); } } @@ -480,7 +496,7 @@ export class ClassInstType extends BaseType { let classInstLiterals: Array = new Array(); classInstLiterals.push(new Literal(LiteralTag.INTEGER, L2Type.CLASSINST)); - classInstLiterals.push(new Literal(LiteralTag.INTEGER, this.shiftedReferredClassIndex)); + this.transferType2Literal(this.shiftedReferredClassIndex, classInstLiterals); classInstBuf.addLiterals(...classInstLiterals); return classInstBuf; @@ -585,20 +601,20 @@ export class FunctionType extends BaseType { funcTypeLiterals.push(new Literal(LiteralTag.STRING, this.name)); if (this.containThisParam) { funcTypeLiterals.push(new Literal(LiteralTag.INTEGER, 1)); // marker for having 'this' param - funcTypeLiterals.push(new Literal(LiteralTag.INTEGER, this.parameters[0])); + this.transferType2Literal(this.parameters[0], funcTypeLiterals); funcTypeLiterals.push(new Literal(LiteralTag.INTEGER, this.parameters.length - 1)); - for (let i = 1; i < this.parameters.length; i++) { - funcTypeLiterals.push(new Literal(LiteralTag.INTEGER, this.parameters[i])); + for (let i = 1; i < this.parameters.length; i++) { // normal parameter types + this.transferType2Literal(this.parameters[i], funcTypeLiterals); } } else { funcTypeLiterals.push(new Literal(LiteralTag.INTEGER, 0)); // marker for not having 'this' param funcTypeLiterals.push(new Literal(LiteralTag.INTEGER, this.parameters.length)); for (let i = 0; i < this.parameters.length; i++) { - funcTypeLiterals.push(new Literal(LiteralTag.INTEGER, this.parameters[i])); + this.transferType2Literal(this.parameters[i], funcTypeLiterals); } } - funcTypeLiterals.push(new Literal(LiteralTag.INTEGER, this.returnType)); + this.transferType2Literal(this.returnType, funcTypeLiterals); funcTypeBuf.addLiterals(...funcTypeLiterals); return funcTypeBuf; } @@ -675,7 +691,7 @@ export class UnionType extends BaseType { UnionTypeLiterals.push(new Literal(LiteralTag.INTEGER, L2Type.UNION)); UnionTypeLiterals.push(new Literal(LiteralTag.INTEGER, this.unionedTypeArray.length)); for (let type of this.unionedTypeArray) { - UnionTypeLiterals.push(new Literal(LiteralTag.INTEGER, type)); + this.transferType2Literal(type, UnionTypeLiterals); } UnionTypeBuf.addLiterals(...UnionTypeLiterals); return UnionTypeBuf; @@ -720,7 +736,7 @@ export class ArrayType extends BaseType { let arrayBuf = new LiteralBuffer(); let arrayLiterals: Array = new Array(); arrayLiterals.push(new Literal(LiteralTag.INTEGER, L2Type.ARRAY)); - arrayLiterals.push(new Literal(LiteralTag.INTEGER, this.referedTypeIndex)); + this.transferType2Literal(this.referedTypeIndex, arrayLiterals); arrayBuf.addLiterals(...arrayLiterals); return arrayBuf; } @@ -755,7 +771,7 @@ export class ObjectType extends BaseType { objLiterals.push(new Literal(LiteralTag.INTEGER, this.properties.size)); this.properties.forEach((typeIndex, name) => { objLiterals.push(new Literal(LiteralTag.STRING, name)); - objLiterals.push(new Literal(LiteralTag.INTEGER, typeIndex)); + this.transferType2Literal(typeIndex, objLiterals); }); objTypeBuf.addLiterals(...objLiterals); return objTypeBuf; @@ -868,7 +884,7 @@ export class InterfaceType extends BaseType { interfaceTypeLiterals.push(new Literal(LiteralTag.INTEGER, this.heritages.length)); this.heritages.forEach(heritage => { - interfaceTypeLiterals.push(new Literal(LiteralTag.INTEGER, heritage)); + this.transferType2Literal(heritage, interfaceTypeLiterals) }); // record fields and methods @@ -885,7 +901,7 @@ export class InterfaceType extends BaseType { interfaceTypeLiterals.push(new Literal(LiteralTag.INTEGER, transferredTarget.size)); transferredTarget.forEach((typeInfo, name) => { interfaceTypeLiterals.push(new Literal(LiteralTag.STRING, name)); - interfaceTypeLiterals.push(new Literal(LiteralTag.INTEGER, typeInfo[0])); // typeIndex + this.transferType2Literal(typeInfo[0], interfaceTypeLiterals); interfaceTypeLiterals.push(new Literal(LiteralTag.INTEGER, typeInfo[1])); // accessFlag interfaceTypeLiterals.push(new Literal(LiteralTag.INTEGER, typeInfo[2])); // readonly }); @@ -896,7 +912,7 @@ export class InterfaceType extends BaseType { interfaceTypeLiterals.push(new Literal(LiteralTag.INTEGER, transferredTarget.length)); transferredTarget.forEach(method => { - interfaceTypeLiterals.push(new Literal(LiteralTag.INTEGER, method)); + this.transferType2Literal(method, interfaceTypeLiterals); }); } } @@ -925,10 +941,10 @@ export class BuiltinContainerType extends BaseType { let UnionTypeBuf = new LiteralBuffer(); let UnionTypeLiterals: Array = new Array(); UnionTypeLiterals.push(new Literal(LiteralTag.INTEGER, L2Type.BUILTINCONTAINER)); - UnionTypeLiterals.push(new Literal(LiteralTag.INTEGER, this.builtinTypeIndex)); + this.transferType2Literal(this.builtinTypeIndex, UnionTypeLiterals); UnionTypeLiterals.push(new Literal(LiteralTag.INTEGER, this.containerArray.length)); for (let type of this.containerArray) { - UnionTypeLiterals.push(new Literal(LiteralTag.INTEGER, type)); + this.transferType2Literal(type, UnionTypeLiterals); } UnionTypeBuf.addLiterals(...UnionTypeLiterals); return UnionTypeBuf; diff --git a/ts2panda/src/base/util.ts b/ts2panda/src/base/util.ts index 7f2742eb4a8cfbc18421931aed8891b55c95a090..3b3f432eaac653cfc19d4397d1ae39c3840f4423 100644 --- a/ts2panda/src/base/util.ts +++ b/ts2panda/src/base/util.ts @@ -355,3 +355,11 @@ export function hasAbstractModifier(node: ts.Node): boolean { } return false; } + +export function getRecordName(node: ts.SourceFile): string { + return ""; // need to be fixed later +} + +export function getLiteralKey(node: ts.SourceFile, idx:number): string { + return `${getRecordName(node)}_${idx}`; +} \ No newline at end of file diff --git a/ts2panda/src/cmdOptions.ts b/ts2panda/src/cmdOptions.ts index bf19d72cd51dce6f019b031fb97c0b04d61618c4..e03707db0e2e80fcfa5110a53a438a68718fa83f 100644 --- a/ts2panda/src/cmdOptions.ts +++ b/ts2panda/src/cmdOptions.ts @@ -34,7 +34,7 @@ const ts2pandaOptions = [ { name: 'timeout', alias: 't', type: Number, defaultValue: 0, description: "js to abc timeout threshold(unit: seconds)." }, { name: 'opt-log-level', type: String, defaultValue: "error", description: "specifie optimizer log level. Possible values: ['debug', 'info', 'error', 'fatal']" }, { - name: 'opt-level', type: Number, defaultValue: 2, description: "Optimization level. Possible values: [0, 1, 2]. Default: 0\n 0: no optimizations\n \ + name: 'opt-level', type: Number, defaultValue: 0, description: "Optimization level. Possible values: [0, 1, 2]. Default: 0\n 0: no optimizations\n \ 1: basic bytecode optimizations, including valueNumber, lowering, constantResolver, regAccAllocator\n \ 2: other bytecode optimizations, unimplemented yet"}, { name: 'help', alias: 'h', type: Boolean, description: "Show usage guide." }, diff --git a/ts2panda/src/compilerDriver.ts b/ts2panda/src/compilerDriver.ts index 934449b3a2c3ab9636efe4441ceab5a9540e58f6..4f994de533fcfe37ea991d27bbb48188ad9273bc 100644 --- a/ts2panda/src/compilerDriver.ts +++ b/ts2panda/src/compilerDriver.ts @@ -17,7 +17,8 @@ import { writeFileSync } from "fs"; import * as ts from "typescript"; import { addVariableToScope } from "./addVariable2Scope"; import { AssemblyDumper } from "./assemblyDumper"; -import { hasDefaultKeywordModifier, hasExportKeywordModifier, initiateTs2abc, listenChildExit, listenErrorEvent, terminateWritePipe, getRecordTypeFlag } from "./base/util"; +import { hasDefaultKeywordModifier, hasExportKeywordModifier, initiateTs2abc, listenChildExit, + listenErrorEvent, terminateWritePipe, getRecordTypeFlag } from "./base/util"; import { CmdOptions } from "./cmdOptions"; import { Compiler @@ -45,6 +46,7 @@ import { Ts2Panda } from "./ts2panda"; import { TypeRecorder } from "./typeRecorder"; import { LiteralBuffer } from "./base/literal"; import { findOuterNodeOfParenthesis } from "./expression/parenthesizedExpression"; +import { getRecordName } from "./base/util"; export class PendingCompilationUnit { constructor( @@ -59,6 +61,7 @@ export class PendingCompilationUnit { * It handles all dependencies and run passes. */ export class CompilerDriver { + static srcNode: ts.SourceFile | undefined = undefined; static isTsFile: boolean = false; private fileName: string; private passes: Pass[] = []; @@ -179,6 +182,7 @@ export class CompilerDriver { try { Ts2Panda.dumpCmdOptions(ts2abcProc); + Ts2Panda.dumpRecordName(ts2abcProc, getRecordName(CompilerDriver.srcNode)); for (let i = 0; i < this.pendingCompilationUnits.length; i++) { let unit: PendingCompilationUnit = this.pendingCompilationUnits[i]; diff --git a/ts2panda/src/expression/arrayLiteralExpression.ts b/ts2panda/src/expression/arrayLiteralExpression.ts index 1d16860880ccd9101984bc037477ab55d1e0d2f8..3f8b3152a3a64e8ec66813d3775a34e9caf8a9a0 100644 --- a/ts2panda/src/expression/arrayLiteralExpression.ts +++ b/ts2panda/src/expression/arrayLiteralExpression.ts @@ -162,9 +162,8 @@ function emitCreateArrayWithBuffer(pandaGen: PandaGen, literalBuffer: LiteralBuf if (literalBuffer.isEmpty()) { pandaGen.createEmptyArray(element); } else { - let literalArrayBuffer = PandaGen.getLiteralArrayBuffer(); - let bufferIdx = literalArrayBuffer.length; - literalArrayBuffer.push(literalBuffer); + let bufferIdx = PandaGen.getLiteralArrayBuffer().length; + PandaGen.appendLiteralArrayBuffer(literalBuffer); pandaGen.createArrayWithBuffer(element, bufferIdx); } } diff --git a/ts2panda/src/expression/objectLiteralExpression.ts b/ts2panda/src/expression/objectLiteralExpression.ts index b7f34f646dd7f74a5c15af4082a60ae79b34520a..4b4adffe436d20433796a09efb6ac7cdbc605ad0 100644 --- a/ts2panda/src/expression/objectLiteralExpression.ts +++ b/ts2panda/src/expression/objectLiteralExpression.ts @@ -112,9 +112,8 @@ function createObject(expr: ts.ObjectLiteralExpression, pandaGen: PandaGen, objR if (literalBuffer.isEmpty()) { pandaGen.createEmptyObject(expr); } else { - let literalArrayBuffer = PandaGen.getLiteralArrayBuffer(); - let bufferIdx = literalArrayBuffer.length; - literalArrayBuffer.push(literalBuffer); + let bufferIdx = PandaGen.getLiteralArrayBuffer().length; + PandaGen.appendLiteralArrayBuffer(literalBuffer); if (hasMethod) { let env = compiler.getCurrentEnv(); pandaGen.createObjectHavingMethod(expr, bufferIdx, env); diff --git a/ts2panda/src/index.ts b/ts2panda/src/index.ts index e243c78b0d2e4615206e0435985e8a5be7ff6307..b4e7c8aad739596c17b5764dd9ff96e020a53c2e 100644 --- a/ts2panda/src/index.ts +++ b/ts2panda/src/index.ts @@ -119,6 +119,7 @@ function main(fileNames: string[], options: ts.CompilerOptions) { } let outputBinName = getOutputBinName(node); let compilerDriver = new CompilerDriver(outputBinName); + CompilerDriver.srcNode = node; setGlobalStrict(jshelpers.isEffectiveStrictModeSourceFile(node, options)); compilerDriver.compile(node); compilerDriver.showStatistics(); diff --git a/ts2panda/src/pandagen.ts b/ts2panda/src/pandagen.ts index a89c41a6c23d8ead45b73271b1a6d22aa9028a66..98e72836e5f122f7c4bb79515ae9f56aa38885e5 100644 --- a/ts2panda/src/pandagen.ts +++ b/ts2panda/src/pandagen.ts @@ -192,6 +192,8 @@ import { import { CatchTable } from "./statement/tryStatement"; import { TypeRecorder } from "./typeRecorder"; import { Variable } from "./variable"; +import { CompilerDriver } from "./compilerDriver"; +import { getLiteralKey } from "./base/util"; export class PandaGen { // @ts-ignore @@ -240,7 +242,7 @@ export class PandaGen { scopeInfoLiterals.push(new Literal(LiteralTag.INTEGER, slot)); }); scopeInfo.addLiterals(...scopeInfoLiterals); - PandaGen.getLiteralArrayBuffer().push(scopeInfo); + PandaGen.appendLiteralArrayBuffer(scopeInfo); return scopeInfoIdx; } @@ -306,14 +308,24 @@ export class PandaGen { } } + static appendLiteralArrayBuffer(litBuf: LiteralBuffer) { + let index = PandaGen.literalArrayBuffer.length; + litBuf.setKey(getLiteralKey(CompilerDriver.srcNode, index)); + PandaGen.literalArrayBuffer.push(litBuf); + } + static appendTypeArrayBuffer(type: BaseType): number { let index = PandaGen.literalArrayBuffer.length; - PandaGen.literalArrayBuffer.push(type.transfer2LiteralBuffer()); + let typeBuf = type.transfer2LiteralBuffer(); + typeBuf.setKey(getLiteralKey(CompilerDriver.srcNode, index)); + PandaGen.literalArrayBuffer.push(typeBuf); return index; } static setTypeArrayBuffer(type: BaseType, index: number) { - PandaGen.literalArrayBuffer[index] = type.transfer2LiteralBuffer(); + let typeBuf = type.transfer2LiteralBuffer(); + typeBuf.setKey(getLiteralKey(CompilerDriver.srcNode, index)); + PandaGen.literalArrayBuffer[index] = typeBuf; } getFirstStmt() { diff --git a/ts2panda/src/statement/classStatement.ts b/ts2panda/src/statement/classStatement.ts index ace78ccba5dac0c932900b0dabb51245a86a631c..c135ac813266dad92f6edae635be1133f1fae1ef 100644 --- a/ts2panda/src/statement/classStatement.ts +++ b/ts2panda/src/statement/classStatement.ts @@ -252,15 +252,14 @@ function compileUnCompiledVariable(compiler: Compiler, prop: Property, classReg: function createClassLiteralBuf(compiler: Compiler, classBuffer: LiteralBuffer, stmt: ts.ClassLikeDeclaration, vregs: VReg[]) { - let classLiteralBuf = PandaGen.getLiteralArrayBuffer(); - classLiteralBuf.push(classBuffer); + PandaGen.appendLiteralArrayBuffer(classBuffer); let ctorNode = compiler.getRecorder().getCtorOfClass(stmt); let internalName = compiler.getCompilerDriver().getInternalNameForCtor(stmt, ctorNode); let pandaGen = compiler.getPandaGen(); let parameterLength = getParameterLength4Ctor(stmt); - let buffIdx = classLiteralBuf.length - 1; + let buffIdx = PandaGen.getLiteralArrayBuffer().length - 1; pandaGen.defineClassWithBuffer(stmt, internalName, buffIdx, parameterLength, vregs[0]); pandaGen.storeAccumulator(stmt, vregs[1]); } diff --git a/ts2panda/src/ts2panda.ts b/ts2panda/src/ts2panda.ts index 190871169d9fdc1d8dde509ca1f0a5c30bc3ec73..dc3b26341cf12214cbfa7b7772a8653b4e8118d2 100644 --- a/ts2panda/src/ts2panda.ts +++ b/ts2panda/src/ts2panda.ts @@ -54,6 +54,7 @@ import { ModuleScope } from "./scope"; import { TypeRecorder } from "./typeRecorder"; import { isGlobalDeclare } from "./strictMode"; import { isFunctionLikeDeclaration } from "./syntaxCheckHelper"; +import { getLiteralKey } from "./base/util"; const dollarSign: RegExp = /\$/g; @@ -64,7 +65,8 @@ const JsonType = { "literal_arr": 3, "module": 4, "options": 5, - 'type_info': 6 + 'type_info': 6, + 'record_name': 7 }; export class Ts2Panda { static strings: Set = new Set(); @@ -191,7 +193,22 @@ 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, "module_mode": CmdOptions.isModules(), @@ -201,7 +218,8 @@ export class Ts2Panda { "opt_level": CmdOptions.getOptLevel(), "opt_log_level": CmdOptions.getOptLogLevel(), "display_typeinfo": CmdOptions.getDisplayTypeinfo(), - "is_dts_file": isGlobalDeclare() + "is_dts_file": isGlobalDeclare(), + "record_type": enableRecordType }; let jsonOpt = JSON.stringify(options, null, 2); jsonOpt = "$" + jsonOpt.replace(dollarSign, '#$') + "$"; @@ -422,9 +440,9 @@ export class Ts2Panda { static dumpTypeInfoRecord(ts2abc: any, recordType: boolean): void { let enableTypeRecord = getRecordTypeFlag(recordType); - let typeSummaryIndex = 0; + let typeSummaryIndex = getLiteralKey(CompilerDriver.srcNode, 0); if (enableTypeRecord) { - typeSummaryIndex = TypeRecorder.getInstance().getTypeSummaryIndex(); + typeSummaryIndex = getLiteralKey(CompilerDriver.srcNode, TypeRecorder.getInstance().getTypeSummaryIndex()); } let typeInfo = { 'tf': enableTypeRecord, diff --git a/ts2panda/ts2abc/ts2abc.cpp b/ts2panda/ts2abc/ts2abc.cpp index ebd96d2f48ed0c7b34cb6b6d9a3aa652fe951d03..a372b1f54e6d363587f44183dc79794dad412234 100644 --- a/ts2panda/ts2abc/ts2abc.cpp +++ b/ts2panda/ts2abc/ts2abc.cpp @@ -45,9 +45,12 @@ bool g_displayTypeinfo = false; bool g_isDtsFile = false; std::string g_optLogLevel = "error"; uint32_t g_literalArrayCount = 0; +int32_t g_newLiteralArrayIndex = -1; static constexpr const char* TSTYPE_ANNO_RECORD_NAME = "_ESTypeAnnotation"; static constexpr const char* TSTYPE_ANNO_ELEMENT_NAME = "_TypeOfInstruction"; std::string g_compilerOutputProto = ""; +std::string g_recordName = ""; +constexpr uint32_t LITERALBUFFERINDEXOFFSET = 100; constexpr std::size_t BOUND_LEFT = 0; constexpr std::size_t BOUND_RIGHT = 0; @@ -168,6 +171,11 @@ static std::string ConvertUtf8ToMUtf8(const std::string &data) return ConvertUtf16ToMUtf8(u16Data, u16DataSize); } +static std::string GetLiteralId(int64_t index) +{ + return g_recordName + "_" + std::to_string(index); +} + static std::string ParseUnicodeEscapeString(const std::string &data) { const int unicodeEscapeSymbolLen = 2; @@ -265,8 +273,16 @@ static void ParseLiteral(const Json::Value &literal, std::vector(panda::panda_file::LiteralTag::LITERALBUFFERINDEX): { - valueLiteral.tag_ = panda::panda_file::LiteralTag::LITERALBUFFERINDEX; - valueLiteral.value_ = static_cast(literal["v"].asInt()); + UNREACHABLE(); + } + case static_cast(panda::panda_file::LiteralTag::LITERALARRAY): { + valueLiteral.tag_ = panda::panda_file::LiteralTag::LITERALARRAY; + valueLiteral.value_ = ParseString(literal["v"].asString()); + break; + } + case static_cast(panda::panda_file::LiteralTag::BUILTINTYPEINDEX): { + valueLiteral.tag_ = panda::panda_file::LiteralTag::BUILTINTYPEINDEX; + valueLiteral.value_ = static_cast(literal["v"].asInt()); break; } case static_cast(panda::panda_file::LiteralTag::NULLVALUE): { @@ -649,27 +665,106 @@ static std::vector> GetInstTypeMap(const Json::Valu return instTypeMap; } -static void ParseFunctionTypeInfo(const Json::Value &function, panda::pandasm::Function &pandaFunc) +static void ParseFunctionTypeInfo(const Json::Value &function, panda::pandasm::Function &pandaFunc, + panda::pandasm::Program &prog) { auto instTypeMap = GetInstTypeMap(function, pandaFunc); if (!instTypeMap.empty()) { - std::vector elements; + std::vector literalArray; for (auto &it : instTypeMap) { - elements.emplace_back(panda::pandasm::ScalarValue::Create(it.first)); - elements.emplace_back(panda::pandasm::ScalarValue::Create(it.second)); + panda::pandasm::LiteralArray::Literal instTagLiteral; + panda::pandasm::LiteralArray::Literal instValueLiteral; + instTagLiteral.tag_ = panda::panda_file::LiteralTag::TAGVALUE; + instTagLiteral.value_ = static_cast(panda::panda_file::LiteralTag::INTEGER); + literalArray.emplace_back(instTagLiteral); + instValueLiteral.tag_ = panda::panda_file::LiteralTag::INTEGER; + instValueLiteral.value_ = static_cast(it.first); + literalArray.emplace_back(instValueLiteral); + + panda::pandasm::LiteralArray::Literal typeTagLiteral; + panda::pandasm::LiteralArray::Literal typeValueLiteral; + typeTagLiteral.tag_ = panda::panda_file::LiteralTag::TAGVALUE; + auto type = it.second; + if (type < LITERALBUFFERINDEXOFFSET) { + typeTagLiteral.value_ = static_cast(panda::panda_file::LiteralTag::BUILTINTYPEINDEX); + typeValueLiteral.tag_ = panda::panda_file::LiteralTag::BUILTINTYPEINDEX; + typeValueLiteral.value_ = static_cast(type); + } else { + typeTagLiteral.value_ = static_cast(panda::panda_file::LiteralTag::LITERALARRAY); + typeValueLiteral.tag_ = panda::panda_file::LiteralTag::LITERALARRAY; + std::string typeId = g_recordName + "_" + std::to_string(type - LITERALBUFFERINDEXOFFSET); + typeValueLiteral.value_ = typeId; + } + literalArray.emplace_back(typeTagLiteral); + literalArray.emplace_back(typeValueLiteral); } + std::string litId = GetLiteralId(g_newLiteralArrayIndex--); + auto literalarrayInstance = panda::pandasm::LiteralArray(literalArray); + prog.literalarray_table.emplace(litId, std::move(literalarrayInstance)); + panda::pandasm::AnnotationData funcAnnotation(TSTYPE_ANNO_RECORD_NAME); panda::pandasm::AnnotationElement typeOfVregElement( - TSTYPE_ANNO_ELEMENT_NAME, std::make_unique(panda::pandasm::ArrayValue( - panda::pandasm::Value::Type::U32, elements))); + TSTYPE_ANNO_ELEMENT_NAME, std::make_unique( + panda::pandasm::ScalarValue::Create(litId))); funcAnnotation.AddElement(std::move(typeOfVregElement)); const_cast&>(pandaFunc.metadata->GetAnnotations()).push_back( std::move(funcAnnotation)); } } -static void ParseFunctionExportedType(const Json::Value &function, panda::pandasm::Function &pandaFunc) +static std::string CreateLiteralArrayForType(const Json::Value &types, panda::pandasm::Program &prog) +{ + std::vector literalArray; + for (Json::ArrayIndex i = 0; i < types.size(); i++) { + auto type = types[i]; + if (!type.isObject()) { + continue; + } + + panda::pandasm::LiteralArray::Literal symbolTagLiteral; + panda::pandasm::LiteralArray::Literal symbolValueLiteral; + std::string symbol = ""; + if (type.isMember("symbol") && type["symbol"].isString()) { + symbol = type["symbol"].asString(); + } + symbolTagLiteral.tag_ = panda::panda_file::LiteralTag::TAGVALUE; + symbolTagLiteral.value_ = static_cast(panda::panda_file::LiteralTag::STRING); + symbolValueLiteral.tag_ = panda::panda_file::LiteralTag::STRING; + symbolValueLiteral.value_ = symbol; + literalArray.emplace_back(symbolTagLiteral); + literalArray.emplace_back(symbolValueLiteral); + + panda::pandasm::LiteralArray::Literal typeTagLiteral; + panda::pandasm::LiteralArray::Literal typeValueLiteral; + uint32_t typeIndex = 0; + if (type.isMember("type") && type["type"].isInt()) { + typeIndex = type["type"].asUInt(); + } + typeTagLiteral.tag_ = panda::panda_file::LiteralTag::TAGVALUE; + if (typeIndex < LITERALBUFFERINDEXOFFSET) { + typeTagLiteral.value_ = static_cast(panda::panda_file::LiteralTag::BUILTINTYPEINDEX); + typeValueLiteral.tag_ = panda::panda_file::LiteralTag::BUILTINTYPEINDEX; + typeValueLiteral.value_ = static_cast(typeIndex); + } else { + typeTagLiteral.value_ = static_cast(panda::panda_file::LiteralTag::LITERALARRAY); + typeValueLiteral.tag_ = panda::panda_file::LiteralTag::LITERALARRAY; + std::string litId = GetLiteralId(typeIndex - LITERALBUFFERINDEXOFFSET); + typeValueLiteral.value_ = litId; + } + + literalArray.emplace_back(typeTagLiteral); + literalArray.emplace_back(typeValueLiteral); + } + + std::string litId = GetLiteralId(g_newLiteralArrayIndex--); + auto literalarrayInstance = panda::pandasm::LiteralArray(literalArray); + prog.literalarray_table.emplace(litId, std::move(literalarrayInstance)); + return litId; +} + +static void ParseFunctionExportedType(const Json::Value &function, panda::pandasm::Function &pandaFunc, + panda::pandasm::Program &prog) { std::string funcName = ""; if (function.isMember("n") && function["n"].isString()) { @@ -682,42 +777,12 @@ static void ParseFunctionExportedType(const Json::Value &function, panda::pandas if (function.isMember("es2t") && function["es2t"].isArray()) { auto exportedTypes = function["es2t"]; panda::pandasm::AnnotationData funcAnnotation(TSTYPE_ANNO_RECORD_NAME); - std::vector symbolElements; - std::vector symbolTypeElements; - for (Json::ArrayIndex i = 0; i < exportedTypes.size(); i++) { - auto exportedType = exportedTypes[i]; - if (!exportedType.isObject()) { - continue; - } - - std::string exportedSymbol = ""; - if (exportedType.isMember("symbol") && exportedType["symbol"].isString()) { - exportedSymbol = exportedType["symbol"].asString(); - } - - uint32_t typeIndex = 0; - if (exportedType.isMember("type") && exportedType["type"].isInt()) { - typeIndex = exportedType["type"].asUInt(); - } - - panda::pandasm::ScalarValue symbol( - panda::pandasm::ScalarValue::Create(exportedSymbol)); - symbolElements.emplace_back(std::move(symbol)); - panda::pandasm::ScalarValue tIndex( - panda::pandasm::ScalarValue::Create(typeIndex)); - symbolTypeElements.emplace_back(std::move(tIndex)); - } - - std::string symbolAnnotationName = "exportedSymbols"; - panda::pandasm::AnnotationElement exportedSymbolsElement(symbolAnnotationName, - std::make_unique(panda::pandasm::ArrayValue( - panda::pandasm::Value::Type::STRING, symbolElements))); - funcAnnotation.AddElement(std::move(exportedSymbolsElement)); + std::string litId = CreateLiteralArrayForType(exportedTypes, prog); std::string symbolTypeAnnotationName = "exportedSymbolTypes"; panda::pandasm::AnnotationElement exportedSymbolTypesElement(symbolTypeAnnotationName, - std::make_unique(panda::pandasm::ArrayValue( - panda::pandasm::Value::Type::U32, symbolTypeElements))); + std::make_unique( + panda::pandasm::ScalarValue::Create(litId))); funcAnnotation.AddElement(std::move(exportedSymbolTypesElement)); const_cast&>( @@ -725,7 +790,8 @@ static void ParseFunctionExportedType(const Json::Value &function, panda::pandas } } -static void ParseFunctionDeclaredType(const Json::Value &function, panda::pandasm::Function &pandaFunc) +static void ParseFunctionDeclaredType(const Json::Value &function, panda::pandasm::Function &pandaFunc, + panda::pandasm::Program &prog) { std::string funcName = ""; if (function.isMember("n") && function["n"].isString()) { @@ -738,42 +804,12 @@ static void ParseFunctionDeclaredType(const Json::Value &function, panda::pandas if (function.isMember("ds2t") && function["ds2t"].isArray()) { auto declaredTypes = function["ds2t"]; panda::pandasm::AnnotationData funcAnnotation(TSTYPE_ANNO_RECORD_NAME); - std::vector symbolElements; - std::vector symbolTypeElements; - for (Json::ArrayIndex i = 0; i < declaredTypes.size(); i++) { - auto declaredType = declaredTypes[i]; - if (!declaredType.isObject()) { - continue; - } - - std::string declaredSymbol = ""; - if (declaredType.isMember("symbol") && declaredType["symbol"].isString()) { - declaredSymbol = declaredType["symbol"].asString(); - } - - uint32_t typeIndex = 0; - if (declaredType.isMember("type") && declaredType["type"].isInt()) { - typeIndex = declaredType["type"].asUInt(); - } - - panda::pandasm::ScalarValue symbol( - panda::pandasm::ScalarValue::Create(declaredSymbol)); - symbolElements.emplace_back(std::move(symbol)); - panda::pandasm::ScalarValue tIndex( - panda::pandasm::ScalarValue::Create(typeIndex)); - symbolTypeElements.emplace_back(std::move(tIndex)); - } - - std::string symbolAnnotationName = "declaredSymbols"; - panda::pandasm::AnnotationElement declaredSymbolsElement(symbolAnnotationName, - std::make_unique(panda::pandasm::ArrayValue( - panda::pandasm::Value::Type::STRING, symbolElements))); - funcAnnotation.AddElement(std::move(declaredSymbolsElement)); + std::string litId = CreateLiteralArrayForType(declaredTypes, prog); std::string symbolTypeAnnotationName = "declaredSymbolTypes"; panda::pandasm::AnnotationElement declaredSymbolTypesElement(symbolTypeAnnotationName, - std::make_unique(panda::pandasm::ArrayValue( - panda::pandasm::Value::Type::U32, symbolTypeElements))); + std::make_unique( + panda::pandasm::ScalarValue::Create(litId))); funcAnnotation.AddElement(std::move(declaredSymbolTypesElement)); const_cast&>(pandaFunc.metadata->GetAnnotations()).push_back( @@ -781,7 +817,7 @@ static void ParseFunctionDeclaredType(const Json::Value &function, panda::pandas } } -static panda::pandasm::Function ParseFunction(const Json::Value &function) +static panda::pandasm::Function ParseFunction(const Json::Value &function, panda::pandasm::Program &prog) { auto pandaFunc = GetFunctionDefintion(function); ParseFunctionInstructions(function, pandaFunc); @@ -791,9 +827,9 @@ static panda::pandasm::Function ParseFunction(const Json::Value &function) ParseFunctionCatchTables(function, pandaFunc); // parsing call opt type ParseFunctionCallType(function, pandaFunc); - ParseFunctionTypeInfo(function, pandaFunc); - ParseFunctionExportedType(function, pandaFunc); - ParseFunctionDeclaredType(function, pandaFunc); + ParseFunctionTypeInfo(function, pandaFunc, prog); + ParseFunctionExportedType(function, pandaFunc, prog); + ParseFunctionDeclaredType(function, pandaFunc, prog); if (g_isDtsFile && pandaFunc.name != "func_main_0") { pandaFunc.metadata->SetAttribute("external"); @@ -839,7 +875,7 @@ static void GenerateESModuleRecord(panda::pandasm::Program &prog) prog.record_table.emplace(ecmaModuleRecord.name, std::move(ecmaModuleRecord)); } -static void AddModuleRecord(panda::pandasm::Program &prog, const std::string &moduleName, uint32_t moduleIdx) +static void AddModuleRecord(panda::pandasm::Program &prog, const std::string &moduleName) { auto iter = prog.record_table.find("_ESModuleRecord"); if (iter != prog.record_table.end()) { @@ -847,8 +883,9 @@ static void AddModuleRecord(panda::pandasm::Program &prog, const std::string &mo auto moduleIdxField = panda::pandasm::Field(LANG_EXT); moduleIdxField.name = moduleName; moduleIdxField.type = panda::pandasm::Type("u32", 0); - moduleIdxField.metadata->SetValue(panda::pandasm::ScalarValue::Create( - static_cast(moduleIdx))); + std::string moduleId = GetLiteralId(g_newLiteralArrayIndex); + moduleIdxField.metadata->SetValue(panda::pandasm::ScalarValue::Create( + moduleId)); rec.field_list.emplace_back(std::move(moduleIdxField)); } @@ -944,6 +981,14 @@ static void ParseIsDtsFile(const Json::Value &rootValue) } } +static void ParseEnableTypeInfo(const Json::Value &rootValue) +{ + Logd("-----------------parse enable type info-----------------"); + if (rootValue.isMember("record_type") && rootValue["record_type"].isBool()) { + g_enableTypeinfo = rootValue["record_type"].asBool(); + } +} + static void ParseCompilerOutputProto(const Json::Value &rootValue) { Logd("-----------------parse compiler output proto-----------------"); @@ -974,12 +1019,13 @@ static void ParseOptions(const Json::Value &rootValue, panda::pandasm::Program & ParseDisplayTypeinfo(rootValue); ParseOptLogLevel(rootValue); ParseIsDtsFile(rootValue); + ParseEnableTypeInfo(rootValue); ParseCompilerOutputProto(rootValue); } static void ParseSingleFunc(const Json::Value &rootValue, panda::pandasm::Program &prog) { - auto function = ParseFunction(rootValue["fb"]); + auto function = ParseFunction(rootValue["fb"], prog); prog.function_table.emplace(function.name.c_str(), std::move(function)); } @@ -1007,7 +1053,8 @@ static void ParseSingleLiteralBuf(const Json::Value &rootValue, panda::pandasm:: } auto literalarrayInstance = panda::pandasm::LiteralArray(literalArray); - prog.literalarray_table.emplace(std::to_string(g_literalArrayCount++), std::move(literalarrayInstance)); + auto litId = literalBuffer["k"].asString(); + prog.literalarray_table.emplace(litId, std::move(literalarrayInstance)); } static void ParseModuleRequests(const Json::Value &moduleRequests, @@ -1127,18 +1174,19 @@ static void ParseSingleModule(const Json::Value &rootValue, panda::pandasm::Prog ParseIndirectExportEntries(moduleRecord["indirectExportEntries"], moduleLiteralArray); ParseStarExportEntries(moduleRecord["starExportEntries"], moduleLiteralArray); - auto moduleName = ParseString(moduleRecord["moduleName"].asString()); - AddModuleRecord(prog, moduleName, g_literalArrayCount); + std::string moduleName = ParseString(moduleRecord["moduleName"].asString()); + AddModuleRecord(prog, moduleName); + std::string moduleId = GetLiteralId(g_newLiteralArrayIndex--); auto moduleLiteralarrayInstance = panda::pandasm::LiteralArray(moduleLiteralArray); - prog.literalarray_table.emplace(std::to_string(g_literalArrayCount++), std::move(moduleLiteralarrayInstance)); + prog.literalarray_table.emplace(moduleId, std::move(moduleLiteralarrayInstance)); } static void ParseSingleTypeInfo(const Json::Value &rootValue, panda::pandasm::Program &prog) { auto typeInfoRecord = rootValue["ti"]; auto typeFlag = typeInfoRecord["tf"].asBool(); - auto typeSummaryIndex = typeInfoRecord["tsi"].asUInt(); + auto typeSummaryIndex = typeInfoRecord["tsi"].asString(); auto ecmaTypeInfoRecord = panda::pandasm::Record("_ESTypeInfoRecord", LANG_EXT); ecmaTypeInfoRecord.metadata->SetAccessFlags(panda::ACC_PUBLIC); @@ -1148,12 +1196,15 @@ static void ParseSingleTypeInfo(const Json::Value &rootValue, panda::pandasm::Pr typeFlagField.metadata->SetValue(panda::pandasm::ScalarValue::Create( static_cast(typeFlag))); ecmaTypeInfoRecord.field_list.emplace_back(std::move(typeFlagField)); - auto typeSummaryIndexField = panda::pandasm::Field(LANG_EXT); - typeSummaryIndexField.name = "typeSummaryIndex"; - typeSummaryIndexField.type = panda::pandasm::Type("u32", 0); - typeSummaryIndexField.metadata->SetValue(panda::pandasm::ScalarValue::Create( - static_cast(typeSummaryIndex))); - ecmaTypeInfoRecord.field_list.emplace_back(std::move(typeSummaryIndexField)); + + if (g_enableTypeinfo) { + auto typeSummaryIndexField = panda::pandasm::Field(LANG_EXT); + typeSummaryIndexField.name = "typeSummaryIndex"; + typeSummaryIndexField.type = panda::pandasm::Type("u32", 0); + typeSummaryIndexField.metadata->SetValue( + panda::pandasm::ScalarValue::Create(typeSummaryIndex)); + ecmaTypeInfoRecord.field_list.emplace_back(std::move(typeSummaryIndexField)); + } prog.record_table.emplace(ecmaTypeInfoRecord.name, std::move(ecmaTypeInfoRecord)); } @@ -1210,6 +1261,12 @@ static int ParseSmallPieceJson(const std::string &subJson, panda::pandasm::Progr } break; } + case static_cast(JsonType::RECORDNAME): { + if (rootValue.isMember("rn") && rootValue["rn"].isString()) { + g_recordName = rootValue["rn"].asString(); + } + break; + } default: { std::cerr << "Unreachable json type: " << type << std::endl; return RETURN_FAILED; diff --git a/ts2panda/ts2abc/ts2abc.h b/ts2panda/ts2abc/ts2abc.h index 421205bb35905ff34455f39acfdbcb1e7b5dbb8b..4b4658dfdb431b8337ffa9a6a5be827e7d8af10d 100644 --- a/ts2panda/ts2abc/ts2abc.h +++ b/ts2panda/ts2abc/ts2abc.h @@ -36,7 +36,8 @@ enum class JsonType { LITERALBUFFER, MODULE, OPTIONS, - TYPEINFO + TYPEINFO, + RECORDNAME }; constexpr int RETURN_SUCCESS = 0;