I am trying to migrate an antlr project from c++ to go. The grammar and code generation is mostly done (based on the solution provided in 65038949), but one pending item is to write the custom error reporter in go.
I am looking for a custom error reporter for these purposes:
I would like to print my custom message, maybe with extra information (eg the file name, which is not printed by the default error printer).
On every error, the error reporter updates a global counter, and in the main program if this error_count>0 then further processing is skipped.
So here is what was done in the c++ project:
A custom message was defined in this function:
string MyErrorMessage(unsigned int l, unsigned int p, string m) { stringstream s; s << "ERR: line " << l << "::" << p << " " << m; global->errors++; return s.str(); }And the antlr runtime (
ConsoleErrorListener.cpp) had been updated to call the above function:void ConsoleErrorListener::syntaxError(IRecognizer *, Token * , size_t line, size_t charPositionInLine, const std::string &msg, std::exception_ptr) { std::cerr << MyErrorMessage(line, charPositionInLine, msg) << std::endl; }Finally, the main program would skip the further processing like this:
parser.top_rule(); if(global->errors > 0) { exit(0); }
How can these pieces of c++ code be re-written for the go target of antlr?
Some additional notes, after browsing the antlr runtime code (from github.com/antlr/antlr4/runtime/Go/antlr):
parser.go has a variable "_SyntaxErrors", which gets incremented on every error, but nobody seems to be using it. What is the purpose of this variable, and how do I use it after parsing, to check if any errors have occurred? I did the following, but obviously that did not work! (A workaround is to add a new variable MyErrorCount in the parser, and increment it whenever _SyntaxErrors also gets incremented, but that does not look like an elegant solution, because here I am editing the runtime code!)
tree := parser.Top_rule() // this is ok fmt.Printf("errors=%d\n", parser._SyntaxErrors) // this gives a compiler error //fmt.Printf("errors=%d\n", parser.MyErrorCount) // this is okIn the above note, I had introduced a new variable in antlr code, and reading it in the user code - bad coding style, but works. But I also need to do the reverse - the antlr error reporter (error_listener.go:SyntaxError()) needs to read the user code's variable having the file name and print it. I can do it by adding a new function in antlr to pass this argument and register this filename in a new variable, but is there a better way to do this?