":my $foo" 的范围是什么?它有什么用?

What scope does ":my $foo" have and what is it used for?

使用正则表达式、标记或规则,可以像这样定义变量;

token directive {
    :my $foo = "in command";
    <command> <subject> <value>?
}

语言文档here, and very little in S05 - Regexes and Rules中没有关于它的任何内容,引用;

任何语法正则表达式实际上只是一种方法,您可以在这样的例程中声明变量,使用冒号后跟任何由 Perl 6 语法解析的范围声明符,包括 my、our、状态, 恒定. (作为准声明符,temp 和 let 也被识别。)单个语句(通过终止分号或行末结束括号)被解析为正常的 Perl 6 代码:

token prove-nondeterministic-parsing {
    :my $threshold = rand;
    'maybe' \s+ <it($threshold)>
}

我知道语法中的正则表达式与 类 中的方法非常相似;我知道你可以在规则内的任何地方开始一个块,如果解析成功到达那一点,该块将被执行——但我不明白这到底是干什么用的。

有人可以清楚地定义它的范围吗?解释它满足什么需求并给出典型用例?

:my $foo;有什么范围?

:my $foo ...; 具有它出现的 rule/token/regex 的 lexical scope

(和 :my $*foo ...;——注意表示动态变量的额外 *——具有它出现的 rule/token/regex 的词法和 dynamic scope。 )

这是做什么用的

如果没有这个构造,会发生以下情况:

regex scope-too-small {    # Opening `{` opens a regex lexical scope.
    { my $foo = / bar / }  # Block with its own inner lexical scope.
    $foo                   # ERROR: Variable '$foo' is not declared
}

grammar scope-too-large {  # Opening `{` opens lexical scope for gramamr.
    my $foo = / bar / ;
    regex r1   { ... }     # `$foo` is recognized inside `r1`...
    ...
    regex r999 { ... }     # ...but also inside r999
}

因此 : ... ; 语法用于准确获得所需的范围——既不太宽也不太窄。

典型用例

此功能通常用于大型或复杂的语法中,以避免松散的范围界定(这会滋生错误)。

有关精确 仅词法作用域 的合适示例,请参阅 token babble as defined in a current snapshot of Rakudo's Grammar.nqp source code@extra_tweaks 的声明和使用。

P6支持action objects. These are classes with methods corresponding one-to-one with the rules in a grammar. Whenever a rule matches, it calls its corresponding action method. Dynamic variables provide precisely the right scoping for declaring variables that are scoped to the block (method, rule, etc.) they're declared in both lexically and dynamically -- which latter means they're available in the corresponding action method too. For an example of this, see the declaration of @*nibbles in Rakudo's Grammar module and its use in Rakudo's Actions module.