Skip to content

Commit b0c2f8b

Browse files
authored
Merge pull request #800 from Shopify/vs/fix_nesting_with_specified_target_class
Fix nesting when a target class is specified
2 parents 2d67e09 + 33f8849 commit b0c2f8b

File tree

2 files changed

+26
-10
lines changed

2 files changed

+26
-10
lines changed

lib/ruby_lsp/document.rb

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -154,16 +154,6 @@ def locate(node, char_position, node_types: [])
154154
# already
155155
break if char_position < loc.start_char
156156

157-
# If there are node types to filter by, and the current node is not one of those types, then skip it
158-
next if node_types.any? && node_types.none? { |type| candidate.class == type }
159-
160-
# If the current node is narrower than or equal to the previous closest node, then it is more precise
161-
closest_loc = closest.location
162-
if loc.end_char - loc.start_char <= closest_loc.end_char - closest_loc.start_char
163-
parent = closest
164-
closest = candidate
165-
end
166-
167157
# If the candidate starts after the end of the previous nesting level, then we've exited that nesting level and
168158
# need to pop the stack
169159
previous_level = nesting.last
@@ -174,6 +164,16 @@ def locate(node, char_position, node_types: [])
174164
if candidate.is_a?(SyntaxTree::ClassDeclaration) || candidate.is_a?(SyntaxTree::ModuleDeclaration)
175165
nesting << candidate
176166
end
167+
168+
# If there are node types to filter by, and the current node is not one of those types, then skip it
169+
next if node_types.any? && node_types.none? { |type| candidate.class == type }
170+
171+
# If the current node is narrower than or equal to the previous closest node, then it is more precise
172+
closest_loc = closest.location
173+
if loc.end_char - loc.start_char <= closest_loc.end_char - closest_loc.start_char
174+
parent = closest
175+
closest = candidate
176+
end
177177
end
178178

179179
[closest, parent, nesting.map { |n| n.constant.constant.value }]

test/document_test.rb

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -502,6 +502,22 @@ def baz
502502
assert_equal(["Foo", "Other"], nesting)
503503
end
504504

505+
def test_locate_returns_correct_nesting_when_specifying_target_classes
506+
document = RubyLsp::Document.new(source: <<~RUBY, version: 1, uri: "file:///foo/bar.rb")
507+
module Foo
508+
class Bar
509+
def baz
510+
Qux
511+
end
512+
end
513+
end
514+
RUBY
515+
516+
found, _parent, nesting = document.locate_node({ line: 3, character: 6 }, node_types: [SyntaxTree::Const])
517+
assert_equal("Qux", T.cast(found, SyntaxTree::Const).value)
518+
assert_equal(["Foo", "Bar"], nesting)
519+
end
520+
505521
def test_reparsing_without_new_edits_does_nothing
506522
document = RubyLsp::Document.new(source: +"", version: 1, uri: "file:///foo/bar.rb")
507523
document.push_edits(

0 commit comments

Comments
 (0)