在 Crystal 0.21.1 中用 "macro inherited" 定义实例方法

Define instance method with "macro inherited" in Crystal 0.21.1

据我了解,类型声明的工作方式类似于 kind_of

“So types aren't strictly the type named but rather act like a is_a? or kind_of?.” https://github.com/crystal-lang/crystal/issues/4232

所以我认为这段代码的一部分有效。

但是当我使用宏在继承的 class 上定义实例方法时,错误消息抱怨错误的对象缺少方法。

class Base
  macro inherited
    def name
      "Joe Smith"
    end
  end
end

class Context < Base; end

class Render
  def initialize(@inner_context : Base); end

  def display
    name
  end

  forward_missing_to inner_context

  private property inner_context
end

puts Render.new(Context.new).display

输出为:

Error in line 23: instantiating 'Render#display()'

in line 15: instantiating 'name()'

in macro 'forward_missing_to' /usr/lib/crystal/object.cr:1132, line 1:

>  1.     macro method_missing(call)
   2.       inner_context.{{call}}
   3.     end
   4.   

expanding macro
in macro 'method_missing' expanded macro: forward_missing_to:1, line 1:

>  1.       inner_context.name
   2.     

undefined method 'name' for Base (compile-time type is Base+)

我在这里错过了什么?

@inner_context 可能是 Base 类型, 没有 定义 base 方法。

一种解决方案是将 Base 标记为摘要:abstract class Base.