CoutStatementNode * ParserClass::CoutStatement() { Match(COUT_TOKEN); Match(INSERTION_TOKEN); CoutStatementNode *csn = new CoutStatementNode(); ExpressionNode *expression = Expression(); csn->AddExpression(expression); while (true) { TokenType tt = mScanner->PeekNextToken().GetTokenType(); if (tt == INSERTION_TOKEN) { Match(INSERTION_TOKEN); TokenClass next = mScanner->PeekNextToken(); if (next.GetTokenType() == ENDL_TOKEN) { Match(ENDL_TOKEN); csn->AddExpression(NULL); } else { ExpressionNode *nextExpression = Expression(); csn->AddExpression(nextExpression); } } else { if (tt == ENDL_TOKEN) { Match(ENDL_TOKEN); csn->AddExpression(NULL); } Match(SEMICOLON_TOKEN); break; } } return csn; }
TokenClass ParserClass::Match(TokenType expectedType) { TokenClass currToken = mScanner->GetNextToken(); if (currToken.GetTokenType() != expectedType) { cerr << "Error in ParserClass::Match. " << endl; cerr << "Recieved token type " << currToken.GetTokenTypeName() << endl; exit(1); } MSG("Sucessfully matched Token Type: " << currentToken.GetTokenTypeName() << ". Lexeme: \"" << currentToken.GetLexeme() << "\""); return currToken; }
// Verify that the next token in the input file is of the same type // that the parser expects. TokenClass ParserClass::Match(TokenType expectedType) { TokenClass currentToken = this->mScanner->GetNextToken(); if (currentToken.GetTokenType() != expectedType) { std::cerr << "Error in ParserClass::Match. " << std::endl; std::cerr << "Expected token type " << TokenClass::GetTokenTypeName(expectedType) << ", but got type " << currentToken.GetTokenTypeName() << std::endl; exit(1); } MSG("\tSuccessfully matched Token Type: " << currentToken.GetTokenTypeName() << ". Lexeme: \"" << currentToken.GetLexeme() << "\""); return currentToken; // the one we just processed }
StatementNode * ParserClass::Statement() { TokenClass nextToken = mScanner->PeekNextToken(); TokenType tt = nextToken.GetTokenType(); if (tt == INT_TOKEN) { return DeclarationStatement(); } else if (tt == IDENTIFIER_TOKEN) { return AssignmentStatement(); } else if (tt == COUT_TOKEN) { return CoutStatement(); } else if (tt == LCURLY_TOKEN) { return Block(); } else if (tt == IF_TOKEN) { return IfStatement(); } else if (tt == DO_TOKEN) { return DoWhile(); } return NULL; }