在被调用者中获取被称为 str 的方法

Get method called-as str in the callee

我想从被调用方反省方法调用的尾端。

现在我正在明确地这样做...

# caller side
s.pd: '.shape';
s.pd: '.to_json("test.json")';
s.pd: '.iloc[2] = 23';

# callee side
method pd( Str $call ) {
    given $call {
        when /shape/   { ... }
        when /to_json/ { ... }
        #etc
    }
}

但是,我喜欢通过'slang method call'的方式来做到这一点,像这样的代码...

# caller side
s.pd.shape;
s.pd.to_json("test.json");
s.pd.iloc[2] = 23;
^ ^^ ^^^^^^^^^^^^^^^^^^^$
|  |       |
|  |       L a q// str I can put into eg. a custom Grammar
|  |
|  L general method name
|
L invocant

#callee side
method pd( ?? ) {
    my $called-as-str = self.^was-called-as;
    say $called-as-str;   #'pd.to_json("test.json")'
    ...
}

(如何)这可以在 raku 中完成吗?

由于有 422 个调用要处理,在许多 arity 模式中,需要在调用的 Class 中声明 422 个方法和签名的答案将不那么有吸引力。

根据@jonathans 的评论,raku docs 状态:

A method with the special name FALLBACK will be called when other means to resolve the name produce no result. The first argument holds the name and all following arguments are forwarded from the original call. Multi methods and sub-signatures are supported.

class Magic {
    method FALLBACK ($name, |c(Int, Str)) {
    put "$name called with parameters {c.raku}"  }
};
Magic.new.simsalabim(42, "answer");
 
# OUTPUT: «simsalabim called with parameters ⌈\(42, "answer")⌋␤»

所以我的代码示例将是:

# callee side
class Pd-Stub {
    method FALLBACK ($name, Str $arg-str ) {
        say "$name called with args: <<$arg-str>>"
    }
}

class Series { 
    has Pd-Stub $.pd 
}

my \s = Series.new;

# caller side
s.pd.shape;                 #shape called with args: <<>>        
s.pd.to_json("test.json");  #to_json called with args: <<test.json>>
s.pd.iloc[2] = 23;          #iloc called with args: <<>>

#iloc needs to use AT-POS and Proxy to handle subscript and assignment