Grako - How to do error handling?

196 views Asked by At

How do I do error handling with Grako?

EBNF (MyGrammar.ebnf):

pattern   = { tag | function }* ;
tag       = tag:( "%" name:id "%" );
function  = function:("$" name:id "()" );
id        = ?/([^\\%$,()=])+/? ;

I'm generating the parser with

python -m grako --whitespace '' MyGrammar.ebnf > my_parser.py

Parsing an empty string and a "bad" string (that could not be matched by the grammar) both results to an empty AST Closure.

parser = MyGrammarParser()
ast = parser.parse(u"%test%", rule_name='pattern')     #ast contains something
ast = parser.parse(u"", rule_name='pattern')           #ast = []
ast = parser.parse(u"$bad $test", rule_name='pattern') #ast = []

And additionally: Is there any error message like 'expected foo at position 123'?

1

There are 1 answers

1
Apalala On BEST ANSWER

For starters, the first rule does match the empty string. Perhaps you'd want to try something like:

pattern   = { tag | function }+ $ ;

Yes, the generated parser will raise an exception if it can't parse the input string; note the $in the above rule: it tells the parser it should see the end of the input in that position. Without it, the parser is happy to succeed having parsed only part of the input.

Then, I don't think that named elements within named elements will produce the desired results.

This is a version of the grammar that may produce what you want:

pattern   = { tag | function }+ $ ;
tag       = ( "%" tag:id "%" );
function  = ("$" function:id "()" );
id        = ?/([^\\%$,()=])+/? ;