-
Notifications
You must be signed in to change notification settings - Fork 304
Add LSP support for showing Macro Expansions #1436
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
ahoppen
merged 2 commits into
swiftlang:main
from
lokesh-tr:gsoc24-expansion-of-macros-in-vscode
Jun 20, 2024
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
52 changes: 52 additions & 0 deletions
52
Sources/LanguageServerProtocol/Requests/ShowDocumentRequest.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
//===----------------------------------------------------------------------===// | ||
// | ||
// This source file is part of the Swift.org open source project | ||
// | ||
// Copyright (c) 2014 - 2024 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 | ||
// | ||
//===----------------------------------------------------------------------===// | ||
|
||
/// Request from the server to the client to show a document on the client | ||
/// side. | ||
public struct ShowDocumentRequest: RequestType { | ||
public static let method: String = "window/showDocument" | ||
public typealias Response = ShowDocumentResponse | ||
|
||
/// The uri to show. | ||
public var uri: DocumentURI | ||
|
||
/// An optional boolean indicates to show the resource in an external | ||
/// program. To show, for example, `https://www.swift.org/ in the default WEB | ||
/// browser set `external` to `true`. | ||
public var external: Bool? | ||
|
||
/// An optional boolean to indicate whether the editor showing the document | ||
/// should take focus or not. Clients might ignore this property if an | ||
/// external program is started. | ||
public var takeFocus: Bool? | ||
|
||
/// An optional selection range if the document is a text document. Clients | ||
/// might ignore the property if an external program is started or the file | ||
/// is not a text file. | ||
public var selection: Range<Position>? | ||
|
||
public init(uri: DocumentURI, external: Bool? = nil, takeFocus: Bool? = nil, selection: Range<Position>? = nil) { | ||
self.uri = uri | ||
self.external = external | ||
self.takeFocus = takeFocus | ||
self.selection = selection | ||
} | ||
} | ||
|
||
public struct ShowDocumentResponse: Codable, Hashable, ResponseType { | ||
/// A boolean indicating if the show was successful. | ||
public var success: Bool | ||
|
||
public init(success: Bool) { | ||
self.success = success | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,80 @@ | ||
//===----------------------------------------------------------------------===// | ||
// | ||
// This source file is part of the Swift.org open source project | ||
// | ||
// Copyright (c) 2014 - 2024 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 | ||
// | ||
//===----------------------------------------------------------------------===// | ||
|
||
import LanguageServerProtocol | ||
import SourceKitD | ||
|
||
public struct ExpandMacroCommand: RefactorCommand { | ||
typealias Response = MacroExpansion | ||
|
||
public static let identifier: String = "expand.macro.command" | ||
|
||
/// The name of this refactoring action. | ||
public var title = "Expand Macro" | ||
|
||
/// The sourcekitd identifier of the refactoring action. | ||
public var actionString = "source.refactoring.kind.expand.macro" | ||
|
||
/// The range to expand. | ||
public var positionRange: Range<Position> | ||
|
||
/// The text document related to the refactoring action. | ||
public var textDocument: TextDocumentIdentifier | ||
|
||
public init(positionRange: Range<Position>, textDocument: TextDocumentIdentifier) { | ||
self.positionRange = positionRange | ||
self.textDocument = textDocument | ||
} | ||
|
||
public init?(fromLSPDictionary dictionary: [String: LSPAny]) { | ||
guard case .dictionary(let documentDict)? = dictionary[CodingKeys.textDocument.stringValue], | ||
case .string(let title)? = dictionary[CodingKeys.title.stringValue], | ||
case .string(let actionString)? = dictionary[CodingKeys.actionString.stringValue], | ||
case .dictionary(let rangeDict)? = dictionary[CodingKeys.positionRange.stringValue] | ||
else { | ||
return nil | ||
} | ||
guard let positionRange = Range<Position>(fromLSPDictionary: rangeDict), | ||
let textDocument = TextDocumentIdentifier(fromLSPDictionary: documentDict) | ||
else { | ||
return nil | ||
} | ||
|
||
self.init( | ||
title: title, | ||
actionString: actionString, | ||
positionRange: positionRange, | ||
textDocument: textDocument | ||
) | ||
} | ||
|
||
public init( | ||
title: String, | ||
actionString: String, | ||
positionRange: Range<Position>, | ||
textDocument: TextDocumentIdentifier | ||
) { | ||
self.title = title | ||
self.actionString = actionString | ||
self.positionRange = positionRange | ||
self.textDocument = textDocument | ||
} | ||
|
||
public func encodeToLSPAny() -> LSPAny { | ||
return .dictionary([ | ||
CodingKeys.title.stringValue: .string(title), | ||
CodingKeys.actionString.stringValue: .string(actionString), | ||
CodingKeys.positionRange.stringValue: positionRange.encodeToLSPAny(), | ||
CodingKeys.textDocument.stringValue: textDocument.encodeToLSPAny(), | ||
]) | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,132 @@ | ||
//===----------------------------------------------------------------------===// | ||
// | ||
// This source file is part of the Swift.org open source project | ||
// | ||
// Copyright (c) 2014 - 2024 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 | ||
// | ||
//===----------------------------------------------------------------------===// | ||
|
||
import Foundation | ||
import LSPLogging | ||
import LanguageServerProtocol | ||
import SourceKitD | ||
|
||
/// Detailed information about the result of a macro expansion operation. | ||
/// | ||
/// Wraps the information returned by sourcekitd's `semantic_refactoring` | ||
/// request, such as the necessary macro expansion edits. | ||
struct MacroExpansion: RefactoringResponse { | ||
/// The title of the refactoring action. | ||
var title: String | ||
|
||
/// The URI of the file where the macro is used | ||
var uri: DocumentURI | ||
|
||
/// The resulting array of `RefactoringEdit` of a semantic refactoring request | ||
var edits: [RefactoringEdit] | ||
|
||
init(title: String, uri: DocumentURI, refactoringEdits: [RefactoringEdit]) { | ||
self.title = title | ||
self.uri = uri | ||
self.edits = refactoringEdits.compactMap { refactoringEdit in | ||
if refactoringEdit.bufferName == nil && !refactoringEdit.newText.isEmpty { | ||
logger.fault("Unable to retrieve some parts of the expansion") | ||
return nil | ||
} | ||
|
||
return refactoringEdit | ||
} | ||
} | ||
} | ||
|
||
extension SwiftLanguageService { | ||
/// Handles the `ExpandMacroCommand`. | ||
/// | ||
/// Makes a request to sourcekitd and wraps the result into a `MacroExpansion` | ||
/// and then makes a `ShowDocumentRequest` to the client side for each | ||
/// expansion to be displayed. | ||
/// | ||
/// - Parameters: | ||
/// - expandMacroCommand: The `ExpandMacroCommand` that triggered this request. | ||
/// | ||
/// - Returns: A `[RefactoringEdit]` with the necessary edits and buffer name as a `LSPAny` | ||
func expandMacro( | ||
_ expandMacroCommand: ExpandMacroCommand | ||
) async throws -> LSPAny { | ||
guard let sourceKitLSPServer else { | ||
// `SourceKitLSPServer` has been destructed. We are tearing down the | ||
// language server. Nothing left to do. | ||
throw ResponseError.unknown("Connection to the editor closed") | ||
} | ||
|
||
guard let sourceFileURL = expandMacroCommand.textDocument.uri.fileURL else { | ||
throw ResponseError.unknown("Given URI is not a file URL") | ||
} | ||
|
||
let expansion = try await self.refactoring(expandMacroCommand) | ||
|
||
for macroEdit in expansion.edits { | ||
if let bufferName = macroEdit.bufferName { | ||
// buffer name without ".swift" | ||
let macroExpansionBufferDirectoryName = | ||
bufferName.hasSuffix(".swift") | ||
? String(bufferName.dropLast(6)) | ||
: bufferName | ||
|
||
let macroExpansionBufferDirectoryURL = self.generatedMacroExpansionsPath | ||
.appendingPathComponent(macroExpansionBufferDirectoryName) | ||
do { | ||
try FileManager.default.createDirectory( | ||
at: macroExpansionBufferDirectoryURL, | ||
withIntermediateDirectories: true | ||
) | ||
} catch { | ||
throw ResponseError.unknown( | ||
"Failed to create directory for macro expansion buffer at path: \(macroExpansionBufferDirectoryURL.path)" | ||
) | ||
} | ||
|
||
// name of the source file | ||
let macroExpansionFileName = sourceFileURL.deletingPathExtension().lastPathComponent | ||
|
||
// github permalink notation for position range | ||
let macroExpansionPositionRangeIndicator = | ||
"L\(macroEdit.range.lowerBound.line)C\(macroEdit.range.lowerBound.utf16index)-L\(macroEdit.range.upperBound.line)C\(macroEdit.range.upperBound.utf16index)" | ||
|
||
let macroExpansionFilePath = | ||
macroExpansionBufferDirectoryURL | ||
.appendingPathComponent( | ||
"\(macroExpansionFileName)_\(macroExpansionPositionRangeIndicator).\(sourceFileURL.pathExtension)" | ||
) | ||
|
||
do { | ||
try macroEdit.newText.write(to: macroExpansionFilePath, atomically: true, encoding: .utf8) | ||
} catch { | ||
throw ResponseError.unknown( | ||
"Unable to write macro expansion to file path: \"\(macroExpansionFilePath.path)\"" | ||
) | ||
} | ||
|
||
Task { | ||
let req = ShowDocumentRequest(uri: DocumentURI(macroExpansionFilePath), selection: macroEdit.range) | ||
|
||
let response = await orLog("Sending ShowDocumentRequest to Client") { | ||
try await sourceKitLSPServer.sendRequestToClient(req) | ||
} | ||
|
||
if let response, !response.success { | ||
logger.error("client refused to show document for \(expansion.title, privacy: .public)") | ||
} | ||
} | ||
} else if !macroEdit.newText.isEmpty { | ||
logger.fault("Unable to retrieve some parts of macro expansion") | ||
} | ||
} | ||
|
||
return expansion.edits.encodeToLSPAny() | ||
lokesh-tr marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
//===----------------------------------------------------------------------===// | ||
// | ||
// This source file is part of the Swift.org open source project | ||
// | ||
// Copyright (c) 2014 - 2024 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 | ||
// | ||
//===----------------------------------------------------------------------===// | ||
|
||
import LanguageServerProtocol | ||
import SourceKitD | ||
|
||
/// A protocol to be utilised by all commands that are served by sourcekitd refactorings. | ||
protocol RefactorCommand: SwiftCommand { | ||
/// The response type of the refactor command | ||
associatedtype Response: RefactoringResponse | ||
|
||
/// The sourcekitd identifier of the refactoring action. | ||
var actionString: String { get set } | ||
|
||
/// The range to refactor. | ||
var positionRange: Range<Position> { get set } | ||
|
||
/// The text document related to the refactoring action. | ||
var textDocument: TextDocumentIdentifier { get set } | ||
|
||
init(title: String, actionString: String, positionRange: Range<Position>, textDocument: TextDocumentIdentifier) | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.