这是我的一个 Perl 6 项目中的一个动作类方法,它可以按照您的描述进行操作。
它与 Christoph 发布的内容几乎相同,但写得更冗长(我添加了大量评论以使其更容易理解):
#| Fallback action method that produces a Hash tree from named captures.
method FALLBACK ($name, $/) {
# Unless an embedded { } block in the grammar already called make()...
unless $/.made.defined {
# If the Match has named captures, produce a hash with one entry
# per capture:
if $/.hash -> %captures {
make hash do for %captures.kv -> $k, $v {
# The key of the hash entry is the capture's name.
$k => $v ~~ Array
# If the capture was repeated by a quantifier, the
# value becomes a list of what each repetition of the
# sub-rule produced:
?? $v.map(*.made).cache
# If the capture wasn't quantified, the value becomes
# what the sub-rule produced:
!! $v.made
}
}
# If the Match has no named captures, produce the string it matched:
else { make ~$/ }
}
}
笔记:
- 这完全忽略了位置捕获(即
( )
在语法内部进行的那些) - 只有命名的捕获(例如<foo>
or <foo=bar>
)用于构建哈希树。也可以对其进行修改以处理它们,具体取决于您要对它们做什么。请记住:
$/.hash
给出命名的捕获,作为Map
.
$/.list
给出位置捕获,作为List
.
$/.caps
(or $/.pairs
) 给出命名和位置捕获,作为name=>submatch
和/或index=>submatch
对的序列。
- 它允许您覆盖特定规则的 AST 生成,方法是
{ make ... }
在语法中的规则内添加一个块(假设您从不故意想要make
未定义的值),或者通过将具有规则名称的方法添加到操作类。