Class: Steep::Services::GotoService

Inherits:
Object
  • Object
show all
Includes:
ModuleHelper
Defined in:
lib/steep/services/goto_service.rb

Defined Under Namespace

Modules: SourceHelper Classes: ConstantQuery, MethodQuery, TypeNameQuery

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from ModuleHelper

#module_name_from_node, #namespace_from_node

Constructor Details

#initialize(type_check:, assignment:) ⇒ GotoService

Returns a new instance of GotoService.



27
28
29
30
# File 'lib/steep/services/goto_service.rb', line 27

def initialize(type_check:, assignment:)
  @type_check = type_check
  @assignment = assignment
end

Instance Attribute Details

#assignmentObject (readonly)

Returns the value of attribute assignment.



25
26
27
# File 'lib/steep/services/goto_service.rb', line 25

def assignment
  @assignment
end

#type_checkObject (readonly)

Returns the value of attribute type_check.



25
26
27
# File 'lib/steep/services/goto_service.rb', line 25

def type_check
  @type_check
end

Class Method Details

.find_singleton_method_dot(string) ⇒ Object

Finds the index of a ‘.` that separates a type from a singleton method name.

Returns the index of the last ‘.` that is not followed by another `.` (to avoid matching the empty string) and that is not part of `::`. Returns `nil` if none is found.



76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/steep/services/goto_service.rb', line 76

def self.find_singleton_method_dot(string)
  index = string.length - 1
  while index > 0
    char = string[index]
    if char == "."
      prev = string[index - 1]
      if prev != "." && prev != ":"
        return index
      end
    end
    index -= 1
  end
  nil
end

.parse_name(name_string) ⇒ Object

Parses a string representing a class/type/constant/method name into a query value.

Supported formats:

  • ‘RBS::Location` – type name (class, module, interface, type alias, class/module alias, or constant)

  • ‘::RBS::Location` – type name, fully qualified

  • ‘RBS::Parser#parse_type` – instance method

  • ‘RBS::Parser.parse_signature` – singleton method

Returns ‘nil` when the given string cannot be parsed as any of the above.



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/steep/services/goto_service.rb', line 47

def self.parse_name(name_string)
  return nil if name_string.nil? || name_string.empty?

  if index = name_string.index("#")
    type_part = name_string[0...index] or return nil
    method_part = name_string[(index + 1)..] or return nil
    return nil if type_part.empty? || method_part.empty?

    type_name = parse_type_name(type_part) or return nil
    InstanceMethodName.new(type_name: type_name, method_name: method_part.to_sym)
  elsif index = find_singleton_method_dot(name_string)
    type_part = name_string[0...index] or return nil
    method_part = name_string[(index + 1)..] or return nil
    return nil if type_part.empty? || method_part.empty?

    type_name = parse_type_name(type_part) or return nil
    SingletonMethodName.new(type_name: type_name, method_name: method_part.to_sym)
  else
    parse_type_name(name_string)
  end
rescue RBS::ParsingError, StandardError
  nil
end

.parse_type_name(string) ⇒ Object



91
92
93
94
95
96
# File 'lib/steep/services/goto_service.rb', line 91

def self.parse_type_name(string)
  string = "::#{string}" unless string.start_with?("::")
  RBS::TypeName.parse(string)
rescue RBS::ParsingError, StandardError
  nil
end

Instance Method Details

#constant_definition_in_rbs(name, locations:) ⇒ Object



480
481
482
483
484
485
486
487
488
489
490
491
492
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
# File 'lib/steep/services/goto_service.rb', line 480

def constant_definition_in_rbs(name, locations:)
  project.targets.each do |target|
    signature = type_check.signature_services.fetch(target.name)
    env = signature.latest_env #: RBS::Environment

    case entry = env.constant_entry(name)
    when RBS::Environment::ConstantEntry
      case decl = entry.decl
      when RBS::AST::Declarations::Constant
        if entry.decl.location
          locations << [target, entry.decl.location[:name]]
        end
      when RBS::AST::Ruby::Declarations::ConstantDecl
        locations << [target, entry.decl.name_location]
      else
        raise "Unknown declaration: #{entry.decl.inspect}"
      end
    when RBS::Environment::ClassEntry, RBS::Environment::ModuleEntry
      entry.each_decl do |decl|
        case decl
        when RBS::AST::Declarations::Base
          if decl.location
            locations << [target, decl.location[:name]]
          end
        when RBS::AST::Ruby::Declarations::ClassDecl, RBS::AST::Ruby::Declarations::ModuleDecl
          locations << [target, decl.name_location]
        else
          raise "Unknown declaration: #{decl.inspect}"
        end
      end
    when RBS::Environment::ClassAliasEntry, RBS::Environment::ModuleAliasEntry
      if entry.decl.is_a?(RBS::AST::Declarations::Base)
        if entry.decl.location
          locations << [target, entry.decl.location[:new_name]]
        end
      else
        locations << [target, entry.decl.name_location]
      end
    end
  end

  locations
end

#constant_definition_in_ruby(name, locations:) ⇒ Object



524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
# File 'lib/steep/services/goto_service.rb', line 524

def constant_definition_in_ruby(name, locations:)
  type_check.source_files.each do |path, source|
    if typing = source.typing
      target = project.target_for_source_path(path) or raise
      entry = typing.source_index.entry(constant: name)
      entry.definitions.each do |node|
        case node.type
        when :const
          locations << [target, node.location.expression]
        when :casgn
          parent = node.children[0]
          location =
            if parent
              parent.location.expression.join(node.location.name)
            else
              node.location.name
            end
          locations << [target, location]
        end
      end
    end
  end

  locations
end

#definition(path:, line:, column:) ⇒ Object



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
# File 'lib/steep/services/goto_service.rb', line 176

def definition(path:, line:, column:)
  locations = [] #: Array[target_loc]

  queries = query_at(path: path, line: line, column: column)
  queries.uniq!

  queries.each do |query|
    case query
    when ConstantQuery
      constant_definition_in_rbs(query.name, locations: locations) if query.from_ruby?
      constant_definition_in_ruby(query.name, locations: locations) if query.from_rbs?
    when MethodQuery
      method_locations(
        query.name,
        locations: locations,
        in_ruby: query.from_rbs?,
        in_rbs: query.from_ruby?
      )
    when TypeNameQuery
      type_name_locations(query.name, locations: locations)
    end
  end

  # Drop un-assigned paths here.
  # The path assignment makes sense only for `.rbs` files, because un-assigned `.rb` files are already skipped since they are not type checked.
  #
  locations.filter_map do |target, loc|
    case loc
    when RBS::Location
      if assignment =~ [target, loc.name]
        loc
      end
    else
      loc
    end
  end.uniq
end

#each_type_name(type, &block) ⇒ Object



249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
# File 'lib/steep/services/goto_service.rb', line 249

def each_type_name(type, &block)
  if block
    case type
    when AST::Types::Name::Instance, AST::Types::Name::Alias, AST::Types::Name::Singleton, AST::Types::Name::Interface
      yield type.name
    when AST::Types::Literal
      yield type.back_type.name
    when AST::Types::Nil
      yield RBS::TypeName.new(name: :NilClass, namespace: RBS::Namespace.root)
    when AST::Types::Boolean
      yield RBS::BuiltinNames::TrueClass.name
      yield RBS::BuiltinNames::FalseClass.name
    end

    type.each_child do |child|
      each_type_name(child, &block)
    end
  else
    enum_for :each_type_name, type
  end
end

#implementation(path:, line:, column:) ⇒ Object



156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
# File 'lib/steep/services/goto_service.rb', line 156

def implementation(path:, line:, column:)
  locations = [] #: Array[target_loc]

  queries = query_at(path: path, line: line, column: column)
  queries.uniq!

  queries.each do |query|
    case query
    when ConstantQuery
      constant_definition_in_ruby(query.name, locations: locations)
    when MethodQuery
      method_locations(query.name, locations: locations, in_ruby: true, in_rbs: false)
    when TypeNameQuery
      constant_definition_in_ruby(query.name, locations: locations)
    end
  end

  locations.map { _1[1] }.uniq
end

#interface_and_type_alias_locations(name, locations:) ⇒ Object



133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
# File 'lib/steep/services/goto_service.rb', line 133

def interface_and_type_alias_locations(name, locations:)
  project.targets.each do |target|
    signature = type_check.signature_services.fetch(target.name)
    env = signature.latest_env

    if entry = env.interface_decls[name]
      decl = entry.decl
      if loc = decl.location
        locations << [target, loc[:name]]
      end
    end

    if entry = env.type_alias_decls[name]
      decl = entry.decl
      if loc = decl.location
        locations << [target, loc[:name]]
      end
    end
  end

  locations
end

#method_locations(name, in_ruby:, in_rbs:, locations:) ⇒ Object



550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
# File 'lib/steep/services/goto_service.rb', line 550

def method_locations(name, in_ruby:, in_rbs:, locations:)
  if in_ruby
    type_check.source_files.each do |path, source|
      if typing = source.typing
        target = project.target_for_source_path(path) or raise
        entry = typing.source_index.entry(method: name)

        if entry.definitions.empty?
          if name.is_a?(SingletonMethodName) && name.method_name == :new
            initialize = InstanceMethodName.new(method_name: :initialize, type_name: name.type_name)
            entry = typing.source_index.entry(method: initialize)
          end
        end

        entry.definitions.each do |node|
          case node.type
          when :def
            locations << [target, node.location.name]
          when :defs
            locations << [target, node.location.name]
          end
        end
      end
    end
  end

  if in_rbs
    project.targets.each do |target|
      signature = type_check.signature_services.fetch(target.name)
      index = signature.latest_rbs_index

      entry = index.entry(method_name: name)

      if entry.declarations.empty?
        if name.is_a?(SingletonMethodName) && name.method_name == :new
          initialize = InstanceMethodName.new(method_name: :initialize, type_name: name.type_name)
          entry = index.entry(method_name: initialize)
        end
      end

      entry.declarations.each do |decl|
        case decl
        when RBS::AST::Members::MethodDefinition
          if decl.location
            locations << [target, decl.location[:name]]
          end
        when RBS::AST::Members::Alias
          if decl.location
            locations << [target, decl.location[:new_name]]
          end
        when RBS::AST::Members::AttrAccessor, RBS::AST::Members::AttrReader, RBS::AST::Members::AttrWriter
          if decl.location
            locations << [target, decl.location[:name]]
          end
        when RBS::AST::Ruby::Members::DefMember
          locations << [target, decl.name_location]
        end
      end
    end
  end

  locations
end

#projectObject



32
33
34
# File 'lib/steep/services/goto_service.rb', line 32

def project
  type_check.project
end

#query_at(path:, line:, column:) ⇒ Object



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
337
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
375
# File 'lib/steep/services/goto_service.rb', line 279

def query_at(path:, line:, column:)
  queries = [] #: Array[query]

  relative_path = project.relative_path(path)

  case
  when target = type_check.project.target_for_inline_source_path(relative_path)
    signature = type_check.signature_services.fetch(target.name)
    source = signature.latest_env.sources.find do
      if _1.is_a?(::RBS::Source::Ruby)
        _1.buffer.name == relative_path
      end
    end

    if source.is_a?(::RBS::Source::Ruby)
      locator = Locator::Inline.new(source)
      result = locator.find(line, column)

      case result
      when Locator::InlineTypeNameResult
        queries << TypeNameQuery.new(name: result.type_name)
      end
    end

    if queries.empty?
      source = type_check.source_files.fetch(relative_path, nil) or return []
      typing, signature, subtyping = type_check_path(target: target, path: relative_path, content: source.content, line: line, column: column)
      if typing && signature && subtyping
        queries.concat query_at_implementation(typing, subtyping, line: line, column: column)
      end
    end
  when target = type_check.project.target_for_source_path(relative_path)
    source = type_check.source_files.fetch(relative_path, nil) or return []
    typing, _signature, subtyping = type_check_path(target: target, path: relative_path, content: source.content, line: line, column: column)
    if typing && subtyping
      queries.concat query_at_implementation(typing, subtyping, line: line, column: column)
    end
  when target_names = type_check.signature_file?(path) #: Array[Symbol]
    target_names.each do |target_name|
      signature_service = type_check.signature_services[target_name] #: SignatureService

      env = signature_service.latest_env
      source = env.each_rbs_source.find {|src| src.buffer.name == relative_path } or raise
      buffer = source.buffer
      dirs = source.directives
      decls = source.declarations

      locator = RBS::Locator.new(buffer: buffer, dirs: dirs, decls: decls)
      last, nodes = locator.find2(line: line, column: column)

      nodes or raise

      case nodes[0]
      when RBS::AST::Declarations::Class, RBS::AST::Declarations::Module
        if last == :name
          queries << ConstantQuery.new(name: nodes[0].name, from: :rbs)
        end
      when RBS::AST::Declarations::Constant
        if last == :name
          queries << ConstantQuery.new(name: nodes[0].name, from: :rbs)
        end
      when RBS::AST::Members::MethodDefinition
        if last == :name
          parent_node = nodes[1] #: RBS::AST::Declarations::Class | RBS::AST::Declarations::Module | RBS::AST::Declarations::Interface
          type_name = parent_node.name
          method_name = nodes[0].name
          if nodes[0].instance?
            queries << MethodQuery.new(
              name: InstanceMethodName.new(type_name: type_name, method_name: method_name),
              from: :rbs
            )
          end
          if nodes[0].singleton?
            queries << MethodQuery.new(
              name: SingletonMethodName.new(type_name: type_name, method_name: method_name),
              from: :rbs
            )
          end
        end
      when RBS::AST::Members::Include, RBS::AST::Members::Extend, RBS::AST::Members::Prepend
        if last == :name
          queries << TypeNameQuery.new(name: nodes[0].name)
        end
      when RBS::Types::ClassInstance, RBS::Types::ClassSingleton, RBS::Types::Interface, RBS::Types::Alias
        if last == :name
          queries << TypeNameQuery.new(name: nodes[0].name)
        end
      when RBS::AST::Declarations::Class::Super, RBS::AST::Declarations::Module::Self
        if last == :name
          queries << TypeNameQuery.new(name: nodes[0].name)
        end
      end
    end
  end

  queries
end

#query_at_implementation(typing, subtyping, line:, column:) ⇒ Object



377
378
379
380
381
382
383
384
385
386
387
388
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
435
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
# File 'lib/steep/services/goto_service.rb', line 377

def query_at_implementation(typing, subtyping, line:, column:)
  queries = [] #: Array[query]

  locator = Locator::Ruby.new(typing.source)
  result = locator.find(line, column)

  case result
  when Locator::NodeResult
    node = result.node
    parents = result.parents

    case node.type
    when :const, :casgn
      named_location = (_ = node.location) #: Parser::AST::_NamedLocation
      if test_ast_location(named_location.name, line: line, column: column)
        if name = typing.source_index.reference(constant_node: node)
          queries << ConstantQuery.new(name: name, from: :ruby)
        end
      end
    when :def, :defs
      named_location = (_ = node.location) #: Parser::AST::_NamedLocation
      if test_ast_location(named_location.name, line: line, column: column)
        if method_context = typing.cursor_context.context&.method_context
          if method = method_context.method
            method.defs.each do |defn|
              singleton_method =
                case defn.member
                when RBS::AST::Members::MethodDefinition
                  defn.member.singleton?
                when RBS::AST::Members::Attribute
                  defn.member.kind == :singleton
                end

              name =
                if singleton_method
                  SingletonMethodName.new(type_name: defn.defined_in, method_name: method_context.name)
                else
                  InstanceMethodName.new(type_name: defn.defined_in, method_name: method_context.name)
                end

              queries << MethodQuery.new(name: name, from: :ruby)
            end
          end
        end
      end
    when :send
      location = (_ = node.location) #: Parser::AST::_SelectorLocation
      if test_ast_location(location.selector, line: line, column: column)
        if (parent = parents[0]) && parent.type == :block && parent.children[0] === node
          node = parents[0]
        end

        case call = typing.call_of(node: node)
        when TypeInference::MethodCall::Typed, TypeInference::MethodCall::Error
          call.method_decls.each do |decl|
            queries << MethodQuery.new(name: decl.method_name, from: :ruby)
          end
        when TypeInference::MethodCall::Untyped
          # nop
        when TypeInference::MethodCall::NoMethodError
          # nop
        end
      end
    end
  when Locator::TypeAssertionResult
    context = typing.cursor_context.context or raise
    nesting = context.module_context.nesting
    type_vars = context.variable_context.type_params.map(&:name)
    pos = typing.source.buffer.loc_to_pos([line, column])

    if pair = result.locate_type_name(pos, nesting, subtyping, type_vars)
      queries << TypeNameQuery.new(name: pair[0])
    end
  when Locator::TypeApplicationResult
    context = typing.cursor_context.context or raise
    nesting = context.module_context.nesting
    type_vars = context.variable_context.type_params.map(&:name)
    pos = typing.source.buffer.loc_to_pos([line, column])

    if pair = result.locate_type_name(pos, nesting, subtyping, type_vars)
      queries << TypeNameQuery.new(name: pair[0])
    end
  end

  queries
end

#query_definition(name) ⇒ Object

Returns array of locations that is a response to a *Query definition* request.

Unlike ‘#definition`, this method takes a parsed name value instead of a source position. The caller is expected to parse the name via `.parse_name` before calling this method.

Each returned entry is either an ‘RBS::Location` (for RBS declarations) or a `Parser::Source::Range` (for Ruby source locations).



106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
# File 'lib/steep/services/goto_service.rb', line 106

def query_definition(name)
  locations = [] #: Array[target_loc]

  case name
  when RBS::TypeName
    # `constant_definition_in_rbs` covers classes, modules, class/module aliases,
    # and plain constants (via `env.constant_entry`).
    constant_definition_in_rbs(name, locations: locations)
    constant_definition_in_ruby(name, locations: locations)
    # Additional lookups for declarations that are not reachable via `env.constant_entry`.
    interface_and_type_alias_locations(name, locations: locations)
  when InstanceMethodName, SingletonMethodName
    method_locations(name, in_ruby: true, in_rbs: true, locations: locations)
  end

  locations.filter_map do |target, loc|
    case loc
    when RBS::Location
      if assignment =~ [target, loc.name]
        loc
      end
    else
      loc
    end
  end.uniq
end

#test_ast_location(loc, line:, column:) ⇒ Object



271
272
273
274
275
276
277
# File 'lib/steep/services/goto_service.rb', line 271

def test_ast_location(loc, line:, column:)
  return false if line < loc.line
  return false if line == loc.line && column < loc.column
  return false if loc.last_line < line
  return false if line == loc.last_line && loc.last_column < column
  true
end

#type_check_path(target:, path:, content:, line:, column:) ⇒ Object



464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
# File 'lib/steep/services/goto_service.rb', line 464

def type_check_path(target:, path:, content:, line:, column:)
  signature_service = type_check.signature_services.fetch(target.name)
  subtyping = signature_service.current_subtyping or return
  source = Source.parse(content, path: path, factory: subtyping.factory)
  source = source.without_unrelated_defs(line: line, column: column)
  resolver = RBS::Resolver::ConstantResolver.new(builder: subtyping.factory.definition_builder)
  loc = source.buffer.loc_to_pos([line, column])
  [
    Services::TypeCheckService.type_check(source: source, subtyping: subtyping, constant_resolver: resolver, cursor: loc),
    signature_service,
    subtyping
  ]
rescue
  nil
end

#type_definition(path:, line:, column:) ⇒ Object



214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
# File 'lib/steep/services/goto_service.rb', line 214

def type_definition(path:, line:, column:)
  locations = [] #: Array[target_loc]

  relative_path = project.relative_path(path)

  target = type_check.project.target_for_path(relative_path) or return []
  source = type_check.source_files.fetch(relative_path)
  typing, signature = type_check_path(target: target, path: relative_path, content: source.content, line: line, column: column)

  typing or return []
  signature or return []

  node, *_parents = typing.source.find_nodes(line: line, column: column)
  node or return []

  type = typing.type_of(node: node)

  subtyping = signature.current_subtyping or return []

  each_type_name(type).uniq.each do |name|
    type_name_locations(name, locations: locations)
  end

  locations.filter_map do |target, loc|
    case loc
    when RBS::Location
      if assignment =~ [target, loc.name]
        loc
      end
    else
      loc
    end
  end.uniq
end

#type_name_locations(name, locations: []) ⇒ Object



614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
# File 'lib/steep/services/goto_service.rb', line 614

def type_name_locations(name, locations: [])
  project.targets.each do |target|
    signature = type_check.signature_services.fetch(target.name)
    index = signature.latest_rbs_index

    entry = index.entry(type_name: name)
    entry.declarations.each do |decl|
      case decl
      when RBS::AST::Declarations::Class, RBS::AST::Declarations::Module, RBS::AST::Declarations::Interface, RBS::AST::Declarations::TypeAlias
        if decl.location
          locations << [target, decl.location[:name]]
        end
      when RBS::AST::Declarations::AliasDecl
        if decl.location
          locations << [target, decl.location[:new_name]]
        end
      when RBS::AST::Ruby::Declarations::ClassDecl, RBS::AST::Ruby::Declarations::ModuleDecl
        locations << [target, decl.name_location]
      when RBS::AST::Ruby::Declarations::ClassModuleAliasDecl
        locations << [target, decl.name_location]
      else
        raise
      end
    end
  end

  locations
end