/* * espc.cc * by CMB 10/04 * * Compiles the espresso file given on the command line as * .esp * Generated code is written to .s * unless there were errors. * * Run as follows: * espc [-s][-c] .esp * * the optional -s argument turns on debugging output for * semantic analysis phase (flag is semantDebug). * * the optional -c argument turns on debugging output for * code generation phase (flag is codegenDebug). * */ #include using namespace std; #include "ast.h" #include "SymTab.h" #include "semant.h" #include "SError.h" #include "codegen.h" bool semantDebug = false; bool codegenDebug = false; // linenum was defined in testlexer.cc, so it needs // to be defined here instead int linenum = 1; #include extern FILE *yyin; // defined in espresso.y extern void initParser(); extern int yyparse(); // defined below string makeAssemName(const string &srcFileName); ofstream * openAssemFile(const string &srcFileName); char * processCmdLine(int argc, char *argv[]); int main(int argc, char* argv[]) { string srcFileName = string(processCmdLine(argc, argv)); initParser(); int status = yyparse(); if (status == 1) { // parse was not successful cerr << "Compilation halted due to lex and parse errors" << endl; exit(1); } Semant *semant = new Semant(ast, srcFileName); // entry point to your semantic analyzer code semant->analyzeProg(); if (semantDebug) { ast->dump(cout, 0); } if (SError::hasErrors()) { cerr << "Compilation halted due to semantic errors" << endl; exit(1); } ofstream *assemFile = openAssemFile(srcFileName); CodeGen *codeGen = new CodeGen(ast, semant->getClassTable(), *assemFile); // entry point to your code generation code codeGen->genCode(); } ofstream *openAssemFile(const string &srcFileName) { string assemFileName = makeAssemName(srcFileName); ofstream *os = new ofstream(assemFileName.c_str()); if (!*os) { cerr << "Error: Cannot open output file " << assemFileName << endl; exit(1); } return os; } string makeAssemName(const string &srcFileName) { int dotPos = srcFileName.find_last_of('.'); return srcFileName.substr(0,dotPos) + ".s"; } char * processCmdLine(int argc, char *argv[]) { if (argc < 2) { cerr << "Error: Missing file to process. Run program as follows:" << endl; cerr << "espc [-s][-c] " << endl; exit(1); } for (int i=1; i < argc-1; i++) { // process options if (strcmp(argv[i], "-s") == 0) { semantDebug = true; } else if (strcmp(argv[i], "-c") == 0) { codegenDebug = true; } else { cerr << "Warning: Ignoring unknown option: " << argv[i] << endl; } } yyin = fopen(argv[argc-1], "r"); // process filename if (yyin == NULL) { cerr << "Error: Could not open input file " << argv[argc-1] << endl; exit(1); } return argv[argc-1]; }