Reputation: 69
I'm trying to write a propositional logic program in Java that determines if a formula is well-formed or not. Obviously, ANTLR is a good choice for doing this since I can write all the rules in a CFG. All of that is nice, and I have my grammar working perfectly (it detects when a formula is or is not well-formed correctly). However, this program is aimed for beginners in the subject, and I want to be able to tell them where they went wrong with typing the formula in.
If I type in the formula (A -> B
, the parser recognizes that this is not well-formed because it is missing a closing parenthesis. However, the error it generates is lackluster to say the least: line 1:5 no viable alternative at input '(A -> B'
(this is slightly modified from vanilla ANTLR to include the line numbers iirc). I've seen people embed rules in the grammar with notifyErrorListener(...), but this means that all of my rules must be non-left recursive. For instance, I have the rule
propImpRule: OPEN_PAREN propWff IMPLIES propWff CLOSE_PAREN;
propImpRule: OPEN_PAREN propWff IMPLIES propWff {notifyErrorListener("Missing ')'");};
If I want to do the same with the opening parenthesis (or both for that matter), I can't because of how ANTLR's parser works (and I really don't want to have to go through the trouble of converting every rule to be non-left recursive. Plus, embedding the rules in the grammar seems cumbersome and a way around the actual problem).
I've tried to follow examples from past StackOverflow answers and by reading the ANTLR manual/documentation, but nothing really provides what I want or need (or enough documentation to do so). Can anyone point me in the right direction? Thanks!
Upvotes: 1
Views: 194
Reputation: 6785
The standard “no viable alternative” message will also list what characters are expected. That information is also available for producing your own messages.
That being said, I suspect that will still not meet your needs.
It’s going to be difficult for a general purpose tool to produce great messages for beginners.
One suggestion that might help:
Go ahead and write parser rules that match the mistakes you might anticipate. This is a bit counter-intuitive, as most people expect a grammar to only recognize valid constructs. But, that’s not really a “rule”. You can also recognize invalid constructs and then, when they show up in your parse tree, you can add semantic processing to provide error messages that are as “nice” and informative as you’re willing to make them.
Upvotes: 3