Seems you have an older version of this book. The API has changed and it should be clear that the book is using Java, so you cannot copy the code 1:1. In C++ the call is:
void parse(const std::string &sql, bool dumpTokenStream, bool dumpParseTree) {
ANTLRInputStream input(sql);
MySQLLexer lexer(&input);
CommonTokenStream tokens(&lexer);
MySQLParser parser(&tokens);
parser.setBuildParseTree(true);
// First parse with the bail error strategy to get quick feedback for correct queries.
parser.setErrorHandler(std::make_shared<BailErrorStrategy>());
parser.getInterpreter<ParserATNSimulator>()->setPredictionMode(PredictionMode::SLL);
parser.removeErrorListeners();
try {
tokens.fill();
} catch (IllegalStateException &) {
std::cout << "Error: illegal state found, probably unfinished string." << std::endl;
}
if (dumpTokenStream) {
for (auto token : tokens.getTokens())
std::cout << token->toString() << std::endl;
std::cout << std::endl;
}
tree::ParseTree *tree;
auto start = std::chrono::steady_clock::now();
try {
tree = parser.query();
} catch (ParseCancellationException &pce) {
// If parsing was cancelled we either really have a syntax error or we need to do a second step,
// now with the default strategy and LL parsing.
tokens.reset();
parser.reset();
parser.setErrorHandler(std::make_shared<DefaultErrorStrategy>());
parser.getInterpreter<ParserATNSimulator>()->setPredictionMode(PredictionMode::LL);
parser.addErrorListener(&ConsoleErrorListener::INSTANCE);
tree = parser.query();
}
auto duration = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::steady_clock::now() - start);
if (parser.getNumberOfSyntaxErrors() > 0 || lexer.getNumberOfSyntaxErrors() > 0) {
std::cout << "Errors encountered: " << parser.getNumberOfSyntaxErrors() + lexer.getNumberOfSyntaxErrors()<< std::endl;
std::cout << "Query: " << sql << std::endl;
}
std::cout << "Parse time: " << duration.count() / 1000.0 << " ms" << std::endl;
if (dumpParseTree && tree != nullptr) {
std::cout << std::endl << "Parse tree: " << tree->toStringTree(&parser) << std::endl;
}
}
Side note: the separate token.fill() call is not necessary normally and only used to here for timing reasons.