我有这个 raku 语法:
#!/usr/bin/env raku
use v6.d;
use Grammar::Tracer;
grammar Grammar {
token TOP {
<city> \v
<state-zip> \v?
}
token city {
^^ \V* $$
}
token state-zip {
^^ <state> <.ws>? <zipcode> $$ #<.ws> is [\h* | \v]
}
token state {
\w \w
}
token zipcode {
\d ** 5
}
}
class Actions {
method TOP($/) {
#works
say "city is ", $_ with $<city>.made;
say "state is ", $_ with $<state-zip><state>.made;
say "zipcode is ", $_ with $<state-zip><zipcode>.made;
#doesn't work
say "state2 is ", $_ with $<state>.made;
say "zipcode2 is ", $_ with $<zipcode>.made;
}
method city($/) { make ~$/ }
method state($/) { make ~$/ }
method zipcode($/) { make ~$/ }
}
my $address = q:to/END/;
Springfield,
IL 62704
END
Grammar.parse($address, :actions(Actions));
效果很好:
TOP
| city
| * MATCH "Springfield,"
| state-zip
| | state
| | * MATCH "IL"
| | zipcode
| | * MATCH "62704"
| * MATCH "IL 62704"
city is Springfield,
state is IL
zipcode is 62704
* MATCH "Springfield,\nIL 62704\n"
token <state-zip>
是让状态和邮政编码共存于一行还是跨越多行。请记住,这是一个 MRE,因此我正在寻找不会改变语法的答案,但会改变操作的 make / made 方面。
但是 - 为了简化我的代码,我希望能够从method TOP($/) {}
我的示例 state2 和 zipcode2 的操作中访问顶层的州和邮政编码。我一直在尝试将状态和令牌的制作值“提升”到匹配树上 - 例如可能是这样的:
# doesn't work
method TOP($/) {
make $<state>.made;
make $<zip>.made;
...
}
method state-zip($/) {
make $<state>.made;
make $<zip>.made;
}
这可能吗?