Grako - How to do error handling?

梦想的初衷 提交于 2019-12-12 04:17:28

问题


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:


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        = ?/([^\\%$,()=])+/? ;


来源:https://stackoverflow.com/questions/35397192/grako-how-to-do-error-handling

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!