Skip to content

Commit

Permalink
Fix NodeContext's handling of namespaced singleton method (#2385)
Browse files Browse the repository at this point in the history
When handling namespaced singleton method, the `handle_nesting_nodes`
method should split the current last nesting before creating the singleton class
nesting with it.

Failing to do so would let the TypeInferrer infer the wrong type for the
singleton method's receiver.
  • Loading branch information
st0012 authored Jul 30, 2024
1 parent efbfab2 commit 935c7e6
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
4 changes: 2 additions & 2 deletions lib/ruby_lsp/node_context.rb
Original file line number Diff line number Diff line change
Expand Up @@ -89,12 +89,12 @@ def handle_nesting_nodes(nodes)
when Prism::ClassNode, Prism::ModuleNode
nesting << node.constant_path.slice
when Prism::SingletonClassNode
nesting << "<Class:#{nesting.last}>"
nesting << "<Class:#{nesting.flat_map { |n| n.split("::") }.last}>"
when Prism::DefNode
surrounding_method = node.name.to_s
next unless node.receiver.is_a?(Prism::SelfNode)

nesting << "<Class:#{nesting.last}>"
nesting << "<Class:#{nesting.flat_map { |n| n.split("::") }.last}>"
end
end

Expand Down
13 changes: 13 additions & 0 deletions test/type_inferrer_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,19 @@ class << self
assert_equal("Foo::<Class:Foo>::<Class:<Class:Foo>>", @type_inferrer.infer_receiver_type(node_context).name)
end

def test_infer_receiver_type_in_namespaced_singleton_method
node_context = index_and_locate(<<~RUBY, { line: 2, character: 4 })
class Foo::Bar
def self.foo
bar
end
end
RUBY

result = @type_inferrer.infer_receiver_type(node_context).name
assert_equal("Foo::Bar::<Class:Bar>", result)
end

def test_infer_receiver_type_instance_variables_in_singleton_block_method
node_context = index_and_locate(<<~RUBY, { line: 3, character: 6 })
class Foo
Expand Down

0 comments on commit 935c7e6

Please sign in to comment.