当尝试解析grako中的括号表达式时,“FailedParse:[...]期望文本结束”

时间:2016-09-12 15:44:44

标签: python ebnf grako

search_query.ebnf中,我对grako 3.14.0有以下语法定义:

@@grammar :: SearchQuery

start = search_query $;

search_query = parenthesized_query | combined_query | search_term;
parenthesized_query = '(' search_query ')';
combined_query = search_query binary_operator search_query;
binary_operator = '&' | '|';
search_term = /\w+/;

我使用生成解析器

grako search_query.ebnf --outfile search_query_parser.py

结果与我对这些输入的预期有效:

import search_query_parser

parser = search_query_parser.SearchQueryParser()
parser.parse('a')  # -> 'a'
parser.parse('(a)')  # -> ['(', 'a', ')']
parser.parse('a & b')  # -> ['a', '&', 'b']
parser.parse('a | b')  # -> ['a', '|', 'b']
parser.parse('(a|b)&c')  # -> ['(', ['a', '|', 'b'], ')', '&', 'c']

但如果我在运算符的右侧有一个带括号的表达式,解析器会给出一条错误消息:

parser.parse('c&(a|b)')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/das-g/.virtualenvs/tmp-d0fd5a9428f7612a/search_query_parser.py", line 82, in parse
    return super(SearchQueryParser, self).parse(text, *args, **kwargs)
  File "/home/das-g/.virtualenvs/tmp-d0fd5a9428f7612a/lib/python3.5/site-packages/grako/contexts.py", line 227, in parse
    result = rule()
  File "/home/das-g/.virtualenvs/tmp-d0fd5a9428f7612a/lib/python3.5/site-packages/grako/contexts.py", line 86, in wrapper
    return self._call(rule, name, params, kwparams)
  File "/home/das-g/.virtualenvs/tmp-d0fd5a9428f7612a/lib/python3.5/site-packages/grako/contexts.py", line 475, in _call
    node, newpos, newstate = self._invoke_rule(rule, name, params, kwparams)
  File "/home/das-g/.virtualenvs/tmp-d0fd5a9428f7612a/lib/python3.5/site-packages/grako/contexts.py", line 511, in _invoke_rule
    rule(self)
  File "/home/das-g/.virtualenvs/tmp-d0fd5a9428f7612a/search_query_parser.py", line 87, in _start_
    self._check_eof()
  File "/home/das-g/.virtualenvs/tmp-d0fd5a9428f7612a/lib/python3.5/site-packages/grako/contexts.py", line 650, in _check_eof
    self._error('Expecting end of text.')
  File "/home/das-g/.virtualenvs/tmp-d0fd5a9428f7612a/lib/python3.5/site-packages/grako/contexts.py", line 450, in _error
    item
grako.exceptions.FailedParse: (1:2) Expecting end of text. :
c&(a|b)
 ^
start

我做错了吗?

1 个答案:

答案 0 :(得分:1)

  

我做错了吗?

我不这么认为。

这似乎是grako中关于“左递归”的known bug

错误中提到的解决方法似乎也适用于您的情况:

@@grammar :: SearchQuery

start = search_query $;

search_query = parenthesized_query | combined_query | search_term;
parenthesized_query = '(' search_query | search_term ')';  ## Workaround
combined_query = search_query binary_operator search_query;
binary_operator = '&' | '|';
search_term = /\w+/;

即。尽管search_term规则也应该能够生成它,但在括号内明确提到search_query