Class: RBS::Prototype::Runtime

Inherits:
Object
  • Object
show all
Includes:
Helpers
Defined in:
lib/rbs/prototype/runtime.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(patterns:, env:, merge:, owners_included: []) ⇒ Runtime

Returns a new instance of Runtime.



14
15
16
17
18
19
20
21
22
23
24
# File 'lib/rbs/prototype/runtime.rb', line 14

def initialize(patterns:, env:, merge:, owners_included: [])
  @patterns = patterns
  @decls = nil
  @modules = []
  @env = env
  @merge = merge
  @owners_included = owners_included.map do |name|
    Object.const_get(name)
  end
  @outline = false
end

Instance Attribute Details

#envObject (readonly)

Returns the value of attribute env.



9
10
11
# File 'lib/rbs/prototype/runtime.rb', line 9

def env
  @env
end

#mergeObject (readonly)

Returns the value of attribute merge.



10
11
12
# File 'lib/rbs/prototype/runtime.rb', line 10

def merge
  @merge
end

#outlineObject

Returns the value of attribute outline.



12
13
14
# File 'lib/rbs/prototype/runtime.rb', line 12

def outline
  @outline
end

#owners_includedObject (readonly)

Returns the value of attribute owners_included.



11
12
13
# File 'lib/rbs/prototype/runtime.rb', line 11

def owners_included
  @owners_included
end

#patternsObject (readonly)

Returns the value of attribute patterns.



8
9
10
# File 'lib/rbs/prototype/runtime.rb', line 8

def patterns
  @patterns
end

Instance Method Details

#block_from_ast_of(method) ⇒ Object



574
575
576
577
578
579
580
581
582
583
584
# File 'lib/rbs/prototype/runtime.rb', line 574

def block_from_ast_of(method)
  return nil if RUBY_VERSION < '3.1'

  begin
    ast = RubyVM::AbstractSyntaxTree.of(method)
  rescue ArgumentError
    return # When the method is defined in eval
  end

  block_from_body(ast) if ast&.type == :SCOPE
end

#builderObject



39
40
41
# File 'lib/rbs/prototype/runtime.rb', line 39

def builder
  @builder ||= DefinitionBuilder.new(env: env)
end

#const_name(const) ⇒ Object



542
543
544
545
546
547
548
549
550
551
552
553
554
555
# File 'lib/rbs/prototype/runtime.rb', line 542

def const_name(const)
  @module_name_method ||= Module.instance_method(:name)
  name = @module_name_method.bind(const).call
  return nil unless name

  begin
    Object.const_get(name)
  rescue NameError
    # Should generate const name if anonymous or internal module (e.g. NameError::message)
    nil
  else
    name
  end
end

#declsObject



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/rbs/prototype/runtime.rb', line 47

def decls
  unless @decls
    @decls = []
    @modules = ObjectSpace.each_object(Module).to_a
    @modules.select {|mod| target?(mod) }.sort_by{|mod| const_name(mod) }.each do |mod|
      case mod
      when Class
        generate_class mod
      when Module
        generate_module mod
      end
    end
  end

  @decls
end

#each_included_module(type_name, mod) ⇒ Object



78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
# File 'lib/rbs/prototype/runtime.rb', line 78

def each_included_module(type_name, mod)
  supers = Set[]

  mod.included_modules.each do |mix|
    supers.merge(mix.included_modules)
  end

  if mod.is_a?(Class) && mod.superclass
    mod.superclass.included_modules.each do |mix|
      supers << mix
      supers.merge(mix.included_modules)
    end
  end

  mod.included_modules.each do |mix|
    unless supers.include?(mix)
      unless const_name(mix)
        RBS.logger.warn("Skipping anonymous module #{mix} included in #{mod}")
      else
        module_name = module_full_name = to_type_name(const_name(mix), full_name: true)
        if module_full_name.namespace == type_name.namespace
          module_name = TypeName.new(name: module_full_name.name, namespace: Namespace.empty)
        end

        yield module_name, module_full_name, mix
      end
    end
  end
end

#ensure_outer_module_declarations(mod) ⇒ Object

Generate/find outer module declarations This is broken down into another method to comply with ‘DRY` This generates/finds declarations in nested form & returns the last array of declarations



493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
# File 'lib/rbs/prototype/runtime.rb', line 493

def ensure_outer_module_declarations(mod)
  *outer_module_names, _ = const_name(mod).split(/::/) #=> parent = [A, B], mod = C
  destination = @decls # Copy the entries in ivar @decls, not .dup

  outer_module_names&.each_with_index do |outer_module_name, i|
    current_name = outer_module_names[0, i + 1].join('::')
    outer_module = @modules.detect { |x| const_name(x) == current_name }
    outer_decl = destination.detect { |decl| decl.is_a?(outer_module.is_a?(Class) ? AST::Declarations::Class : AST::Declarations::Module) && decl.name.name == outer_module_name.to_sym }

    # Insert AST::Declarations if declarations are not added previously
    unless outer_decl
      if outer_module.is_a?(Class)
        outer_decl = AST::Declarations::Class.new(
          name: to_type_name(outer_module_name),
          type_params: type_params(outer_module),
          super_class: generate_super_class(outer_module),
          members: [],
          annotations: [],
          location: nil,
          comment: nil
        )
      else
        outer_decl = AST::Declarations::Module.new(
          name: to_type_name(outer_module_name),
          type_params: type_params(outer_module),
          self_types: [],
          members: [],
          annotations: [],
          location: nil,
          comment: nil
        )
      end

      destination << outer_decl
    end

    destination = outer_decl.members
  end

  # Return the array of declarations checked out at the end
  destination
end

#generate_class(mod) ⇒ Object



389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
# File 'lib/rbs/prototype/runtime.rb', line 389

def generate_class(mod)
  type_name = to_type_name(const_name(mod))
  outer_decls = ensure_outer_module_declarations(mod)

  # Check if a declaration exists for the actual module
  decl = outer_decls.detect { |decl| decl.is_a?(AST::Declarations::Class) && decl.name.name == only_name(mod).to_sym }
  unless decl
    decl = AST::Declarations::Class.new(
      name: to_type_name(only_name(mod)),
      type_params: type_params(mod),
      super_class: generate_super_class(mod),
      members: [],
      annotations: [],
      location: nil,
      comment: nil
    )

    outer_decls << decl
  end

  each_included_module(type_name, mod) do |module_name, module_full_name, _|
    args = type_args(module_full_name)
    decl.members << AST::Members::Include.new(
      name: module_name,
      args: args,
      location: nil,
      comment: nil,
      annotations: []
    )
  end

  each_included_module(type_name, mod.singleton_class) do |module_name, module_full_name ,_|
    args = type_args(module_full_name)
    decl.members << AST::Members::Extend.new(
      name: module_name,
      args: args,
      location: nil,
      comment: nil,
      annotations: []
    )
  end

  generate_methods(mod, type_name, decl.members) unless outline

  generate_constants mod, decl.members
end

#generate_constants(mod, decls) ⇒ Object



338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
# File 'lib/rbs/prototype/runtime.rb', line 338

def generate_constants(mod, decls)
  mod.constants(false).sort.each do |name|
    begin
      value = mod.const_get(name)
    rescue StandardError, LoadError => e
      RBS.logger.warn("Skipping constant #{name} of #{mod} since #{e}")
      next
    end

    next if value.is_a?(Class) || value.is_a?(Module)
    unless value.class.name
      RBS.logger.warn("Skipping constant #{name} #{value} of #{mod} as an instance of anonymous class")
      next
    end

    type = case value
           when true, false
             Types::Bases::Bool.new(location: nil)
           when nil
             Types::Optional.new(
               type: Types::Bases::Any.new(location: nil),
               location: nil
             )
           else
             value_type_name = to_type_name(const_name(value.class))
             args = type_args(value_type_name)
             Types::ClassInstance.new(name: value_type_name, args: args, location: nil)
           end

    decls << AST::Declarations::Constant.new(
      name: to_type_name(name.to_s),
      type: type,
      location: nil,
      comment: nil
    )
  end
end

#generate_methods(mod, module_name, members) ⇒ Object



230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
# File 'lib/rbs/prototype/runtime.rb', line 230

def generate_methods(mod, module_name, members)
  mod.singleton_methods.select {|name| target_method?(mod, singleton: name) }.sort.each do |name|
    method = mod.singleton_class.instance_method(name)

    if method.name == method.original_name
      merge_rbs(module_name, members, singleton: name) do
        RBS.logger.info "missing #{module_name}.#{name} #{method.source_location}"

        members << AST::Members::MethodDefinition.new(
          name: method.name,
          overloads: [
            AST::Members::MethodDefinition::Overload.new(annotations: [], method_type: method_type(method))
          ],
          kind: :singleton,
          location: nil,
          comment: nil,
          annotations: [],
          overloading: false,
          visibility: nil
        )
      end
    else
      members << AST::Members::Alias.new(
        new_name: method.name,
        old_name: method.original_name,
        kind: :singleton,
        location: nil,
        comment: nil,
        annotations: [],
        )
    end
  end

  public_instance_methods = mod.public_instance_methods.select {|name| target_method?(mod, instance: name) }
  unless public_instance_methods.empty?
    members << AST::Members::Public.new(location: nil)

    public_instance_methods.sort.each do |name|
      method = mod.instance_method(name)

      if method.name == method.original_name
        merge_rbs(module_name, members, instance: name) do
          RBS.logger.info "missing #{module_name}##{name} #{method.source_location}"

          members << AST::Members::MethodDefinition.new(
            name: method.name,
            overloads: [
              AST::Members::MethodDefinition::Overload.new(annotations: [], method_type: method_type(method))
            ],
            kind: :instance,
            location: nil,
            comment: nil,
            annotations: [],
            overloading: false,
            visibility: nil
          )
        end
      else
        members << AST::Members::Alias.new(
          new_name: method.name,
          old_name: method.original_name,
          kind: :instance,
          location: nil,
          comment: nil,
          annotations: [],
          )
      end
    end
  end

  private_instance_methods = mod.private_instance_methods.select {|name| target_method?(mod, instance: name) }
  unless private_instance_methods.empty?
    members << AST::Members::Private.new(location: nil)

    private_instance_methods.sort.each do |name|
      method = mod.instance_method(name)

      if method.name == method.original_name
        merge_rbs(module_name, members, instance: name) do
          RBS.logger.info "missing #{module_name}##{name} #{method.source_location}"

          members << AST::Members::MethodDefinition.new(
            name: method.name,
            overloads: [
              AST::Members::MethodDefinition::Overload.new(annotations: [], method_type: method_type(method))
            ],
            kind: :instance,
            location: nil,
            comment: nil,
            annotations: [],
            overloading: false,
            visibility: nil
          )
        end
      else
        members << AST::Members::Alias.new(
          new_name: method.name,
          old_name: method.original_name,
          kind: :instance,
          location: nil,
          comment: nil,
          annotations: [],
          )
      end
    end
  end
end

#generate_module(mod) ⇒ Object



436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
# File 'lib/rbs/prototype/runtime.rb', line 436

def generate_module(mod)
  name = const_name(mod)

  unless name
    RBS.logger.warn("Skipping anonymous module #{mod}")
    return
  end

  type_name = to_type_name(name)
  outer_decls = ensure_outer_module_declarations(mod)

  # Check if a declaration exists for the actual class
  decl = outer_decls.detect { |decl| decl.is_a?(AST::Declarations::Module) && decl.name.name == only_name(mod).to_sym }
  unless decl
    decl = AST::Declarations::Module.new(
      name: to_type_name(only_name(mod)),
      type_params: type_params(mod),
      self_types: [],
      members: [],
      annotations: [],
      location: nil,
      comment: nil
    )

    outer_decls << decl
  end

  each_included_module(type_name, mod) do |module_name, module_full_name, _|
    args = type_args(module_full_name)
    decl.members << AST::Members::Include.new(
      name: module_name,
      args: args,
      location: nil,
      comment: nil,
      annotations: []
    )
  end

  each_included_module(type_name, mod.singleton_class) do |module_name, module_full_name, _|
    args = type_args(module_full_name)
    decl.members << AST::Members::Extend.new(
      name: module_name,
      args: args,
      location: nil,
      comment: nil,
      annotations: []
    )
  end

  generate_methods(mod, type_name, decl.members) unless outline

  generate_constants mod, decl.members
end

#generate_super_class(mod) ⇒ Object



376
377
378
379
380
381
382
383
384
385
386
387
# File 'lib/rbs/prototype/runtime.rb', line 376

def generate_super_class(mod)
  if mod.superclass.nil? || mod.superclass == ::Object
    nil
  elsif const_name(mod.superclass).nil?
    RBS.logger.warn("Skipping anonymous superclass #{mod.superclass} of #{mod}")
    nil
  else
    super_name = to_type_name(const_name(mod.superclass), full_name: true).absolute!
    super_args = type_args(super_name)
    AST::Declarations::Class::Super.new(name: super_name, args: super_args, location: nil)
  end
end

#merge_rbs(module_name, members, instance: nil, singleton: nil) ⇒ Object



175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
# File 'lib/rbs/prototype/runtime.rb', line 175

def merge_rbs(module_name, members, instance: nil, singleton: nil)
  if merge
    if env.class_decls[module_name.absolute!]
      case
      when instance
        method = builder.build_instance(module_name.absolute!).methods[instance]
        method_name = instance
        kind = :instance
      when singleton
        method = builder.build_singleton(module_name.absolute!).methods[singleton]
        method_name = singleton
        kind = :singleton
      end

      if method
        members << AST::Members::MethodDefinition.new(
          name: method_name,
          overloads: method.method_types.map {|type|
            AST::Members::MethodDefinition::Overload.new(
              annotations: [],
              method_type: type.update.tap do |ty|
                def ty.to_s
                  location.source
                end
              end
            )
          },
          kind: kind,
          location: nil,
          comment: method.comments[0],
          annotations: method.annotations,
          overloading: false,
          visibility: nil
        )
        return
      end
    end

    yield
  else
    yield
  end
end

#method_type(method) ⇒ Object



108
109
110
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
162
163
164
165
166
167
168
169
170
171
172
173
# File 'lib/rbs/prototype/runtime.rb', line 108

def method_type(method)
  untyped = Types::Bases::Any.new(location: nil)

  required_positionals = []
  optional_positionals = []
  rest = nil
  trailing_positionals = []
  required_keywords = {}
  optional_keywords = {}
  rest_keywords = nil

  requireds = required_positionals

  block = nil

  method.parameters.each do |kind, name|
    case kind
    when :req
      requireds << Types::Function::Param.new(name: name, type: untyped)
    when :opt
      requireds = trailing_positionals
      optional_positionals << Types::Function::Param.new(name: name, type: untyped)
    when :rest
      requireds = trailing_positionals
      name = nil if name == :* # For `def f(...) end` syntax
      rest = Types::Function::Param.new(name: name, type: untyped)
    when :keyreq
      required_keywords[name] = Types::Function::Param.new(name: nil, type: untyped)
    when :key
      optional_keywords[name] = Types::Function::Param.new(name: nil, type: untyped)
    when :keyrest
      rest_keywords = Types::Function::Param.new(name: nil, type: untyped)
    when :block
      block = Types::Block.new(
        type: Types::Function.empty(untyped).update(rest_positionals: Types::Function::Param.new(name: nil, type: untyped)),
        required: true,
        self_type: nil
      )
    end
  end

  block ||= block_from_ast_of(method)

  return_type = if method.name == :initialize
                  Types::Bases::Void.new(location: nil)
                else
                  untyped
                end
  method_type = Types::Function.new(
    required_positionals: required_positionals,
    optional_positionals: optional_positionals,
    rest_positionals: rest,
    trailing_positionals: trailing_positionals,
    required_keywords: required_keywords,
    optional_keywords: optional_keywords,
    rest_keywords: rest_keywords,
    return_type: return_type,
  )

  MethodType.new(
    location: nil,
    type_params: [],
    type: method_type,
    block: block
  )
end

#only_name(mod) ⇒ Object

Returns the exact name & not compactly declared name



537
538
539
540
# File 'lib/rbs/prototype/runtime.rb', line 537

def only_name(mod)
  # No nil check because this method is invoked after checking if the module exists
  const_name(mod).split(/::/).last # (A::B::C) => C
end

#parse(file) ⇒ Object



43
44
45
# File 'lib/rbs/prototype/runtime.rb', line 43

def parse(file)
  require file
end

#target?(const) ⇒ Boolean

Returns:

  • (Boolean)


26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/rbs/prototype/runtime.rb', line 26

def target?(const)
  name = const_name(const)
  return false unless name

  patterns.any? do |pattern|
    if pattern.end_with?("*")
      (name || "").start_with?(pattern.chop)
    else
      name == pattern
    end
  end
end

#target_method?(mod, instance: nil, singleton: nil) ⇒ Boolean

Returns:

  • (Boolean)


219
220
221
222
223
224
225
226
227
228
# File 'lib/rbs/prototype/runtime.rb', line 219

def target_method?(mod, instance: nil, singleton: nil)
  case
  when instance
    method = mod.instance_method(instance)
    method.owner == mod || owners_included.any? {|m| method.owner == m }
  when singleton
    method = mod.singleton_class.instance_method(singleton)
    method.owner == mod.singleton_class || owners_included.any? {|m| method.owner == m.singleton_class }
  end
end

#to_type_name(name, full_name: false) ⇒ Object



64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/rbs/prototype/runtime.rb', line 64

def to_type_name(name, full_name: false)
  *prefix, last = name.split(/::/)

  if full_name
    if prefix.empty?
      TypeName.new(name: last.to_sym, namespace: Namespace.empty)
    else
      TypeName.new(name: last.to_sym, namespace: Namespace.parse(prefix.join("::")))
    end
  else
    TypeName.new(name: last.to_sym, namespace: Namespace.empty)
  end
end

#type_args(type_name) ⇒ Object



557
558
559
560
561
562
563
# File 'lib/rbs/prototype/runtime.rb', line 557

def type_args(type_name)
  if class_decl = env.class_decls[type_name.absolute!]
    class_decl.type_params.size.times.map { :untyped }
  else
    []
  end
end

#type_params(mod) ⇒ Object



565
566
567
568
569
570
571
572
# File 'lib/rbs/prototype/runtime.rb', line 565

def type_params(mod)
  type_name = to_type_name(const_name(mod), full_name: true)
  if class_decl = env.class_decls[type_name.absolute!]
    class_decl.type_params
  else
    []
  end
end