我正在尝试使用Parse::RecDescent解析 HAML ( haml.info ) 。如果您不知道haml,那么问题与解析Python 相同——语法块按缩进级别分组。
从一个非常简单的子集开始,我尝试了一些方法,但我认为我不太了解 P::RD 的贪婪或递归顺序。鉴于haml:
%p
%span foo
我认为应该工作的最简单的语法是(上面的代码片段不需要一些位):
<autotree>
startrule : <skip:''> block(s?)
non_space : /[^ ]/
space : ' '
indent : space(s?)
indented_line : indent line
indented_lines : indented_line(s) <reject: do { Perl6::Junction::any(map { $_->level } @{$item[1]}) != $item[1][0]->level }>
block : indented_line block <reject: do { $item[2]->level <= $item[1]->level }>
| indented_lines
line : single_line | multiple_lines
single_line : line_head space line_body newline | line_head space(s?) newline | plain_text newline
# ALL subsequent lines ending in | are consumed
multiple_lines : line_head space line_body continuation_marker newline continuation_line(s)
continuation_marker : space(s) '|' space(s?)
continuation_line : space(s?) line_body continuation_marker
newline : "\n"
line_head : haml_comment | html_element
haml_comment : '-#'
html_element : '%' tag
# TODO: xhtml tags technically allow unicode
tag_start_char : /[:_a-z]/i
tag_char : /[-:_a-z.0-9]/i
tag : tag_start_char tag_char(s?)
line_body : /.*/
plain_text : backslash ('%' | '!' | '.' | '#' | '-' | '/' | '=' | '&' | ':' | '~') /.*/ | /.*/
backslash : '\\'
问题在于block
定义。如上所述,它不捕获任何文本,但它确实正确捕获了以下内容:
-# haml comment
%p a paragraph
如果我从上面删除第二reject
行(第一条block
规则中的那一行),那么它确实会捕获所有内容,但当然会错误地分组,因为第一个块会吞掉所有行,而与缩进无关。
我也尝试过使用前瞻动作来检查$text
和其他一些没有运气的方法。
任何人都可以(a)解释为什么上述方法不起作用和/或(b)如果有一种方法不使用 perl 操作/拒绝?我尝试获取缩进中的空格数,然后在下一行中的空格数的插值前瞻条件中使用它,但我永远无法完全正确地获得插值语法(因为它需要箭头运算符)。