Lex.h /* * lex.h * * CS280 * Spring 2023 */ #ifndef LEX_H_ #define LEX_H_ #include <string> #include <iostream> #include <map> using namespace std; //Definition of all the possible token types enum Token { // keywords WRITELN, IF, ELSE, // identifiers IDENT, NIDENT, SIDENT, // an integer, real, and string constant ICONST, RCONST, SCONST, // the numeric operators, assignment, numeric and string comparison operators PLUS, MINUS, MULT, DIV, EXPONENT, ASSOP, NEQ, NGTHAN, NLTHAN, CAT, SREPEAT, SEQ, SLTHAN, SGTHAN, //Delimiters COMMA, SEMICOL, LPAREN, RPAREN, LBRACES, RBRACES, // any error returns this token ERR, // when completed (EOF), return this token DONE, }; //Class definition of LexItem class LexItem { Token token; string lexeme; int lnum; public: LexItem() { token = ERR; lnum = -1; } LexItem(Token token, string lexeme, int line) { this->token = token; this->lexeme = lexeme; this->lnum = line; } bool operator==(const Token token) const { return this->token == token; } bool operator!=(const Token token) const { return this->token != token; } Token GetToken() const { return token; } string GetLexeme() const { return lexeme; } int GetLinenum() const { return lnum; } }; extern ostream& operator<<(ostream& out, const LexItem& tok); extern LexItem id_or_kw(const string& lexeme, int linenum); extern LexItem getNextToken(istream& in, int& linenum); #endif /* LEX_H_ */ tokensListing.cpp #include "lex.h" extern ostream operator <<(ostream & out, const tok & tok) { out<< "Token: "<< tok.GetToken( )<< "lex:" << tok.Getlexeme( )<< "Line No: " <<tok.linenum( ); } #ifndef LEX_H_ #define LEX_H_ #include<string> #include<iostream> using std:: string; using std:: istream; using std:: ostream; Enum Token { //Keywords PRINT,PRINTLN, REPEAT, BEGIN, END // an identifier INDENT, // an Integer and String constant ICONST, SCONST, //Operators, Parens, semicolon PLUS, MINUS, STAR, SLASH, EQ, LPAREN, RPAREN, SC, // any error returns this token ERR, //When completed (EDF), return this token DONE }; Class Tok { Token token; String lexeme; int inum; public Tok( ){ token = ERR; lnum = -1; } Token( Token token, string lexeme, int line){ this -> token = token; this -> lexeme = lexeme; this -> lnum = line; } bool operator == (const Token token) const { return this -> token == token; } bool operator != (const Token token) const { return this -> token == token; } Token GetToken ( ) const { return token; } String Getlexeme( ) const { return lexeme;} int GetLinenum( ) const { return lnum;} }; extern ostream &operator << (ostream &out, const Tok &tok); extern Tok getNextToken (istream&in, int & line num); #endif /*LEX_H_*/ #include 'lex.h' int main( ) { Tok toks[ ] = { TOK(PRINT, "PRINT", 3); TOK(PRINTLN, "PRINTLN",3); TOK(REPEAT, "REPEAT", 3); TOK(BEGIN, "BEGIN",3); TOK(END, "END", 3); TOK(IDENT, "foo", 3); TOK(CONST,"347",3); TOK(SCONST, "Hello world", 3); TOK(PLUS, " +" , 3); TOK(MINUS, "-", 3); TOK(STAR, "*",3); TOK(SLASH, "/",3); TOK(EQ, "=",3); TOK(LPAREN, "(",3); TOK(RPAREN.