【问题标题】:Overriding method call operator or some other way to catch method name resolution errors覆盖方法调用运算符或其他方法来捕获方法名称解析错误
【发布时间】:2018-05-24 07:33:41
【问题描述】:

我正在尝试为X::NYI 类编写一个示例,作为对this issue 的响应。我想出了这样的事情:

class Nothing {
    sub postfix:<.&>( $sub, **@args) {
        die X::NYI.new( feature => $sub,
                        did-you-mean => "nothing",
                        workaround => "Implement it yourself" );
    }
}

my $let's-see = Nothing.newish;

它试图重新实现the method call postfix operator 为任何被调用的东西抛出异常。这不起作用:

No such method 'newish' for invocant of type 'Nothing'

在 NYI.p6 第 13 行的街区

事实上,文档说:

从技术上讲,不是真正的操作员;它是编译器中的特殊语法。

这很可能意味着它不能被覆盖。这也意味着做我想做的意味着与metamodel 交互以拦截类解析方法。但我真的不明白如何做到这一点。 Rakudo 源代码中的大多数示例,例如this one,都会在调用具体函数时抛出异常,事实上,the exception we see is thrown by the dispatch method at the Mu level

那么覆盖dispatch 是做这种事情的正确方法吗?还是其他完全不同的东西?

【问题讨论】:

  • Afaict 你已经排序了,因为 Lizmat 提供了一个很好的答案,你已经接受了它并关闭了文档问题。此评论提醒您或未来的读者,他们正在考虑尝试让您的postfix:&lt;.&amp;&gt; 方法发挥作用。我可以看到你在想什么,但到目前为止你的尝试在多个方面都被打破了。有些是可以修复的,但总的来说它不能工作,因为它与 P6 的语法不兼容。这就是为什么它是特殊情况。如果007 演变为涵盖此案例并重新合并到未来的 P6 中,Aiui 有朝一日可能会实现。
  • (在some discussion at the 007 project 之后,作为一种覆盖方法调用运算符的方法,俚语可能比宏更好。)

标签: oop raku dispatch


【解决方案1】:

我觉得你想要FALLBACK

https://docs.raku.org/language/typesystem#index-entry-FALLBACK_%28method%29

这将转化为:

class Nothing {
    method FALLBACK($name, |c) is hidden-from-backtrace {
        die X::NYI.new( feature => $name,
                        did-you-mean => "nothing",
                        workaround => "Implement it yourself" );
    }
}

my $a = Nothing.newish;
============================
newish not yet implemented. Sorry.
Did you mean: nothing?
Workaround: Implement it yourself
  in block <unit> at file line 10

请注意,我还使用了 is hidden-from-backtrace 特征来确保在回溯中未提及 FALLBACK 方法。

【讨论】:

    猜你喜欢
    • 2022-01-23
    • 2015-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-25
    • 2022-07-29
    • 2023-03-24
    • 2010-10-19
    相关资源
    最近更新 更多