如何使用 add_attribute() 在 Raku 中添加属性及其访问器?

Fer*_*ata 9 metaprogramming rakudo raku

我有这个程序:

\n
class Foo {\n  has $.first;\n}\n\nmy $a = Attribute.new(\n          :name('$!second'),\n          :type(Int),\n          :package('Foo'),\n          :has_accessor(True)\n        );\nFoo.^add_attribute($a);\nFoo.^compose;\n\nFoo.^attributes\xc2\xbb.say; # Mu $!first\xe2\x90\xa4Int $!second\xe2\x90\xa4\n\nmy $foo = Foo.new: :42first, :21second;\n\n$foo.second.say; # P6opaque: no such attribute '$!second' on type Foo in a Foo when trying to get a value\n
Run Code Online (Sandbox Code Playgroud)\n

attributes方法显示该属性已添加,创建对象显然成功,但是当我尝试访问该$!second属性时,我收到错误。

\n

我缺少什么?

\n

Eli*_*sen 7

我缺少什么?

看来你没有遗漏任何东西。对我来说看起来像一个错误。

在 RakuAST 开发的现阶段,我认为它不会得到解决。

如果您真的热衷于以编程方式构建类,我建议您开始考虑使用 RakuAST。

文档仍然大部分缺失,但是有一个强大的.AST方法可以在示例代码上运行,它将生成RakuAST创建该代码所需的语句。例如:

$ raku -e 'say Q|class A { has $.a; has $.b }|.AST'
RakuAST::StatementList.new(
  RakuAST::Statement::Expression.new(
    expression => RakuAST::Package.new(
      declarator => "class",
      name       => RakuAST::Name.from-identifier("A"),
      body       => RakuAST::Block.new(
        body => RakuAST::Blockoid.new(
          RakuAST::StatementList.new(
            RakuAST::Statement::Expression.new(
              expression => RakuAST::VarDeclaration::Simple.new(
                scope       => "has",
                sigil       => "\$",
                twigil      => ".",
                desigilname => RakuAST::Name.from-identifier("a")
              )
            ),
            RakuAST::Statement::Expression.new(
              expression => RakuAST::VarDeclaration::Simple.new(
                scope       => "has",
                sigil       => "\$",
                twigil      => ".",
                desigilname => RakuAST::Name.from-identifier("b")
              )
            )
          )
        )
      )
    )
  )
)
Run Code Online (Sandbox Code Playgroud)