Initial commit from sysy-main

This commit is contained in:
Lixuanwang
2025-02-27 23:14:53 +08:00
commit cc523fd30b
1125 changed files with 257793 additions and 0 deletions

96
src/sysyc.cpp Normal file
View File

@@ -0,0 +1,96 @@
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <unistd.h>
using namespace std;
#include "SysYLexer.h"
#include "SysYParser.h"
using namespace antlr4;
#include "ASTPrinter.h"
#include "Backend.h"
#include "SysYIRGenerator.h"
using namespace sysy;
static string argStopAfter;
static string argInputFile;
static bool argFormat = false;
void usage(int code = EXIT_FAILURE) {
const char *msg = "Usage: sysyc [options] inputfile\n\n"
"Supported options:\n"
" -h \tprint help message and exit\n";
" -f \tpretty-format the input file\n";
" -s {ast,ir,asm}\tstop after generating AST/IR/Assembly\n";
cerr << msg;
exit(code);
}
void parseArgs(int argc, char **argv) {
const char *optstr = "hfs:";
int opt = 0;
while ((opt = getopt(argc, argv, optstr)) != -1) {
switch (opt) {
case 'h':
usage(EXIT_SUCCESS);
break;
case 'f':
argFormat = true;
break;
case 's':
argStopAfter = optarg;
break;
default: /* '?' */
usage();
}
}
if (optind >= argc)
usage();
argInputFile = argv[optind];
}
int main(int argc, char **argv) {
parseArgs(argc, argv);
// open the input file
ifstream fin(argInputFile);
if (not fin) {
cerr << "Failed to open file " << argv[1];
return EXIT_FAILURE;
}
// parse sysy source to AST
ANTLRInputStream input(fin);
SysYLexer lexer(&input);
CommonTokenStream tokens(&lexer);
SysYParser parser(&tokens);
auto moduleAST = parser.module();
if (argStopAfter == "ast") {
cout << moduleAST->toStringTree(true) << '\n';
return EXIT_SUCCESS;
}
// pretty format the input file
if (argFormat) {
ASTPrinter printer;
printer.visitModule(moduleAST);
return EXIT_SUCCESS;
}
// visit AST to generate IR
SysYIRGenerator generator;
generator.visitModule(moduleAST);
auto moduleIR = generator.get();
if (argStopAfter == "ir") {
moduleIR->print(cout);
return EXIT_SUCCESS;
}
// generate assembly
CodeGen codegen(moduleIR);
string asmCode = codegen.code_gen();
cout << asmCode << endl;
if (argStopAfter == "asm")
return EXIT_SUCCESS;
return EXIT_SUCCESS;
}