Skip to content

Commit 429003c

Browse files
committed
Don’t include local variables in document symbols
Fixes #962 rdar://117810784
1 parent 8af0bb5 commit 429003c

File tree

2 files changed

+20
-15
lines changed

2 files changed

+20
-15
lines changed

Sources/SourceKitLSP/Swift/DocumentSymbols.swift

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -180,7 +180,9 @@ fileprivate final class DocumentSymbolsFinder: SyntaxAnyVisitor {
180180
// If there is only one pattern binding within the variable decl, consider the entire variable decl as the
181181
// referenced range. If there are multiple, consider each pattern binding separately since the `var` keyword doesn't
182182
// belong to any pattern binding in particular.
183-
guard let variableDecl = node.parent?.parent?.as(VariableDeclSyntax.self) else {
183+
guard let variableDecl = node.parent?.parent?.as(VariableDeclSyntax.self),
184+
variableDecl.isMemberOrTopLevelDeclaration
185+
else {
184186
return .visitChildren
185187
}
186188
let rangeNode: Syntax = variableDecl.bindings.count == 1 ? Syntax(variableDecl) : Syntax(node)
@@ -228,6 +230,19 @@ fileprivate extension SyntaxProtocol {
228230
var rangeWithoutTrivia: Range<AbsolutePosition> {
229231
return positionAfterSkippingLeadingTrivia..<endPositionBeforeTrailingTrivia
230232
}
233+
234+
/// Whether this is a top-level constant or a member of a type, ie. if this is not a local variable.
235+
var isMemberOrTopLevelDeclaration: Bool {
236+
if self.parent?.is(MemberBlockItemSyntax.self) ?? false {
237+
return true
238+
} else if let codeBlockItem = self.parent?.as(CodeBlockItemSyntax.self),
239+
codeBlockItem.parent?.parent?.is(SourceFileSyntax.self) ?? false
240+
{
241+
return true
242+
} else {
243+
return false
244+
}
245+
}
231246
}
232247

233248
fileprivate extension TokenKind {

Tests/SourceKitLSPTests/DocumentSymbolTests.swift

Lines changed: 4 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -571,8 +571,8 @@ final class DocumentSymbolTests: XCTestCase {
571571
try await assertDocumentSymbols(
572572
"""
573573
1️⃣func 2️⃣f()3️⃣ {
574-
4️⃣let 5️⃣localConstant6️⃣ = 07️⃣
575-
}8️⃣
574+
let localConstant = 0
575+
}4️⃣
576576
"""
577577
) { positions in
578578
[
@@ -581,19 +581,9 @@ final class DocumentSymbolTests: XCTestCase {
581581
detail: nil,
582582
kind: .function,
583583
deprecated: nil,
584-
range: positions["1️⃣"]..<positions["8️⃣"],
584+
range: positions["1️⃣"]..<positions["4️⃣"],
585585
selectionRange: positions["2️⃣"]..<positions["3️⃣"],
586-
children: [
587-
DocumentSymbol(
588-
name: "localConstant",
589-
detail: nil,
590-
kind: .variable,
591-
deprecated: nil,
592-
range: positions["4️⃣"]..<positions["7️⃣"],
593-
selectionRange: positions["5️⃣"]..<positions["6️⃣"],
594-
children: []
595-
)
596-
]
586+
children: []
597587
)
598588
]
599589
}

0 commit comments

Comments
 (0)