Class: RbsMacros::Macros::ForwardableMacros

Inherits:
RbsMacros::Macro show all
Defined in:
lib/rbs_macros/macros/forwardable.rb

Overview

Implements macros for the ‘Forwardable` module.

Instance Method Summary collapse

Instance Method Details

#meta_def_delegator(params) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/rbs_macros/macros/forwardable.rb', line 20

def meta_def_delegator(params)
  recv = params.receiver
  return unless recv.is_a?(MetaModule)

  accessor = params.positional[0]
  method = params.positional[1]
  ali = params.positional[2] || method
  return unless accessor.is_a?(Symbol) || accessor.is_a?(String)
  return unless method.is_a?(Symbol) || method.is_a?(String)
  return unless ali.is_a?(Symbol) || ali.is_a?(String)

  builder = RBS::DefinitionBuilder.new(env: params.env.rbs)
  self_instance = builder.build_instance(recv.rbs_type)
  accessor_type =
    case accessor.to_s
    when /\A@/
      ivar = self_instance.instance_variables[accessor.to_sym]
      return unless ivar

      ivar.type
    else
      # TODO
      return
    end
  accessor_instance = widened_instance(accessor_type, builder:)
  return unless accessor_instance

  meth = accessor_instance[0].methods[method.to_sym]&.sub(accessor_instance[1])
  return unless meth

  params.env.add_decl(
    RBS::AST::Members::MethodDefinition.new(
      name: ali.to_sym,
      kind: :instance,
      overloads:
        meth.defs.map do |typedef|
          RBS::AST::Members::MethodDefinition::Overload.new(
            method_type: typedef.type,
            annotations: []
          )
        end,
      annotations: [],
      location: nil,
      comment: nil,
      overloading: false,
      visibility: nil
    ),
    mod: recv,
    file: params.filename
  )
end

#meta_def_delegators(params) ⇒ Object



72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/rbs_macros/macros/forwardable.rb', line 72

def meta_def_delegators(params)
  recv = params.receiver
  return unless recv.is_a?(MetaModule)

  accessor = params.positional[0]
  methods = params.positional[1..] || []
  methods.each do |method|
    params.env.invoke(
      params.with(
        name: :def_instance_delegator,
        positional: [accessor, method],
        keyword: {},
        block: nil
      )
    )
  end
end

#setup(env) ⇒ Object



12
13
14
15
16
17
18
# File 'lib/rbs_macros/macros/forwardable.rb', line 12

def setup(env)
  env.register_handler(:def_delegator, method(:meta_def_delegator))
  env.register_handler(:def_instance_delegator, method(:meta_def_delegator))

  env.register_handler(:def_delegators, method(:meta_def_delegators))
  env.register_handler(:def_instance_delegators, method(:meta_def_delegators))
end