/* * testlexer.cc * by CMB 8/04 * * test driver for Espresso lexical analyzer produced by flex. * Do not change this file. * * MOD 8/17/05 by CMB * Include parser.h so we don't need to modify it later. * * MOD 1/12/05 by CMB * Changed to print tokens and linenums in fixed width fields * * MOD 9/14/04 by CMB * changed initialization of linenum to a more useful value */ #include // needed for FILE #include // needed for setw #include #include "StringTab.h" // so it recognizes the class names used in YYSTYPE from espresso.tab.h #include "parser.h" #include "espresso.tab.h" #include "printToken.h" #include "lexer.h" // defined below void processCmdLine(int argc, char *argv[]); bool hasAValue(int token); void printTokenValue(ostream &o, int token, YYSTYPE yylval); // needs to be global to be used by flex-gen code and code here. StringTab stringtab; // the variable for communicating lexical values from lex anal to here YYSTYPE yylval; // need to define here because not compiling with a parser // espresso.flex needs to maintain this value int linenum = 1; int main (int argc, char* argv[]) { initLexer(); processCmdLine(argc, argv); int token; do { token = yylex(); cerr << "Token: "; printToken(cerr, token); cerr << " Line: " << setw(4) << linenum; if (hasAValue(token)) { cerr<< " Value: "; printTokenValue(cerr, token, yylval); } cerr << endl; } while (token != 0); // end by listing all the strings in the string table // using the function dumpStringTab cerr << endl << "Contents of the string table:" << endl; stringtab.dumpStringTab(cerr); return 0; } // NOTE: yyin is the file variable defined by and used by flex void processCmdLine(int argc, char *argv[]) { if (argc < 2) { cerr << "Error: Missing file to process. Run program as follows:" << endl; cerr << "testlexer " << endl; exit(1); } else { yyin = fopen(argv[1], "r"); if (yyin == NULL) { cerr << "Error: Could not open input file " << argv[1] << endl; exit(1); } } } bool hasAValue(int token) { return ((token == INT_LITERAL) || (token == BOOL_LITERAL) || (token == ID) || (token == ERROR)); } // prints out the correct token value based on the token type // note: most tokens do not have a value void printTokenValue(ostream &o, int token, YYSTYPE yylval) { switch (token) { case INT_LITERAL: o << yylval.intLiteral; break; case BOOL_LITERAL: o << ((yylval.boolLiteral == true) ? "true" : "false"); break; case ID: o << yylval.id->getName(); break; case ERROR: o << yylval.errorMsg; break; default: ; // has no token value } }