Lark-parser缩进式DSL和多行文档字符串

5

我正在尝试使用lark实现一个记录定义DSL。它基于缩进,这使得事情变得有点复杂。

Lark是一个很棒的工具,但我面临一些困难。

这是我正在实现的DSL的片段:

record Order :
    """Order record documentation
    should have arbitrary size"""

    field1 Int
    field2 Datetime:
        """Attributes should also have
        multiline documentation"""

    field3 String "inline documentation also works"

这里使用的语法是:

?start: (_NEWLINE | redorddef)*

simple_type: NAME

multiline_doc:  MULTILINE_STRING _NEWLINE
inline_doc: INLINE_STRING

?element_doc:  ":" _NEWLINE _INDENT multiline_doc _DEDENT | inline_doc

attribute_name: NAME
attribute_simple_type: attribute_name simple_type [element_doc] _NEWLINE
attributes: attribute_simple_type+
_recordbody: _NEWLINE _INDENT [multiline_doc] attributes _DEDENT
redorddef: "record" NAME ":" _recordbody



MULTILINE_STRING: /"""([^"\\]*(\\.[^"\\]*)*)"""/
INLINE_STRING: /"([^"\\]*(\\.[^"\\]*)*)"/

_WS_INLINE: (" "|/\t/)+
COMMENT: /#[^\n]*/
_NEWLINE: ( /\r?\n[\t ]*/ | COMMENT )+

%import common.CNAME -> NAME
%import common.INT

%ignore /[\t \f]+/  // WS
%ignore /\\[\t \f]*\r?\n/   // LINE_CONT
%ignore COMMENT
%declare _INDENT _DEDENT

它可以很好地处理多行字符串文档的记录定义,可以很好地处理内联属性定义,但对于属性多行字符串文档则无法正常工作。
我用来执行的代码是这样的:
import sys
import pprint

from pathlib import Path

from lark import Lark, UnexpectedInput
from lark.indenter import Indenter

scheman_data_works = '''
record Order :
        """Order record documentation
        should have arbitrary size"""

        field1 Int
        # field2 Datetime:
        #   """Attributes should also have
        #   multiline documentation"""

        field3 String "inline documentation also works"
'''

scheman_data_wrong = '''
record Order :
        """Order record documentation
        should have arbitrary size"""

        field1 Int
        field2 Datetime:
                """Attributes should also have
                multiline documentation"""

        field3 String "inline documentation also works"
'''
grammar = r'''

?start: (_NEWLINE | redorddef)*

simple_type: NAME

multiline_doc:  MULTILINE_STRING _NEWLINE
inline_doc: INLINE_STRING

?element_doc:  ":" _NEWLINE _INDENT multiline_doc _DEDENT | inline_doc

attribute_name: NAME
attribute_simple_type: attribute_name simple_type [element_doc] _NEWLINE
attributes: attribute_simple_type+
_recordbody: _NEWLINE _INDENT [multiline_doc] attributes _DEDENT
redorddef: "record" NAME ":" _recordbody



MULTILINE_STRING: /"""([^"\\]*(\\.[^"\\]*)*)"""/
INLINE_STRING: /"([^"\\]*(\\.[^"\\]*)*)"/

_WS_INLINE: (" "|/\t/)+
COMMENT: /#[^\n]*/
_NEWLINE: ( /\r?\n[\t ]*/ | COMMENT )+

%import common.CNAME -> NAME
%import common.INT

%ignore /[\t \f]+/  // WS
%ignore /\\[\t \f]*\r?\n/   // LINE_CONT
%ignore COMMENT
%declare _INDENT _DEDENT

'''

class SchemanIndenter(Indenter):
    NL_type = '_NEWLINE'
    OPEN_PAREN_types = ['LPAR', 'LSQB', 'LBRACE']
    CLOSE_PAREN_types = ['RPAR', 'RSQB', 'RBRACE']
    INDENT_type = '_INDENT'
    DEDENT_type = '_DEDENT'
    tab_len = 4

scheman_parser = Lark(grammar, parser='lalr', postlex=SchemanIndenter())
print(scheman_parser.parse(scheman_data_works).pretty())
print("\n\n")
print(scheman_parser.parse(scheman_data_wrong).pretty())

结果是:

redorddef
Order
multiline_doc """Order record documentation
        should have arbitrary size"""
attributes
    attribute_simple_type
    attribute_name    field1
    simple_type       Int
    attribute_simple_type
    attribute_name    field3
    simple_type       String
    inline_doc        "inline documentation also works"




Traceback (most recent call last):
File "schema_parser.py", line 83, in <module>
    print(scheman_parser.parse(scheman_data_wrong).pretty())
File "/Users/branquif/Dropbox/swf_projects/schema-manager/.venv/lib/python3.7/site-packages/lark/lark.py", line 228, in parse
    return self.parser.parse(text)
File "/Users/branquif/Dropbox/swf_projects/schema-manager/.venv/lib/python3.7/site-packages/lark/parser_frontends.py", line 38, in parse
    return self.parser.parse(token_stream, *[sps] if sps is not NotImplemented else [])
File "/Users/branquif/Dropbox/swf_projects/schema-manager/.venv/lib/python3.7/site-packages/lark/parsers/lalr_parser.py", line 68, in parse
    for token in stream:
File "/Users/branquif/Dropbox/swf_projects/schema-manager/.venv/lib/python3.7/site-packages/lark/indenter.py", line 31, in process
    for token in stream:
File "/Users/branquif/Dropbox/swf_projects/schema-manager/.venv/lib/python3.7/site-packages/lark/lexer.py", line 319, in lex
    for x in l.lex(stream, self.root_lexer.newline_types, self.root_lexer.ignore_types):
File "/Users/branquif/Dropbox/swf_projects/schema-manager/.venv/lib/python3.7/site-packages/lark/lexer.py", line 167, in lex
    raise UnexpectedCharacters(stream, line_ctr.char_pos, line_ctr.line, line_ctr.column, state=self.state)
lark.exceptions.UnexpectedCharacters: No terminal defined for 'f' at line 11 col 2

        field3 String "inline documentation also
^

我理解缩进语法更为复杂,lark似乎能够简化这一过程,但我在这里找不到错误。

另外,我也尝试了pyparsing,但在相同的情况下没有成功,而且由于可能需要大量代码,转移到PLY会很困难。


field2 DateTime 后面应该加上 : 吗? - PaulMcG
是的。我想在“:”后面为该元素添加一个缩进的多行文档字符串。Erez的答案对我有用。 - Branquif
2个回答

4
错误来自于错放的_NEWLINE终端符。通常情况下,建议确保规则在语法中的角色平衡。因此,下面是您应该如何定义element_doc
?element_doc:  ":" _NEWLINE _INDENT multiline_doc _DEDENT
            | inline_doc _NEWLINE

注意新增的换行符,这意味着无论解析器采取哪种选项,它都以类似的状态结束,从语法上讲(_DEDENT也匹配一个换行符)。
第二个变化是由于第一个变化而引起的:
attribute_simple_type: attribute_name simple_type (element_doc|_NEWLINE)

作为element_doc已经处理了换行符,我们不应该尝试两次匹配。

谢谢Erez!我没有意识到_DEDENT正在匹配换行符..关于平衡规则的好建议。 - Branquif

0

你提到过尝试使用pyparsing,否则我可能会放弃回答你的问题。

pyparsing对于敏感于空格的解析并不是非常出色,但它确实为这种情况做出了努力,使用pyparsing.indentedBlock。在写作时可能会有一定程度的困难,但确实可以完成。

import pyparsing as pp

COLON = pp.Suppress(':')
tpl_quoted_string = pp.QuotedString('"""', multiline=True) | pp.QuotedString("'''", multiline=True)
quoted_string = pp.ungroup(tpl_quoted_string | pp.quotedString().addParseAction(pp.removeQuotes))
RECORD = pp.Keyword("record")
ident = pp.pyparsing_common.identifier()

field_expr = (ident("name")
              + ident("type") + pp.Optional(COLON)
              + pp.Optional(quoted_string)("docstring"))

indent_stack = []
STACK_RESET = pp.Empty()
def reset_indent_stack(s, l, t):
    indent_stack[:] = [pp.col(l, s)]
STACK_RESET.addParseAction(reset_indent_stack)

record_expr = pp.Group(STACK_RESET
                       + RECORD - ident("name") + COLON + pp.Optional(quoted_string)("docstring")
                       + (pp.indentedBlock(field_expr, indent_stack))("fields"))

record_expr.ignore(pp.pythonStyleComment)

如果您的示例已写入变量“sample”,请执行以下操作:
print(record_expr.parseString(sample).dump())

并获得:

[['record', 'Order', 'Order record documentation\n    should have arbitrary size', [['field1', 'Int'], ['field2', 'Datetime', 'Attributes should also have\n        multiline documentation'], ['field3', 'String', 'inline documentation also works']]]]
[0]:
  ['record', 'Order', 'Order record documentation\n    should have arbitrary size', [['field1', 'Int'], ['field2', 'Datetime', 'Attributes should also have\n        multiline documentation'], ['field3', 'String', 'inline documentation also works']]]
  - docstring: 'Order record documentation\n    should have arbitrary size'
  - fields: [['field1', 'Int'], ['field2', 'Datetime', 'Attributes should also have\n        multiline documentation'], ['field3', 'String', 'inline documentation also works']]
    [0]:
      ['field1', 'Int']
      - name: 'field1'
      - type: 'Int'
    [1]:
      ['field2', 'Datetime', 'Attributes should also have\n        multiline documentation']
      - docstring: 'Attributes should also have\n        multiline documentation'
      - name: 'field2'
      - type: 'Datetime'
    [2]:
      ['field3', 'String', 'inline documentation also works']
      - docstring: 'inline documentation also works'
      - name: 'field3'
      - type: 'String'
  - name: 'Order'

嗨,保罗。我很高兴你回答了!我确实投资了Pyparsing,但正如你所强调的,缩进语法并不是它的长处。尝试过操作空格,使用indentedBlock,但没有成功......看了你的代码现在就明白了。对于解析的门外汉来说,要想独自弄清这一切还有很长的路要走。感谢你! - Branquif

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接