Grako-如何进行错误处理? [英] Grako - How to do error handling?

查看:100
本文介绍了Grako-如何进行错误处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何使用Grako进行错误处理?

How do I do error handling with Grako?

EBNF(MyGrammar.ebnf):

EBNF (MyGrammar.ebnf):

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

我正在使用生成解析器

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

解析一个空字符串和一个不好的"字符串(语法无法匹配)都会导致一个空的AST闭包.

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 = []

另外:是否有任何错误消息,例如"123位置的预期foo"?

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

推荐答案

对于初学者,第一个规则确实与空字符串匹配.也许您想尝试类似的方法:

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

这篇关于Grako-如何进行错误处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆