diff --git a/grammar/main.cc b/grammar/main.cc index 47b6152..3e4af82 100644 --- a/grammar/main.cc +++ b/grammar/main.cc @@ -5,11 +5,13 @@ #include "CListener.h" #include "CParser.h" #include "CVisitor.h" +#include #include -#include #include #include #include +#include +#include int main(int argc, char **argv) { auto llvmin = llvm::MemoryBuffer::getFileOrSTDIN("-"); @@ -18,44 +20,31 @@ int main(int argc, char **argv) { sysu_grammar::CLexer lexer(&input); antlr4::CommonTokenStream tokens(&lexer); tokens.fill(); - if (argc >= 2 && !std::strcmp(argv[1], "-dump-tokens")) { -// 请完成此处的词法分析器 -#if 0 + if (argc >= 2 && argv[1] == std::string("-dump-tokens")) { + // 请完成此处的词法分析器 for (auto token : tokens.getTokens()) { - llvm::outs() << token->toString() << "\n"; + if (token->getChannel() != antlr4::Token::HIDDEN_CHANNEL) { + std::string t = lexer.getVocabulary().getSymbolicName(token->getType()); + std::unordered_map transform_table{ + {"Int", "int"}, + {"Identifier", "identifier"}, + {"LeftParen", "l_paren"}, + {"RightParen", "r_paren"}, + {"LeftBrace", "l_brace"}, + {"Return", "return"}, + {"Constant", "numeric_constant"}, + {"Semi", "semi"}, + {"RightBrace", "r_brace"}, + {"EOF", "eof"}}; + if (transform_table.count(t)) + t = transform_table[t]; + llvm::outs() << t << " \'" << (t != "eof" ? token->getText() : "") + << "\'\t\tLoc=<" + << "" + << ":" << token->getLine() << ":" + << token->getCharPositionInLine() + 1 << ">\n"; + } } -#else - llvm::outs() - << "int \'int\' " - "Loc= " - << "\n" - << "identifier \'main\' " - "Loc= " - << "\n" - << "l_paren \'(\' " - "Loc= " - << "\n" - << "r_paren \')\' " - "Loc= " - << "\n" - << "l_brace \'{\' " - "Loc= " - << "\n" - << "return \'return\' " - "Loc= " - << "\n" - << "numeric_constant \'3\' " - "Loc= " - << "\n" - << "semi \';\' " - "Loc= " - << "\n" - << "r_brace \'}\' " - "Loc= " - << "\n" - << "eof \'\' Loc= " - << "\n"; -#endif return 0; } sysu_grammar::CParser parser(&tokens);