1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 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 BuildServerProtocol
import Foundation
import LSPLogging
import LanguageServerProtocol
import LanguageServerProtocolJSONRPC
import SKSupport
import SwiftExtensions
import struct TSCBasic.AbsolutePath
import protocol TSCBasic.FileSystem
import struct TSCBasic.FileSystemError
import func TSCBasic.getEnvSearchPaths
import var TSCBasic.localFileSystem
import func TSCBasic.lookupExecutablePath
import func TSCBasic.resolveSymlinks
enum BuildServerTestError: Error {
case executableNotFound(String)
}
func executable(_ name: String) -> String {
#if os(Windows)
guard !name.hasSuffix(".exe") else { return name }
return "\(name).exe"
#else
return name
#endif
}
/// A `BuildSystem` based on communicating with a build server
///
/// Provides build settings from a build server launched based on a
/// `buildServer.json` configuration file provided in the repo root.
public actor BuildServerBuildSystem: MessageHandler {
public let projectRoot: AbsolutePath
let serverConfig: BuildServerConfig
var buildServer: JSONRPCConnection?
/// The queue on which all messages that originate from the build server are
/// handled.
///
/// These are requests and notifications sent *from* the build server,
/// not replies from the build server.
///
/// This ensures that messages from the build server are handled in the order
/// they were received. Swift concurrency does not guarentee in-order
/// execution of tasks.
public let bspMessageHandlingQueue = AsyncQueue<Serial>()
let searchPaths: [AbsolutePath]
public private(set) var indexDatabasePath: AbsolutePath?
public private(set) var indexStorePath: AbsolutePath?
// FIXME: Add support for prefix mappings to the Build Server protocol.
public var indexPrefixMappings: [PathPrefixMapping] { return [] }
/// Delegate to handle any build system events.
public weak var delegate: BuildSystemDelegate?
/// - Note: Needed to set the delegate from a different actor isolation context
public func setDelegate(_ delegate: BuildSystemDelegate?) async {
self.delegate = delegate
}
/// The build settings that have been received from the build server.
private var buildSettings: [DocumentURI: FileBuildSettings] = [:]
public init(
projectRoot: AbsolutePath,
fileSystem: FileSystem = localFileSystem
) async throws {
let configPath = projectRoot.appending(component: "buildServer.json")
let config = try loadBuildServerConfig(path: configPath, fileSystem: fileSystem)
#if os(Windows)
self.searchPaths =
getEnvSearchPaths(
pathString: ProcessInfo.processInfo.environment["Path"],
currentWorkingDirectory: fileSystem.currentWorkingDirectory
)
#else
self.searchPaths =
getEnvSearchPaths(
pathString: ProcessInfo.processInfo.environment["PATH"],
currentWorkingDirectory: fileSystem.currentWorkingDirectory
)
#endif
self.projectRoot = projectRoot
self.serverConfig = config
try await self.initializeBuildServer()
}
/// Creates a build system using the Build Server Protocol config.
///
/// - Returns: nil if `projectRoot` has no config or there is an error parsing it.
public init?(projectRoot: AbsolutePath?) async {
guard let projectRoot else { return nil }
do {
try await self.init(projectRoot: projectRoot)
} catch is FileSystemError {
// config file was missing, no build server for this workspace
return nil
} catch {
logger.fault("Failed to start build server: \(error.forLogging)")
return nil
}
}
deinit {
if let buildServer = self.buildServer {
_ = buildServer.send(ShutdownBuild()) { result in
if let error = result.failure {
logger.fault("Error shutting down build server: \(error.forLogging)")
}
buildServer.send(ExitBuildNotification())
buildServer.close()
}
}
}
private func initializeBuildServer() async throws {
var serverPath = try AbsolutePath(validating: serverConfig.argv[0], relativeTo: projectRoot)
var flags = Array(serverConfig.argv[1...])
if serverPath.suffix == ".py" {
flags = [serverPath.pathString] + flags
guard
let interpreterPath =
lookupExecutablePath(
filename: executable("python3"),
searchPaths: searchPaths
)
?? lookupExecutablePath(
filename: executable("python"),
searchPaths: searchPaths
)
else {
throw BuildServerTestError.executableNotFound("python3")
}
serverPath = interpreterPath
}
let languages = [
Language.c,
Language.cpp,
Language.objective_c,
Language.objective_cpp,
Language.swift,
]
let initializeRequest = InitializeBuild(
displayName: "SourceKit-LSP",
version: "1.0",
bspVersion: "2.0",
rootUri: URI(self.projectRoot.asURL),
capabilities: BuildClientCapabilities(languageIds: languages)
)
let buildServer = try makeJSONRPCBuildServer(client: self, serverPath: serverPath, serverFlags: flags)
let response = try await buildServer.send(initializeRequest)
buildServer.send(InitializedBuildNotification())
logger.log("Initialized build server \(response.displayName)")
// see if index store was set as part of the server metadata
if let indexDbPath = readReponseDataKey(data: response.data, key: "indexDatabasePath") {
self.indexDatabasePath = try AbsolutePath(validating: indexDbPath, relativeTo: self.projectRoot)
}
if let indexStorePath = readReponseDataKey(data: response.data, key: "indexStorePath") {
self.indexStorePath = try AbsolutePath(validating: indexStorePath, relativeTo: self.projectRoot)
}
self.buildServer = buildServer
}
/// Handler for notifications received **from** the builder server, ie.
/// the build server has sent us a notification.
///
/// We need to notify the delegate about any updated build settings.
public nonisolated func handle(_ params: some NotificationType) {
logger.info(
"""
Received notification from build server:
\(params.forLogging)
"""
)
bspMessageHandlingQueue.async {
if let params = params as? BuildTargetsChangedNotification {
await self.handleBuildTargetsChanged(params)
} else if let params = params as? FileOptionsChangedNotification {
await self.handleFileOptionsChanged(params)
}
}
}
/// Handler for requests received **from** the build server.
///
/// We currently can't handle any requests sent from the build server to us.
public nonisolated func handle<R: RequestType>(
_ params: R,
id: RequestID,
reply: @escaping (LSPResult<R.Response>) -> Void
) {
logger.info(
"""
Received request from build server:
\(params.forLogging)
"""
)
reply(.failure(ResponseError.methodNotFound(R.method)))
}
func handleBuildTargetsChanged(
_ notification: BuildTargetsChangedNotification
) async {
await self.delegate?.buildTargetsChanged(notification.changes)
}
func handleFileOptionsChanged(
_ notification: FileOptionsChangedNotification
) async {
let result = notification.updatedOptions
let settings = FileBuildSettings(
compilerArguments: result.options,
workingDirectory: result.workingDirectory
)
await self.buildSettingsChanged(for: notification.uri, settings: settings)
}
/// Record the new build settings for the given document and inform the delegate
/// about the changed build settings.
private func buildSettingsChanged(for document: DocumentURI, settings: FileBuildSettings?) async {
buildSettings[document] = settings
await self.delegate?.fileBuildSettingsChanged([document])
}
}
private func readReponseDataKey(data: LSPAny?, key: String) -> String? {
if case .dictionary(let dataDict)? = data,
case .string(let stringVal)? = dataDict[key]
{
return stringVal
}
return nil
}
extension BuildServerBuildSystem: BuildSystem {
public nonisolated var supportsPreparation: Bool { false }
/// The build settings for the given file.
///
/// Returns `nil` if no build settings have been received from the build
/// server yet or if no build settings are available for this file.
public func buildSettings(
for document: DocumentURI,
in target: ConfiguredTarget,
language: Language
) async -> FileBuildSettings? {
return buildSettings[document]
}
public func defaultLanguage(for document: DocumentURI) async -> Language? {
return nil
}
public func toolchain(for uri: DocumentURI, _ language: Language) async -> SKCore.Toolchain? {
return nil
}
public func configuredTargets(for document: DocumentURI) async -> [ConfiguredTarget] {
return [ConfiguredTarget(targetID: "dummy", runDestinationID: "dummy")]
}
public func generateBuildGraph(allowFileSystemWrites: Bool) {}
public func topologicalSort(of targets: [ConfiguredTarget]) async -> [ConfiguredTarget]? {
return nil
}
public func targets(dependingOn targets: [ConfiguredTarget]) -> [ConfiguredTarget]? {
return nil
}
public func prepare(
targets: [ConfiguredTarget],
logMessageToIndexLog: @Sendable (_ taskID: IndexTaskID, _ message: String) -> Void
) async throws {
throw PrepareNotSupportedError()
}
public func registerForChangeNotifications(for uri: DocumentURI) {
let request = RegisterForChanges(uri: uri, action: .register)
_ = self.buildServer?.send(request) { result in
if let error = result.failure {
logger.error("Error registering \(uri): \(error.forLogging)")
Task {
// BuildServer registration failed, so tell our delegate that no build
// settings are available.
await self.buildSettingsChanged(for: uri, settings: nil)
}
}
}
}
/// Unregister the given file for build-system level change notifications, such as command
/// line flag changes, dependency changes, etc.
public func unregisterForChangeNotifications(for uri: DocumentURI) {
let request = RegisterForChanges(uri: uri, action: .unregister)
_ = self.buildServer?.send(request) { result in
if let error = result.failure {
logger.error("Error unregistering \(uri.forLogging): \(error.forLogging)")
}
}
}
public func filesDidChange(_ events: [FileEvent]) {}
public func fileHandlingCapability(for uri: DocumentURI) -> FileHandlingCapability {
guard
let fileUrl = uri.fileURL,
let path = try? AbsolutePath(validating: fileUrl.path)
else {
return .unhandled
}
// FIXME: We should not make any assumptions about which files the build server can handle.
// Instead we should query the build server which files it can handle (#492).
if projectRoot.isAncestorOfOrEqual(to: path) {
return .handled
}
if let realpath = try? resolveSymlinks(path), realpath != path, projectRoot.isAncestorOfOrEqual(to: realpath) {
return .handled
}
return .unhandled
}
public func sourceFiles() async -> [SourceFileInfo] {
// BuildServerBuildSystem does not support syntactic test discovery or background indexing.
// (https://github.com/swiftlang/sourcekit-lsp/issues/1173).
return []
}
public func addSourceFilesDidChangeCallback(_ callback: @escaping () async -> Void) {
// BuildServerBuildSystem does not support syntactic test discovery or background indexing.
// (https://github.com/swiftlang/sourcekit-lsp/issues/1173).
}
}
private func loadBuildServerConfig(path: AbsolutePath, fileSystem: FileSystem) throws -> BuildServerConfig {
let decoder = JSONDecoder()
let fileData = try fileSystem.readFileContents(path).contents
return try decoder.decode(BuildServerConfig.self, from: Data(fileData))
}
struct BuildServerConfig: Codable {
/// The name of the build tool.
let name: String
/// The version of the build tool.
let version: String
/// The bsp version of the build tool.
let bspVersion: String
/// A collection of languages supported by this BSP server.
let languages: [String]
/// Command arguments runnable via system processes to start a BSP server.
let argv: [String]
}
private func makeJSONRPCBuildServer(
client: MessageHandler,
serverPath: AbsolutePath,
serverFlags: [String]?
) throws -> JSONRPCConnection {
let clientToServer = Pipe()
let serverToClient = Pipe()
let connection = JSONRPCConnection(
name: "build server",
protocol: BuildServerProtocol.bspRegistry,
inFD: serverToClient.fileHandleForReading,
outFD: clientToServer.fileHandleForWriting
)
connection.start(receiveHandler: client) {
// FIXME: keep the pipes alive until we close the connection. This
// should be fixed systemically.
withExtendedLifetime((clientToServer, serverToClient)) {}
}
let process = Foundation.Process()
process.executableURL = serverPath.asURL
process.arguments = serverFlags
process.standardOutput = serverToClient
process.standardInput = clientToServer
process.terminationHandler = { process in
logger.log(
level: process.terminationReason == .exit ? .default : .error,
"Build server exited: \(String(reflecting: process.terminationReason)) \(process.terminationStatus)"
)
connection.close()
}
try process.run()
return connection
}
|