Class: RbsMacros::Macros::SingleForwardableMacros

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

Overview

Implements macros for the ‘SingleForwardable` module.

Instance Method Summary collapse

Instance Method Details

#meta_def_delegator(params) ⇒ Object



111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
# File 'lib/rbs_macros/macros/forwardable.rb', line 111

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)
  singleton = builder.build_singleton(recv.rbs_type)
  accessor_type =
    case accessor.to_s
    when /\A@/
      ivar = singleton.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: :singleton,
      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



163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
# File 'lib/rbs_macros/macros/forwardable.rb', line 163

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_single_delegator,
        positional: [accessor, method],
        keyword: {},
        block: nil
      )
    )
  end
end

#setup(env) ⇒ Object



103
104
105
106
107
108
109
# File 'lib/rbs_macros/macros/forwardable.rb', line 103

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

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