Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions Sources/SwiftLanguageService/SwiftLanguageService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1293,3 +1293,65 @@ extension sourcekitd_api_uid_t {
}
}
}

// MARK: - Literal Detection

extension SwiftLanguageService {
/// Determines whether the given document position is on (or immediately after)
/// a literal value token.
///
/// This check is used to disable jump-to-definition on values that do not have
/// a meaningful definition location in source code.
///
/// The function returns `true` when the position resolves to:
/// - A literal token at the exact position, or
/// - A literal token immediately preceding the position (to handle cursor
/// placements just after the literal).
///
/// Supported literal kinds:
/// - String segments
/// - Integer literals
/// - Floating-point literals
/// - Boolean keywords (`true`, `false`)
/// - The `nil` keyword
///
/// If the document snapshot or syntax tree cannot be resolved, the function
/// conservatively returns `false`.
package func isPositionOnLiteralToken(
_ position: Position,
in uri: DocumentURI
) async -> Bool {
guard let snapshot = try? await latestSnapshot(for: uri) else {
return false
}

let tree = await syntaxTreeManager.syntaxTree(for: snapshot)
let absolutePosition = snapshot.absolutePosition(of: position)

func isLiteralTokenKind(_ token: TokenSyntax) -> Bool {
switch token.tokenKind {
case .stringSegment,
.integerLiteral,
.floatLiteral,
.keyword(.true), .keyword(.false), .keyword(.nil):
return true
Comment on lines +1333 to +1337
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this can be simplified slightly

Suggested change
case .stringSegment,
.integerLiteral,
.floatLiteral:
return true
case .keyword(let keyword) where keyword == .true || keyword == .false || keyword == .nil:
return true
case .stringSegment,
.integerLiteral,
.floatLiteral,
.keyword(.true), .keyword(.false), .keyword(.nil)::
return true

default:
return false
}
}

if let token = tree.token(at: absolutePosition) {
if isLiteralTokenKind(token) {
return true
}

if let tokenBefore = token.previousToken(viewMode: .sourceAccurate),
isLiteralTokenKind(tokenBefore)
{
return true
}
}

return false
}
}
7 changes: 7 additions & 0 deletions Sources/SwiftLanguageService/SymbolInfo.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,13 @@ extension SwiftLanguageService {
let uri = req.textDocument.uri
let snapshot = try documentManager.latestSnapshot(uri)
let position = await self.adjustPositionToStartOfIdentifier(req.position, in: snapshot)

// Check if position is on a literal token - return empty if so
// This prevents jump-to-definition for literals like "hello", 25, true, nil, etc.
if await isPositionOnLiteralToken(req.position, in: uri) {
return []
}

return try await cursorInfo(uri, position..<position, fallbackSettingsAfterTimeout: false)
.cursorInfo.map { $0.symbolInfo }
}
Expand Down
78 changes: 78 additions & 0 deletions Tests/SourceKitLSPTests/DefinitionTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -725,4 +725,82 @@ class DefinitionTests: SourceKitLSPTestCase {
)
XCTAssertTrue(definitions?.locations?.first?.uri.pseudoPath.hasSuffix("Lib.swiftinterface") ?? false)
}

func testDefinitionOnLiteralsShouldReturnEmpty() async throws {
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

let testClient = try await TestSourceKitLSPClient()
let uri = DocumentURI(for: .swift)

let positions = testClient.openDocument(
"""
let message = "1️⃣Hello"
let count = 2️⃣25
let flag = 3️⃣true
let pi = 4️⃣3.14
let nothing: Int? = 5️⃣nil
""",
uri: uri
)

// Test string literal
let stringResponse = try await testClient.send(
DefinitionRequest(textDocument: TextDocumentIdentifier(uri), position: positions["1️⃣"])
)
XCTAssertNil(stringResponse, "Jump-to-definition should not work on string literals")

// Test integer literal
let intResponse = try await testClient.send(
DefinitionRequest(textDocument: TextDocumentIdentifier(uri), position: positions["2️⃣"])
)
XCTAssertNil(intResponse, "Jump-to-definition should not work on integer literals")

// Test boolean literal
let boolResponse = try await testClient.send(
DefinitionRequest(textDocument: TextDocumentIdentifier(uri), position: positions["3️⃣"])
)
XCTAssertNil(boolResponse, "Jump-to-definition should not work on boolean literals")

// Test float literal
let floatResponse = try await testClient.send(
DefinitionRequest(textDocument: TextDocumentIdentifier(uri), position: positions["4️⃣"])
)
XCTAssertNil(floatResponse, "Jump-to-definition should not work on float literals")

// Test nil literal
let nilResponse = try await testClient.send(
DefinitionRequest(textDocument: TextDocumentIdentifier(uri), position: positions["5️⃣"])
)
XCTAssertNil(nilResponse, "Jump-to-definition should not work on nil literals")
}

func testDefinitionInsideLiteralsShouldStillWork() async throws {
let testClient = try await TestSourceKitLSPClient()
let uri = DocumentURI(for: .swift)

let positions = testClient.openDocument(
#"""
let name = "Ayman"
let greeting = "Hello \(1️⃣name)"
let items = [2️⃣name, "other"]
"""#,
uri: uri
)

// Identifier inside string interpolation - should work
let interpolationResponse = try await testClient.send(
DefinitionRequest(textDocument: TextDocumentIdentifier(uri), position: positions["1️⃣"])
)
XCTAssertNotNil(
interpolationResponse,
"Jump-to-definition should work for identifiers inside string interpolation"
)

// Identifier inside array literal - should work
let arrayResponse = try await testClient.send(
DefinitionRequest(textDocument: TextDocumentIdentifier(uri), position: positions["2️⃣"])
)
XCTAssertNotNil(
arrayResponse,
"Jump-to-definition should work for identifiers inside array literals"
)
}
}