Reputation: 682
I am trying to use antlr4 to write some error checking for my simple grammar.
The grammar itself is constructed by functions.
ie
FUNCTION hello (n){
......
}
FUNCTION main (n) {
......
}
I am not sure how it suppose to catch specific errors such as missing function name, or missing main function
Here is what my ErrorListener looks like
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.tree.*;
public class SimpleErrorListener extends BaseErrorListener {
@Override
public void syntaxError(Recognizer<?, ?> recognizer,
Object offendingSymbol,
int line,
int charPositionInLine,
String msg,
RecognitionException e) {
List<String> stack = ((Parser) recognizer.getRuleInvocationStack();
Collections.reverse(stack);
System.err.println("rule stack: " + stack);
System.err.println("line" + line + ":" +
charPositionInLine + "at" + offendingSymbol + ": " + msg);
}
}
I also removed the console error listener and add this one, but I don't know how to deal with those specific errors. Any suggestions appreciated. Thanks a lot.
Upvotes: 1
Views: 1774
Reputation: 99869
Reporting semantic errors is much easier in general than reporting syntax errors. If you want custom reporting of syntax errors, you need to alter your grammar so those syntax errors become semantic errors. For example, if you currently parse your function like this:
function : FUNCTION ID '(' ...
Then you can turn "Missing function name" into a syntax error by using one of the following rules instead:
function : FUNCTION ID? '(' ...
// alternate
function : FUNCTION (ID | /*missing function name; reported in listener*/) '(' ...
Note that your grammar will quickly become unmanageable as you add more and more special cases.
Upvotes: 1