1 /*
2 * Copyright (c) 2021-2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "options.h"
17
18 #include <fstream>
19 #include <set>
20 #include <sstream>
21 #include <utility>
22
23 #if defined(PANDA_TARGET_WINDOWS)
24 #include <io.h>
25 #else
26 #include <dirent.h>
27 #endif
28
29 #include "bytecode_optimizer/bytecodeopt_options.h"
30 #include "compiler_options.h"
31 #include "os/file.h"
32
33 #include "mergeProgram.h"
34 #include "util/helpers.h"
35 #include "utils/pandargs.h"
36
37 namespace panda::es2panda::aot {
38 constexpr char PROCESS_AS_LIST_MARK = '@';
39 // item list: [filePath; recordName; moduleKind; sourceFile; pkgName; isSharedModule]
40 constexpr size_t ITEM_COUNT_MERGE = 6;
41 // item list: [filePath; recordName; moduleKind; sourceFile; outputfile; isSharedModule]
42 constexpr size_t ITEM_COUNT_NOT_MERGE = 6;
43 const std::string LIST_ITEM_SEPERATOR = ";";
44 const std::set<std::string> VALID_EXTENSIONS = { "js", "ts", "as", "abc" };
45
46 template <class T>
RemoveExtension(T const & filename)47 T RemoveExtension(T const &filename)
48 {
49 typename T::size_type const P(filename.find_last_of('.'));
50 return P > 0 && P != T::npos ? filename.substr(0, P) : filename;
51 }
52
GetScriptExtensionFromStr(const std::string & extension)53 static es2panda::ScriptExtension GetScriptExtensionFromStr(const std::string &extension)
54 {
55 if (extension == "js") {
56 return es2panda::ScriptExtension::JS;
57 } else if (extension == "ts") {
58 return es2panda::ScriptExtension::TS;
59 } else if (extension == "as") {
60 return es2panda::ScriptExtension::AS;
61 } else if (extension == "abc") {
62 return es2panda::ScriptExtension::ABC;
63 } else {
64 return es2panda::ScriptExtension::JS;
65 }
66 }
67
GetScriptExtension(const std::string & filename,const std::string & inputExtension)68 static es2panda::ScriptExtension GetScriptExtension(const std::string &filename, const std::string &inputExtension)
69 {
70 std::string fileExtension = "";
71 std::string::size_type pos(filename.find_last_of('.'));
72 if (pos > 0 && pos != std::string::npos) {
73 fileExtension = filename.substr(pos + 1);
74 }
75
76 if (VALID_EXTENSIONS.find(fileExtension) != VALID_EXTENSIONS.end()) {
77 return GetScriptExtensionFromStr(fileExtension);
78 }
79
80 return GetScriptExtensionFromStr(inputExtension);
81 }
82
GetStringItems(std::string & input,const std::string & delimiter)83 static std::vector<std::string> GetStringItems(std::string &input, const std::string &delimiter)
84 {
85 std::vector<std::string> items;
86 size_t pos = 0;
87 std::string token;
88 while ((pos = input.find(delimiter)) != std::string::npos) {
89 token = input.substr(0, pos);
90 if (!token.empty()) {
91 items.push_back(token);
92 }
93 input.erase(0, pos + delimiter.length());
94 }
95 if (!input.empty()) {
96 items.push_back(input);
97 }
98 return items;
99 }
100
CollectInputAbcFile(const std::vector<std::string> & itemList,const std::string & inputExtension)101 void Options::CollectInputAbcFile(const std::vector<std::string> &itemList, const std::string &inputExtension)
102 {
103 std::string fileName = itemList[0];
104 // Split the fileInfo string to itemList by the delimiter ';'. If the element is empty, it will not be added to
105 // the itemList. The fileInfo string of the abc file only contains the file path and pkgName, so the index
106 // of pkgName is 1.
107 constexpr uint32_t PKG_NAME_IDX = 1;
108 es2panda::SourceFile src(fileName, "", parser::ScriptKind::SCRIPT, GetScriptExtension(fileName,
109 inputExtension));
110 src.isSourceMode = false;
111 if (itemList.size() > PKG_NAME_IDX && compilerOptions_.mergeAbc) {
112 src.pkgName = itemList[PKG_NAME_IDX];
113 }
114 sourceFiles_.push_back(src);
115 }
116
CollectInputSourceFile(const std::vector<std::string> & itemList,const std::string & inputExtension)117 void Options::CollectInputSourceFile(const std::vector<std::string> &itemList, const std::string &inputExtension)
118 {
119 std::string fileName = itemList[0];
120 std::string recordName = compilerOptions_.mergeAbc ? itemList[1] : "";
121 constexpr uint32_t SCRIPT_KIND_IDX = 2;
122 constexpr uint32_t SOURCE_FIEL_IDX = 3;
123 constexpr uint32_t PKG_NAME_IDX = 4;
124 constexpr uint32_t Is_SHARED_MODULE_IDX = 5;
125 parser::ScriptKind scriptKind;
126 if (itemList[SCRIPT_KIND_IDX] == "script") {
127 scriptKind = parser::ScriptKind::SCRIPT;
128 } else if (itemList[SCRIPT_KIND_IDX] == "commonjs") {
129 scriptKind = parser::ScriptKind::COMMONJS;
130 } else {
131 scriptKind = parser::ScriptKind::MODULE;
132 }
133
134 es2panda::SourceFile src(fileName, recordName, scriptKind, GetScriptExtension(fileName, inputExtension));
135 src.sourcefile = itemList[SOURCE_FIEL_IDX];
136 if (compilerOptions_.mergeAbc) {
137 src.pkgName = itemList[PKG_NAME_IDX];
138 }
139
140 if (itemList.size() == ITEM_COUNT_MERGE) {
141 src.isSharedModule = itemList[Is_SHARED_MODULE_IDX] == "true";
142 }
143
144 sourceFiles_.push_back(src);
145 if (!compilerOptions_.mergeAbc) {
146 outputFiles_.insert({fileName, itemList[PKG_NAME_IDX]});
147 }
148 }
149
CheckFilesValidity(const std::string & input,const std::vector<std::string> & itemList,const std::string & line)150 bool Options::CheckFilesValidity(const std::string &input, const std::vector<std::string> &itemList,
151 const std::string &line)
152 {
153 // For compatibility, only throw error when item list's size is bigger than given size.
154 if ((compilerOptions_.mergeAbc && itemList.size() > ITEM_COUNT_MERGE) ||
155 (!compilerOptions_.mergeAbc && itemList.size() > ITEM_COUNT_NOT_MERGE) || itemList.empty()) {
156 std::cerr << "Failed to parse line " << line << " of the input file: '"
157 << input << "'." << std::endl
158 << "Expected " << (compilerOptions_.mergeAbc ? ITEM_COUNT_MERGE : ITEM_COUNT_NOT_MERGE)
159 << " items per line, but found " << itemList.size() << " items." << std::endl
160 << "Please check the file format and content for correctness." << std::endl;
161 return false;
162 }
163 return true;
164 }
165
IsAbcFile(const std::string & fileName,const std::string & inputExtension)166 bool Options::IsAbcFile(const std::string &fileName, const std::string &inputExtension)
167 {
168 return (GetScriptExtension(fileName, inputExtension) == es2panda::ScriptExtension::ABC);
169 }
170
171 // Options
CollectInputFilesFromFileList(const std::string & input,const std::string & inputExtension)172 bool Options::CollectInputFilesFromFileList(const std::string &input, const std::string &inputExtension)
173 {
174 std::ifstream ifs;
175 std::string line;
176 ifs.open(panda::os::file::File::GetExtendedFilePath(input));
177 if (!ifs.is_open()) {
178 std::cerr << "Failed to open source list file '" << input << "' during input file collection." << std::endl
179 << "Please check if the file exists or the path is correct, "
180 << "and you have the necessary permissions to access it." << std::endl;
181 return false;
182 }
183
184 while (std::getline(ifs, line)) {
185 std::vector<std::string> itemList = GetStringItems(line, LIST_ITEM_SEPERATOR);
186 if (!CheckFilesValidity(input, itemList, line)) {
187 return false;
188 }
189 if (IsAbcFile(itemList[0], inputExtension)) {
190 CollectInputAbcFile(itemList, inputExtension);
191 } else {
192 CollectInputSourceFile(itemList, inputExtension);
193 }
194 }
195 return true;
196 }
197
CollectInputFilesFromFileDirectory(const std::string & input,const std::string & extension)198 bool Options::CollectInputFilesFromFileDirectory(const std::string &input, const std::string &extension)
199 {
200 std::vector<std::string> files;
201 if (!proto::MergeProgram::GetProtoFiles(input, extension, files)) {
202 return false;
203 }
204
205 for (const auto &f : files) {
206 es2panda::SourceFile src(f, RemoveExtension(f.substr(input.length() + 1)),
207 scriptKind_, GetScriptExtensionFromStr(extension));
208 sourceFiles_.push_back(src);
209 }
210
211 return true;
212 }
213
ParseCacheFileOption(const std::string & cacheInput)214 void Options::ParseCacheFileOption(const std::string &cacheInput)
215 {
216 if (cacheInput[0] != PROCESS_AS_LIST_MARK) {
217 compilerOptions_.cacheFiles.insert({sourceFile_, cacheInput});
218 return;
219 }
220
221 std::ifstream ifs;
222 std::string line;
223 ifs.open(panda::os::file::File::GetExtendedFilePath(cacheInput.substr(1)));
224 if (!ifs.is_open()) {
225 std::cerr << "Failed to open cache file list from the provided path: '" << cacheInput << "'." << std::endl
226 << "Please check if the file exists or the path is correct, "
227 << "and you have the necessary permissions to read the file." << std::endl;
228 return;
229 }
230
231 constexpr int cacheListItemCount = 2;
232 while (std::getline(ifs, line)) {
233 std::vector<std::string> itemList = GetStringItems(line, LIST_ITEM_SEPERATOR);
234 if (itemList.size() != cacheListItemCount) {
235 continue;
236 }
237 compilerOptions_.cacheFiles.insert({itemList[0], itemList[1]});
238 }
239 }
240
ParseUpdateVersionInfo(nlohmann::json & compileContextInfoJson)241 void Options::ParseUpdateVersionInfo(nlohmann::json &compileContextInfoJson)
242 {
243 if (compileContextInfoJson.contains("updateVersionInfo") &&
244 compileContextInfoJson["updateVersionInfo"].is_object()) {
245 std::unordered_map<std::string, std::unordered_map<std::string, PkgInfo>> updateVersionInfo {};
246 for (const auto& [abcName, versionInfo] : compileContextInfoJson["updateVersionInfo"].items()) {
247 if (!versionInfo.is_object()) {
248 std::cerr << "The input file '" << compilerOptions_.compileContextInfoPath
249 << "' is incomplete format of json" << std::endl;
250 }
251 std::unordered_map<std::string, PkgInfo> pkgContextMap {};
252 for (const auto& [pkgName, version] : versionInfo.items()) {
253 PkgInfo pkgInfo;
254 pkgInfo.version = version;
255 pkgInfo.packageName = pkgName;
256 pkgContextMap[pkgName] = pkgInfo;
257 }
258 updateVersionInfo[abcName] = pkgContextMap;
259 }
260 compilerOptions_.compileContextInfo.updateVersionInfo = updateVersionInfo;
261 } else if (compileContextInfoJson.contains("pkgContextInfo") &&
262 compileContextInfoJson["pkgContextInfo"].is_object()) {
263 std::unordered_map<std::string, PkgInfo> pkgContextMap {};
264 for (const auto& [pkgName, pkgContextInfo] : compileContextInfoJson["pkgContextInfo"].items()) {
265 PkgInfo pkgInfo;
266 if (pkgContextInfo.contains("version") && pkgContextInfo["version"].is_string()) {
267 pkgInfo.version = pkgContextInfo["version"];
268 } else {
269 std::cerr << "Failed to get version from pkgContextInfo." << std::endl;
270 }
271 if (pkgContextInfo.contains("packageName") && pkgContextInfo["packageName"].is_string()) {
272 pkgInfo.packageName = pkgContextInfo["packageName"];
273 } else {
274 std::cerr << "Failed to get package name from pkgContextInfo." << std::endl;
275 }
276 pkgContextMap[pkgName] = pkgInfo;
277 }
278 compilerOptions_.compileContextInfo.pkgContextInfo = pkgContextMap;
279 } else {
280 UNREACHABLE();
281 }
282 }
283
ParseCompileContextInfo(const std::string compileContextInfoPath)284 void Options::ParseCompileContextInfo(const std::string compileContextInfoPath)
285 {
286 std::stringstream ss;
287 std::string buffer;
288 if (!util::Helpers::ReadFileToBuffer(compileContextInfoPath, ss)) {
289 return;
290 }
291
292 buffer = ss.str();
293 if (buffer.empty() || !nlohmann::json::accept(buffer)) {
294 std::cerr << "The input file '" << compileContextInfoPath <<"' is incomplete format of json" << std::endl;
295 return;
296 }
297 // Parser compile context info base on the input json file.
298 nlohmann::json compileContextInfoJson = nlohmann::json::parse(buffer);
299 if (!compileContextInfoJson.contains("compileEntries") || !compileContextInfoJson.contains("hspPkgNames")) {
300 std::cerr << "The input json file '" << compileContextInfoPath << "' content format is incorrect" << std::endl;
301 return;
302 }
303 if (!compileContextInfoJson["compileEntries"].is_array() || !compileContextInfoJson["hspPkgNames"].is_array()) {
304 std::cerr << "The input json file '" << compileContextInfoPath << "' content type is incorrect" << std::endl;
305 return;
306 }
307 std::set<std::string> externalPkgNames;
308 for (const auto& elem : compileContextInfoJson["hspPkgNames"]) {
309 if (elem.is_string()) {
310 externalPkgNames.insert(elem.get<std::string>());
311 }
312 }
313 compilerOptions_.compileContextInfo.externalPkgNames = externalPkgNames;
314 compilerOptions_.compileContextInfo.compileEntries = compileContextInfoJson["compileEntries"];
315 ParseUpdateVersionInfo(compileContextInfoJson);
316 }
317
318 // Collect dependencies based on the compile entries.
NeedCollectDepsRelation()319 bool Options::NeedCollectDepsRelation()
320 {
321 return compilerOptions_.enableAbcInput && !compilerOptions_.compileContextInfo.compileEntries.empty();
322 }
323
324 // Remove redundant content from the abc file and remove programs generated from redundant source files.
NeedRemoveRedundantRecord()325 bool Options::NeedRemoveRedundantRecord()
326 {
327 return compilerOptions_.removeRedundantFile && NeedCollectDepsRelation();
328 }
329
Options()330 Options::Options() : argparser_(new panda::PandArgParser()) {}
331
~Options()332 Options::~Options()
333 {
334 delete argparser_;
335 }
336
Parse(int argc,const char ** argv)337 bool Options::Parse(int argc, const char **argv)
338 {
339 panda::PandArg<bool> opHelp("help", false, "Print this message and exit");
340
341 // parser
342 panda::PandArg<std::string> inputExtension("extension", "js",
343 "Parse the input as the given extension (options: js | ts | as | abc)");
344 panda::PandArg<bool> opModule("module", false, "Parse the input as module");
345 panda::PandArg<bool> opCommonjs("commonjs", false, "Parse the input as commonjs");
346 panda::PandArg<bool> opParseOnly("parse-only", false, "Parse the input only");
347 panda::PandArg<bool> opEnableTypeCheck("enable-type-check", false, "Check the type in ts after parse");
348 panda::PandArg<bool> opDumpAst("dump-ast", false, "Dump the parsed AST");
349 panda::PandArg<bool> opDumpTransformedAst("dump-transformed-ast", false, "Dump the parsed AST after transform");
350 panda::PandArg<bool> opCheckTransformedAstStructure("check-transformed-ast-structure", false,
351 "Check the AST structure after transform");
352 panda::PandArg<bool> opRecordDebugSource("record-debug-source", false, "Record source code to support "\
353 "multi-platform debugger & detailed backtrace in debug mode");
354
355 // compiler
356 panda::PandArg<bool> opEnableAbcInput("enable-abc-input", false, "Allow abc file as input");
357 panda::PandArg<bool> opDumpAsmProgram("dump-asm-program", false, "Dump program");
358 std::string descOfDumpNormalizedProg =
359 "Dump program in normalized form to ensure the output of source code compilation is consistent with that of "
360 "abc file compilation.\n"
361 " The normalized form differs mainly as follows:\n"
362 " 1. all instructions will be labled consecutively and all the labels will be dumped\n"
363 " 2. the content of a literal array, rather than its id, will be dumped when the literal array appears in "
364 "an opcode or is nested in another literal array\n"
365 " 3. labels stored in catch blocks will be unified\n"
366 " 4. strings won't be dumped\n"
367 " 5. invalid opcodes won't be dumped, local variables' start and end offset will skip invalid opcodes";
368 panda::PandArg<bool> opDumpNormalizedAsmProgram("dump-normalized-asm-program", false, descOfDumpNormalizedProg);
369 panda::PandArg<bool> opDumpAssembly("dump-assembly", false, "Dump pandasm");
370 panda::PandArg<bool> opDebugInfo("debug-info", false, "Compile with debug info");
371 panda::PandArg<bool> opDumpDebugInfo("dump-debug-info", false, "Dump debug info");
372 panda::PandArg<int> opOptLevel("opt-level", 2,
373 "Compiler optimization level (options: 0 | 1 | 2). In debug and base64Input mode, optimizer is disabled");
374 panda::PandArg<int> opFunctionThreadCount("function-threads", 0, "Number of worker threads to compile function");
375 panda::PandArg<int> opFileThreadCount("file-threads", 0, "Number of worker threads to compile file");
376 panda::PandArg<int> opAbcClassThreadCount("abc-class-threads", 4,
377 "Number of worker threads to compile classes of abc file");
378 panda::PandArg<bool> opSizeStat("dump-size-stat", false, "Dump size statistics");
379 panda::PandArg<bool> opSizePctStat("dump-file-item-size", false, "Dump the size of each kind of file item "\
380 "of the abc file");
381 panda::PandArg<bool> opDumpLiteralBuffer("dump-literal-buffer", false, "Dump literal buffer");
382 panda::PandArg<std::string> outputFile("output", "", "Compiler binary output (.abc)");
383 panda::PandArg<std::string> recordName("record-name", "", "Specify the record name");
384 panda::PandArg<bool> debuggerEvaluateExpression("debugger-evaluate-expression", false,
385 "evaluate expression in debugger mode");
386 panda::PandArg<std::string> base64Input("base64Input", "", "base64 input of js content");
387 panda::PandArg<bool> base64Output("base64Output", false, "output panda file content as base64 to std out");
388 panda::PandArg<std::string> sourceFile("source-file", "",
389 "specify the file path info recorded in generated abc");
390 panda::PandArg<std::string> outputProto("outputProto", "",
391 "specify the output name for serializd protobuf file (.protoBin)");
392 panda::PandArg<std::string> opCacheFile("cache-file", "", "cache file for incremental compile");
393 panda::PandArg<std::string> opNpmModuleEntryList("npm-module-entry-list", "", "entry list file for module compile");
394 panda::PandArg<bool> opMergeAbc("merge-abc", false, "Compile as merge abc");
395 panda::PandArg<bool> opuseDefineSemantic("use-define-semantic", false, "Compile ts class fields "\
396 "in accordance with ECMAScript2022");
397 panda::PandArg<std::string> moduleRecordFieldName("module-record-field-name", "", "Specify the field name "\
398 "of module record in unmerged abc");
399
400 // optimizer
401 panda::PandArg<bool> opBranchElimination("branch-elimination", false, "Enable branch elimination optimization");
402 panda::PandArg<bool> opOptTryCatchFunc("opt-try-catch-func", true, "Enable optimizations for functions with "\
403 "try-catch blocks");
404
405 // patchfix && hotreload
406 panda::PandArg<std::string> opDumpSymbolTable("dump-symbol-table", "", "dump symbol table to file");
407 panda::PandArg<std::string> opInputSymbolTable("input-symbol-table", "", "input symbol table file");
408 panda::PandArg<bool> opGeneratePatch("generate-patch", false, "generate patch abc, default as hotfix mode unless "\
409 "the cold-fix argument is set");
410 panda::PandArg<bool> opHotReload("hot-reload", false, "compile as hot-reload mode");
411 panda::PandArg<bool> opColdReload("cold-reload", false, "compile as cold-reload mode");
412 panda::PandArg<bool> opColdFix("cold-fix", false, "generate patch abc as cold-fix mode");
413
414 // version
415 panda::PandArg<bool> bcVersion("bc-version", false, "Print ark bytecode version. If both bc-version and"\
416 "bc-min-version are enabled, only bc-version will take effects");
417 panda::PandArg<bool> bcMinVersion("bc-min-version", false, "Print ark bytecode minimum supported version");
418 panda::PandArg<int> targetApiVersion("target-api-version", util::Helpers::DEFAULT_TARGET_API_VERSION,
419 "Specify the targeting api version for es2abc to generated the corresponding version of bytecode");
420 panda::PandArg<bool> targetBcVersion("target-bc-version", false, "Print the corresponding ark bytecode version"\
421 "for target api version. If both target-bc-version and bc-version are enabled, only target-bc-version"\
422 "will take effects");
423 panda::PandArg<std::string> targetApiSubVersion("target-api-sub-version",
424 std::string {util::Helpers::DEFAULT_SUB_API_VERSION},
425 "Specify the targeting api sub version for es2abc to generated the corresponding version of bytecode");
426
427 // compile entries and pkg context info
428 panda::PandArg<std::string> compileContextInfoPath("compile-context-info", "", "The path to compile context"\
429 "info file");
430 panda::PandArg<bool> opDumpDepsInfo("dump-deps-info", false, "Dump all dependency files and records "\
431 "including source files and bytecode files");
432 panda::PandArg<bool> opRemoveRedundantFile("remove-redundant-file", false, "Remove redundant info"\
433 " from abc file and remove redundant source file, which is effective when the compile-context-info switch"\
434 " is turned on and there is abc input");
435 panda::PandArg<bool> opDumpString("dump-string", false, "Dump program strings");
436
437 // aop transform
438 panda::PandArg<std::string> transformLib("transform-lib", "", "aop transform lib file path");
439
440 // tail arguments
441 panda::PandArg<std::string> inputFile("input", "", "input file");
442
443 argparser_->Add(&opHelp);
444 argparser_->Add(&opModule);
445 argparser_->Add(&opCommonjs);
446 argparser_->Add(&opDumpAst);
447 argparser_->Add(&opDumpTransformedAst);
448 argparser_->Add(&opCheckTransformedAstStructure);
449 argparser_->Add(&opRecordDebugSource);
450 argparser_->Add(&opParseOnly);
451 argparser_->Add(&opEnableTypeCheck);
452 argparser_->Add(&opEnableAbcInput);
453 argparser_->Add(&opDumpAsmProgram);
454 argparser_->Add(&opDumpNormalizedAsmProgram);
455 argparser_->Add(&opDumpAssembly);
456 argparser_->Add(&opDebugInfo);
457 argparser_->Add(&opDumpDebugInfo);
458 argparser_->Add(&debuggerEvaluateExpression);
459 argparser_->Add(&base64Input);
460 argparser_->Add(&base64Output);
461
462 argparser_->Add(&opOptLevel);
463 argparser_->Add(&opFunctionThreadCount);
464 argparser_->Add(&opFileThreadCount);
465 argparser_->Add(&opAbcClassThreadCount);
466 argparser_->Add(&opSizeStat);
467 argparser_->Add(&opSizePctStat);
468 argparser_->Add(&opDumpLiteralBuffer);
469
470 argparser_->Add(&inputExtension);
471 argparser_->Add(&outputFile);
472 argparser_->Add(&sourceFile);
473 argparser_->Add(&recordName);
474 argparser_->Add(&outputProto);
475 argparser_->Add(&opCacheFile);
476 argparser_->Add(&opNpmModuleEntryList);
477 argparser_->Add(&opMergeAbc);
478 argparser_->Add(&opuseDefineSemantic);
479 argparser_->Add(&moduleRecordFieldName);
480 argparser_->Add(&opBranchElimination);
481 argparser_->Add(&opOptTryCatchFunc);
482
483 argparser_->Add(&opDumpSymbolTable);
484 argparser_->Add(&opInputSymbolTable);
485 argparser_->Add(&opGeneratePatch);
486 argparser_->Add(&opHotReload);
487 argparser_->Add(&opColdReload);
488 argparser_->Add(&opColdFix);
489
490 argparser_->Add(&bcVersion);
491 argparser_->Add(&bcMinVersion);
492 argparser_->Add(&targetApiVersion);
493 argparser_->Add(&targetBcVersion);
494 argparser_->Add(&targetApiSubVersion);
495
496 argparser_->Add(&compileContextInfoPath);
497 argparser_->Add(&opDumpDepsInfo);
498 argparser_->Add(&opRemoveRedundantFile);
499 argparser_->Add(&opDumpString);
500
501 argparser_->Add(&transformLib);
502
503 argparser_->PushBackTail(&inputFile);
504 argparser_->EnableTail();
505 argparser_->EnableRemainder();
506
507 bool parseStatus = argparser_->Parse(argc, argv);
508
509 compilerOptions_.targetApiVersion = targetApiVersion.GetValue();
510 compilerOptions_.targetApiSubVersion = targetApiSubVersion.GetValue();
511 if (parseStatus && targetBcVersion.GetValue()) {
512 compilerOptions_.targetBcVersion = targetBcVersion.GetValue();
513 return true;
514 }
515
516 if (parseStatus && (bcVersion.GetValue() || bcMinVersion.GetValue())) {
517 compilerOptions_.bcVersion = bcVersion.GetValue();
518 compilerOptions_.bcMinVersion = bcMinVersion.GetValue();
519 return true;
520 }
521
522 if (!parseStatus || opHelp.GetValue() || (inputFile.GetValue().empty() && base64Input.GetValue().empty())) {
523 std::stringstream ss;
524
525 ss << argparser_->GetErrorString() << std::endl;
526 ss << "Usage: "
527 << "es2panda"
528 << " [OPTIONS] [input file] -- [arguments]" << std::endl;
529 ss << std::endl;
530 ss << "optional arguments:" << std::endl;
531 ss << argparser_->GetHelpString() << std::endl;
532
533 errorMsg_ = ss.str();
534 return false;
535 }
536
537 bool inputIsEmpty = inputFile.GetValue().empty();
538 bool base64InputIsEmpty = base64Input.GetValue().empty();
539 bool outputIsEmpty = outputFile.GetValue().empty();
540
541 if (!inputIsEmpty && !base64InputIsEmpty) {
542 errorMsg_ = "--input and --base64Input can not be used simultaneously";
543 return false;
544 }
545
546 if (!outputIsEmpty && base64Output.GetValue()) {
547 errorMsg_ = "--output and --base64Output can not be used simultaneously";
548 return false;
549 }
550
551 if (opModule.GetValue() && opCommonjs.GetValue()) {
552 errorMsg_ = "[--module] and [--commonjs] can not be used simultaneously";
553 return false;
554 }
555
556 if (opModule.GetValue()) {
557 scriptKind_ = es2panda::parser::ScriptKind::MODULE;
558 } else if (opCommonjs.GetValue()) {
559 scriptKind_ = es2panda::parser::ScriptKind::COMMONJS;
560 } else {
561 scriptKind_ = es2panda::parser::ScriptKind::SCRIPT;
562 }
563
564 std::string extension = inputExtension.GetValue();
565 if (!extension.empty()) {
566 if (VALID_EXTENSIONS.find(extension) == VALID_EXTENSIONS.end()) {
567 errorMsg_ = "Invalid extension (available options: js, ts, as, abc)";
568 return false;
569 }
570 }
571
572 bool isInputFileList = false;
573 if (!inputIsEmpty) {
574 std::string rawInput = inputFile.GetValue();
575 isInputFileList = rawInput[0] == PROCESS_AS_LIST_MARK;
576 std::string input = isInputFileList ? rawInput.substr(1) : rawInput;
577 sourceFile_ = input;
578 }
579
580 if (base64Output.GetValue()) {
581 compilerOutput_ = "";
582 } else if (!outputIsEmpty) {
583 compilerOutput_ = outputFile.GetValue();
584 } else if (outputIsEmpty && !inputIsEmpty) {
585 compilerOutput_ = RemoveExtension(util::Helpers::BaseName(sourceFile_)).append(".abc");
586 }
587
588 if (opMergeAbc.GetValue()) {
589 recordName_ = recordName.GetValue();
590 if (recordName_.empty()) {
591 recordName_ = compilerOutput_.empty() ? "Base64Output" :
592 RemoveExtension(util::Helpers::BaseName(compilerOutput_));
593 }
594 compilerOptions_.mergeAbc = opMergeAbc.GetValue();
595 }
596
597 if (opuseDefineSemantic.GetValue()) {
598 compilerOptions_.useDefineSemantic = opuseDefineSemantic.GetValue();
599 }
600
601 if (!inputIsEmpty) {
602 // common mode
603 auto inputAbs = panda::os::file::File::GetAbsolutePath(sourceFile_);
604 if (!inputAbs) {
605 std::cerr << "Failed to find file '" << sourceFile_ << "' during input file resolution" << std::endl
606 << "Please check if the file name is correct, the file exists at the specified path, "
607 << "and your project has the necessary permissions to access it." << std::endl;
608 return false;
609 }
610
611 auto fpath = inputAbs.Value();
612 if (isInputFileList) {
613 CollectInputFilesFromFileList(fpath, extension);
614 } else if (panda::os::file::File::IsDirectory(fpath)) {
615 CollectInputFilesFromFileDirectory(fpath, extension);
616 } else {
617 es2panda::SourceFile src(sourceFile_, recordName_, scriptKind_, GetScriptExtension(sourceFile_, extension));
618 src.isSourceMode = !IsAbcFile(sourceFile_, extension);
619 sourceFiles_.push_back(src);
620 }
621 } else if (!base64InputIsEmpty) {
622 // input content is base64 string
623 base64Input_ = ExtractContentFromBase64Input(base64Input.GetValue());
624 if (base64Input_.empty()) {
625 errorMsg_ = "The input string is not a valid base64 data";
626 return false;
627 }
628
629 es2panda::SourceFile src("", recordName_, es2panda::parser::ScriptKind::SCRIPT,
630 GetScriptExtensionFromStr(extension));
631 src.source = base64Input_;
632 sourceFiles_.push_back(src);
633 }
634
635 if (!outputProto.GetValue().empty()) {
636 compilerProtoOutput_ = outputProto.GetValue();
637 }
638
639 optLevel_ = opOptLevel.GetValue();
640 functionThreadCount_ = opFunctionThreadCount.GetValue();
641 fileThreadCount_ = opFileThreadCount.GetValue();
642 abcClassThreadCount_ = opAbcClassThreadCount.GetValue();
643 npmModuleEntryList_ = opNpmModuleEntryList.GetValue();
644
645 if (!opCacheFile.GetValue().empty()) {
646 ParseCacheFileOption(opCacheFile.GetValue());
647 }
648
649 if (opParseOnly.GetValue()) {
650 options_ |= OptionFlags::PARSE_ONLY;
651 }
652
653 if (opSizeStat.GetValue()) {
654 options_ |= OptionFlags::SIZE_STAT;
655 }
656
657 if (opSizePctStat.GetValue()) {
658 options_ |= OptionFlags::SIZE_PCT_STAT;
659 }
660
661 compilerOptions_.recordDebugSource = opRecordDebugSource.GetValue();
662 compilerOptions_.enableAbcInput = opEnableAbcInput.GetValue();
663 compilerOptions_.dumpAsmProgram = opDumpAsmProgram.GetValue();
664 compilerOptions_.dumpNormalizedAsmProgram = opDumpNormalizedAsmProgram.GetValue();
665 compilerOptions_.dumpAsm = opDumpAssembly.GetValue();
666 compilerOptions_.dumpAst = opDumpAst.GetValue();
667 compilerOptions_.dumpTransformedAst = opDumpTransformedAst.GetValue();
668 compilerOptions_.checkTransformedAstStructure = opCheckTransformedAstStructure.GetValue();
669 compilerOptions_.dumpDebugInfo = opDumpDebugInfo.GetValue();
670 compilerOptions_.isDebug = opDebugInfo.GetValue();
671 compilerOptions_.parseOnly = opParseOnly.GetValue();
672 compilerOptions_.enableTypeCheck = opEnableTypeCheck.GetValue();
673 compilerOptions_.dumpLiteralBuffer = opDumpLiteralBuffer.GetValue();
674 compilerOptions_.isDebuggerEvaluateExpressionMode = debuggerEvaluateExpression.GetValue();
675
676 compilerOptions_.functionThreadCount = functionThreadCount_;
677 compilerOptions_.fileThreadCount = fileThreadCount_;
678 compilerOptions_.abcClassThreadCount = abcClassThreadCount_;
679 compilerOptions_.output = compilerOutput_;
680 compilerOptions_.debugInfoSourceFile = sourceFile.GetValue();
681 compilerOptions_.optLevel = (compilerOptions_.isDebug || !base64Input.GetValue().empty() ||
682 base64Output.GetValue()) ? 0 : opOptLevel.GetValue();
683 compilerOptions_.sourceFiles = sourceFiles_;
684 compilerOptions_.mergeAbc = opMergeAbc.GetValue();
685 compilerOptions_.compileContextInfoPath = compileContextInfoPath.GetValue();
686 if (!compileContextInfoPath.GetValue().empty()) {
687 ParseCompileContextInfo(compileContextInfoPath.GetValue());
688 }
689 compilerOptions_.dumpDepsInfo = opDumpDepsInfo.GetValue();
690 compilerOptions_.updatePkgVersionForAbcInput = compilerOptions_.enableAbcInput &&
691 (!compilerOptions_.compileContextInfo.pkgContextInfo.empty() ||
692 !compilerOptions_.compileContextInfo.updateVersionInfo.empty());
693 compilerOptions_.removeRedundantFile = opRemoveRedundantFile.GetValue();
694 compilerOptions_.dumpString = opDumpString.GetValue();
695 compilerOptions_.moduleRecordFieldName = moduleRecordFieldName.GetValue();
696
697 compilerOptions_.patchFixOptions.dumpSymbolTable = opDumpSymbolTable.GetValue();
698 compilerOptions_.patchFixOptions.symbolTable = opInputSymbolTable.GetValue();
699
700 bool generatePatch = opGeneratePatch.GetValue();
701 bool hotReload = opHotReload.GetValue();
702 bool coldReload = opColdReload.GetValue();
703 bool coldFix = opColdFix.GetValue();
704 if (generatePatch && hotReload) {
705 errorMsg_ = "--generate-patch and --hot-reload can not be used simultaneously";
706 return false;
707 }
708 if (coldFix && !generatePatch) {
709 errorMsg_ = "--cold-fix can not be used without --generate-patch";
710 return false;
711 }
712 compilerOptions_.patchFixOptions.generatePatch = generatePatch;
713 compilerOptions_.patchFixOptions.hotReload = hotReload;
714 compilerOptions_.patchFixOptions.coldReload = coldReload;
715 compilerOptions_.patchFixOptions.coldFix = coldFix;
716
717 bool transformLibIsEmpty = transformLib.GetValue().empty();
718 if (!transformLibIsEmpty) {
719 auto libName = transformLib.GetValue();
720 // check file exist or not
721 auto transformLibAbs = panda::os::file::File::GetAbsolutePath(libName);
722 if (!transformLibAbs) {
723 std::cerr << "Failed to find file '" << libName << "' during transformLib file resolution" << std::endl
724 << "Please check if the file name is correct, the file exists at the specified path, "
725 << "and your project has the necessary permissions to access it." << std::endl;
726 return false;
727 }
728 compilerOptions_.transformLib = transformLibAbs.Value();
729 }
730
731 compilerOptions_.branchElimination = opBranchElimination.GetValue();
732 compilerOptions_.requireGlobalOptimization = compilerOptions_.optLevel > 0 &&
733 compilerOptions_.branchElimination &&
734 compilerOptions_.mergeAbc;
735 panda::compiler::options.SetCompilerBranchElimination(compilerOptions_.branchElimination);
736 panda::bytecodeopt::options.SetSkipMethodsWithEh(!opOptTryCatchFunc.GetValue());
737
738 return true;
739 }
740
ExtractContentFromBase64Input(const std::string & inputBase64String)741 std::string Options::ExtractContentFromBase64Input(const std::string &inputBase64String)
742 {
743 std::string inputContent = util::Base64Decode(inputBase64String);
744 if (inputContent == "") {
745 return "";
746 }
747 bool validBase64Input = util::Base64Encode(inputContent) == inputBase64String;
748 if (!validBase64Input) {
749 return "";
750 }
751 return inputContent;
752 }
753 } // namespace panda::es2panda::aot
754