簡體   English   中英

lark-parser縮進DSL和多行文檔字符串

[英]lark-parser indented DSL and multiline documentation strings

我正在嘗試使用百靈鳥實現記錄定義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

它適用於記錄定義的多行字符串文檔,適用於內聯屬性定義,但不適用於屬性多行字符串doc。

我用來執行的代碼是這樣的:

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
^

我看不見縮進的語法更復雜,而且百靈似乎更容易,但在這里找不到錯誤。

PS:我也嘗試過pyparsing,沒有成功,同樣的情況,並且考慮到可能需要的代碼量,我很難轉移到PLY。

該錯誤來自錯誤的_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已經處理換行符,我們不應該嘗試將其匹配兩次。

你提到嘗試過pyparsing,否則我會單獨留下你的問題。

對於pyparsing,空格敏感的解析並不是很好,但它確實在這種情況下使用pyparsing.indentedBlock進行了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'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM