Skip to content

Implement "textDocument/implementation" request #126

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Aug 9, 2019
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
40 changes: 40 additions & 0 deletions Sources/LanguageServerProtocol/ImplementationRequest.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

/// The go to implementation request is sent from the client to the server
/// to resolve the implementation location of a symbol at a given
/// text document position.
///
/// Servers that provide Goto Implementation support should set
/// the `implementationProvider` server capability.
///
/// - Parameters:
/// - textDocument: The document in which the given symbol is located.
/// - position: The document location of a given symbol.
///
/// - Returns: The location of the implementations of protocol requirements,
/// protocol conforming types, subclasses, or overrides.
public struct ImplementationRequest: TextDocumentRequest, Hashable {
public static let method: String = "textDocument/implementation"
public typealias Response = [Location]

/// The document in which the given symbol is located.
public var textDocument: TextDocumentIdentifier

/// The document location of a given symbol.
public var position: Position

public init(textDocument: TextDocumentIdentifier, position: Position) {
self.textDocument = textDocument
self.position = position
}
}
1 change: 1 addition & 0 deletions Sources/LanguageServerProtocol/Messages.swift
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ public let builtinRequests: [_RequestType.Type] = [
HoverRequest.self,
WorkspaceSymbolsRequest.self,
DefinitionRequest.self,
ImplementationRequest.self,
ReferencesRequest.self,
DocumentHighlightRequest.self,
DocumentFormatting.self,
Expand Down
8 changes: 7 additions & 1 deletion Sources/LanguageServerProtocol/ServerCapabilities.swift
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ public struct ServerCapabilities: Codable, Hashable {
/// Whether the server provides "textDocument/definition".
public var definitionProvider: Bool?

/// Whether the server provides "textDocument/implementation".
public var implementationProvider: Bool?

/// Whether the server provides "textDocument/references".
public var referencesProvider: Bool?

Expand Down Expand Up @@ -53,14 +56,15 @@ public struct ServerCapabilities: Codable, Hashable {

/// The server provides workspace symbol support.
public var workspaceSymbolProvider: Bool?

// TODO: fill-in the rest.

public init(
textDocumentSync: TextDocumentSyncOptions? = nil,
completionProvider: CompletionOptions? = nil,
hoverProvider: Bool? = nil,
definitionProvider: Bool? = nil,
implementationProvider: Bool? = nil,
referencesProvider: Bool? = nil,
documentHighlightProvider: Bool? = nil,
documentFormattingProvider: Bool? = nil,
Expand All @@ -77,6 +81,7 @@ public struct ServerCapabilities: Codable, Hashable {
self.completionProvider = completionProvider
self.hoverProvider = hoverProvider
self.definitionProvider = definitionProvider
self.implementationProvider = implementationProvider
self.referencesProvider = referencesProvider
self.documentHighlightProvider = documentHighlightProvider
self.documentFormattingProvider = documentFormattingProvider
Expand All @@ -94,6 +99,7 @@ public struct ServerCapabilities: Codable, Hashable {
self.completionProvider = try container.decodeIfPresent(CompletionOptions.self, forKey: .completionProvider)
self.hoverProvider = try container.decodeIfPresent(Bool.self, forKey: .hoverProvider)
self.definitionProvider = try container.decodeIfPresent(Bool.self, forKey: .definitionProvider)
self.implementationProvider = try container.decodeIfPresent(Bool.self, forKey: .implementationProvider)
self.foldingRangeProvider = try container.decodeIfPresent(Bool.self, forKey: .foldingRangeProvider)
self.documentSymbolProvider = try container.decodeIfPresent(Bool.self, forKey: .documentSymbolProvider)
self.colorProvider = try container.decodeIfPresent(Bool.self, forKey: .colorProvider)
Expand Down
51 changes: 51 additions & 0 deletions Sources/SourceKit/SourceKitServer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ public final class SourceKitServer: LanguageServer {
registerWorkspaceRequest(SourceKitServer.hover)
registerWorkspaceRequest(SourceKitServer.workspaceSymbols)
registerWorkspaceRequest(SourceKitServer.definition)
registerWorkspaceRequest(SourceKitServer.implementation)
registerWorkspaceRequest(SourceKitServer.references)
registerWorkspaceRequest(SourceKitServer.documentSymbolHighlight)
registerWorkspaceRequest(SourceKitServer.foldingRange)
Expand Down Expand Up @@ -261,6 +262,7 @@ extension SourceKitServer {
),
hoverProvider: true,
definitionProvider: true,
implementationProvider: true,
referencesProvider: true,
documentHighlightProvider: true,
foldingRangeProvider: true,
Expand Down Expand Up @@ -468,6 +470,55 @@ extension SourceKitServer {
}
}

// FIXME: a lot of duplication with definition request
func implementation(_ req: Request<ImplementationRequest>, workspace: Workspace) {
// FIXME: sending yourself a request isn't very convenient

guard let service = workspace.documentService[req.params.textDocument.url] else {
req.reply([])
return
}

let id = service.send(SymbolInfoRequest(textDocument: req.params.textDocument, position: req.params.position), queue: queue) { result in
guard let symbols: [SymbolDetails] = result.success ?? nil, let symbol = symbols.first else {
if let error = result.failure {
req.reply(.failure(error))
} else {
req.reply([])
}
return
}

guard let usr = symbol.usr, let index = workspace.index else {
return req.reply([])
}

var occurs = index.occurrences(ofUSR: usr, roles: .baseOf)
if occurs.isEmpty {
occurs = index.occurrences(relatedToUSR: usr, roles: .overrideOf)
}

let locations = occurs.compactMap { occur -> Location? in
if occur.location.path.isEmpty {
return nil
}
return Location(
url: URL(fileURLWithPath: occur.location.path),
range: Range(Position(
line: occur.location.line - 1, // 1-based -> 0-based
// FIXME: we need to convert the utf8/utf16 column, which may require reading the file!
utf16index: occur.location.utf8Column - 1
))
)
}

req.reply(locations)
}
req.cancellationToken.addCancellationHandler { [weak service] in
service?.send(CancelRequest(id: id))
}
}

// FIXME: a lot of duplication with definition request
func references(_ req: Request<ReferencesRequest>, workspace: Workspace) {
// FIXME: sending yourself a request isn't very convenient
Expand Down
1 change: 1 addition & 0 deletions Sources/SourceKit/sourcekitd/SwiftLanguageServer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,7 @@ extension SwiftLanguageServer {
triggerCharacters: ["."]),
hoverProvider: true,
definitionProvider: nil,
implementationProvider: true,
referencesProvider: nil,
documentHighlightProvider: true,
foldingRangeProvider: true,
Expand Down
53 changes: 53 additions & 0 deletions Tests/INPUTS/Implementation/a.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/*a.swift*/
protocol /*Protocol*/Protocol {
static var /*ProtocolStaticVar*/staticVar: Int { get }
static func /*ProtocolStaticFunction*/staticFunction()
var /*ProtocolVariable*/variable: Int { get }
func /*ProtocolFunction*/function()
}
class /*Class*/Class {
class var /*ClassClassVar*/classVar: Int { 123 }
class func /*ClassClassFunction*/classFunction() {}
var /*ClassVariable*/variable: Int { 123 }
func /*ClassFunction*/function() {}
}


class /*Sepulcidae*/Sepulcidae {}
class /*Parapamphiliinae*/Parapamphiliinae: /*ParapamphiliinaeConformance*/Sepulcidae {}
class Micramphilius: /*MicramphiliusConformance*/Parapamphiliinae {}
class Pamparaphilius: /*PamparaphiliusConformance*/Parapamphiliinae {}
class /*Xyelulinae*/Xyelulinae: /*XyelulinaeConformance*/Sepulcidae {}
class Xyelula: /*XyelulaConformance*/Xyelulinae {}
class /*Trematothoracinae*/Trematothoracinae: /*TrematothoracinaeConformance*/Sepulcidae {}


protocol /*Prozaiczne*/Prozaiczne {}
protocol /*Sepulkowate*/Sepulkowate {
func /*rozpocznijSepulenie*/rozpocznijSepulenie()
}

class Pćma {}
class /*Murkwia*/Murkwia: /*MurkwiaConformance1*/Sepulkowate, /*MurkwiaConformance2*/Prozaiczne {
func /*MurkwiaFunc*/rozpocznijSepulenie() {}
}
class /*Sepulka*/Sepulka: /*SepulkaConformance1*/Prozaiczne, /*SepulkaConformance2*/Sepulkowate {
var size: Double { 10 }
var /*SepulkaVar*/patroka: String { "puszysta" }
func /*SepulkaFunc*/rozpocznijSepulenie() {}
}
class SepulkaDwuuszna: /*SepulkaDwuusznaConformance*/Sepulka {
override var /*SepulkaDwuusznaVar*/patroka: String { "glazurowana" }
}
class SepulkaPrzechylna: /*SepulkaPrzechylnaConformance*/Sepulka {
override var /*SepulkaPrzechylnaVar*/patroka: String { "piaskowana" }
}
class PćmaŁagodna: Pćma {
func /*PćmaŁagodnaFunc*/rozpocznijSepulenie() { }
}
extension PćmaŁagodna: /*PćmaŁagodnaConformance*/Sepulkowate {}

class PćmaZwyczajna: Pćma {}
extension PćmaZwyczajna: /*PćmaZwyczajnaConformance*/Sepulkowate {
func /*PćmaZwyczajnaFunc*/rozpocznijSepulenie() { }
}
13 changes: 13 additions & 0 deletions Tests/INPUTS/Implementation/b.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
/*b.swift*/
struct Struct: /*StructConformance*/Protocol {
static var /*StructStaticVar*/staticVar: Int { 123 }
static func /*StructStaticFunction*/staticFunction() {}
var /*StructVariable*/variable: Int { 123 }
func /*StructFunction*/function() {}
}
class Subclass: /*SubclassConformance*/Class {
override class var /*SubclassClassVar*/classVar: Int { 123 }
override class func /*SubclassClassFunction*/classFunction() {}
override var /*SubclassVariable*/variable: Int { 123 }
override func /*SubclassFunction*/function() {}
}
1 change: 1 addition & 0 deletions Tests/INPUTS/Implementation/project.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"sources": ["a.swift", "b.swift"]}
1 change: 1 addition & 0 deletions Tests/LanguageServerProtocolJSONRPCTests/CodingTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ final class CodingTests: XCTestCase {
triggerCharacters: ["."]),
hoverProvider: nil,
definitionProvider: nil,
implementationProvider: nil,
referencesProvider: nil,
documentHighlightProvider: nil,
foldingRangeProvider: nil,
Expand Down
67 changes: 67 additions & 0 deletions Tests/SourceKitTests/ImplementationTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

@testable import SourceKit
import LanguageServerProtocol
import XCTest
import SKTestSupport
import ISDBTestSupport

final class ImplementationTests: XCTestCase {
func testImplementation() throws {
let ws = try staticSourceKitTibsWorkspace(name: "Implementation")!
try ws.buildAndIndex()

try ws.openDocument(ws.testLoc("a.swift").url, language: .swift)
try ws.openDocument(ws.testLoc("b.swift").url, language: .swift)

func impls(at testLoc: TestLocation) throws -> Set<Location> {
let textDocument = testLoc.docIdentifier
let request = ImplementationRequest(textDocument: textDocument, position: Position(testLoc))
let implementations = try ws.sk.sendSync(request)
return Set(implementations)
}
func testLoc(_ name: String) -> TestLocation {
ws.testLoc(name)
}
func loc(_ name: String) -> Location {
Location(ws.testLoc(name))
}

try XCTAssertEqual(impls(at: testLoc("Protocol")), [loc("StructConformance")])
try XCTAssertEqual(impls(at: testLoc("ProtocolStaticVar")), [loc("StructStaticVar")])
try XCTAssertEqual(impls(at: testLoc("ProtocolStaticFunction")), [loc("StructStaticFunction")])
try XCTAssertEqual(impls(at: testLoc("ProtocolVariable")), [loc("StructVariable")])
try XCTAssertEqual(impls(at: testLoc("ProtocolFunction")), [loc("StructFunction")])
try XCTAssertEqual(impls(at: testLoc("Class")), [loc("SubclassConformance")])
try XCTAssertEqual(impls(at: testLoc("ClassClassVar")), [loc("SubclassClassVar")])
try XCTAssertEqual(impls(at: testLoc("ClassClassFunction")), [loc("SubclassClassFunction")])
try XCTAssertEqual(impls(at: testLoc("ClassVariable")), [loc("SubclassVariable")])
try XCTAssertEqual(impls(at: testLoc("ClassFunction")), [loc("SubclassFunction")])

try XCTAssertEqual(impls(at: testLoc("Sepulcidae")), [loc("ParapamphiliinaeConformance"), loc("XyelulinaeConformance"), loc("TrematothoracinaeConformance")])
Copy link
Contributor

Choose a reason for hiding this comment

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

The order of these is not guaranteed in the index. Maybe we should change impls to return a Set for testing purposes?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

changed

try XCTAssertEqual(impls(at: testLoc("Parapamphiliinae")), [loc("MicramphiliusConformance"), loc("PamparaphiliusConformance")])
try XCTAssertEqual(impls(at: testLoc("Xyelulinae")), [loc("XyelulaConformance")])
try XCTAssertEqual(impls(at: testLoc("Trematothoracinae")), [])

try XCTAssertEqual(impls(at: testLoc("Prozaiczne")), [loc("MurkwiaConformance2"), loc("SepulkaConformance1")])
// FIXME: For some reason we get a location in the middle of a symbol for PćmaŁagodnaConformance
// try XCTAssertEqual(impls(at: testLoc("Sepulkowate")), [loc("MurkwiaConformance1"), loc("SepulkaConformance2"), loc("PćmaŁagodnaConformance"), loc("PćmaZwyczajnaConformance")])
// FIXME: sourcekit returns wrong locations for the function (subclasses that don't override it, and extensions that don't implement it)
Copy link
Contributor

Choose a reason for hiding this comment

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

Could you file a bug for this one? It seems worth understanding and fixing either in the index or in sourcekit-lsp.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

// try XCTAssertEqual(impls(at: testLoc("rozpocznijSepulenie")), [loc("MurkwiaFunc"), loc("SepulkaFunc"), loc("PćmaŁagodnaFunc"), loc("PćmaZwyczajnaFunc")])
try XCTAssertEqual(impls(at: testLoc("Murkwia")), [])
try XCTAssertEqual(impls(at: testLoc("MurkwiaFunc")), [])
try XCTAssertEqual(impls(at: testLoc("Sepulka")), [loc("SepulkaDwuusznaConformance"), loc("SepulkaPrzechylnaConformance")])
try XCTAssertEqual(impls(at: testLoc("SepulkaVar")), [loc("SepulkaDwuusznaVar"), loc("SepulkaPrzechylnaVar")])
try XCTAssertEqual(impls(at: testLoc("SepulkaFunc")), [])
}
}
10 changes: 10 additions & 0 deletions Tests/SourceKitTests/XCTestManifests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,15 @@ extension FoldingRangeTests {
]
}

extension ImplementationTests {
// DO NOT MODIFY: This is autogenerated, use:
// `swift test --generate-linuxmain`
// to regenerate.
static let __allTests__ImplementationTests = [
("testImplementation", testImplementation),
]
}

extension LocalClangTests {
// DO NOT MODIFY: This is autogenerated, use:
// `swift test --generate-linuxmain`
Expand Down Expand Up @@ -104,6 +113,7 @@ public func __allTests() -> [XCTestCaseEntry] {
testCase(DocumentColorTests.__allTests__DocumentColorTests),
testCase(DocumentSymbolTest.__allTests__DocumentSymbolTest),
testCase(FoldingRangeTests.__allTests__FoldingRangeTests),
testCase(ImplementationTests.__allTests__ImplementationTests),
testCase(LocalClangTests.__allTests__LocalClangTests),
testCase(LocalSwiftTests.__allTests__LocalSwiftTests),
testCase(SKTests.__allTests__SKTests),
Expand Down