|
| 1 | +//===----------------------------------------------------------------------===// |
| 2 | +// |
| 3 | +// This source file is part of the Swift.org open source project |
| 4 | +// |
| 5 | +// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors |
| 6 | +// Licensed under Apache License v2.0 with Runtime Library Exception |
| 7 | +// |
| 8 | +// See https://swift.org/LICENSE.txt for license information |
| 9 | +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors |
| 10 | +// |
| 11 | +//===----------------------------------------------------------------------===// |
| 12 | + |
| 13 | +import Foundation |
| 14 | +import LanguageServerProtocol |
| 15 | + |
| 16 | +import struct TSCBasic.AbsolutePath |
| 17 | +import class TSCBasic.Process |
| 18 | +import func TSCBasic.withTemporaryFile |
| 19 | + |
| 20 | +fileprivate extension String { |
| 21 | + init?(bytes: [UInt8], encoding: Encoding) { |
| 22 | + let data = bytes.withUnsafeBytes { buffer in |
| 23 | + guard let baseAddress = buffer.baseAddress else { |
| 24 | + return Data() |
| 25 | + } |
| 26 | + return Data(bytes: baseAddress, count: buffer.count) |
| 27 | + } |
| 28 | + self.init(data: data, encoding: encoding) |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +/// If a parent directory of `fileURI` contains a `.swift-format` file, return the path to that file. |
| 33 | +/// Otherwise, return `nil`. |
| 34 | +private func swiftFormatFile(for fileURI: DocumentURI) -> AbsolutePath? { |
| 35 | + guard var path = try? AbsolutePath(validating: fileURI.pseudoPath) else { |
| 36 | + return nil |
| 37 | + } |
| 38 | + repeat { |
| 39 | + path = path.parentDirectory |
| 40 | + let configFile = path.appending(component: ".swift-format") |
| 41 | + if FileManager.default.isReadableFile(atPath: configFile.pathString) { |
| 42 | + return configFile |
| 43 | + } |
| 44 | + } while !path.isRoot |
| 45 | + return nil |
| 46 | +} |
| 47 | + |
| 48 | +/// If a `.swift-format` file is discovered that applies to `fileURI`, return the path to that file. |
| 49 | +/// Otherwise, return a JSON object containing the configuration parameters from `options`. |
| 50 | +/// |
| 51 | +/// The result of this function can be passed to the `--configuration` parameter of swift-format. |
| 52 | +private func swiftFormatConfiguration( |
| 53 | + for fileURI: DocumentURI, |
| 54 | + options: FormattingOptions |
| 55 | +) throws -> String { |
| 56 | + if let configFile = swiftFormatFile(for: fileURI) { |
| 57 | + // If we find a .swift-format file, we ignore the options passed to us by the editor. |
| 58 | + // Most likely, the editor inferred them from the current document and thus the options |
| 59 | + // passed by the editor are most likely less correct than those in .swift-format. |
| 60 | + return configFile.pathString |
| 61 | + } |
| 62 | + |
| 63 | + // The following options are not supported by swift-format and ignored: |
| 64 | + // - trimTrailingWhitespace: swift-format always trims trailing whitespace |
| 65 | + // - insertFinalNewline: swift-format always inserts a final newline to the file |
| 66 | + // - trimFinalNewlines: swift-format always trims final newlines |
| 67 | + |
| 68 | + if options.insertSpaces { |
| 69 | + return """ |
| 70 | + { |
| 71 | + "version": 1, |
| 72 | + "tabWidth": \(options.tabSize), |
| 73 | + "indentation": { "spaces": \(options.tabSize) } |
| 74 | + } |
| 75 | + """ |
| 76 | + } else { |
| 77 | + return """ |
| 78 | + { |
| 79 | + "version": 1, |
| 80 | + "tabWidth": \(options.tabSize), |
| 81 | + "indentation": { "tabs": 1 } |
| 82 | + } |
| 83 | + """ |
| 84 | + } |
| 85 | +} |
| 86 | + |
| 87 | +extension CollectionDifference.Change { |
| 88 | + var offset: Int { |
| 89 | + switch self { |
| 90 | + case .insert(offset: let offset, element: _, associatedWith: _): |
| 91 | + return offset |
| 92 | + case .remove(offset: let offset, element: _, associatedWith: _): |
| 93 | + return offset |
| 94 | + } |
| 95 | + } |
| 96 | +} |
| 97 | + |
| 98 | +/// Compute the text edits that need to be made to transform `original` into `edited`. |
| 99 | +private func edits(from original: DocumentSnapshot, to edited: String) -> [TextEdit] { |
| 100 | + let difference = edited.difference(from: original.text) |
| 101 | + |
| 102 | + // `Collection.difference` returns sequential edits that are expected to be applied on-by-one. Offsets reference |
| 103 | + // the string that results if all previous edits are applied. |
| 104 | + // LSP expects concurrent edits that are applied simultaneously. Translate between them. |
| 105 | + |
| 106 | + struct StringBasedEdit { |
| 107 | + /// Offset into the collection originalString. |
| 108 | + /// Ie. to get a string index out of this, run `original(original.startIndex, offsetBy: range.lowerBound)`. |
| 109 | + var range: Range<Int> |
| 110 | + /// The string the range is being replaced with. |
| 111 | + var replacement: String |
| 112 | + } |
| 113 | + |
| 114 | + var edits: [StringBasedEdit] = [] |
| 115 | + for change in difference { |
| 116 | + // Adjust the index offset based on changes that `Collection.difference` expects to already have been applied. |
| 117 | + var adjustment: Int = 0 |
| 118 | + for edit in edits { |
| 119 | + if edit.range.upperBound < change.offset { |
| 120 | + adjustment = adjustment + edit.range.count - edit.replacement.count |
| 121 | + } |
| 122 | + } |
| 123 | + let adjustedOffset = change.offset + adjustment |
| 124 | + let edit = |
| 125 | + switch change { |
| 126 | + case .insert(offset: _, element: let element, associatedWith: _): |
| 127 | + StringBasedEdit(range: adjustedOffset..<adjustedOffset, replacement: String(element)) |
| 128 | + case .remove(offset: _, element: _, associatedWith: _): |
| 129 | + StringBasedEdit(range: adjustedOffset..<(adjustedOffset + 1), replacement: "") |
| 130 | + } |
| 131 | + |
| 132 | + // If we have an existing edit that is adjacent to this one, merge them. |
| 133 | + // Otherwise, just append them. |
| 134 | + if let mergableEditIndex = edits.firstIndex(where: { |
| 135 | + $0.range.upperBound == edit.range.lowerBound || edit.range.upperBound == $0.range.lowerBound |
| 136 | + }) { |
| 137 | + let mergableEdit = edits[mergableEditIndex] |
| 138 | + if mergableEdit.range.upperBound == edit.range.lowerBound { |
| 139 | + edits[mergableEditIndex] = StringBasedEdit( |
| 140 | + range: mergableEdit.range.lowerBound..<edit.range.upperBound, |
| 141 | + replacement: mergableEdit.replacement + edit.replacement |
| 142 | + ) |
| 143 | + } else { |
| 144 | + precondition(edit.range.upperBound == mergableEdit.range.lowerBound) |
| 145 | + edits[mergableEditIndex] = StringBasedEdit( |
| 146 | + range: edit.range.lowerBound..<mergableEdit.range.upperBound, |
| 147 | + replacement: edit.replacement + mergableEdit.replacement |
| 148 | + ) |
| 149 | + } |
| 150 | + } else { |
| 151 | + edits.append(edit) |
| 152 | + } |
| 153 | + } |
| 154 | + |
| 155 | + // Map the string-based edits to line-column based edits to be consumed by LSP |
| 156 | + |
| 157 | + return edits.map { edit in |
| 158 | + let (startLine, startColumn) = original.lineTable.lineAndUTF16ColumnOf( |
| 159 | + original.text.index(original.text.startIndex, offsetBy: edit.range.lowerBound) |
| 160 | + ) |
| 161 | + let (endLine, endColumn) = original.lineTable.lineAndUTF16ColumnOf( |
| 162 | + original.text.index(original.text.startIndex, offsetBy: edit.range.upperBound) |
| 163 | + ) |
| 164 | + |
| 165 | + return TextEdit( |
| 166 | + range: Position(line: startLine, utf16index: startColumn)..<Position(line: endLine, utf16index: endColumn), |
| 167 | + newText: edit.replacement |
| 168 | + ) |
| 169 | + } |
| 170 | +} |
| 171 | + |
| 172 | +extension SwiftLanguageServer { |
| 173 | + public func documentFormatting(_ req: DocumentFormattingRequest) async throws -> [TextEdit]? { |
| 174 | + let snapshot = try documentManager.latestSnapshot(req.textDocument.uri) |
| 175 | + |
| 176 | + guard let swiftFormat else { |
| 177 | + throw ResponseError.unknown( |
| 178 | + "Formatting not supported because the toolchain is missing the swift-format executable" |
| 179 | + ) |
| 180 | + } |
| 181 | + |
| 182 | + let process = TSCBasic.Process( |
| 183 | + args: swiftFormat.pathString, |
| 184 | + "format", |
| 185 | + "--configuration", |
| 186 | + try swiftFormatConfiguration(for: req.textDocument.uri, options: req.options) |
| 187 | + ) |
| 188 | + let writeStream = try process.launch() |
| 189 | + |
| 190 | + // Send the file to format to swift-format's stdin. That way we don't have to write it to a file. |
| 191 | + writeStream.send(snapshot.text) |
| 192 | + try writeStream.close() |
| 193 | + |
| 194 | + let result = try await process.waitUntilExit() |
| 195 | + guard result.exitStatus == .terminated(code: 0) else { |
| 196 | + let swiftFormatErrorMessage: String |
| 197 | + switch result.stderrOutput { |
| 198 | + case .success(let stderrBytes): |
| 199 | + swiftFormatErrorMessage = String(bytes: stderrBytes, encoding: .utf8) ?? "unknown error" |
| 200 | + case .failure(let error): |
| 201 | + swiftFormatErrorMessage = String(describing: error) |
| 202 | + } |
| 203 | + throw ResponseError.unknown( |
| 204 | + """ |
| 205 | + Running swift-format failed |
| 206 | + \(swiftFormatErrorMessage) |
| 207 | + """ |
| 208 | + ) |
| 209 | + } |
| 210 | + let formattedBytes: [UInt8] |
| 211 | + switch result.output { |
| 212 | + case .success(let bytes): |
| 213 | + formattedBytes = bytes |
| 214 | + case .failure(let error): |
| 215 | + throw error |
| 216 | + } |
| 217 | + |
| 218 | + guard let formattedString = String(bytes: formattedBytes, encoding: .utf8) else { |
| 219 | + throw ResponseError.unknown("Failed to decode response from swift-format as UTF-8") |
| 220 | + } |
| 221 | + |
| 222 | + return edits(from: snapshot, to: formattedString) |
| 223 | + } |
| 224 | +} |
0 commit comments