最终,我跑出来的研究时间,并有相当的手动跳过定居。基本上每次解析器失败时,我们尝试将光标前进一个字符并重复。不管空白/评论/语法错误,流程中跳过的任何部分都将转储到Text
结构中。代码是可重复使用的,除了你必须将它合并到所有重复结果的地方以及原始解析器可能会失败的地方。
下面的代码,如果它可以帮助任何人。它写为Parsy。
class Text(object):
'''Structure to contain all the parts that the parser does not understand.
A better name would be Whitespace
'''
def __init__(self, text=''):
self.text = text
def __repr__(self):
return "Text(text='{}')".format(self.text)
def __eq__(self, other):
return self.text.strip() == getattr(other, 'text', '').strip()
def many_skip_error(parser, skip=lambda t, i: i + 1, until=None):
'''Repeat the original `parser`, aggregate result into `values`
and error in `Text`.
'''
@Parser
def _parser(stream, index):
values, result = [], None
while index < len(stream):
result = parser(stream, index)
# Original parser success
if result.status:
values.append(result.value)
index = result.index
# Check for end condition, effectively `manyTill` in Parsec
elif until is not None and until(stream, index).status:
break
# Aggregate skipped text into last `Text` value, or create a new one
else:
if len(values) > 0 and isinstance(values[-1], Text):
values[-1].text += stream[index]
else:
values.append(Text(stream[index]))
index = skip(stream, index)
return Result.success(index, values).aggregate(result)
return _parser
# Example usage
skip_error_parser = many_skip_error(original_parser)
在其他的说明,我想这里真正的问题是,我使用的是解析器组合库,而不是一个适当的两个阶段分析的过程。在传统的解析中,标记器将处理保留/跳过任何空格/注释/语法错误,使它们全部有效地空白并且对解析器不可见。