/// Consume whitespace and comments void Input::eatWS() { // Until the end of the whitespace for (;;) { // Consume whitespace characters if (isspace(peekCh())) { readCh(); continue; } // If this is a single-line comment if (matchStr("//")) { // Read until and end of line is reached for (;;) { char ch = readCh(); if (ch == '\n' || ch == '\0') break; } continue; } // If this is a multi-line comment if (matchStr("/*")) { // Read until the end of the comment for (;;) { char ch = readCh(); if (ch == '*' && matchCh('/')) break; } continue; } // This isn't whitespace, stop break; } }
/// Try and match a given character in the input /// The character is consumed if matched bool Input::matchCh(char ch) { if (peekCh() == ch) { readCh(); return true; } return false; }
/// Try and match a given string in the input /// The string is consumed if matched bool Input::matchStr(const std::string& str) { if (peekStr(str)) { for (size_t i = 0; i < str.length(); ++i) readCh(); return true; } return false; }
void LexicalAnalyzer::LexicalAnalyze(const string& srcCodeFilePath) // an integrated automaton using if-else sentence // according to current input symbol, a sub-automaton would be activated { FILE* fp = fopen("./test.cpp", "r"); char ch; ch = fgetc(fp); while(ch != EOF) { // cout << ch; if(isalpha(ch) || ch == '_') { // cout << "will read id" << endl; readID(fp, ch); // cout << "read id ok" << endl; } else if(ch == '\'') { // cout << "will read character" << endl; readCh(fp, ch); // cout << "read character ok" << endl; } else if(ch == '\"') { // cout << "will read string" << endl; readStr(fp, ch); // cout << "read string ok" << endl; } else if(isdigit(ch)) { // cout << "will read constant" << endl; readConst(fp, ch); // cout << "read constant ok" << endl; } else if(ch == ' ' || ch == '\t' || ch == '\n') { // cout << "will read space tab and newline" << endl; readSpaceTabNewline(fp, ch); // cout << "read space tab and newline ok" << endl; } else { // cout << "will read symbol" << endl; readSymbol(fp, ch); // cout << "read symbol ok" << endl; } } // cout << endl; fclose(fp); }