diff --git a/.vscode/launch.json b/.vscode/launch.json index 01a73b222..bf881902f 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -7,7 +7,7 @@ "program": "${workspaceFolder:sourcekit-lsp}/.build/debug/sourcekit-lsp", "args": [], "cwd": "${workspaceFolder:sourcekit-lsp}", - "preLaunchTask": "swift: Build Debug sourcekit-lsp", + "preLaunchTask": "swift: Build Debug sourcekit-lsp" }, { "type": "swift", @@ -16,7 +16,7 @@ "program": "${workspaceFolder:sourcekit-lsp}/.build/release/sourcekit-lsp", "args": [], "cwd": "${workspaceFolder:sourcekit-lsp}", - "preLaunchTask": "swift: Build Release sourcekit-lsp", + "preLaunchTask": "swift: Build Release sourcekit-lsp" }, { "type": "swift", @@ -24,6 +24,24 @@ "name": "Attach sourcekit-lsp (debug)", "program": "${workspaceFolder:sourcekit-lsp}/.build/debug/sourcekit-lsp", "waitFor": true + }, + { + "type": "swift", + "request": "launch", + "args": [], + "cwd": "${workspaceFolder:sourcekit-lsp}/SourceKitLSPDevUtils", + "name": "Debug sourcekit-lsp-dev-utils (SourceKitLSPDevUtils)", + "program": "${workspaceFolder:sourcekit-lsp}/SourceKitLSPDevUtils/.build/debug/sourcekit-lsp-dev-utils", + "preLaunchTask": "swift: Build Debug sourcekit-lsp-dev-utils (SourceKitLSPDevUtils)" + }, + { + "type": "swift", + "request": "launch", + "args": [], + "cwd": "${workspaceFolder:sourcekit-lsp}/SourceKitLSPDevUtils", + "name": "Release sourcekit-lsp-dev-utils (SourceKitLSPDevUtils)", + "program": "${workspaceFolder:sourcekit-lsp}/SourceKitLSPDevUtils/.build/release/sourcekit-lsp-dev-utils", + "preLaunchTask": "swift: Build Release sourcekit-lsp-dev-utils (SourceKitLSPDevUtils)" } ] } diff --git a/Contributor Documentation/BSP Extensions.md b/Contributor Documentation/BSP Extensions.md index 19e5371dd..cb28c6f3d 100644 --- a/Contributor Documentation/BSP Extensions.md +++ b/Contributor Documentation/BSP Extensions.md @@ -78,7 +78,7 @@ export interface SourceKitSourceItemData { /** The language of the source file. If `nil`, the language is inferred from the file extension. */ language?: LanguageId; - /** + /** * The kind of source file that this source item represents. If omitted, the item is assumed to be a normal source * file, ie. omitting this key is equivalent to specifying it as `source`. */ @@ -172,7 +172,7 @@ export interface SourceKitBuildTarget { ## `workspace/didChangeWatchedFiles` -Notification sent from SourceKit-LSP to the build system to indicate that files within the project have been modified. +Notification sent from SourceKit-LSP to the build server to indicate that files within the project have been modified. SourceKit-LSP may send file change notifications for a superset of the files that the BSP server requested to watch in `watchers`. It is the BSP server’s responsibility to filter the file watch notifications for the ones it is actually interested in. @@ -182,6 +182,6 @@ Definition is the same as in LSP. This request is a no-op and doesn't have any effects. -If the build system is currently updating the build graph, this request should return after those updates have finished processing. +If the build server is currently updating the build graph, this request should return after those updates have finished processing. - method: `workspace/waitForBuildSystemUpdates` diff --git a/Contributor Documentation/Background Indexing.md b/Contributor Documentation/Background Indexing.md index 4de8b1567..70fd43d80 100644 --- a/Contributor Documentation/Background Indexing.md +++ b/Contributor Documentation/Background Indexing.md @@ -12,9 +12,9 @@ Preparation of a target should perform the minimal amount of work to build all ` ### Status tracking -When SourceKit-LSP is launched, all targets are considered to be out-of-date. This needs to be done because source files might have changed since SourceKit-LSP was last started – if the module wasn’t modified since the last SourceKit-LSP launch, we re-prepare the target and rely on the build system to produce a fast null build. +When SourceKit-LSP is launched, all targets are considered to be out-of-date. This needs to be done because source files might have changed since SourceKit-LSP was last started – if the module wasn’t modified since the last SourceKit-LSP launch, we re-prepare the target and rely on the build server to produce a fast null build. -After we have prepared a target, we mark it as being up-to-date in `SemanticIndexManager.preparationUpToDateTracker`. That way we don’t need to invoke the build system every time we want to perform semantic functionality of a source file, which saves us the time of a null build (which can hundreds of milliseconds for SwiftPM). If a source file is changed (as noted through file watching), all of its target’s dependencies are marked as out-of-date. Note that the target that the source file belongs to is not marked as out-of-date – preparation of a target builds all dependencies but does not need to build the target’s module itself. The next operation that requires the target to be prepared will trigger a preparation job. +After we have prepared a target, we mark it as being up-to-date in `SemanticIndexManager.preparationUpToDateTracker`. That way we don’t need to invoke the build server every time we want to perform semantic functionality of a source file, which saves us the time of a null build (which can hundreds of milliseconds for SwiftPM). If a source file is changed (as noted through file watching), all of its target’s dependencies are marked as out-of-date. Note that the target that the source file belongs to is not marked as out-of-date – preparation of a target builds all dependencies but does not need to build the target’s module itself. The next operation that requires the target to be prepared will trigger a preparation job. ## Updating the index store diff --git a/Contributor Documentation/Implementing a BSP server.md b/Contributor Documentation/Implementing a BSP server.md index 3842a4b84..1b18f4c88 100644 --- a/Contributor Documentation/Implementing a BSP server.md +++ b/Contributor Documentation/Implementing a BSP server.md @@ -29,7 +29,7 @@ If the build system loads the entire build graph during initialization, it may i ## Supporting background indexing -To support background indexing, the build system must set `data.prepareProvider: true` in the `build/initialize` response and implement the `buildTarget/prepare` method. The compiler options used to prepare a target should match those sent for `textDocument/sourceKitOptions` in order to avoid mismatches when loading modules. +To support background indexing, the build server must set `data.prepareProvider: true` in the `build/initialize` response and implement the `buildTarget/prepare` method. The compiler options used to prepare a target should match those sent for `textDocument/sourceKitOptions` in order to avoid mismatches when loading modules. ## Optional methods diff --git a/Contributor Documentation/LSP Extensions.md b/Contributor Documentation/LSP Extensions.md index bbc53fca7..a9cc131ad 100644 --- a/Contributor Documentation/LSP Extensions.md +++ b/Contributor Documentation/LSP Extensions.md @@ -611,7 +611,7 @@ export interface SourceKitOptionsRequest { * If set to `true` and build settings could not be determined within a timeout (see `buildSettingsTimeout` in the * SourceKit-LSP configuration file), this request returns fallback build settings. * - * If set to `true` the request only finishes when build settings were provided by the build system. + * If set to `true` the request only finishes when build settings were provided by the build server. */ allowFallbackSettings: bool } diff --git a/Contributor Documentation/Modules.md b/Contributor Documentation/Modules.md index dfaf54ee6..ae454ba2f 100644 --- a/Contributor Documentation/Modules.md +++ b/Contributor Documentation/Modules.md @@ -6,9 +6,9 @@ The SourceKit-LSP package contains the following non-testing modules. Swift types to represent the [Build Server Protocol (BSP) specification](https://build-server-protocol.github.io/docs/specification). These types should also be usable when implementing a BSP client and thus this module should not have any dependencies other than the LanguageServerProtocol module, with which it shares some types. -### BuildSystemIntegration +### BuildServerIntegration -Defines the queries SourceKit-LSP can ask of a build system, like getting compiler arguments for a file, finding a target’s dependencies or preparing a target. +Defines the queries SourceKit-LSP can ask of a build server, like getting compiler arguments for a file, finding a target’s dependencies or preparing a target. ### CAtomics diff --git a/Contributor Documentation/Overview.md b/Contributor Documentation/Overview.md index 801ab8f81..81aeea182 100644 --- a/Contributor Documentation/Overview.md +++ b/Contributor Documentation/Overview.md @@ -18,12 +18,12 @@ For requests that require knowledge about the project’s index, like call hiera [sourcekitd](https://github.com/apple/swift/tree/main/tools/SourceKit) is implemented in the Swift compiler’s repository and uses the Swift compiler’s understanding of Swift code to provide semantic functionality. On macOS, sourcekitd is run as an XPC service and all other platforms sourcekitd is run in the sourcekit-lsp process. This means that on macOS, a crash of sourcekitd can be recovered by re-launching sourcekitd, while on other platforms a crash inside sourcekitd crashes sourcekit-lsp. -## Build systems +## Build servers -Basically all semantic functionality requires knowledge about how a file is being built (like module search paths to be able to resolve `import` statements). SourceKit-LSP consults a `BuildSystem` to get this information. Note that the term build system has a somewhat loose definition in SourceKit-LSP. It’s less about building the project and more about providing information that would be used if building the project. Build systems that are currently supported are: -- `SwiftPMBuildSystem`: Reads a `Package.swift` at the project’s root -- `CompilationDatabaseBuildSystem`: Reads a `compile_commands.json` file to provide build settings for files. `compile_commands.json` can eg. be generated by CMake. -- `BuildServerBuildSystem`: Launches an external build server process to provide build settings. +Basically all semantic functionality requires knowledge about how a file is being built (like module search paths to be able to resolve `import` statements). SourceKit-LSP consults a *build server* to get this information. Build servers that are currently supported are: +- `SwiftPMBuildServer`: Reads a `Package.swift` at the project’s root +- `CompilationDatabaseBuildServer`: Reads a `compile_commands.json` file to provide build settings for files. `compile_commands.json` can eg. be generated by CMake. +- `ExternalBuildServerAdapter`: Launches an external BSP server process to provide build settings. ## Logging diff --git a/Documentation/Configuration File.md b/Documentation/Configuration File.md index 055bb4c26..27e31a060 100644 --- a/Documentation/Configuration File.md +++ b/Documentation/Configuration File.md @@ -30,12 +30,12 @@ The structure of the file is currently not guaranteed to be stable. Options may - `disableSandbox: boolean`: Disables running subprocesses from SwiftPM in a sandbox. Equivalent to SwiftPM's `--disable-sandbox` option. Useful when running `sourcekit-lsp` in a sandbox because nested sandboxes are not supported. - `compilationDatabase`: Dictionary with the following keys, defining options for workspaces with a compilation database. - `searchPaths: string[]`: Additional paths to search for a compilation database, relative to a workspace root. -- `fallbackBuildSystem`: Dictionary with the following keys, defining options for files that aren't managed by any build system. +- `fallbackBuildSystem`: Dictionary with the following keys, defining options for files that aren't managed by any build server. - `cCompilerFlags: string[]`: Extra arguments passed to the compiler for C files. - `cxxCompilerFlags: string[]`: Extra arguments passed to the compiler for C++ files. - `swiftCompilerFlags: string[]`: Extra arguments passed to the compiler for Swift files. - `sdk: string`: The SDK to use for fallback arguments. Default is to infer the SDK using `xcrun`. -- `buildSettingsTimeout: integer`: Number of milliseconds to wait for build settings from the build system before using fallback build settings. +- `buildSettingsTimeout: integer`: Number of milliseconds to wait for build settings from the build server before using fallback build settings. - `clangdOptions: string[]`: Extra command line arguments passed to `clangd` when launching it. - `index`: Options related to indexing. - `indexPrefixMap: [string: string]`: Path remappings for remapping index data for local use. diff --git a/Package.swift b/Package.swift index b7930e0a1..3d51c8ad5 100644 --- a/Package.swift +++ b/Package.swift @@ -37,7 +37,7 @@ var targets: [Target] = [ .executableTarget( name: "sourcekit-lsp", dependencies: [ - "BuildSystemIntegration", + "BuildServerIntegration", "Diagnose", "LanguageServerProtocol", "LanguageServerProtocolExtensions", @@ -74,10 +74,10 @@ var targets: [Target] = [ swiftSettings: globalSwiftSettings ), - // MARK: BuildSystemIntegration + // MARK: BuildServerIntegration .target( - name: "BuildSystemIntegration", + name: "BuildServerIntegration", dependencies: [ "BuildServerProtocol", "LanguageServerProtocol", @@ -101,9 +101,9 @@ var targets: [Target] = [ ), .testTarget( - name: "BuildSystemIntegrationTests", + name: "BuildServerIntegrationTests", dependencies: [ - "BuildSystemIntegration", + "BuildServerIntegration", "LanguageServerProtocol", "SKOptions", "SKTestSupport", @@ -183,7 +183,7 @@ var targets: [Target] = [ .target( name: "Diagnose", dependencies: [ - "BuildSystemIntegration", + "BuildServerIntegration", "InProcessClient", "LanguageServerProtocolExtensions", "SKLogging", @@ -204,7 +204,7 @@ var targets: [Target] = [ .testTarget( name: "DiagnoseTests", dependencies: [ - "BuildSystemIntegration", + "BuildServerIntegration", "Diagnose", "SKLogging", "SKTestSupport", @@ -221,7 +221,7 @@ var targets: [Target] = [ name: "DocCDocumentation", dependencies: [ "BuildServerProtocol", - "BuildSystemIntegration", + "BuildServerIntegration", "LanguageServerProtocol", "SemanticIndex", "SKLogging", @@ -239,7 +239,7 @@ var targets: [Target] = [ .target( name: "InProcessClient", dependencies: [ - "BuildSystemIntegration", + "BuildServerIntegration", "LanguageServerProtocol", "SKLogging", "SKOptions", @@ -313,7 +313,7 @@ var targets: [Target] = [ name: "SemanticIndex", dependencies: [ "BuildServerProtocol", - "BuildSystemIntegration", + "BuildServerIntegration", "LanguageServerProtocol", "LanguageServerProtocolExtensions", "SKLogging", @@ -428,7 +428,7 @@ var targets: [Target] = [ .target( name: "SKTestSupport", dependencies: [ - "BuildSystemIntegration", + "BuildServerIntegration", "CSKTestSupport", "Csourcekitd", "InProcessClient", @@ -481,7 +481,7 @@ var targets: [Target] = [ .testTarget( name: "SourceKitDTests", dependencies: [ - "BuildSystemIntegration", + "BuildServerIntegration", "SourceKitD", "SKTestSupport", "SwiftExtensions", @@ -496,7 +496,7 @@ var targets: [Target] = [ name: "SourceKitLSP", dependencies: [ "BuildServerProtocol", - "BuildSystemIntegration", + "BuildServerIntegration", "DocCDocumentation", "LanguageServerProtocol", "LanguageServerProtocolExtensions", @@ -529,7 +529,7 @@ var targets: [Target] = [ name: "SourceKitLSPTests", dependencies: [ "BuildServerProtocol", - "BuildSystemIntegration", + "BuildServerIntegration", "LanguageServerProtocol", "LanguageServerProtocolExtensions", "SemanticIndex", @@ -643,7 +643,7 @@ var targets: [Target] = [ .testTarget( name: "SwiftSourceKitPluginTests", dependencies: [ - "BuildSystemIntegration", + "BuildServerIntegration", "CompletionScoring", "Csourcekitd", "LanguageServerProtocol", diff --git a/Sources/BuildSystemIntegration/BuildSystemHooks.swift b/Sources/BuildServerIntegration/BuildServerHooks.swift similarity index 95% rename from Sources/BuildSystemIntegration/BuildSystemHooks.swift rename to Sources/BuildServerIntegration/BuildServerHooks.swift index 68f170c56..cb2d14d93 100644 --- a/Sources/BuildSystemIntegration/BuildSystemHooks.swift +++ b/Sources/BuildServerIntegration/BuildServerHooks.swift @@ -26,16 +26,16 @@ package struct SwiftPMTestHooks: Sendable { } } -package struct BuildSystemHooks: Sendable { +package struct BuildServerHooks: Sendable { package var swiftPMTestHooks: SwiftPMTestHooks - /// A hook that will be executed before a request is handled by a `BuiltInBuildSystem`. + /// A hook that will be executed before a request is handled by a `BuiltInBuildServer`. /// /// This allows requests to be artificially delayed. package var preHandleRequest: (@Sendable (any RequestType) async -> Void)? /// When running SourceKit-LSP in-process, allows the creator of `SourceKitLSPServer` to create a message handler that - /// handles BSP requests instead of SourceKit-LSP creating build systems as needed. + /// handles BSP requests instead of SourceKit-LSP creating build server as needed. package var injectBuildServer: (@Sendable (_ projectRoot: URL, _ connectionToSourceKitLSP: any Connection) async -> any Connection)? diff --git a/Sources/BuildSystemIntegration/BuildSystemManager.swift b/Sources/BuildServerIntegration/BuildServerManager.swift similarity index 87% rename from Sources/BuildSystemIntegration/BuildSystemManager.swift rename to Sources/BuildServerIntegration/BuildServerManager.swift index ca127874a..c50351893 100644 --- a/Sources/BuildSystemIntegration/BuildSystemManager.swift +++ b/Sources/BuildServerIntegration/BuildServerManager.swift @@ -70,7 +70,7 @@ package struct SourceFileInfo: Sendable { package var mayContainTests: Bool /// Source files returned here fall into two categories: - /// - Buildable source files are files that can be built by the build system and that make sense to background index + /// - Buildable source files are files that can be built by the build server and that make sense to background index /// - Non-buildable source files include eg. the SwiftPM package manifest or header files. We have sufficient /// compiler arguments for these files to provide semantic editor functionality but we can't build them. package var isBuildable: Bool @@ -134,21 +134,21 @@ fileprivate extension InitializeBuildResponse { } } -/// A build system adapter is responsible for receiving messages from the `BuildSystemManager` and forwarding them to -/// the build system. For built-in build systems, this means that we need to translate the BSP messages to methods in -/// the `BuiltInBuildSystem` protocol. For external (aka. out-of-process, aka. BSP servers) build systems, this means -/// that we need to manage the external build system's lifetime. -private enum BuildSystemAdapter { - case builtIn(BuiltInBuildSystemAdapter, connectionToBuildSystem: any Connection) - case external(ExternalBuildSystemAdapter) +/// A build server adapter is responsible for receiving messages from the `BuildServerManager` and forwarding them to +/// the build server. For built-in build servers, this means that we need to translate the BSP messages to methods in +/// the `BuiltInBuildServer` protocol. For external (aka. out-of-process, aka. BSP servers) build servers, this means +/// that we need to manage the external build server's lifetime. +private enum BuildServerAdapter { + case builtIn(BuiltInBuildServerAdapter, connectionToBuildServer: any Connection) + case external(ExternalBuildServerAdapter) /// A message handler that was created by `injectBuildServer` and will handle all BSP messages. case injected(any Connection) /// Send a notification to the build server. func send(_ notification: some NotificationType) async { switch self { - case .builtIn(_, let connectionToBuildSystem): - connectionToBuildSystem.send(notification) + case .builtIn(_, let connectionToBuildServer): + connectionToBuildServer.send(notification) case .external(let external): await external.send(notification) case .injected(let connection): @@ -159,8 +159,8 @@ private enum BuildSystemAdapter { /// Send a request to the build server. func send(_ request: Request) async throws -> Request.Response { switch self { - case .builtIn(_, let connectionToBuildSystem): - return try await connectionToBuildSystem.send(request) + case .builtIn(_, let connectionToBuildServer): + return try await connectionToBuildServer.send(request) case .external(let external): return try await external.send(request) case .injected(let messageHandler): @@ -194,93 +194,93 @@ private enum BuildSystemAdapter { } } -private extension BuildSystemSpec { - private func createBuiltInBuildSystemAdapter( +private extension BuildServerSpec { + private func createBuiltInBuildServerAdapter( messagesToSourceKitLSPHandler: any MessageHandler, - buildSystemHooks: BuildSystemHooks, - _ createBuildSystem: @Sendable (_ connectionToSourceKitLSP: any Connection) async throws -> BuiltInBuildSystem? - ) async -> BuildSystemAdapter? { + buildServerHooks: BuildServerHooks, + _ createBuildServer: @Sendable (_ connectionToSourceKitLSP: any Connection) async throws -> BuiltInBuildServer? + ) async -> BuildServerAdapter? { let connectionToSourceKitLSP = LocalConnection( - receiverName: "BuildSystemManager for \(projectRoot.lastPathComponent)", + receiverName: "BuildServerManager for \(projectRoot.lastPathComponent)", handler: messagesToSourceKitLSPHandler ) - let buildSystem = await orLog("Creating build system") { - try await createBuildSystem(connectionToSourceKitLSP) + let buildServer = await orLog("Creating build server") { + try await createBuildServer(connectionToSourceKitLSP) } - guard let buildSystem else { - logger.log("Failed to create build system at \(projectRoot)") + guard let buildServer else { + logger.log("Failed to create build server at \(projectRoot)") return nil } - logger.log("Created \(type(of: buildSystem), privacy: .public) at \(projectRoot)") - let buildSystemAdapter = BuiltInBuildSystemAdapter( - underlyingBuildSystem: buildSystem, + logger.log("Created \(type(of: buildServer), privacy: .public) at \(projectRoot)") + let buildServerAdapter = BuiltInBuildServerAdapter( + underlyingBuildServer: buildServer, connectionToSourceKitLSP: connectionToSourceKitLSP, - buildSystemHooks: buildSystemHooks + buildServerHooks: buildServerHooks ) - let connectionToBuildSystem = LocalConnection( - receiverName: "\(type(of: buildSystem)) for \(projectRoot.lastPathComponent)", - handler: buildSystemAdapter + let connectionToBuildServer = LocalConnection( + receiverName: "\(type(of: buildServer)) for \(projectRoot.lastPathComponent)", + handler: buildServerAdapter ) - return .builtIn(buildSystemAdapter, connectionToBuildSystem: connectionToBuildSystem) + return .builtIn(buildServerAdapter, connectionToBuildServer: connectionToBuildServer) } - /// Create a `BuildSystemAdapter` that manages a build system of this kind and return a connection that can be used - /// to send messages to the build system. - func createBuildSystemAdapter( + /// Create a `BuildServerAdapter` that manages a build server of this kind and return a connection that can be used + /// to send messages to the build server. + func createBuildServerAdapter( toolchainRegistry: ToolchainRegistry, options: SourceKitLSPOptions, - buildSystemHooks: BuildSystemHooks, + buildServerHooks: BuildServerHooks, messagesToSourceKitLSPHandler: any MessageHandler - ) async -> BuildSystemAdapter? { + ) async -> BuildServerAdapter? { switch self.kind { - case .buildServer: - let buildSystem = await orLog("Creating external build system") { - try await ExternalBuildSystemAdapter( + case .externalBuildServer: + let buildServer = await orLog("Creating external build server") { + try await ExternalBuildServerAdapter( projectRoot: projectRoot, configPath: configPath, messagesToSourceKitLSPHandler: messagesToSourceKitLSPHandler ) } - guard let buildSystem else { - logger.log("Failed to create external build system at \(projectRoot)") + guard let buildServer else { + logger.log("Failed to create external build server at \(projectRoot)") return nil } logger.log("Created external build server at \(projectRoot)") - return .external(buildSystem) + return .external(buildServer) case .jsonCompilationDatabase: - return await createBuiltInBuildSystemAdapter( + return await createBuiltInBuildServerAdapter( messagesToSourceKitLSPHandler: messagesToSourceKitLSPHandler, - buildSystemHooks: buildSystemHooks + buildServerHooks: buildServerHooks ) { connectionToSourceKitLSP in - try JSONCompilationDatabaseBuildSystem( + try JSONCompilationDatabaseBuildServer( configPath: configPath, toolchainRegistry: toolchainRegistry, connectionToSourceKitLSP: connectionToSourceKitLSP ) } case .fixedCompilationDatabase: - return await createBuiltInBuildSystemAdapter( + return await createBuiltInBuildServerAdapter( messagesToSourceKitLSPHandler: messagesToSourceKitLSPHandler, - buildSystemHooks: buildSystemHooks + buildServerHooks: buildServerHooks ) { connectionToSourceKitLSP in - try FixedCompilationDatabaseBuildSystem( + try FixedCompilationDatabaseBuildServer( configPath: configPath, connectionToSourceKitLSP: connectionToSourceKitLSP ) } case .swiftPM: #if !NO_SWIFTPM_DEPENDENCY - return await createBuiltInBuildSystemAdapter( + return await createBuiltInBuildServerAdapter( messagesToSourceKitLSPHandler: messagesToSourceKitLSPHandler, - buildSystemHooks: buildSystemHooks + buildServerHooks: buildServerHooks ) { connectionToSourceKitLSP in - try await SwiftPMBuildSystem( + try await SwiftPMBuildServer( projectRoot: projectRoot, toolchainRegistry: toolchainRegistry, options: options, connectionToSourceKitLSP: connectionToSourceKitLSP, - testHooks: buildSystemHooks.swiftPMTestHooks + testHooks: buildServerHooks.swiftPMTestHooks ) } #else @@ -288,7 +288,7 @@ private extension BuildSystemSpec { #endif case .injected(let injector): let connectionToSourceKitLSP = LocalConnection( - receiverName: "BuildSystemManager for \(projectRoot.lastPathComponent)", + receiverName: "BuildServerManager for \(projectRoot.lastPathComponent)", handler: messagesToSourceKitLSPHandler ) return .injected( @@ -298,48 +298,48 @@ private extension BuildSystemSpec { } } -/// Entry point for all build system queries. -package actor BuildSystemManager: QueueBasedMessageHandler { +/// Entry point for all build server queries. +package actor BuildServerManager: QueueBasedMessageHandler { package let messageHandlingHelper = QueueBasedMessageHandlerHelper( - signpostLoggingCategory: "build-system-manager-message-handling", + signpostLoggingCategory: "build-server-manager-message-handling", createLoggingScope: false ) - package let messageHandlingQueue = AsyncQueue() + package let messageHandlingQueue = AsyncQueue() - /// The path to the main configuration file (or directory) that this build system manages. + /// The path to the main configuration file (or directory) that this build server manages. /// /// Some examples: /// - The path to `Package.swift` for SwiftPM packages /// - The path to `compile_commands.json` for a JSON compilation database /// - /// `nil` if the `BuildSystemManager` does not have an underlying build system. + /// `nil` if the `BuildServerManager` does not have an underlying build server. package let configPath: URL? /// The files for which the delegate has requested change notifications, ie. the files for which the delegate wants to /// get `fileBuildSettingsChanged` and `filesDependenciesUpdated` callbacks. private var watchedFiles: [DocumentURI: (mainFile: DocumentURI, language: Language)] = [:] - private var connectionToClient: BuildSystemManagerConnectionToClient + private var connectionToClient: BuildServerManagerConnectionToClient - /// The build system adapter that is used to answer build system queries. - private var buildSystemAdapter: BuildSystemAdapter? + /// The build serer adapter that is used to answer build server queries. + private var buildServerAdapter: BuildServerAdapter? - /// The build system adapter after initialization finishes. When sending messages to the BSP server, this should be - /// preferred over `buildSystemAdapter` because no messages must be sent to the build server before initialization + /// The build server adapter after initialization finishes. When sending messages to the BSP server, this should be + /// preferred over `buildServerAdapter` because no messages must be sent to the build server before initialization /// finishes. - private var buildSystemAdapterAfterInitialized: BuildSystemAdapter? { + private var buildServerAdapterAfterInitialized: BuildServerAdapter? { get async { _ = await initializeResult.value - return buildSystemAdapter + return buildServerAdapter } } /// Provider of file to main file mappings. private var mainFilesProvider: MainFilesProvider? - /// Build system delegate that will receive notifications about setting changes, etc. - private weak var delegate: BuildSystemManagerDelegate? + /// Build server delegate that will receive notifications about setting changes, etc. + private weak var delegate: BuildServerManagerDelegate? /// The list of toolchains that are available. /// @@ -359,8 +359,8 @@ package actor BuildSystemManager: QueueBasedMessageHandler { } } - /// For tasks from the build system that should create a work done progress in the client, a mapping from the `TaskId` - /// in the build system to a `WorkDoneProgressManager` that manages that work done progress in the client. + /// For tasks from the build server that should create a work done progress in the client, a mapping from the `TaskId` + /// in the build server to a `WorkDoneProgressManager` that manages that work done progress in the client. private var workDoneProgressManagers: [TaskIdentifier: WorkDoneProgressManager] = [:] /// Debounces calls to `delegate.filesDependenciesUpdated`. @@ -381,7 +381,7 @@ package actor BuildSystemManager: QueueBasedMessageHandler { /// Debounces calls to `delegate.fileBuildSettingsChanged`. /// - /// This helps in the following situation: A build system takes 5s to return build settings for a file and we have 10 + /// This helps in the following situation: A build server takes 5s to return build settings for a file and we have 10 /// requests for those build settings coming in that time period. Once we get build settings, we get 10 calls to /// `resultReceivedAfterTimeout` in `buildSettings(for:in:language:fallbackAfterTimeout:)`, all for the same document. /// But calling `fileBuildSettingsChanged` once is totally sufficient. @@ -440,20 +440,20 @@ package actor BuildSystemManager: QueueBasedMessageHandler { } package init( - buildSystemSpec: BuildSystemSpec?, + buildServerSpec: BuildServerSpec?, toolchainRegistry: ToolchainRegistry, options: SourceKitLSPOptions, - connectionToClient: BuildSystemManagerConnectionToClient, - buildSystemHooks: BuildSystemHooks + connectionToClient: BuildServerManagerConnectionToClient, + buildServerHooks: BuildServerHooks ) async { self.toolchainRegistry = toolchainRegistry self.options = options self.connectionToClient = connectionToClient - self.configPath = buildSystemSpec?.configPath - self.buildSystemAdapter = await buildSystemSpec?.createBuildSystemAdapter( + self.configPath = buildServerSpec?.configPath + self.buildServerAdapter = await buildServerSpec?.createBuildServerAdapter( toolchainRegistry: toolchainRegistry, options: options, - buildSystemHooks: buildSystemHooks, + buildServerHooks: buildServerHooks, messagesToSourceKitLSPHandler: WeakMessageHandler(self) ) @@ -464,7 +464,7 @@ package actor BuildSystemManager: QueueBasedMessageHandler { ) { [weak self] (filesWithUpdatedDependencies) in guard let self, let delegate = await self.delegate else { - logger.fault("Not calling filesDependenciesUpdated because no delegate exists in SwiftPMBuildSystem") + logger.fault("Not calling filesDependenciesUpdated because no delegate exists in SwiftPMBuildServer") return } let changedWatchedFiles = await self.watchedFilesReferencing(mainFiles: filesWithUpdatedDependencies) @@ -483,7 +483,7 @@ package actor BuildSystemManager: QueueBasedMessageHandler { ) { [weak self] (filesWithChangedBuildSettings) in guard let self, let delegate = await self.delegate else { - logger.fault("Not calling fileBuildSettingsChanged because no delegate exists in SwiftPMBuildSystem") + logger.fault("Not calling fileBuildSettingsChanged because no delegate exists in SwiftPMBuildServer") return } if !filesWithChangedBuildSettings.isEmpty { @@ -494,44 +494,44 @@ package actor BuildSystemManager: QueueBasedMessageHandler { // TODO: Forward file watch patterns from this initialize request to the client // (https://github.com/swiftlang/sourcekit-lsp/issues/1671) initializeResult = Task { () -> InitializeBuildResponse? in - guard let buildSystemAdapter else { + guard let buildServerAdapter else { return nil } - guard let buildSystemSpec else { - logger.fault("If we have a connectionToBuildSystem, we must have had a buildSystemSpec") + guard let buildServerSpec else { + logger.fault("If we have a connectionToBuildServer, we must have had a buildServerSpec") return nil } - let initializeResponse = await orLog("Initializing build system") { - try await buildSystemAdapter.send( + let initializeResponse = await orLog("Initializing build server") { + try await buildServerAdapter.send( InitializeBuildRequest( displayName: "SourceKit-LSP", version: "", bspVersion: "2.2.0", - rootUri: URI(buildSystemSpec.projectRoot), + rootUri: URI(buildServerSpec.projectRoot), capabilities: BuildClientCapabilities(languageIds: [.c, .cpp, .objective_c, .objective_cpp, .swift]) ) ) } if let initializeResponse, !(initializeResponse.sourceKitData?.sourceKitOptionsProvider ?? false), - case .external(let externalBuildSystemAdapter) = buildSystemAdapter + case .external(let externalBuildServerAdapter) = buildServerAdapter { - // The BSP server does not support the pull-based settings model. Inject a `LegacyBuildServerBuildSystem` that - // offers the pull-based model to `BuildSystemManager` and uses the push-based model to get build settings from + // The BSP server does not support the pull-based settings model. Inject a `LegacyBuildServerBuildServer` that + // offers the pull-based model to `BuildServerManager` and uses the push-based model to get build settings from // the build server. logger.log("Launched a legacy BSP server. Using push-based build settings model.") - let legacyBuildServer = await LegacyBuildServerBuildSystem( - projectRoot: buildSystemSpec.projectRoot, - configPath: buildSystemSpec.configPath, + let legacyBuildServer = await LegacyBuildServer( + projectRoot: buildServerSpec.projectRoot, + configPath: buildServerSpec.configPath, initializationData: initializeResponse, - externalBuildSystemAdapter + externalBuildServerAdapter ) - let adapter = BuiltInBuildSystemAdapter( - underlyingBuildSystem: legacyBuildServer, + let adapter = BuiltInBuildServerAdapter( + underlyingBuildServer: legacyBuildServer, connectionToSourceKitLSP: legacyBuildServer.connectionToSourceKitLSP, - buildSystemHooks: buildSystemHooks + buildServerHooks: buildServerHooks ) - let connectionToBuildSystem = LocalConnection(receiverName: "Legacy BSP server", handler: adapter) - self.buildSystemAdapter = .builtIn(adapter, connectionToBuildSystem: connectionToBuildSystem) + let connectionToBuildSerer = LocalConnection(receiverName: "Legacy BSP server", handler: adapter) + self.buildServerAdapter = .builtIn(adapter, connectionToBuildServer: connectionToBuildSerer) } Task { var filesToWatch = initializeResponse?.sourceKitData?.watchers ?? [] @@ -541,68 +541,68 @@ package actor BuildSystemManager: QueueBasedMessageHandler { } await connectionToClient.watchFiles(filesToWatch) } - await buildSystemAdapter.send(OnBuildInitializedNotification()) + await buildServerAdapter.send(OnBuildInitializedNotification()) return initializeResponse } } /// Explicitly shut down the build server. /// - /// The build server is automatically shut down using a background task when `BuildSystemManager` is deallocated. + /// The build server is automatically shut down using a background task when `BuildServerManager` is deallocated. /// This, however, leads to possible race conditions where the shutdown task might not finish before the test is done, /// which could result in the connection being reported as a leak. To avoid this problem, we want to explicitly shut /// down the build server when the `SourceKitLSPServer` gets shut down. package func shutdown() async { // Clear any pending work done progresses from the build server. self.workDoneProgressManagers.removeAll() - guard let buildSystemAdapter = await self.buildSystemAdapterAfterInitialized else { + guard let buildServerAdapter = await self.buildServerAdapterAfterInitialized else { return } await orLog("Sending shutdown request to build server") { // Give the build server 2 seconds to shut down by itself. If it doesn't shut down within that time, terminate it. try await withTimeout(.seconds(2)) { - _ = try await buildSystemAdapter.send(BuildShutdownRequest()) - await buildSystemAdapter.send(OnBuildExitNotification()) + _ = try await buildServerAdapter.send(BuildShutdownRequest()) + await buildServerAdapter.send(OnBuildExitNotification()) } } - if case .external(let externalBuildSystemAdapter) = buildSystemAdapter { + if case .external(let externalBuildServerAdapter) = buildServerAdapter { await orLog("Terminating external build server") { // Give the build server 1 second to exit after receiving the `build/exit` notification. If it doesn't exit // within that time, terminate it. - try await externalBuildSystemAdapter.terminateIfRunning(after: .seconds(1)) + try await externalBuildServerAdapter.terminateIfRunning(after: .seconds(1)) } } - self.buildSystemAdapter = nil + self.buildServerAdapter = nil } deinit { // Shut down the build server before closing the connection to it - Task { [buildSystemAdapter, initializeResult] in - guard let buildSystemAdapter else { + Task { [buildServerAdapter, initializeResult] in + guard let buildServerAdapter else { return } // We are accessing the raw connection to the build server, so we need to ensure that it has been initialized here _ = await initializeResult?.value await orLog("Sending shutdown request to build server") { - _ = try await buildSystemAdapter.send(BuildShutdownRequest()) - await buildSystemAdapter.send(OnBuildExitNotification()) + _ = try await buildServerAdapter.send(BuildShutdownRequest()) + await buildServerAdapter.send(OnBuildExitNotification()) } } } - /// - Note: Needed because `BuildSystemManager` is created before `Workspace` is initialized and `Workspace` needs to - /// create the `BuildSystemManager`, then initialize itself and then set itself as the delegate. - package func setDelegate(_ delegate: BuildSystemManagerDelegate?) { + /// - Note: Needed because `BuildSererManager` is created before `Workspace` is initialized and `Workspace` needs to + /// create the `BuildServerManager`, then initialize itself and then set itself as the delegate. + package func setDelegate(_ delegate: BuildServerManagerDelegate?) { self.delegate = delegate } - /// - Note: Needed because we need the `indexStorePath` and `indexDatabasePath` from the build system to create an + /// - Note: Needed because we need the `indexStorePath` and `indexDatabasePath` from the build server to create an /// IndexStoreDB, which serves as the `MainFilesProvider`. And thus this can't be set during initialization. package func setMainFilesProvider(_ mainFilesProvider: MainFilesProvider?) { self.mainFilesProvider = mainFilesProvider } - // MARK: Handling messages from the build system + // MARK: Handling messages from the build server package func handle(notification: some NotificationType) async { switch notification { @@ -718,7 +718,7 @@ package actor BuildSystemManager: QueueBasedMessageHandler { workDoneProgressManagers[notification.taskId.id] = nil } - // MARK: Build System queries + // MARK: Build server queries /// Returns the toolchain that should be used to process the given document. package func toolchain( @@ -761,8 +761,8 @@ package actor BuildSystemManager: QueueBasedMessageHandler { } } - /// Ask the build system if it explicitly specifies a language for this document. Return `nil` if it does not. - private func languageInferredFromBuildSystem( + /// Ask the build server if it explicitly specifies a language for this document. Return `nil` if it does not. + private func languageInferredFromBuildServer( for document: DocumentURI, in target: BuildTargetIdentifier ) async throws -> Language? { @@ -785,10 +785,10 @@ package actor BuildSystemManager: QueueBasedMessageHandler { /// Returns the language that a document should be interpreted in for background tasks where the editor doesn't /// specify the document's language. package func defaultLanguage(for document: DocumentURI, in target: BuildTargetIdentifier) async -> Language? { - let languageFromBuildSystem = await orLog("Getting source files to determine default language") { - try await languageInferredFromBuildSystem(for: document, in: target) + let languageFromBuildServer = await orLog("Getting source files to determine default language") { + try await languageInferredFromBuildServer(for: document, in: target) } - return languageFromBuildSystem ?? Language(inferredFromFileExtension: document) + return languageFromBuildServer ?? Language(inferredFromFileExtension: document) } /// Retrieve information about the given source file within the build server. @@ -864,15 +864,15 @@ package actor BuildSystemManager: QueueBasedMessageHandler { } } - /// Returns the build settings for `document` from `buildSystem`. + /// Returns the build settings for `document` from `buildServer`. /// /// Implementation detail of `buildSettings(for:language:)`. - private func buildSettingsFromBuildSystem( + private func buildSettingsFromBuildServer( for document: DocumentURI, in target: BuildTargetIdentifier, language: Language ) async throws -> FileBuildSettings? { - guard let buildSystemAdapter = await buildSystemAdapterAfterInitialized else { + guard let buildServerAdapter = await buildServerAdapterAfterInitialized else { return nil } let request = TextDocumentSourceKitOptionsRequest( @@ -881,7 +881,7 @@ package actor BuildSystemManager: QueueBasedMessageHandler { language: language ) let response = try await cachedAdjustedSourceKitOptions.get(request, isolation: self) { request in - let options = try await buildSystemAdapter.send(request) + let options = try await buildServerAdapter.send(request) switch language.semanticKind { case .swift: return options?.adjustArgsForSemanticSwiftFunctionality(fileToIndex: document) @@ -922,19 +922,19 @@ package actor BuildSystemManager: QueueBasedMessageHandler { fallbackAfterTimeout: Bool ) async -> FileBuildSettings? { if let target { - let buildSettingsFromBuildSystem = await orLog("Getting build settings") { + let buildSettingsFromBuildServer = await orLog("Getting build settings") { if fallbackAfterTimeout { try await withTimeout(options.buildSettingsTimeoutOrDefault) { - return try await self.buildSettingsFromBuildSystem(for: document, in: target, language: language) + return try await self.buildSettingsFromBuildServer(for: document, in: target, language: language) } resultReceivedAfterTimeout: { await self.filesBuildSettingsChangedDebouncer.scheduleCall([document]) } } else { - try await self.buildSettingsFromBuildSystem(for: document, in: target, language: language) + try await self.buildSettingsFromBuildServer(for: document, in: target, language: language) } } - if let buildSettingsFromBuildSystem { - return buildSettingsFromBuildSystem + if let buildSettingsFromBuildServer { + return buildSettingsFromBuildServer } } @@ -947,8 +947,8 @@ package actor BuildSystemManager: QueueBasedMessageHandler { else { return nil } - if buildSystemAdapter == nil { - // If there is no build system and we only have the fallback build system, we will never get real build settings. + if buildServerAdapter == nil { + // If there is no build server and we only have the fallback build server, we will never get real build settings. // Consider the build settings non-fallback. settings.isFallback = false } @@ -965,7 +965,7 @@ package actor BuildSystemManager: QueueBasedMessageHandler { /// When a target is passed in, the build settings for the document, interpreted as part of that target, are returned, /// otherwise a canonical target is inferred for the source file. /// - /// If no language is passed, this method tries to infer the language of the document from the build system. If that + /// If no language is passed, this method tries to infer the language of the document from the build server. If that /// fails, it returns `nil`. package func buildSettingsInferredFromMainFile( for document: DocumentURI, @@ -996,7 +996,7 @@ package actor BuildSystemManager: QueueBasedMessageHandler { } else if let language = Language(inferredFromFileExtension: mainFile) { languageForFile = language } else { - // We don't know the language as which to interpret the document, so we can't ask the build system for its + // We don't know the language as which to interpret the document, so we can't ask the build server for its // settings. return nil } @@ -1038,12 +1038,12 @@ package actor BuildSystemManager: QueueBasedMessageHandler { } package func waitForUpToDateBuildGraph() async { - await orLog("Waiting for build system updates") { - let _: VoidResponse? = try await buildSystemAdapterAfterInitialized?.send( + await orLog("Waiting for build server updates") { + let _: VoidResponse? = try await buildServerAdapterAfterInitialized?.send( WorkspaceWaitForBuildSystemUpdatesRequest() ) } - // Handle any messages the build system might have sent us while updating. + // Handle any messages the build server might have sent us while updating. await messageHandlingQueue.async(metadata: .stateChange) {}.valuePropagatingCancellation // Ensure that we send out all delegate calls so that everybody is informed about the changes. @@ -1113,7 +1113,7 @@ package actor BuildSystemManager: QueueBasedMessageHandler { } package func prepare(targets: Set) async throws { - let _: VoidResponse? = try await buildSystemAdapterAfterInitialized?.send( + let _: VoidResponse? = try await buildServerAdapterAfterInitialized?.send( BuildTargetPrepareRequest(targets: targets.sorted { $0.uri.stringValue < $1.uri.stringValue }) ) await orLog("Calling fileDependenciesUpdated") { @@ -1132,13 +1132,13 @@ package actor BuildSystemManager: QueueBasedMessageHandler { } private func buildTargets() async throws -> [BuildTargetIdentifier: BuildTargetInfo] { - guard let buildSystemAdapter = await buildSystemAdapterAfterInitialized else { + guard let buildServerAdapter = await buildServerAdapterAfterInitialized else { return [:] } let request = WorkspaceBuildTargetsRequest() let result = try await cachedBuildTargets.get(request, isolation: self) { request in - let buildTargets = try await buildSystemAdapter.send(request).targets + let buildTargets = try await buildServerAdapter.send(request).targets let (depths, dependents) = await self.targetDepthsAndDependents(for: buildTargets) var result: [BuildTargetIdentifier: BuildTargetInfo] = [:] result.reserveCapacity(buildTargets.count) @@ -1172,7 +1172,7 @@ package actor BuildSystemManager: QueueBasedMessageHandler { } package func sourceFiles(in targets: Set) async throws -> [SourcesItem] { - guard let buildSystemAdapter = await buildSystemAdapterAfterInitialized, !targets.isEmpty else { + guard let buildServerAdapter = await buildServerAdapterAfterInitialized, !targets.isEmpty else { return [] } @@ -1192,7 +1192,7 @@ package actor BuildSystemManager: QueueBasedMessageHandler { } let response = try await cachedTargetSources.get(request, isolation: self) { request in - try await buildSystemAdapter.send(request) + try await buildServerAdapter.send(request) } return response.items } @@ -1230,7 +1230,7 @@ package actor BuildSystemManager: QueueBasedMessageHandler { return try await sourceFilesAndDirectories().buildableSourceFiles } - /// Get all files and directories that are known to the build system, ie. that are returned by a `buildTarget/sources` + /// Get all files and directories that are known to the build server, ie. that are returned by a `buildTarget/sources` /// request for any target in the project. /// /// - Important: This method returns both buildable and non-buildable source files. Callers need to check @@ -1337,8 +1337,8 @@ package actor BuildSystemManager: QueueBasedMessageHandler { /// Returns all main files that include the given document. /// /// On Darwin platforms, this also performs the following normalization: indexstore-db by itself returns realpaths - /// but the build system might be using standardized Darwin paths (eg. realpath is `/private/tmp` but the standardized - /// path is `/tmp`). If the realpath that indexstore-db returns could not be found in the build system's source files + /// but the build server might be using standardized Darwin paths (eg. realpath is `/private/tmp` but the standardized + /// path is `/tmp`). If the realpath that indexstore-db returns could not be found in the build server's source files /// but the standardized path is part of the source files, return the standardized path instead. package func mainFiles(containing uri: DocumentURI) async -> [DocumentURI] { guard let mainFilesProvider else { @@ -1351,7 +1351,7 @@ package actor BuildSystemManager: QueueBasedMessageHandler { if mainFile == uri { // Do not apply the standardized file normalization to the source file itself. Otherwise we would get the // following behavior: - // - We have a build system that uses standardized file paths and index a file as /tmp/test.c + // - We have a build server that uses standardized file paths and index a file as /tmp/test.c // - We are asking for the main files of /private/tmp/test.c // - Since indexstore-db uses realpath for everything, we find the unit for /tmp/test.c as a unit containg // /private/tmp/test.c, which has /private/tmp/test.c as the main file. @@ -1385,11 +1385,11 @@ package actor BuildSystemManager: QueueBasedMessageHandler { return self.watchedFiles[uri]?.mainFile } - // MARK: Informing BuildSystemManager about changes + // MARK: Informing BuildSererManager about changes package func filesDidChange(_ events: [FileEvent]) async { - if let buildSystemAdapter = await buildSystemAdapterAfterInitialized { - await buildSystemAdapter.send(OnWatchedFilesDidChangeNotification(changes: events)) + if let buildServerAdapter = await buildServerAdapterAfterInitialized { + await buildServerAdapter.send(OnWatchedFilesDidChangeNotification(changes: events)) } var targetsWithUpdatedDependencies: Set = [] @@ -1451,7 +1451,7 @@ package actor BuildSystemManager: QueueBasedMessageHandler { guard let language = watchedFiles[file]?.language else { continue } - // Re-register for notifications of this file within the build system. + // Re-register for notifications of this file within the build server. // This is the easiest way to make sure we are watching for build setting // changes of the new main file and stop watching for build setting // changes in the old main file if no other watched file depends on it. diff --git a/Sources/BuildSystemIntegration/BuildSystemManagerDelegate.swift b/Sources/BuildServerIntegration/BuildServerManagerDelegate.swift similarity index 78% rename from Sources/BuildSystemIntegration/BuildSystemManagerDelegate.swift rename to Sources/BuildServerIntegration/BuildServerManagerDelegate.swift index 0ccaa6895..d03c8e44c 100644 --- a/Sources/BuildSystemIntegration/BuildSystemManagerDelegate.swift +++ b/Sources/BuildServerIntegration/BuildServerManagerDelegate.swift @@ -13,9 +13,9 @@ package import BuildServerProtocol package import LanguageServerProtocol -/// Handles build system events, such as file build settings changes. -package protocol BuildSystemManagerDelegate: AnyObject, Sendable { - /// Notify the delegate that the result of `BuildSystemManager.buildSettingsInferredFromMainFile` might have changed +/// Handles build server events, such as file build settings changes. +package protocol BuildServerManagerDelegate: AnyObject, Sendable { + /// Notify the delegate that the result of `BuildServerManager.buildSettingsInferredFromMainFile` might have changed /// for the given files. func fileBuildSettingsChanged(_ changedFiles: Set) async @@ -32,12 +32,12 @@ package protocol BuildSystemManagerDelegate: AnyObject, Sendable { func buildTargetsChanged(_ changes: [BuildTargetEvent]?) async } -/// Methods with which the `BuildSystemManager` can send messages to the client (aka. editor). +/// Methods with which the `BuildServerManager` can send messages to the client (aka. editor). /// -/// This is distinct from `BuildSystemManagerDelegate` because the delegate only gets set on the build system after the -/// workspace that created it has been initialized (see `BuildSystemManager.setDelegate`). But the `BuildSystemManager` +/// This is distinct from `BuildServerManagerDelegate` because the delegate only gets set on the build server after the +/// workspace that created it has been initialized (see `BuildServerManager.setDelegate`). But the `BuildServerManager` /// can send notifications to the client immediately. -package protocol BuildSystemManagerConnectionToClient: Sendable, Connection { +package protocol BuildServerManagerConnectionToClient: Sendable, Connection { /// Whether the client can handle `WorkDoneProgress` requests. var clientSupportsWorkDoneProgress: Bool { get async } diff --git a/Sources/BuildSystemIntegration/BuildSystemMessageDependencyTracker.swift b/Sources/BuildServerIntegration/BuildServerMessageDependencyTracker.swift similarity index 96% rename from Sources/BuildSystemIntegration/BuildSystemMessageDependencyTracker.swift rename to Sources/BuildServerIntegration/BuildServerMessageDependencyTracker.swift index d145b0ba6..1850badce 100644 --- a/Sources/BuildSystemIntegration/BuildSystemMessageDependencyTracker.swift +++ b/Sources/BuildServerIntegration/BuildServerMessageDependencyTracker.swift @@ -18,7 +18,7 @@ import SwiftExtensions /// A lightweight way of describing tasks that are created from handling BSP /// requests or notifications for the purpose of dependency tracking. -package enum BuildSystemMessageDependencyTracker: QueueBasedMessageHandlerDependencyTracker { +package enum BuildServerMessageDependencyTracker: QueueBasedMessageHandlerDependencyTracker { /// A task that modifies some state. It is a barrier for all requests that read state. case stateChange @@ -31,7 +31,7 @@ package enum BuildSystemMessageDependencyTracker: QueueBasedMessageHandlerDepend case taskProgress /// Whether this request needs to finish before `other` can start executing. - package func isDependency(of other: BuildSystemMessageDependencyTracker) -> Bool { + package func isDependency(of other: BuildServerMessageDependencyTracker) -> Bool { switch (self, other) { case (.stateChange, .stateChange): return true case (.stateChange, .stateRead): return true diff --git a/Sources/BuildSystemIntegration/BuildSettingsLogger.swift b/Sources/BuildServerIntegration/BuildSettingsLogger.swift similarity index 100% rename from Sources/BuildSystemIntegration/BuildSettingsLogger.swift rename to Sources/BuildServerIntegration/BuildSettingsLogger.swift diff --git a/Sources/BuildSystemIntegration/BuildTargetIdentifierExtensions.swift b/Sources/BuildServerIntegration/BuildTargetIdentifierExtensions.swift similarity index 98% rename from Sources/BuildSystemIntegration/BuildTargetIdentifierExtensions.swift rename to Sources/BuildServerIntegration/BuildTargetIdentifierExtensions.swift index db38c3f4e..d853afb20 100644 --- a/Sources/BuildSystemIntegration/BuildTargetIdentifierExtensions.swift +++ b/Sources/BuildServerIntegration/BuildTargetIdentifierExtensions.swift @@ -25,7 +25,7 @@ package enum BuildDestinationIdentifier { /// A string that can be used to identify the build triple in a `BuildTargetIdentifier`. /// - /// `BuildSystemManager.canonicalBuildTargetIdentifier` picks the canonical target based on alphabetical + /// `BuildServerManager.canonicalBuildTargetIdentifier` picks the canonical target based on alphabetical /// ordering. We rely on the string "destination" being ordered before "tools" so that we prefer a /// `destination` (or "target") target over a `tools` (or "host") target. var id: String { diff --git a/Sources/BuildSystemIntegration/BuiltInBuildSystem.swift b/Sources/BuildServerIntegration/BuiltInBuildServer.swift similarity index 89% rename from Sources/BuildSystemIntegration/BuiltInBuildSystem.swift rename to Sources/BuildServerIntegration/BuiltInBuildServer.swift index 54457c5c6..814448e61 100644 --- a/Sources/BuildSystemIntegration/BuiltInBuildSystem.swift +++ b/Sources/BuildServerIntegration/BuiltInBuildServer.swift @@ -17,7 +17,7 @@ import SKLogging import SKOptions import ToolchainRegistry -/// An error build systems can throw from `prepare` if they don't support preparation of targets. +/// An error build servers can throw from `prepare` if they don't support preparation of targets. package struct PrepareNotSupportedError: Error, CustomStringConvertible { package init() {} @@ -25,7 +25,7 @@ package struct PrepareNotSupportedError: Error, CustomStringConvertible { } /// Provider of FileBuildSettings and other build-related information. -package protocol BuiltInBuildSystem: AnyObject, Sendable { +package protocol BuiltInBuildServer: AnyObject, Sendable { /// The files to watch for changes. var fileWatchers: [FileSystemWatcher] { get async } @@ -35,12 +35,12 @@ package protocol BuiltInBuildSystem: AnyObject, Sendable { /// The path to put the index database, if any. var indexDatabasePath: URL? { get async } - /// Whether the build system is capable of preparing a target for indexing and determining the output paths for the + /// Whether the build server is capable of preparing a target for indexing and determining the output paths for the /// target, ie. whether the `prepare` method has been implemented and this build server populates the `outputPath` /// property in the `buildTarget/sources` request. var supportsPreparationAndOutputPaths: Bool { get } - /// Returns all targets in the build system + /// Returns all targets in the build server func buildTargets(request: WorkspaceBuildTargetsRequest) async throws -> WorkspaceBuildTargetsResponse /// Returns all the source files in the given targets @@ -55,7 +55,7 @@ package protocol BuiltInBuildSystem: AnyObject, Sendable { /// Retrieve build settings for the given document. /// - /// Returns `nil` if the build system can't provide build settings for this file. + /// Returns `nil` if the build server can't provide build settings for this file. func sourceKitOptions( request: TextDocumentSourceKitOptionsRequest ) async throws -> TextDocumentSourceKitOptionsResponse? diff --git a/Sources/BuildSystemIntegration/BuiltInBuildSystemAdapter.swift b/Sources/BuildServerIntegration/BuiltInBuildServerAdapter.swift similarity index 66% rename from Sources/BuildSystemIntegration/BuiltInBuildSystemAdapter.swift rename to Sources/BuildServerIntegration/BuiltInBuildServerAdapter.swift index 2fbbcabde..a22396175 100644 --- a/Sources/BuildSystemIntegration/BuiltInBuildSystemAdapter.swift +++ b/Sources/BuildServerIntegration/BuiltInBuildServerAdapter.swift @@ -19,10 +19,10 @@ import SKOptions import SwiftExtensions import ToolchainRegistry -/// The details necessary to create a `BuildSystemAdapter`. -package struct BuildSystemSpec { +/// The details necessary to create a `BuildServerAdapter`. +package struct BuildServerSpec { package enum Kind { - case buildServer + case externalBuildServer case jsonCompilationDatabase case fixedCompilationDatabase case swiftPM @@ -33,47 +33,47 @@ package struct BuildSystemSpec { package var kind: Kind - /// The folder that best describes the root of the project that this build system handles. + /// The folder that best describes the root of the project that this build server handles. package var projectRoot: URL - /// The main path that provides the build system configuration. + /// The main path that provides the build server configuration. package var configPath: URL - package init(kind: BuildSystemSpec.Kind, projectRoot: URL, configPath: URL) { + package init(kind: BuildServerSpec.Kind, projectRoot: URL, configPath: URL) { self.kind = kind self.projectRoot = projectRoot self.configPath = configPath } } -/// A type that outwardly acts as a BSP build server and internally uses a `BuiltInBuildSystem` to satisfy the requests. -actor BuiltInBuildSystemAdapter: QueueBasedMessageHandler { +/// A type that outwardly acts as a BSP build server and internally uses a `BuiltInBuildServer` to satisfy the requests. +actor BuiltInBuildServerAdapter: QueueBasedMessageHandler { let messageHandlingHelper = QueueBasedMessageHandlerHelper( - signpostLoggingCategory: "build-system-message-handling", + signpostLoggingCategory: "build-server-message-handling", createLoggingScope: false ) - /// The queue on which all messages from SourceKit-LSP (or more specifically `BuildSystemManager`) are handled. - package let messageHandlingQueue = AsyncQueue() + /// The queue on which all messages from SourceKit-LSP (or more specifically `BuildServerManager`) are handled. + package let messageHandlingQueue = AsyncQueue() - /// The underlying build system - private var underlyingBuildSystem: BuiltInBuildSystem + /// The underlying build server + private var underlyingBuildServer: BuiltInBuildServer - /// The connection with which messages are sent to `BuildSystemManager`. + /// The connection with which messages are sent to `BuildServerManager`. private let connectionToSourceKitLSP: LocalConnection - private let buildSystemHooks: BuildSystemHooks + private let buildServerHooks: BuildServerHooks - /// Create a `BuiltInBuildSystemAdapter` form an existing `BuiltInBuildSystem` and connection to communicate messages - /// from the build system to SourceKit-LSP. + /// Create a `BuiltInBuildServerAdapter` form an existing `BuiltInBuildServer` and connection to communicate messages + /// from the build server to SourceKit-LSP. init( - underlyingBuildSystem: BuiltInBuildSystem, + underlyingBuildServer: BuiltInBuildServer, connectionToSourceKitLSP: LocalConnection, - buildSystemHooks: BuildSystemHooks + buildServerHooks: BuildServerHooks ) { - self.underlyingBuildSystem = underlyingBuildSystem + self.underlyingBuildServer = underlyingBuildServer self.connectionToSourceKitLSP = connectionToSourceKitLSP - self.buildSystemHooks = buildSystemHooks + self.buildServerHooks = buildServerHooks } deinit { @@ -82,22 +82,22 @@ actor BuiltInBuildSystemAdapter: QueueBasedMessageHandler { private func initialize(request: InitializeBuildRequest) async -> InitializeBuildResponse { return InitializeBuildResponse( - displayName: "\(type(of: underlyingBuildSystem))", + displayName: "\(type(of: underlyingBuildServer))", version: "", bspVersion: "2.2.0", capabilities: BuildServerCapabilities(), dataKind: .sourceKit, data: SourceKitInitializeBuildResponseData( indexDatabasePath: await orLog("getting index database file path") { - try await underlyingBuildSystem.indexDatabasePath?.filePath + try await underlyingBuildServer.indexDatabasePath?.filePath }, indexStorePath: await orLog("getting index store file path") { - try await underlyingBuildSystem.indexStorePath?.filePath + try await underlyingBuildServer.indexStorePath?.filePath }, - outputPathsProvider: underlyingBuildSystem.supportsPreparationAndOutputPaths, - prepareProvider: underlyingBuildSystem.supportsPreparationAndOutputPaths, + outputPathsProvider: underlyingBuildServer.supportsPreparationAndOutputPaths, + prepareProvider: underlyingBuildServer.supportsPreparationAndOutputPaths, sourceKitOptionsProvider: true, - watchers: await underlyingBuildSystem.fileWatchers + watchers: await underlyingBuildServer.fileWatchers ).encodeToLSPAny() ) } @@ -109,7 +109,7 @@ actor BuiltInBuildSystemAdapter: QueueBasedMessageHandler { case is OnBuildInitializedNotification: break case let notification as OnWatchedFilesDidChangeNotification: - await self.underlyingBuildSystem.didChangeWatchedFiles(notification: notification) + await self.underlyingBuildServer.didChangeWatchedFiles(notification: notification) default: logger.error("Ignoring unknown notification \(type(of: notification).method) from SourceKit-LSP") } @@ -121,22 +121,22 @@ actor BuiltInBuildSystemAdapter: QueueBasedMessageHandler { reply: @Sendable @escaping (LSPResult) -> Void ) async { let request = RequestAndReply(request, reply: reply) - await buildSystemHooks.preHandleRequest?(request.params) + await buildServerHooks.preHandleRequest?(request.params) switch request { case let request as RequestAndReply: await request.reply { VoidResponse() } case let request as RequestAndReply: - await request.reply { try await underlyingBuildSystem.prepare(request: request.params) } + await request.reply { try await underlyingBuildServer.prepare(request: request.params) } case let request as RequestAndReply: - await request.reply { try await underlyingBuildSystem.buildTargetSources(request: request.params) } + await request.reply { try await underlyingBuildServer.buildTargetSources(request: request.params) } case let request as RequestAndReply: await request.reply { await self.initialize(request: request.params) } case let request as RequestAndReply: - await request.reply { try await underlyingBuildSystem.sourceKitOptions(request: request.params) } + await request.reply { try await underlyingBuildServer.sourceKitOptions(request: request.params) } case let request as RequestAndReply: - await request.reply { try await underlyingBuildSystem.buildTargets(request: request.params) } + await request.reply { try await underlyingBuildServer.buildTargets(request: request.params) } case let request as RequestAndReply: - await request.reply { await underlyingBuildSystem.waitForBuildSystemUpdates(request: request.params) } + await request.reply { await underlyingBuildServer.waitForBuildSystemUpdates(request: request.params) } default: await request.reply { throw ResponseError.methodNotFound(Request.method) } } diff --git a/Sources/BuildServerIntegration/CMakeLists.txt b/Sources/BuildServerIntegration/CMakeLists.txt new file mode 100644 index 000000000..8e4d61f98 --- /dev/null +++ b/Sources/BuildServerIntegration/CMakeLists.txt @@ -0,0 +1,45 @@ + +add_library(BuildServerIntegration STATIC + BuildServerHooks.swift + BuildServerManager.swift + BuildServerManagerDelegate.swift + BuildServerMessageDependencyTracker.swift + BuildSettingsLogger.swift + BuildTargetIdentifierExtensions.swift + BuiltInBuildServer.swift + BuiltInBuildServerAdapter.swift + CMakeLists.txt + CompilationDatabase.swift + CompilerCommandLineOption.swift + DetermineBuildServer.swift + ExternalBuildServerAdapter.swift + FallbackBuildSettings.swift + FileBuildSettings.swift + FixedCompilationDatabaseBuildServer.swift + JSONCompilationDatabaseBuildServer.swift + LegacyBuildServer.swift + MainFilesProvider.swift + SplitShellCommand.swift + SwiftlyResolver.swift + SwiftPMBuildServer.swift) +set_target_properties(BuildServerIntegration PROPERTIES + INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY}) +target_link_libraries(BuildServerIntegration PUBLIC + BuildServerProtocol + LanguageServerProtocol + LanguageServerProtocolJSONRPC + SKLogging + SKOptions + LanguageServerProtocolExtensions + SourceKitD + SwiftExtensions + ToolchainRegistry + PackageModel + TSCBasic + Build + SourceKitLSPAPI + SwiftASN1) + +target_link_libraries(BuildServerIntegration PRIVATE + SKUtilities + TSCExtensions) diff --git a/Sources/BuildSystemIntegration/CompilationDatabase.swift b/Sources/BuildServerIntegration/CompilationDatabase.swift similarity index 99% rename from Sources/BuildSystemIntegration/CompilationDatabase.swift rename to Sources/BuildServerIntegration/CompilationDatabase.swift index 9d92d7eff..731fd600b 100644 --- a/Sources/BuildSystemIntegration/CompilationDatabase.swift +++ b/Sources/BuildServerIntegration/CompilationDatabase.swift @@ -127,7 +127,7 @@ package struct JSONCompilationDatabase: Equatable, Codable { /// /// - Returns: `nil` if `compile_commands.json` was not found package init(directory: URL) throws { - let path = directory.appendingPathComponent(JSONCompilationDatabaseBuildSystem.dbName) + let path = directory.appendingPathComponent(JSONCompilationDatabaseBuildServer.dbName) try self.init(file: path) } diff --git a/Sources/BuildSystemIntegration/CompilerCommandLineOption.swift b/Sources/BuildServerIntegration/CompilerCommandLineOption.swift similarity index 100% rename from Sources/BuildSystemIntegration/CompilerCommandLineOption.swift rename to Sources/BuildServerIntegration/CompilerCommandLineOption.swift diff --git a/Sources/BuildSystemIntegration/DetermineBuildSystem.swift b/Sources/BuildServerIntegration/DetermineBuildServer.swift similarity index 72% rename from Sources/BuildSystemIntegration/DetermineBuildSystem.swift rename to Sources/BuildServerIntegration/DetermineBuildServer.swift index ea752717d..75c7c26a3 100644 --- a/Sources/BuildSystemIntegration/DetermineBuildSystem.swift +++ b/Sources/BuildServerIntegration/DetermineBuildServer.swift @@ -24,7 +24,7 @@ import struct TSCBasic.RelativePath private func searchForCompilationDatabaseConfig( in workspaceFolder: URL, options: SourceKitLSPOptions -) -> BuildSystemSpec? { +) -> BuildServerSpec? { let searchPaths = (options.compilationDatabaseOrDefault.searchPaths ?? []).compactMap { try? RelativePath(validating: $0) @@ -40,14 +40,14 @@ private func searchForCompilationDatabaseConfig( .compactMap { searchPath in let path = workspaceFolder.appending(searchPath) - let jsonPath = path.appendingPathComponent(JSONCompilationDatabaseBuildSystem.dbName) + let jsonPath = path.appendingPathComponent(JSONCompilationDatabaseBuildServer.dbName) if FileManager.default.isFile(at: jsonPath) { - return BuildSystemSpec(kind: .jsonCompilationDatabase, projectRoot: workspaceFolder, configPath: jsonPath) + return BuildServerSpec(kind: .jsonCompilationDatabase, projectRoot: workspaceFolder, configPath: jsonPath) } - let fixedPath = path.appendingPathComponent(FixedCompilationDatabaseBuildSystem.dbName) + let fixedPath = path.appendingPathComponent(FixedCompilationDatabaseBuildServer.dbName) if FileManager.default.isFile(at: fixedPath) { - return BuildSystemSpec(kind: .fixedCompilationDatabase, projectRoot: workspaceFolder, configPath: fixedPath) + return BuildServerSpec(kind: .fixedCompilationDatabase, projectRoot: workspaceFolder, configPath: fixedPath) } return nil @@ -55,41 +55,41 @@ private func searchForCompilationDatabaseConfig( .first } -/// Determine which build system should be started to handle the given workspace folder and at which folder that build -/// system's project root is (see `BuiltInBuildSystem.projectRoot(for:options:)`). `onlyConsiderRoot` controls whether +/// Determine which build server should be started to handle the given workspace folder and at which folder that build +/// servers's project root is (see `BuiltInBuildServer.projectRoot(for:options:)`). `onlyConsiderRoot` controls whether /// paths outside the root should be considered (eg. configuration files in the user's home directory). /// -/// Returns `nil` if no build system can handle this workspace folder. -package func determineBuildSystem( +/// Returns `nil` if no build server can handle this workspace folder. +package func determineBuildServer( forWorkspaceFolder workspaceFolder: DocumentURI, onlyConsiderRoot: Bool, options: SourceKitLSPOptions, - hooks: BuildSystemHooks -) -> BuildSystemSpec? { + hooks: BuildServerHooks +) -> BuildServerSpec? { if let injectBuildServer = hooks.injectBuildServer { - return BuildSystemSpec( + return BuildServerSpec( kind: .injected(injectBuildServer), projectRoot: workspaceFolder.arbitrarySchemeURL, configPath: workspaceFolder.arbitrarySchemeURL ) } - var buildSystemPreference: [WorkspaceType] = [ + var buildServerPreference: [WorkspaceType] = [ .buildServer, .swiftPM, .compilationDatabase, ] - if let defaultBuildSystem = options.defaultWorkspaceType { - buildSystemPreference.removeAll(where: { $0 == defaultBuildSystem }) - buildSystemPreference.insert(defaultBuildSystem, at: 0) + if let defaultBuildServer = options.defaultWorkspaceType { + buildServerPreference.removeAll(where: { $0 == defaultBuildServer }) + buildServerPreference.insert(defaultBuildServer, at: 0) } guard let workspaceFolderUrl = workspaceFolder.fileURL else { return nil } - for buildSystemType in buildSystemPreference { - var spec: BuildSystemSpec? = nil + for buildServerType in buildServerPreference { + var spec: BuildServerSpec? = nil - switch buildSystemType { + switch buildServerType { case .buildServer: - spec = ExternalBuildSystemAdapter.searchForConfig( + spec = ExternalBuildServerAdapter.searchForConfig( in: workspaceFolderUrl, onlyConsiderRoot: onlyConsiderRoot, options: options @@ -98,7 +98,7 @@ package func determineBuildSystem( spec = searchForCompilationDatabaseConfig(in: workspaceFolderUrl, options: options) case .swiftPM: #if !NO_SWIFTPM_DEPENDENCY - spec = SwiftPMBuildSystem.searchForConfig(in: workspaceFolderUrl, options: options) + spec = SwiftPMBuildServer.searchForConfig(in: workspaceFolderUrl, options: options) #endif } diff --git a/Sources/BuildSystemIntegration/ExternalBuildSystemAdapter.swift b/Sources/BuildServerIntegration/ExternalBuildServerAdapter.swift similarity index 97% rename from Sources/BuildSystemIntegration/ExternalBuildSystemAdapter.swift rename to Sources/BuildServerIntegration/ExternalBuildServerAdapter.swift index 372a4d211..481bffa72 100644 --- a/Sources/BuildSystemIntegration/ExternalBuildSystemAdapter.swift +++ b/Sources/BuildServerIntegration/ExternalBuildServerAdapter.swift @@ -74,7 +74,7 @@ private struct BuildServerConfig: Codable { /// A collection of languages supported by this BSP server. let languages: [String] - /// Command arguments runnable via system processes to start a BSP server. + /// Command arguments runnable via server processes to start a BSP server. let argv: [String] static func load(from path: URL) throws -> BuildServerConfig { @@ -85,14 +85,14 @@ private struct BuildServerConfig: Codable { } /// Launches a subprocess that is a BSP server and manages the process's lifetime. -actor ExternalBuildSystemAdapter { +actor ExternalBuildServerAdapter { /// The root folder of the project. Used to resolve relative server paths. private let projectRoot: URL /// The file that specifies the configuration for this build server. private let configPath: URL - /// The `BuildSystemManager` that handles messages from the BSP server to SourceKit-LSP. + /// The `BuildServerManager` that handles messages from the BSP server to SourceKit-LSP. var messagesToSourceKitLSPHandler: MessageHandler /// The JSON-RPC connection between SourceKit-LSP and the BSP server. @@ -113,12 +113,12 @@ actor ExternalBuildSystemAdapter { in workspaceFolder: URL, onlyConsiderRoot: Bool, options: SourceKitLSPOptions - ) -> BuildSystemSpec? { + ) -> BuildServerSpec? { guard let configPath = getConfigPath(for: workspaceFolder, onlyConsiderRoot: onlyConsiderRoot) else { return nil } - return BuildSystemSpec(kind: .buildServer, projectRoot: workspaceFolder, configPath: configPath) + return BuildServerSpec(kind: .externalBuildServer, projectRoot: workspaceFolder, configPath: configPath) } init( @@ -134,7 +134,7 @@ actor ExternalBuildSystemAdapter { /// Change the handler that handles messages from the build server. /// - /// The intended use of this is to intercept messages from the build server by `LegacyBuildServerBuildSystem`. + /// The intended use of this is to intercept messages from the build server by `LegacyBuildServer`. func changeMessageToSourceKitLSPHandler(to newHandler: MessageHandler) { messagesToSourceKitLSPHandler = newHandler connectionToBuildServer?.changeReceiveHandler(messagesToSourceKitLSPHandler) diff --git a/Sources/BuildSystemIntegration/FallbackBuildSettings.swift b/Sources/BuildServerIntegration/FallbackBuildSettings.swift similarity index 100% rename from Sources/BuildSystemIntegration/FallbackBuildSettings.swift rename to Sources/BuildServerIntegration/FallbackBuildSettings.swift diff --git a/Sources/BuildSystemIntegration/FileBuildSettings.swift b/Sources/BuildServerIntegration/FileBuildSettings.swift similarity index 94% rename from Sources/BuildSystemIntegration/FileBuildSettings.swift rename to Sources/BuildServerIntegration/FileBuildSettings.swift index 8e147f6e7..4af0dfbca 100644 --- a/Sources/BuildSystemIntegration/FileBuildSettings.swift +++ b/Sources/BuildServerIntegration/FileBuildSettings.swift @@ -17,7 +17,7 @@ import LanguageServerProtocolExtensions /// Build settings for a single file. /// /// Encapsulates all the settings needed to compile a single file, including the compiler arguments -/// and working directory. FileBuildSettings are typically the result of a BuildSystem query. +/// and working directory. `FileBuildSettings`` are typically the result of a build server query. package struct FileBuildSettings: Equatable, Sendable { /// The compiler arguments to use for this file. @@ -34,7 +34,8 @@ package struct FileBuildSettings: Equatable, Sendable { /// SourceKit-LSP but returned to clients in the `workspace/_sourceKitOptions` LSP request. package var data: LSPAny? - /// Whether the build settings were computed from a real build system or whether they are synthesized fallback arguments while the build system is still busy computing build settings. + /// Whether the build settings were computed from a real build server or whether they are synthesized fallback + /// arguments while the build server is still busy computing build settings. package var isFallback: Bool package init( diff --git a/Sources/BuildSystemIntegration/FixedCompilationDatabaseBuildSystem.swift b/Sources/BuildServerIntegration/FixedCompilationDatabaseBuildServer.swift similarity index 96% rename from Sources/BuildSystemIntegration/FixedCompilationDatabaseBuildSystem.swift rename to Sources/BuildServerIntegration/FixedCompilationDatabaseBuildServer.swift index a27e10e10..ef084482a 100644 --- a/Sources/BuildSystemIntegration/FixedCompilationDatabaseBuildSystem.swift +++ b/Sources/BuildServerIntegration/FixedCompilationDatabaseBuildServer.swift @@ -25,8 +25,8 @@ func lastIndexStorePathArgument(in compilerArgs: [String]) -> String? { return nil } -/// A `BuildSystem` that provides compiler arguments from a `compile_flags.txt` file. -package actor FixedCompilationDatabaseBuildSystem: BuiltInBuildSystem { +/// A `BuiltInBuildServer` that provides compiler arguments from a `compile_flags.txt` file. +package actor FixedCompilationDatabaseBuildServer: BuiltInBuildServer { package static let dbName = "compile_flags.txt" private let connectionToSourceKitLSP: any Connection diff --git a/Sources/BuildSystemIntegration/JSONCompilationDatabaseBuildSystem.swift b/Sources/BuildServerIntegration/JSONCompilationDatabaseBuildServer.swift similarity index 97% rename from Sources/BuildSystemIntegration/JSONCompilationDatabaseBuildSystem.swift rename to Sources/BuildServerIntegration/JSONCompilationDatabaseBuildServer.swift index 4227bcc0f..abd8e5196 100644 --- a/Sources/BuildSystemIntegration/JSONCompilationDatabaseBuildSystem.swift +++ b/Sources/BuildServerIntegration/JSONCompilationDatabaseBuildServer.swift @@ -45,8 +45,8 @@ fileprivate extension CompilationDatabaseCompileCommand { } } -/// A `BuildSystem` that provides compiler arguments from a `compile_commands.json` file. -package actor JSONCompilationDatabaseBuildSystem: BuiltInBuildSystem { +/// A `BuiltInBuildServer` that provides compiler arguments from a `compile_commands.json` file. +package actor JSONCompilationDatabaseBuildServer: BuiltInBuildServer { package static let dbName: String = "compile_commands.json" /// The compilation database. diff --git a/Sources/BuildSystemIntegration/LegacyBuildServerBuildSystem.swift b/Sources/BuildServerIntegration/LegacyBuildServer.swift similarity index 94% rename from Sources/BuildSystemIntegration/LegacyBuildServerBuildSystem.swift rename to Sources/BuildServerIntegration/LegacyBuildServer.swift index 5066757d9..44e49b262 100644 --- a/Sources/BuildSystemIntegration/LegacyBuildServerBuildSystem.swift +++ b/Sources/BuildServerIntegration/LegacyBuildServer.swift @@ -26,13 +26,13 @@ import ToolchainRegistry /// Bridges the gap between the legacy push-based BSP settings model and the new pull based BSP settings model. /// -/// On the one side, this type is a `BuiltInBuildSystem` that offers pull-based build settings. To serve these queries, +/// On the one side, this type is a `BuiltInBuildServer` that offers pull-based build settings. To serve these queries, /// it communicates with an external BSP server that uses `build/sourceKitOptionsChanged` notifications to communicate /// build settings. /// /// This build server should be phased out in favor of the pull-based settings model described in /// https://forums.swift.org/t/extending-functionality-of-build-server-protocol-with-sourcekit-lsp/74400 -actor LegacyBuildServerBuildSystem: MessageHandler, BuiltInBuildSystem { +actor LegacyBuildServer: MessageHandler, BuiltInBuildServer { private var buildServer: JSONRPCConnection? /// The queue on which all messages that originate from the build server are @@ -67,18 +67,18 @@ actor LegacyBuildServerBuildSystem: MessageHandler, BuiltInBuildSystem { projectRoot: URL, configPath: URL, initializationData: InitializeBuildResponse, - _ externalBuildSystemAdapter: ExternalBuildSystemAdapter + _ externalBuildServerAdapter: ExternalBuildServerAdapter ) async { self.projectRoot = projectRoot self.configPath = configPath self.indexDatabasePath = nil self.indexStorePath = nil self.connectionToSourceKitLSP = LocalConnection( - receiverName: "BuildSystemManager", - handler: await externalBuildSystemAdapter.messagesToSourceKitLSPHandler + receiverName: "BuildServerManager", + handler: await externalBuildServerAdapter.messagesToSourceKitLSPHandler ) - await externalBuildSystemAdapter.changeMessageToSourceKitLSPHandler(to: self) - self.buildServer = await externalBuildSystemAdapter.connectionToBuildServer + await externalBuildServerAdapter.changeMessageToSourceKitLSPHandler(to: self) + self.buildServer = await externalBuildServerAdapter.connectionToBuildServer } /// Handler for notifications received **from** the builder server, ie. diff --git a/Sources/BuildSystemIntegration/MainFilesProvider.swift b/Sources/BuildServerIntegration/MainFilesProvider.swift similarity index 100% rename from Sources/BuildSystemIntegration/MainFilesProvider.swift rename to Sources/BuildServerIntegration/MainFilesProvider.swift diff --git a/Sources/BuildSystemIntegration/SplitShellCommand.swift b/Sources/BuildServerIntegration/SplitShellCommand.swift similarity index 100% rename from Sources/BuildSystemIntegration/SplitShellCommand.swift rename to Sources/BuildServerIntegration/SplitShellCommand.swift diff --git a/Sources/BuildSystemIntegration/SwiftPMBuildSystem.swift b/Sources/BuildServerIntegration/SwiftPMBuildServer.swift similarity index 97% rename from Sources/BuildSystemIntegration/SwiftPMBuildSystem.swift rename to Sources/BuildServerIntegration/SwiftPMBuildServer.swift index 5eaf798a5..f0b609341 100644 --- a/Sources/BuildSystemIntegration/SwiftPMBuildSystem.swift +++ b/Sources/BuildServerIntegration/SwiftPMBuildServer.swift @@ -80,12 +80,12 @@ fileprivate extension TSCBasic.AbsolutePath { fileprivate let preparationTaskID: AtomicUInt32 = AtomicUInt32(initialValue: 0) -/// Swift Package Manager build system and workspace support. +/// Swift Package Manager build server and workspace support. /// -/// This class implements the `BuiltInBuildSystem` interface to provide the build settings for a Swift +/// This class implements the `BuiltInBuildServe` interface to provide the build settings for a Swift /// Package Manager (SwiftPM) package. The settings are determined by loading the Package.swift /// manifest using `libSwiftPM` and constructing a build plan using the default (debug) parameters. -package actor SwiftPMBuildSystem: BuiltInBuildSystem { +package actor SwiftPMBuildServer: BuiltInBuildServer { package enum Error: Swift.Error { /// Could not determine an appropriate toolchain for swiftpm to use for manifest loading. case cannotDetermineHostToolchain @@ -104,11 +104,11 @@ package actor SwiftPMBuildSystem: BuiltInBuildSystem { package let connectionToSourceKitLSP: any Connection - /// Whether the `SwiftPMBuildSystem` is pointed at a `.build/index-build` directory that's independent of the + /// Whether the `SwiftPMBuildServer` is pointed at a `.build/index-build` directory that's independent of the /// user's build. private var isForIndexBuild: Bool { options.backgroundIndexingOrDefault } - // MARK: Build system options (set once and not modified) + // MARK: Build server options (set once and not modified) /// The directory containing `Package.swift`. private let projectRoot: URL @@ -127,7 +127,7 @@ package actor SwiftPMBuildSystem: BuiltInBuildSystem { /// A `ObservabilitySystem` from `SwiftPM` that logs. private let observabilitySystem: ObservabilitySystem - // MARK: Build system state (modified on package reload) + // MARK: Build server state (modified on package reload) /// The entry point via with we can access the `SourceKitLSPAPI` provided by SwiftPM. private var buildDescription: SourceKitLSPAPI.BuildDescription? @@ -137,17 +137,17 @@ package actor SwiftPMBuildSystem: BuiltInBuildSystem { private var targetDependencies: [BuildTargetIdentifier: Set] = [:] - static package func searchForConfig(in path: URL, options: SourceKitLSPOptions) -> BuildSystemSpec? { + static package func searchForConfig(in path: URL, options: SourceKitLSPOptions) -> BuildServerSpec? { let packagePath = path.appendingPathComponent("Package.swift") if (try? String(contentsOf: packagePath, encoding: .utf8))?.contains("PackageDescription") ?? false { - return BuildSystemSpec(kind: .swiftPM, projectRoot: path, configPath: packagePath) + return BuildServerSpec(kind: .swiftPM, projectRoot: path, configPath: packagePath) } return nil } - /// Creates a build system using the Swift Package Manager, if this workspace is a package. + /// Creates a build server using the Swift Package Manager, if this workspace is a package. /// /// - Parameters: /// - projectRoot: The directory containing `Package.swift` @@ -318,9 +318,9 @@ package actor SwiftPMBuildSystem: BuiltInBuildSystem { packageLoadingQueue.async { await orLog("Initial package loading") { - // Schedule an initial generation of the build graph. Once the build graph is loaded, the build system will send + // Schedule an initial generation of the build graph. Once the build graph is loaded, the build server will send // call `fileHandlingCapabilityChanged`, which allows us to move documents to a workspace with this build - // system. + // server. try await self.reloadPackageAssumingOnPackageLoadingQueue() } } @@ -539,7 +539,7 @@ package actor SwiftPMBuildSystem: BuiltInBuildSystem { package func buildTargetSources(request: BuildTargetSourcesRequest) async throws -> BuildTargetSourcesResponse { var result: [SourcesItem] = [] - // TODO: Query The SwiftPM build system for the document's language and add it to SourceItem.data + // TODO: Query The SwiftPM build server for the document's language and add it to SourceItem.data // (https://github.com/swiftlang/sourcekit-lsp/issues/1267) for target in request.targets { if target == .forPackageManifest { @@ -641,7 +641,7 @@ package actor SwiftPMBuildSystem: BuiltInBuildSystem { // If `url` is not part of the target's source, it's most likely a header file. Fake compiler arguments for it // from a substitute file within the target. // Even if the file is not a header, this should give reasonable results: Say, there was a new `.cpp` file in a - // target and for some reason the `SwiftPMBuildSystem` doesn’t know about it. Then we would infer the target based + // target and for some reason the `SwiftPMBuildServer` doesn’t know about it. Then we would infer the target based // on the file's location on disk and generate compiler arguments for it by picking a source file in that target, // getting its compiler arguments and then patching up the compiler arguments by replacing the substitute file // with the `.cpp` file. diff --git a/Sources/BuildSystemIntegration/SwiftlyResolver.swift b/Sources/BuildServerIntegration/SwiftlyResolver.swift similarity index 100% rename from Sources/BuildSystemIntegration/SwiftlyResolver.swift rename to Sources/BuildServerIntegration/SwiftlyResolver.swift diff --git a/Sources/BuildServerProtocol/Messages/BuildTargetSourcesRequest.swift b/Sources/BuildServerProtocol/Messages/BuildTargetSourcesRequest.swift index e18a3d3d7..6e952a5c7 100644 --- a/Sources/BuildServerProtocol/Messages/BuildTargetSourcesRequest.swift +++ b/Sources/BuildServerProtocol/Messages/BuildTargetSourcesRequest.swift @@ -129,7 +129,7 @@ public enum SourceKitSourceItemKind: String, Codable { /// For example header files in SwiftPM projects are always associated to one target and SwiftPM can provide build /// settings for that header file. /// - /// In general, build systems don't need to list all header files in the `buildTarget/sources` request: Semantic + /// In general, build servers don't need to list all header files in the `buildTarget/sources` request: Semantic /// functionality for header files is usually provided by finding a main file that includes the header file and /// inferring build settings from it. Listing header files in `buildTarget/sources` allows SourceKit-LSP to provide /// semantic functionality for header files if they haven't been included by any main file. diff --git a/Sources/BuildServerProtocol/Messages/OnWatchedFilesDidChangeNotification.swift b/Sources/BuildServerProtocol/Messages/OnWatchedFilesDidChangeNotification.swift index 472792100..656cf109f 100644 --- a/Sources/BuildServerProtocol/Messages/OnWatchedFilesDidChangeNotification.swift +++ b/Sources/BuildServerProtocol/Messages/OnWatchedFilesDidChangeNotification.swift @@ -12,5 +12,5 @@ public import LanguageServerProtocol -/// Notification sent from SourceKit-LSP to the build system to indicate that files within the project have been modified. +/// Notification sent from SourceKit-LSP to the build server to indicate that files within the project have been modified. public typealias OnWatchedFilesDidChangeNotification = LanguageServerProtocol.DidChangeWatchedFilesNotification diff --git a/Sources/BuildServerProtocol/Messages/WorkspaceWaitForBuildSystemUpdates.swift b/Sources/BuildServerProtocol/Messages/WorkspaceWaitForBuildSystemUpdates.swift index 434d8f0cb..3fa579ade 100644 --- a/Sources/BuildServerProtocol/Messages/WorkspaceWaitForBuildSystemUpdates.swift +++ b/Sources/BuildServerProtocol/Messages/WorkspaceWaitForBuildSystemUpdates.swift @@ -14,7 +14,7 @@ public import LanguageServerProtocol /// This request is a no-op and doesn't have any effects. /// -/// If the build system is currently updating the build graph, this request should return after those updates have +/// If the build server is currently updating the build graph, this request should return after those updates have /// finished processing. public struct WorkspaceWaitForBuildSystemUpdatesRequest: RequestType, Hashable { public typealias Response = VoidResponse diff --git a/Sources/BuildSystemIntegration/CMakeLists.txt b/Sources/BuildSystemIntegration/CMakeLists.txt deleted file mode 100644 index 454bf54a3..000000000 --- a/Sources/BuildSystemIntegration/CMakeLists.txt +++ /dev/null @@ -1,44 +0,0 @@ - -add_library(BuildSystemIntegration STATIC - BuildSettingsLogger.swift - BuildSystemHooks.swift - BuildSystemManager.swift - BuildSystemManagerDelegate.swift - BuildSystemMessageDependencyTracker.swift - BuildTargetIdentifierExtensions.swift - BuiltInBuildSystem.swift - BuiltInBuildSystemAdapter.swift - CompilationDatabase.swift - CompilerCommandLineOption.swift - DetermineBuildSystem.swift - ExternalBuildSystemAdapter.swift - FallbackBuildSettings.swift - FileBuildSettings.swift - FixedCompilationDatabaseBuildSystem.swift - JSONCompilationDatabaseBuildSystem.swift - LegacyBuildServerBuildSystem.swift - MainFilesProvider.swift - SplitShellCommand.swift - SwiftlyResolver.swift - SwiftPMBuildSystem.swift) -set_target_properties(BuildSystemIntegration PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY}) -target_link_libraries(BuildSystemIntegration PUBLIC - BuildServerProtocol - LanguageServerProtocol - LanguageServerProtocolJSONRPC - SKLogging - SKOptions - LanguageServerProtocolExtensions - SourceKitD - SwiftExtensions - ToolchainRegistry - PackageModel - TSCBasic - Build - SourceKitLSPAPI - SwiftASN1) - -target_link_libraries(BuildSystemIntegration PRIVATE - SKUtilities - TSCExtensions) diff --git a/Sources/CMakeLists.txt b/Sources/CMakeLists.txt index 926ea6265..95b2b3749 100644 --- a/Sources/CMakeLists.txt +++ b/Sources/CMakeLists.txt @@ -2,7 +2,7 @@ add_compile_options("$<$:SHELL:-package-name sourcekit_l add_compile_options("$<$:SHELL:-DRESILIENT_LIBRARIES>") add_compile_options("$<$:SHELL:-swift-version 6>") add_subdirectory(BuildServerProtocol) -add_subdirectory(BuildSystemIntegration) +add_subdirectory(BuildServerIntegration) add_subdirectory(CAtomics) add_subdirectory(CCompletionScoring) add_subdirectory(CompletionScoring) diff --git a/Sources/Diagnose/CMakeLists.txt b/Sources/Diagnose/CMakeLists.txt index 3ea6e1159..4ed6d14e9 100644 --- a/Sources/Diagnose/CMakeLists.txt +++ b/Sources/Diagnose/CMakeLists.txt @@ -26,7 +26,7 @@ set_target_properties(Diagnose PROPERTIES INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY}) target_link_libraries(Diagnose PUBLIC - BuildSystemIntegration + BuildServerIntegration InProcessClient SKLogging SKOptions diff --git a/Sources/Diagnose/SwiftFrontendCrashScraper.swift b/Sources/Diagnose/SwiftFrontendCrashScraper.swift index 5741a2bb6..1e6ce6547 100644 --- a/Sources/Diagnose/SwiftFrontendCrashScraper.swift +++ b/Sources/Diagnose/SwiftFrontendCrashScraper.swift @@ -10,7 +10,7 @@ // //===----------------------------------------------------------------------===// -import BuildSystemIntegration +import BuildServerIntegration import Foundation struct SwiftFrontendCrashScraper { diff --git a/Sources/DocCDocumentation/BuildSystemIntegrationExtensions.swift b/Sources/DocCDocumentation/BuildSystemIntegrationExtensions.swift index 5052267e8..a389981f4 100644 --- a/Sources/DocCDocumentation/BuildSystemIntegrationExtensions.swift +++ b/Sources/DocCDocumentation/BuildSystemIntegrationExtensions.swift @@ -10,13 +10,13 @@ // //===----------------------------------------------------------------------===// +package import BuildServerIntegration package import BuildServerProtocol -package import BuildSystemIntegration package import Foundation import LanguageServerProtocol import SKLogging -package extension BuildSystemManager { +package extension BuildServerManager { /// Retrieves the name of the Swift module for a given target. /// /// **Note:** prefer using ``module(for:in:)`` over ths function. This function diff --git a/Sources/DocCDocumentation/DocCDocumentationManager.swift b/Sources/DocCDocumentation/DocCDocumentationManager.swift index f41be2fe9..ec2610d46 100644 --- a/Sources/DocCDocumentation/DocCDocumentationManager.swift +++ b/Sources/DocCDocumentation/DocCDocumentationManager.swift @@ -10,8 +10,8 @@ // //===----------------------------------------------------------------------===// +package import BuildServerIntegration import BuildServerProtocol -package import BuildSystemIntegration package import Foundation package import LanguageServerProtocol import SKLogging @@ -22,9 +22,9 @@ package struct DocCDocumentationManager: Sendable { private let referenceResolutionService: DocCReferenceResolutionService private let catalogIndexManager: DocCCatalogIndexManager - private let buildSystemManager: BuildSystemManager + private let buildServerManager: BuildServerManager - package init(buildSystemManager: BuildSystemManager) { + package init(buildServerManager: BuildServerManager) { let symbolResolutionServer = DocumentationServer(qualityOfService: .unspecified) doccServer = DocCServer( peer: symbolResolutionServer, @@ -33,13 +33,13 @@ package struct DocCDocumentationManager: Sendable { catalogIndexManager = DocCCatalogIndexManager(server: doccServer) referenceResolutionService = DocCReferenceResolutionService() symbolResolutionServer.register(service: referenceResolutionService) - self.buildSystemManager = buildSystemManager + self.buildServerManager = buildServerManager } package func filesDidChange(_ events: [FileEvent]) async { for event in events { - for target in await buildSystemManager.targets(for: event.uri) { - guard let catalogURL = await buildSystemManager.doccCatalog(for: target) else { + for target in await buildServerManager.targets(for: event.uri) { + guard let catalogURL = await buildServerManager.doccCatalog(for: target) else { continue } await catalogIndexManager.invalidate(catalogURL) diff --git a/Sources/InProcessClient/CMakeLists.txt b/Sources/InProcessClient/CMakeLists.txt index 6a524e757..1b5db8d5b 100644 --- a/Sources/InProcessClient/CMakeLists.txt +++ b/Sources/InProcessClient/CMakeLists.txt @@ -5,7 +5,7 @@ set_target_properties(InProcessClient PROPERTIES INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY}) target_link_libraries(InProcessClient PUBLIC - BuildSystemIntegration + BuildServerIntegration LanguageServerProtocol SKLogging SKOptions diff --git a/Sources/InProcessClient/InProcessSourceKitLSPClient.swift b/Sources/InProcessClient/InProcessSourceKitLSPClient.swift index 6ee01360f..fefdd2332 100644 --- a/Sources/InProcessClient/InProcessSourceKitLSPClient.swift +++ b/Sources/InProcessClient/InProcessSourceKitLSPClient.swift @@ -10,7 +10,7 @@ // //===----------------------------------------------------------------------===// -import BuildSystemIntegration +import BuildServerIntegration public import Foundation public import LanguageServerProtocol import LanguageServerProtocolExtensions diff --git a/Sources/LanguageServerProtocol/Requests/SourceKitOptionsRequest.swift b/Sources/LanguageServerProtocol/Requests/SourceKitOptionsRequest.swift index b0191e72b..ef0052d05 100644 --- a/Sources/LanguageServerProtocol/Requests/SourceKitOptionsRequest.swift +++ b/Sources/LanguageServerProtocol/Requests/SourceKitOptionsRequest.swift @@ -43,7 +43,7 @@ public struct SourceKitOptionsRequest: RequestType, Hashable { /// If set to `true` and build settings could not be determined within a timeout (see `buildSettingsTimeout` in the /// SourceKit-LSP configuration file), this request returns fallback build settings. /// - /// If set to `false` the request only finishes when build settings were provided by the build system. + /// If set to `false` the request only finishes when build settings were provided by the build server. public var allowFallbackSettings: Bool public init( diff --git a/Sources/SKOptions/SourceKitLSPOptions.swift b/Sources/SKOptions/SourceKitLSPOptions.swift index 0adccbb17..8ca3cb768 100644 --- a/Sources/SKOptions/SourceKitLSPOptions.swift +++ b/Sources/SKOptions/SourceKitLSPOptions.swift @@ -311,14 +311,14 @@ public struct SourceKitLSPOptions: Sendable, Codable, Equatable { set { compilationDatabase = newValue } } - /// Dictionary with the following keys, defining options for files that aren't managed by any build system. + /// Dictionary with the following keys, defining options for files that aren't managed by any build server. private var fallbackBuildSystem: FallbackBuildSystemOptions? public var fallbackBuildSystemOrDefault: FallbackBuildSystemOptions { get { fallbackBuildSystem ?? .init() } set { fallbackBuildSystem = newValue } } - /// Number of milliseconds to wait for build settings from the build system before using fallback build settings. + /// Number of milliseconds to wait for build settings from the build server before using fallback build settings. public var buildSettingsTimeout: Int? public var buildSettingsTimeoutOrDefault: Duration { // The default timeout of 500ms was chosen arbitrarily without any measurements. diff --git a/Sources/SKTestSupport/CustomBuildServerTestProject.swift b/Sources/SKTestSupport/CustomBuildServerTestProject.swift index 676de5b1f..2f73fdff6 100644 --- a/Sources/SKTestSupport/CustomBuildServerTestProject.swift +++ b/Sources/SKTestSupport/CustomBuildServerTestProject.swift @@ -10,8 +10,8 @@ // //===----------------------------------------------------------------------===// +import BuildServerIntegration package import BuildServerProtocol -import BuildSystemIntegration package import Foundation package import LanguageServerProtocol import LanguageServerProtocolExtensions @@ -266,7 +266,7 @@ package extension CustomBuildServer { /// A test project that launches a custom build server in-process. /// -/// In contrast to `ExternalBuildServerTestProject`, the custom build system runs in-process and is implemented in +/// In contrast to `ExternalBuildServerTestProject`, the custom build server runs in-process and is implemented in /// Swift. package final class CustomBuildServerTestProject: MultiFileTestProject { private let buildServerBox = ThreadSafeBox(initialValue: nil) @@ -282,11 +282,11 @@ package final class CustomBuildServerTestProject testName: String = #function ) async throws { var hooks = hooks - XCTAssertNil(hooks.buildSystemHooks.injectBuildServer) - hooks.buildSystemHooks.injectBuildServer = { [buildServerBox] projectRoot, connectionToSourceKitLSP in + XCTAssertNil(hooks.buildServerHooks.injectBuildServer) + hooks.buildServerHooks.injectBuildServer = { [buildServerBox] projectRoot, connectionToSourceKitLSP in let buildServer = BuildServer(projectRoot: projectRoot, connectionToSourceKitLSP: connectionToSourceKitLSP) buildServerBox.value = buildServer - return LocalConnection(receiverName: "TestBuildSystem", handler: buildServer) + return LocalConnection(receiverName: "TestBuildServer", handler: buildServer) } try await super.init( files: files, diff --git a/Sources/SKTestSupport/DummyBuildSystemManagerConnectionToClient.swift b/Sources/SKTestSupport/DummyBuildServerManagerConnectionToClient.swift similarity index 90% rename from Sources/SKTestSupport/DummyBuildSystemManagerConnectionToClient.swift rename to Sources/SKTestSupport/DummyBuildServerManagerConnectionToClient.swift index 67cb49cba..3197a3e4b 100644 --- a/Sources/SKTestSupport/DummyBuildSystemManagerConnectionToClient.swift +++ b/Sources/SKTestSupport/DummyBuildServerManagerConnectionToClient.swift @@ -10,11 +10,11 @@ // //===----------------------------------------------------------------------===// -import BuildSystemIntegration +import BuildServerIntegration import Foundation package import LanguageServerProtocol -package struct DummyBuildSystemManagerConnectionToClient: BuildSystemManagerConnectionToClient { +package struct DummyBuildServerManagerConnectionToClient: BuildServerManagerConnectionToClient { package var clientSupportsWorkDoneProgress: Bool = false package init() {} diff --git a/Sources/SKTestSupport/IndexedSingleSwiftFileTestProject.swift b/Sources/SKTestSupport/IndexedSingleSwiftFileTestProject.swift index 5c0871708..9a0ca382d 100644 --- a/Sources/SKTestSupport/IndexedSingleSwiftFileTestProject.swift +++ b/Sources/SKTestSupport/IndexedSingleSwiftFileTestProject.swift @@ -10,7 +10,7 @@ // //===----------------------------------------------------------------------===// -@_spi(Testing) import BuildSystemIntegration +@_spi(Testing) import BuildServerIntegration package import Foundation package import LanguageServerProtocol import SKLogging @@ -158,7 +158,7 @@ package struct IndexedSingleSwiftFileTestProject { let encoder = JSONEncoder() encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes] try encoder.encode(compilationDatabase).write( - to: testWorkspaceDirectory.appendingPathComponent(JSONCompilationDatabaseBuildSystem.dbName) + to: testWorkspaceDirectory.appendingPathComponent(JSONCompilationDatabaseBuildServer.dbName) ) // Run swiftc to build the index store diff --git a/Sources/SKUtilities/LineTable.swift b/Sources/SKUtilities/LineTable.swift index 2d9abd05d..80cc35d4e 100644 --- a/Sources/SKUtilities/LineTable.swift +++ b/Sources/SKUtilities/LineTable.swift @@ -130,8 +130,8 @@ extension LineTable { utf8Offset toOff: Int, with replacement: String ) { - let start = content.utf8.index(impl[fromLine], offsetBy: fromOff) - let end = content.utf8.index(impl[toLine], offsetBy: toOff) + let start = self.stringIndexOf(line: fromLine, utf8Column: fromOff) + let end = self.stringIndexOf(line: toLine, utf8Column: toOff) var newText = self.content newText.replaceSubrange(start.. @@ -61,7 +61,7 @@ package struct PreparationTaskDescription: IndexTaskDescription { init( targetsToPrepare: [BuildTargetIdentifier], - buildSystemManager: BuildSystemManager, + buildServerManager: BuildServerManager, preparationUpToDateTracker: UpToDateTracker, logMessageToIndexLog: @escaping @Sendable ( @@ -70,7 +70,7 @@ package struct PreparationTaskDescription: IndexTaskDescription { hooks: IndexHooks ) { self.targetsToPrepare = targetsToPrepare - self.buildSystemManager = buildSystemManager + self.buildServerManager = buildServerManager self.preparationUpToDateTracker = preparationUpToDateTracker self.logMessageToIndexLog = logMessageToIndexLog self.hooks = hooks @@ -104,7 +104,7 @@ package struct PreparationTaskDescription: IndexTaskDescription { signposter.endInterval("Preparing", state) } do { - try await buildSystemManager.prepare(targets: Set(targetsToPrepare)) + try await buildServerManager.prepare(targets: Set(targetsToPrepare)) } catch { logger.error("Preparation failed: \(error.forLogging)") } diff --git a/Sources/SemanticIndex/SemanticIndexManager.swift b/Sources/SemanticIndex/SemanticIndexManager.swift index 67257cd2f..4823b1e4f 100644 --- a/Sources/SemanticIndex/SemanticIndexManager.swift +++ b/Sources/SemanticIndex/SemanticIndexManager.swift @@ -10,8 +10,8 @@ // //===----------------------------------------------------------------------===// +package import BuildServerIntegration package import BuildServerProtocol -package import BuildSystemIntegration import Foundation package import LanguageServerProtocol import LanguageServerProtocolExtensions @@ -166,8 +166,8 @@ package final actor SemanticIndexManager { /// need to be indexed again. private let index: UncheckedIndex - /// The build system manager that is used to get compiler arguments for a file. - private let buildSystemManager: BuildSystemManager + /// The build server manager that is used to get compiler arguments for a file. + private let buildServerManager: BuildServerManager /// How long to wait until we cancel an update indexstore task. This timeout should be long enough that all /// `swift-frontend` tasks finish within it. It prevents us from blocking the index if the type checker gets stuck on @@ -257,7 +257,7 @@ package final actor SemanticIndexManager { package init( index: UncheckedIndex, - buildSystemManager: BuildSystemManager, + buildServerManager: BuildServerManager, updateIndexStoreTimeout: Duration, hooks: IndexHooks, indexTaskScheduler: TaskScheduler, @@ -269,7 +269,7 @@ package final actor SemanticIndexManager { indexProgressStatusDidChange: @escaping @Sendable () -> Void ) { self.index = index - self.buildSystemManager = buildSystemManager + self.buildServerManager = buildServerManager self.updateIndexStoreTimeout = updateIndexStoreTimeout self.hooks = hooks self.indexTaskScheduler = indexTaskScheduler @@ -279,7 +279,7 @@ package final actor SemanticIndexManager { } /// Regenerate the build graph (also resolving package dependencies) and then index all the source files known to the - /// build system that don't currently have a unit with a timestamp that matches the mtime of the file. + /// build server that don't currently have a unit with a timestamp that matches the mtime of the file. /// /// This is a costly operation since it iterates through all the unit files on the file /// system but if existing unit files are not known to the index, we might re-index those files even if they are @@ -290,7 +290,7 @@ package final actor SemanticIndexManager { let generateBuildGraphTask = Task(priority: .low) { await withLoggingSubsystemAndScope(subsystem: indexLoggingSubsystem, scope: "build-graph-generation") { await hooks.buildGraphGenerationDidStart?() - await self.buildSystemManager.waitForUpToDateBuildGraph() + await self.buildServerManager.waitForUpToDateBuildGraph() // Polling for unit changes is a costly operation since it iterates through all the unit files on the file // system but if existing unit files are not known to the index, we might re-index those files even if they are // up-to-date. This operation is worth the cost during initial indexing and during the manual re-index command. @@ -300,7 +300,7 @@ package final actor SemanticIndexManager { // https://github.com/swiftlang/swift/issues/75602 let filesToIndex: [DocumentURI] = await orLog("Getting files to index") { - try await self.buildSystemManager.buildableSourceFiles().sorted { $0.stringValue < $1.stringValue } + try await self.buildServerManager.buildableSourceFiles().sorted { $0.stringValue < $1.stringValue } } ?? [] await self.scheduleIndexing( of: filesToIndex, @@ -381,7 +381,7 @@ package final actor SemanticIndexManager { var outOfDateTargets = Set() var targetsOfChangedFiles = Set() for file in changedFiles { - let changedTargets = await buildSystemManager.targets(for: file) + let changedTargets = await buildServerManager.targets(for: file) targetsOfChangedFiles.formUnion(changedTargets) if Language(inferredFromFileExtension: file) == nil { // Preparation tracking should be per file. For now consider any non-known-language change as having to @@ -390,7 +390,7 @@ package final actor SemanticIndexManager { outOfDateTargets.formUnion(changedTargets) } } - outOfDateTargets.formUnion(await buildSystemManager.targets(dependingOn: targetsOfChangedFiles)) + outOfDateTargets.formUnion(await buildServerManager.targets(dependingOn: targetsOfChangedFiles)) if !outOfDateTargets.isEmpty { logger.info( """ @@ -426,7 +426,7 @@ package final actor SemanticIndexManager { if let targets { var targetsAndDependencies = targets - targetsAndDependencies.formUnion(await buildSystemManager.targets(dependingOn: targets)) + targetsAndDependencies.formUnion(await buildServerManager.targets(dependingOn: targets)) if !targetsAndDependencies.isEmpty { logger.info( """ @@ -447,7 +447,7 @@ package final actor SemanticIndexManager { fileOrBuildTargetChangedTasks[uuid] = Task { await orLog("Scheduling re-indexing of changed targets") { defer { fileOrBuildTargetChangedTasks[uuid] = nil } - var sourceFiles = try await self.buildSystemManager.sourceFiles(includeNonBuildableFiles: false) + var sourceFiles = try await self.buildServerManager.sourceFiles(includeNonBuildableFiles: false) if let targets { sourceFiles = sourceFiles.filter { !targets.isDisjoint(with: $0.value.targets) } } @@ -473,7 +473,7 @@ package final actor SemanticIndexManager { indexFilesWithUpToDateUnits: Bool ) async -> [(file: FileIndexInfo, fileModificationDate: Date?)] { let sourceFiles = await orLog("Getting source files in project") { - try await buildSystemManager.buildableSourceFiles() + try await buildServerManager.buildableSourceFiles() } guard let sourceFiles else { return [] @@ -483,7 +483,7 @@ package final actor SemanticIndexManager { var filesToReIndex: [(FileIndexInfo, Date?)] = [] for uri in files { var didFindTargetToIndex = false - for (target, outputPath) in await buildSystemManager.sourceFileInfo(for: uri)?.targetsToOutputPath ?? [:] { + for (target, outputPath) in await buildServerManager.sourceFileInfo(for: uri)?.targetsToOutputPath ?? [:] { // First, check if we know that the file is up-to-date, in which case we don't need to hit the index or file // system at all if !indexFilesWithUpToDateUnits, await indexStoreUpToDateTracker.isUpToDate(uri, target) { @@ -515,14 +515,14 @@ package final actor SemanticIndexManager { // Deterministically pick a main file. This ensures that we always pick the same main file for a header. This way, // if we request the same header to be indexed twice, we'll pick the same unit file the second time around, // realize that its timestamp is later than the modification date of the header and we don't need to re-index. - let mainFile = await buildSystemManager.mainFiles(containing: uri) + let mainFile = await buildServerManager.mainFiles(containing: uri) .filter { sourceFiles.contains($0) } .sorted(by: { $0.stringValue < $1.stringValue }).first guard let mainFile else { logger.info("Not indexing \(uri.forLogging) because its main file could not be inferred") continue } - let targetAndOutputPath = (await buildSystemManager.sourceFileInfo(for: mainFile)?.targetsToOutputPath ?? [:]) + let targetAndOutputPath = (await buildServerManager.sourceFileInfo(for: mainFile)?.targetsToOutputPath ?? [:]) .sorted(by: { $0.key.uri.stringValue < $1.key.uri.stringValue }).first guard let targetAndOutputPath else { logger.info( @@ -603,7 +603,7 @@ package final actor SemanticIndexManager { /// /// If file's target is known to be up-to-date, this returns almost immediately. package func prepareFileForEditorFunctionality(_ uri: DocumentURI) async { - guard let target = await buildSystemManager.canonicalTarget(for: uri) else { + guard let target = await buildServerManager.canonicalTarget(for: uri) else { return } if Task.isCancelled { @@ -653,7 +653,7 @@ package final actor SemanticIndexManager { let taskDescription = AnyIndexTaskDescription( PreparationTaskDescription( targetsToPrepare: targetsToPrepare, - buildSystemManager: self.buildSystemManager, + buildServerManager: self.buildServerManager, preparationUpToDateTracker: preparationUpToDateTracker, logMessageToIndexLog: logMessageToIndexLog, hooks: hooks @@ -712,7 +712,7 @@ package final actor SemanticIndexManager { let taskDescription = AnyIndexTaskDescription( UpdateIndexStoreTaskDescription( filesToIndex: filesAndTargets, - buildSystemManager: self.buildSystemManager, + buildServerManager: self.buildServerManager, index: index, indexStoreUpToDateTracker: indexStoreUpToDateTracker, indexFilesWithUpToDateUnit: indexFilesWithUpToDateUnit, @@ -834,7 +834,7 @@ package final actor SemanticIndexManager { for (fileIndexInfo, fileModificationDate) in filesToIndex { guard - let language = await buildSystemManager.defaultLanguage( + let language = await buildServerManager.defaultLanguage( for: fileIndexInfo.file.mainFile, in: fileIndexInfo.target ), @@ -862,7 +862,7 @@ package final actor SemanticIndexManager { // The targets sorted in reverse topological order, low-level targets before high-level targets. If topological // sorting fails, sorted in another deterministic way where the actual order doesn't matter. var sortedTargets: [BuildTargetIdentifier] = - await orLog("Sorting targets") { try await buildSystemManager.topologicalSort(of: Array(filesByTarget.keys)) } + await orLog("Sorting targets") { try await buildServerManager.topologicalSort(of: Array(filesByTarget.keys)) } ?? Array(filesByTarget.keys).sorted { $0.uri.stringValue < $1.uri.stringValue } if Set(sortedTargets) != Set(filesByTarget.keys) { diff --git a/Sources/SemanticIndex/UpdateIndexStoreTaskDescription.swift b/Sources/SemanticIndex/UpdateIndexStoreTaskDescription.swift index 7bd2362c9..e96694def 100644 --- a/Sources/SemanticIndex/UpdateIndexStoreTaskDescription.swift +++ b/Sources/SemanticIndex/UpdateIndexStoreTaskDescription.swift @@ -10,8 +10,8 @@ // //===----------------------------------------------------------------------===// +package import BuildServerIntegration package import BuildServerProtocol -package import BuildSystemIntegration import Foundation package import LanguageServerProtocol import LanguageServerProtocolExtensions @@ -96,8 +96,8 @@ package struct UpdateIndexStoreTaskDescription: IndexTaskDescription { /// The files that should be indexed. package let filesToIndex: [FileIndexInfo] - /// The build system manager that is used to get the toolchain and build settings for the files to index. - private let buildSystemManager: BuildSystemManager + /// The build server manager that is used to get the toolchain and build settings for the files to index. + private let buildServerManager: BuildServerManager /// A reference to the underlying index store. Used to check if the index is already up-to-date for a file, in which /// case we don't need to index it again. @@ -142,7 +142,7 @@ package struct UpdateIndexStoreTaskDescription: IndexTaskDescription { init( filesToIndex: [FileIndexInfo], - buildSystemManager: BuildSystemManager, + buildServerManager: BuildServerManager, index: UncheckedIndex, indexStoreUpToDateTracker: UpToDateTracker, indexFilesWithUpToDateUnit: Bool, @@ -154,7 +154,7 @@ package struct UpdateIndexStoreTaskDescription: IndexTaskDescription { hooks: IndexHooks ) { self.filesToIndex = filesToIndex - self.buildSystemManager = buildSystemManager + self.buildServerManager = buildServerManager self.index = index self.indexStoreUpToDateTracker = indexStoreUpToDateTracker self.indexFilesWithUpToDateUnit = indexFilesWithUpToDateUnit @@ -253,11 +253,11 @@ package struct UpdateIndexStoreTaskDescription: IndexTaskDescription { if file.mainFile != file.sourceFile { logger.log("Updating index store of \(file.forLogging) using main file \(file.mainFile.forLogging)") } - guard let language = await buildSystemManager.defaultLanguage(for: file.mainFile, in: target) else { + guard let language = await buildServerManager.defaultLanguage(for: file.mainFile, in: target) else { logger.error("Not indexing \(file.forLogging) because its language could not be determined") return } - let buildSettings = await buildSystemManager.buildSettings( + let buildSettings = await buildServerManager.buildSettings( for: file.mainFile, in: target, language: language, @@ -278,7 +278,7 @@ package struct UpdateIndexStoreTaskDescription: IndexTaskDescription { logger.error("Not indexing \(file.forLogging) because it has fallback compiler arguments") return } - guard let toolchain = await buildSystemManager.toolchain(for: file.mainFile, in: target, language: language) else { + guard let toolchain = await buildServerManager.toolchain(for: file.mainFile, in: target, language: language) else { logger.error( "Not updating index store for \(file.forLogging) because no toolchain could be determined for the document" ) @@ -316,29 +316,29 @@ package struct UpdateIndexStoreTaskDescription: IndexTaskDescription { await indexStoreUpToDateTracker.markUpToDate([(file.sourceFile, target)], updateOperationStartDate: startDate) } - /// If `args` does not contain an `-index-store-path` argument, add it, pointing to the build system's index store - /// path. If an `-index-store-path` already exists, validate that it matches the build system's index store path and - /// replace it by the build system's index store path if they don't match. + /// If `args` does not contain an `-index-store-path` argument, add it, pointing to the build server's index store + /// path. If an `-index-store-path` already exists, validate that it matches the build server's index store path and + /// replace it by the build server's index store path if they don't match. private func addOrReplaceIndexStorePath(in args: [String], for uri: DocumentURI) async throws -> [String] { var args = args - guard let buildSystemIndexStorePath = await self.buildSystemManager.initializationData?.indexStorePath else { + guard let buildServerIndexStorePath = await self.buildServerManager.initializationData?.indexStorePath else { struct NoIndexStorePathError: Error {} throw NoIndexStorePathError() } if let indexStorePathIndex = args.lastIndex(of: "-index-store-path"), indexStorePathIndex + 1 < args.count { let indexStorePath = args[indexStorePathIndex + 1] - if indexStorePath != buildSystemIndexStorePath { + if indexStorePath != buildServerIndexStorePath { logger.error( """ - Compiler arguments for \(uri) specify index store path \(indexStorePath) but build system specified an \ - incompatible index store path \(buildSystemIndexStorePath). Overriding with the path specified by the build \ + Compiler arguments for \(uri) specify index store path \(indexStorePath) but build server specified an \ + incompatible index store path \(buildServerIndexStorePath). Overriding with the path specified by the build \ system. """ ) - args[indexStorePathIndex + 1] = buildSystemIndexStorePath + args[indexStorePathIndex + 1] = buildServerIndexStorePath } } else { - args += ["-index-store-path", buildSystemIndexStorePath] + args += ["-index-store-path", buildServerIndexStorePath] } return args } diff --git a/Sources/SourceKitLSP/CMakeLists.txt b/Sources/SourceKitLSP/CMakeLists.txt index c19ae3313..c1aa45d28 100644 --- a/Sources/SourceKitLSP/CMakeLists.txt +++ b/Sources/SourceKitLSP/CMakeLists.txt @@ -82,7 +82,7 @@ set_target_properties(SourceKitLSP PROPERTIES INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY}) target_link_libraries(SourceKitLSP PUBLIC BuildServerProtocol - BuildSystemIntegration + BuildServerIntegration LanguageServerProtocol LanguageServerProtocolExtensions LanguageServerProtocolJSONRPC diff --git a/Sources/SourceKitLSP/Clang/ClangLanguageService.swift b/Sources/SourceKitLSP/Clang/ClangLanguageService.swift index 6b75bc788..858db8800 100644 --- a/Sources/SourceKitLSP/Clang/ClangLanguageService.swift +++ b/Sources/SourceKitLSP/Clang/ClangLanguageService.swift @@ -10,7 +10,7 @@ // //===----------------------------------------------------------------------===// -import BuildSystemIntegration +import BuildServerIntegration import Foundation import LanguageServerProtocol import LanguageServerProtocolExtensions @@ -133,7 +133,7 @@ actor ClangLanguageService: LanguageService, MessageHandler { return nil } guard - let settings = await workspace.buildSystemManager.buildSettingsInferredFromMainFile( + let settings = await workspace.buildServerManager.buildSettingsInferredFromMainFile( for: document, language: language, fallbackAfterTimeout: fallbackAfterTimeout @@ -436,7 +436,7 @@ extension ClangLanguageService { clangd.send(notification) } - // MARK: - Build System Integration + // MARK: - Build Server Integration package func documentUpdatedBuildSettings(_ uri: DocumentURI) async { guard let url = uri.fileURL else { diff --git a/Sources/SourceKitLSP/Documentation/DoccDocumentationHandler.swift b/Sources/SourceKitLSP/Documentation/DoccDocumentationHandler.swift index 332a335fe..c83f4a179 100644 --- a/Sources/SourceKitLSP/Documentation/DoccDocumentationHandler.swift +++ b/Sources/SourceKitLSP/Documentation/DoccDocumentationHandler.swift @@ -11,7 +11,7 @@ //===----------------------------------------------------------------------===// #if canImport(DocCDocumentation) -import BuildSystemIntegration +import BuildServerIntegration import DocCDocumentation import Foundation @preconcurrency import IndexStoreDB @@ -32,9 +32,9 @@ extension DocumentationLanguageService { let snapshot = try documentManager.latestSnapshot(req.textDocument.uri) var moduleName: String? = nil var catalogURL: URL? = nil - if let target = await workspace.buildSystemManager.canonicalTarget(for: req.textDocument.uri) { - moduleName = await workspace.buildSystemManager.moduleName(for: target) - catalogURL = await workspace.buildSystemManager.doccCatalog(for: target) + if let target = await workspace.buildServerManager.canonicalTarget(for: req.textDocument.uri) { + moduleName = await workspace.buildServerManager.moduleName(for: target) + catalogURL = await workspace.buildServerManager.doccCatalog(for: target) } switch snapshot.language { diff --git a/Sources/SourceKitLSP/Hooks.swift b/Sources/SourceKitLSP/Hooks.swift index bd891c20e..e614fd974 100644 --- a/Sources/SourceKitLSP/Hooks.swift +++ b/Sources/SourceKitLSP/Hooks.swift @@ -10,7 +10,7 @@ // //===----------------------------------------------------------------------===// -package import BuildSystemIntegration +package import BuildServerIntegration import Foundation package import LanguageServerProtocol import LanguageServerProtocolExtensions @@ -23,7 +23,7 @@ import struct TSCBasic.RelativePath public struct Hooks: Sendable { package var indexHooks: IndexHooks - package var buildSystemHooks: BuildSystemHooks + package var buildServerHooks: BuildServerHooks /// A hook that will be executed before a request is handled. /// @@ -36,17 +36,17 @@ public struct Hooks: Sendable { package var preForwardRequestToClangd: (@Sendable (any RequestType) async -> Void)? public init() { - self.init(indexHooks: IndexHooks(), buildSystemHooks: BuildSystemHooks()) + self.init(indexHooks: IndexHooks(), buildServerHooks: BuildServerHooks()) } package init( indexHooks: IndexHooks = IndexHooks(), - buildSystemHooks: BuildSystemHooks = BuildSystemHooks(), + buildServerHooks: BuildServerHooks = BuildServerHooks(), preHandleRequest: (@Sendable (any RequestType) async -> Void)? = nil, preForwardRequestToClangd: (@Sendable (any RequestType) async -> Void)? = nil ) { self.indexHooks = indexHooks - self.buildSystemHooks = buildSystemHooks + self.buildServerHooks = buildServerHooks self.preHandleRequest = preHandleRequest self.preForwardRequestToClangd = preForwardRequestToClangd } diff --git a/Sources/SourceKitLSP/IndexStoreDB+MainFilesProvider.swift b/Sources/SourceKitLSP/IndexStoreDB+MainFilesProvider.swift index 0abc333ef..a879c0f23 100644 --- a/Sources/SourceKitLSP/IndexStoreDB+MainFilesProvider.swift +++ b/Sources/SourceKitLSP/IndexStoreDB+MainFilesProvider.swift @@ -10,7 +10,7 @@ // //===----------------------------------------------------------------------===// -import BuildSystemIntegration +import BuildServerIntegration import Foundation import IndexStoreDB package import LanguageServerProtocol @@ -18,9 +18,9 @@ import SKLogging import SemanticIndex import SwiftExtensions -extension UncheckedIndex: BuildSystemIntegration.MainFilesProvider { - /// - Important: This may return realpaths when the build system might not be using realpaths. Use - /// `BuildSystemManager.mainFiles(containing:)` to work around that problem. +extension UncheckedIndex: BuildServerIntegration.MainFilesProvider { + /// - Important: This may return realpaths when the build server might not be using realpaths. Use + /// `BuildServerManager.mainFiles(containing:)` to work around that problem. package func mainFiles(containing uri: DocumentURI, crossLanguage: Bool) -> Set { let mainFiles: Set if let filePath = orLog("File path to get main files", { try uri.fileURL?.filePath }) { diff --git a/Sources/SourceKitLSP/LanguageService.swift b/Sources/SourceKitLSP/LanguageService.swift index c4dc56cf6..fce4e3f43 100644 --- a/Sources/SourceKitLSP/LanguageService.swift +++ b/Sources/SourceKitLSP/LanguageService.swift @@ -150,14 +150,14 @@ package protocol LanguageService: AnyObject, Sendable { func willSaveDocument(_ notification: WillSaveTextDocumentNotification) async func didSaveDocument(_ notification: DidSaveTextDocumentNotification) async - // MARK: - Build System Integration + // MARK: - Build Server Integration - /// Sent when the `BuildSystem` has resolved build settings, such as for the initial build settings - /// or when the settings have changed (e.g. modified build system files). This may be sent before + /// Sent when the build server has resolved build settings, such as for the initial build settings + /// or when the settings have changed (e.g. modified build server files). This may be sent before /// the respective `DocumentURI` has been opened. func documentUpdatedBuildSettings(_ uri: DocumentURI) async - /// Sent when the `BuildSystem` has detected that dependencies of the given files have changed + /// Sent when the build server has detected that dependencies of the given files have changed /// (e.g. header files, swiftmodule files, other compiler input files). func documentDependenciesUpdated(_ uris: Set) async diff --git a/Sources/SourceKitLSP/SourceKitLSPServer.swift b/Sources/SourceKitLSP/SourceKitLSPServer.swift index 1dd4aee1b..8931acf08 100644 --- a/Sources/SourceKitLSP/SourceKitLSPServer.swift +++ b/Sources/SourceKitLSP/SourceKitLSPServer.swift @@ -10,8 +10,8 @@ // //===----------------------------------------------------------------------===// +import BuildServerIntegration import BuildServerProtocol -import BuildSystemIntegration import Dispatch import Foundation import IndexStoreDB @@ -199,8 +199,8 @@ package actor SourceKitLSPServer { } } - /// Search through all the parent directories of `uri` and check if any of these directories contain a workspace with - /// a build system. + /// Search through all the parent directories of `uri` and check if any of these directories contain a workspace that + /// can be handled by with a build server. /// /// The search will not consider any directory that is not a child of any of the directories in `rootUris`. This /// prevents us from picking up a workspace that is outside of the folders that the user opened. @@ -214,10 +214,10 @@ package actor SourceKitLSPServer { let workspaceRoots = workspacesAndIsImplicit.filter { !$0.isImplicit }.compactMap { $0.workspace.rootUri?.fileURL } // We want to skip creating another workspace if any existing already has the same config path. This could happen if - // an existing workspace hasn't realoaded after a new file was added to it (and thus that build system needs to be + // an existing workspace hasn't reloaded after a new file was added to it (and thus that build server needs to be // reloaded). let configPaths = await workspacesAndIsImplicit.asyncCompactMap { - await $0.workspace.buildSystemManager.configPath + await $0.workspace.buildServerManager.configPath } while url.pathComponents.count > 1 && workspaceRoots.contains(where: { $0.isPrefix(of: url) }) { @@ -228,20 +228,20 @@ package actor SourceKitLSPServer { let uri = DocumentURI(url) let options = SourceKitLSPOptions.merging(base: self.options, workspaceFolder: uri) - // Some build systems consider paths outside of the folder (eg. BSP has settings in the home directory). If we - // allowed those paths, then the very first folder that the file is in would always be its own build system - so + // Some build servers consider paths outside of the folder (eg. BSP has settings in the home directory). If we + // allowed those paths, then the very first folder that the file is in would always be its own build server - so // skip them in that case. guard - let buildSystemSpec = determineBuildSystem( + let buildServerSpec = determineBuildServer( forWorkspaceFolder: uri, onlyConsiderRoot: true, options: options, - hooks: hooks.buildSystemHooks + hooks: hooks.buildServerHooks ) else { continue } - if configPaths.contains(buildSystemSpec.configPath) { + if configPaths.contains(buildServerSpec.configPath) { continue } @@ -249,7 +249,7 @@ package actor SourceKitLSPServer { guard let workspace = await orLog( "Creating implicit workspace", - { try await createWorkspace(workspaceFolder: uri, options: options, buildSystemSpec: buildSystemSpec) } + { try await createWorkspace(workspaceFolder: uri, options: options, buildServerSpec: buildServerSpec) } ) else { continue @@ -297,7 +297,7 @@ package actor SourceKitLSPServer { // Pick the workspace with the best FileHandlingCapability for this file. // If there is a tie, use the workspace that occurred first in the list. var bestWorkspace = await self.workspaces.asyncFirst { - await !$0.buildSystemManager.targets(for: uri).isEmpty + await !$0.buildServerManager.targets(for: uri).isEmpty } if bestWorkspace == nil { // We weren't able to handle the document with any of the known workspaces. See if any of the document's parent @@ -433,7 +433,7 @@ package actor SourceKitLSPServer { continue } - // Close the document properly in the document manager and build system manager to start with a clean sheet when re-opening it. + // Close the document properly in the document manager and build server manager to start with a clean sheet when re-opening it. let closeNotification = DidCloseTextDocumentNotification(textDocument: TextDocumentIdentifier(documentUri)) await self.closeDocument(closeNotification, workspace: workspace) @@ -552,9 +552,9 @@ package actor SourceKitLSPServer { return service } - let toolchain = await workspace.buildSystemManager.toolchain( + let toolchain = await workspace.buildServerManager.toolchain( for: uri, - in: workspace.buildSystemManager.canonicalTarget(for: uri), + in: workspace.buildServerManager.canonicalTarget(for: uri), language: language ) guard let toolchain else { @@ -866,12 +866,12 @@ extension SourceKitLSPServer { /// Creates a workspace at the given `uri`. /// - /// A workspace does not necessarily have any build system attached to it, in which case `buildSystemSpec` may be + /// A workspace does not necessarily have any build server attached to it, in which case `buildServerSpec` may be /// `nil` - consider eg. a top level workspace folder with multiple SwiftPM projects inside it. private func createWorkspace( workspaceFolder: DocumentURI, options: SourceKitLSPOptions, - buildSystemSpec: BuildSystemSpec? + buildServerSpec: BuildServerSpec? ) async throws -> Workspace { guard let capabilityRegistry = capabilityRegistry else { struct NoCapabilityRegistryError: Error {} @@ -894,7 +894,7 @@ extension SourceKitLSPServer { documentManager: self.documentManager, rootUri: workspaceFolder, capabilityRegistry: capabilityRegistry, - buildSystemSpec: buildSystemSpec, + buildServerSpec: buildServerSpec, toolchainRegistry: self.toolchainRegistry, options: options, hooks: hooks, @@ -903,20 +903,20 @@ extension SourceKitLSPServer { return workspace } - /// Determines the build system for the given workspace folder and creates a `Workspace` that uses this inferred build + /// Determines the build server for the given workspace folder and creates a `Workspace` that uses this inferred build /// system. - private func createWorkspaceWithInferredBuildSystem(workspaceFolder: DocumentURI) async throws -> Workspace { + private func createWorkspaceWithInferredBuildServer(workspaceFolder: DocumentURI) async throws -> Workspace { let options = SourceKitLSPOptions.merging(base: self.options, workspaceFolder: workspaceFolder) - let buildSystemSpec = determineBuildSystem( + let buildServerSpec = determineBuildServer( forWorkspaceFolder: workspaceFolder, onlyConsiderRoot: false, options: options, - hooks: hooks.buildSystemHooks + hooks: hooks.buildServerHooks ) return try await self.createWorkspace( workspaceFolder: workspaceFolder, options: options, - buildSystemSpec: buildSystemSpec + buildServerSpec: buildServerSpec ) } @@ -978,7 +978,7 @@ extension SourceKitLSPServer { self.workspacesAndIsImplicit += await workspaceFolders.asyncCompactMap { workspaceFolder in await orLog("Creating workspace from workspaceFolders") { return ( - workspace: try await self.createWorkspaceWithInferredBuildSystem(workspaceFolder: workspaceFolder.uri), + workspace: try await self.createWorkspaceWithInferredBuildServer(workspaceFolder: workspaceFolder.uri), isImplicit: false ) } @@ -986,14 +986,14 @@ extension SourceKitLSPServer { } else if let uri = req.rootURI { await orLog("Creating workspace from rootURI") { self.workspacesAndIsImplicit.append( - (workspace: try await self.createWorkspaceWithInferredBuildSystem(workspaceFolder: uri), isImplicit: false) + (workspace: try await self.createWorkspaceWithInferredBuildServer(workspaceFolder: uri), isImplicit: false) ) } } else if let path = req.rootPath { let uri = DocumentURI(URL(fileURLWithPath: path)) await orLog("Creating workspace from rootPath") { self.workspacesAndIsImplicit.append( - (workspace: try await self.createWorkspaceWithInferredBuildSystem(workspaceFolder: uri), isImplicit: false) + (workspace: try await self.createWorkspaceWithInferredBuildServer(workspaceFolder: uri), isImplicit: false) ) } } @@ -1007,7 +1007,7 @@ extension SourceKitLSPServer { documentManager: self.documentManager, rootUri: req.rootURI, capabilityRegistry: self.capabilityRegistry!, - buildSystemSpec: nil, + buildServerSpec: nil, toolchainRegistry: self.toolchainRegistry, options: options, hooks: hooks, @@ -1209,8 +1209,8 @@ extension SourceKitLSPServer { for workspace in workspaces { taskGroup.addTask { await orLog("Shutting down build server") { - await workspace.buildSystemManager.shutdown() - await workspace.buildSystemManager.setMainFilesProvider(nil) + await workspace.buildServerManager.shutdown() + await workspace.buildServerManager.setMainFilesProvider(nil) workspace.closeIndex() } } @@ -1279,8 +1279,8 @@ extension SourceKitLSPServer { } private func openDocument(_ notification: DidOpenTextDocumentNotification, workspace: Workspace) async { - // Immediately open the document even if the build system isn't ready. This is important since - // we check that the document is open when we receive messages from the build system. + // Immediately open the document even if the build server isn't ready. This is important since + // we check that the document is open when we receive messages from the build server. let snapshot = orLog("Opening document") { try documentManager.open( notification.textDocument.uri, @@ -1303,7 +1303,7 @@ extension SourceKitLSPServer { return } - await workspace.buildSystemManager.registerForChangeNotifications(for: uri, language: language) + await workspace.buildServerManager.registerForChangeNotifications(for: uri, language: language) // If the document is ready, we can immediately send the notification. await service.openDocument(notification, snapshot: snapshot) @@ -1333,14 +1333,14 @@ extension SourceKitLSPServer { func closeDocument(_ notification: DidCloseTextDocumentNotification, workspace: Workspace) async { // Immediately close the document. We need to be sure to clear our pending work queue in case - // the build system still isn't ready. + // the build server still isn't ready. orLog("failed to close document", level: .error) { try documentManager.close(notification.textDocument.uri) } let uri = notification.textDocument.uri - await workspace.buildSystemManager.unregisterForChangeNotifications(for: uri) + await workspace.buildServerManager.unregisterForChangeNotifications(for: uri) await workspace.documentService(for: uri)?.closeDocument(notification) @@ -1458,7 +1458,7 @@ extension SourceKitLSPServer { if let added = notification.event.added { let newWorkspaces = await added.asyncCompactMap { workspaceFolder in await orLog("Creating workspace after workspace folder change") { - try await self.createWorkspaceWithInferredBuildSystem(workspaceFolder: workspaceFolder.uri) + try await self.createWorkspaceWithInferredBuildServer(workspaceFolder: workspaceFolder.uri) } } self.workspacesAndIsImplicit += newWorkspaces.map { (workspace: $0, isImplicit: false) } @@ -1469,9 +1469,9 @@ extension SourceKitLSPServer { func didChangeWatchedFiles(_ notification: DidChangeWatchedFilesNotification) async { // We can't make any assumptions about which file changes a particular build // system is interested in. Just because it doesn't have build settings for - // a file doesn't mean a file can't affect the build system's build settings + // a file doesn't mean a file can't affect the build server's build settings // (e.g. Package.swift doesn't have build settings but affects build - // settings). Inform the build system about all file changes. + // settings). Inform the build server about all file changes. await workspaces.concurrentForEach { await $0.filesDidChange(notification.changes) } } @@ -1500,7 +1500,7 @@ extension SourceKitLSPServer { let target: BuildTargetIdentifier? if let requestedTarget = request.target { target = BuildTargetIdentifier(uri: requestedTarget) - } else if let canonicalTarget = await workspace.buildSystemManager.canonicalTarget(for: uri) { + } else if let canonicalTarget = await workspace.buildServerManager.canonicalTarget(for: uri) { target = canonicalTarget } else { target = nil @@ -1511,7 +1511,7 @@ extension SourceKitLSPServer { } else { didPrepareTarget = nil } - let buildSettings = await workspace.buildSystemManager.buildSettingsInferredFromMainFile( + let buildSettings = await workspace.buildServerManager.buildSettingsInferredFromMainFile( for: request.textDocument.uri, target: target, language: nil, @@ -1536,10 +1536,10 @@ extension SourceKitLSPServer { guard let workspace = self.workspaces.first(where: { $0.rootUri == request.workspace }) else { throw ResponseError.unknown("No workspace with URI \(request.workspace.forLogging) found") } - guard await workspace.buildSystemManager.initializationData?.outputPathsProvider ?? false else { + guard await workspace.buildServerManager.initializationData?.outputPathsProvider ?? false else { throw ResponseError.unknown("Build server for \(request.workspace.forLogging) does not support output paths") } - let outputPaths = try await workspace.buildSystemManager.outputPaths(in: [ + let outputPaths = try await workspace.buildServerManager.outputPaths(in: [ BuildTargetIdentifier(uri: request.target) ]) return OutputPathsResponse(outputPaths: outputPaths) @@ -2657,7 +2657,7 @@ fileprivate struct NotificationRequestOperation { } /// Used to queue up notifications and requests for documents which are blocked -/// on `BuildSystem` operations such as fetching build settings. +/// on build server operations such as fetching build settings. /// /// Note: This is not thread safe. Must be called from the `SourceKitLSPServer.queue`. fileprivate struct DocumentNotificationRequestQueue { diff --git a/Sources/SourceKitLSP/Swift/DoccDocumentation.swift b/Sources/SourceKitLSP/Swift/DoccDocumentation.swift index d57fde7cc..a4d18329e 100644 --- a/Sources/SourceKitLSP/Swift/DoccDocumentation.swift +++ b/Sources/SourceKitLSP/Swift/DoccDocumentation.swift @@ -11,7 +11,7 @@ //===----------------------------------------------------------------------===// #if canImport(DocCDocumentation) -import BuildSystemIntegration +import BuildServerIntegration import DocCDocumentation import Foundation package import LanguageServerProtocol @@ -35,9 +35,9 @@ extension SwiftLanguageService { let snapshot = try documentManager.latestSnapshot(req.textDocument.uri) var moduleName: String? = nil var catalogURL: URL? = nil - if let target = await workspace.buildSystemManager.canonicalTarget(for: req.textDocument.uri) { - moduleName = await workspace.buildSystemManager.moduleName(for: target) - catalogURL = await workspace.buildSystemManager.doccCatalog(for: target) + if let target = await workspace.buildServerManager.canonicalTarget(for: req.textDocument.uri) { + moduleName = await workspace.buildServerManager.moduleName(for: target) + catalogURL = await workspace.buildServerManager.doccCatalog(for: target) } // Search for the nearest documentable symbol at this location diff --git a/Sources/SourceKitLSP/Swift/SwiftLanguageService.swift b/Sources/SourceKitLSP/Swift/SwiftLanguageService.swift index f0c4ca7ed..acaed8c0d 100644 --- a/Sources/SourceKitLSP/Swift/SwiftLanguageService.swift +++ b/Sources/SourceKitLSP/Swift/SwiftLanguageService.swift @@ -10,8 +10,8 @@ // //===----------------------------------------------------------------------===// +package import BuildServerIntegration import BuildServerProtocol -package import BuildSystemIntegration import Csourcekitd import Dispatch import Foundation @@ -299,7 +299,7 @@ package actor SwiftLanguageService: LanguageService, Sendable { guard let workspace = await sourceKitLSPServer.workspaceForDocument(uri: buildSettingsFile) else { return nil } - return await workspace.buildSystemManager.buildSettingsInferredFromMainFile( + return await workspace.buildServerManager.buildSettingsInferredFromMainFile( for: buildSettingsFile, language: .swift, fallbackAfterTimeout: fallbackAfterTimeout @@ -445,7 +445,7 @@ extension SwiftLanguageService { _ = try? await send(sourcekitdRequest: \.crashWithExit, sourcekitd.dictionary([:]), snapshot: nil) } - // MARK: - Build System Integration + // MARK: - Build Server Integration package func reopenDocument(_ notification: ReopenTextDocumentNotification) async { switch try? ReferenceDocumentURL(from: notification.textDocument.uri) { @@ -1053,8 +1053,8 @@ extension SwiftLanguageService { let snapshot = try documentManager.latestSnapshot(req.textDocument.uri) var targetDisplayName: String? = nil if let workspace = await sourceKitLSPServer?.workspaceForDocument(uri: req.textDocument.uri), - let target = await workspace.buildSystemManager.canonicalTarget(for: req.textDocument.uri), - let buildTarget = await workspace.buildSystemManager.buildTarget(named: target) + let target = await workspace.buildServerManager.canonicalTarget(for: req.textDocument.uri), + let buildTarget = await workspace.buildServerManager.buildTarget(named: target) { targetDisplayName = buildTarget.displayName } diff --git a/Sources/SourceKitLSP/Swift/SyntacticTestIndex.swift b/Sources/SourceKitLSP/Swift/SyntacticTestIndex.swift index 84be9450f..44647886f 100644 --- a/Sources/SourceKitLSP/Swift/SyntacticTestIndex.swift +++ b/Sources/SourceKitLSP/Swift/SyntacticTestIndex.swift @@ -18,7 +18,7 @@ import SwiftExtensions /// Task metadata for `SyntacticTestIndexer.indexingQueue` fileprivate enum TaskMetadata: DependencyTracker, Equatable { - /// Determine the list of test files from the build system and scan them for tests. Only created when the + /// Determine the list of test files from the build server and scan them for tests. Only created when the /// `SyntacticTestIndex` is created case initialPopulation @@ -183,7 +183,7 @@ actor SyntacticTestIndex { removedFiles.subtract(uris) // If we already know that the file has an up-to-date index, avoid re-scheduling it to be indexed. This ensures - // that we don't bloat `indexingQueue` if the build system is sending us repeated `buildTarget/didChange` + // that we don't bloat `indexingQueue` if the build server is sending us repeated `buildTarget/didChange` // notifications. // This check does not need to be perfect and there might be an in-progress index operation that is about to index // the file. In that case we still schedule anothe rescan of that file and notice in `rescanFilesAssumingOnQueue` diff --git a/Sources/SourceKitLSP/Swift/WithSnapshotFromDiskOpenedInSourcekitd.swift b/Sources/SourceKitLSP/Swift/WithSnapshotFromDiskOpenedInSourcekitd.swift index 27918784b..305c7c593 100644 --- a/Sources/SourceKitLSP/Swift/WithSnapshotFromDiskOpenedInSourcekitd.swift +++ b/Sources/SourceKitLSP/Swift/WithSnapshotFromDiskOpenedInSourcekitd.swift @@ -10,7 +10,7 @@ // //===----------------------------------------------------------------------===// -import BuildSystemIntegration +import BuildServerIntegration import Foundation import LanguageServerProtocol import SKLogging diff --git a/Sources/SourceKitLSP/TestDiscovery.swift b/Sources/SourceKitLSP/TestDiscovery.swift index 1044e389b..07a7731d4 100644 --- a/Sources/SourceKitLSP/TestDiscovery.swift +++ b/Sources/SourceKitLSP/TestDiscovery.swift @@ -10,8 +10,8 @@ // //===----------------------------------------------------------------------===// +import BuildServerIntegration import BuildServerProtocol -import BuildSystemIntegration import Foundation import IndexStoreDB package import LanguageServerProtocol @@ -196,9 +196,9 @@ extension SourceKitLSPServer { /// The returned list of tests is not sorted. It should be sorted before being returned to the editor. private func tests(in workspace: Workspace) async -> [AnnotatedTestItem] { // If files have recently been added to the workspace (which is communicated by a `workspace/didChangeWatchedFiles` - // notification, wait these changes to be reflected in the build system so we can include the updated files in the + // notification, wait these changes to be reflected in the build server so we can include the updated files in the // tests. - await workspace.buildSystemManager.waitForUpToDateBuildGraph() + await workspace.buildServerManager.waitForUpToDateBuildGraph() // Gather all tests classes and test methods. We include test from different sources: // - For all files that have been not been modified since they were last indexed in the semantic index, include @@ -318,7 +318,7 @@ extension SourceKitLSPServer { languageService: LanguageService ) async throws -> [AnnotatedTestItem] { let snapshot = try self.documentManager.latestSnapshot(req.textDocument.uri) - let mainFileUri = await workspace.buildSystemManager.mainFile( + let mainFileUri = await workspace.buildServerManager.mainFile( for: req.textDocument.uri, language: snapshot.language ) @@ -582,8 +582,8 @@ extension TestItem { } fileprivate func prefixIDWithModuleName(workspace: Workspace) async -> TestItem { - guard let canonicalTarget = await workspace.buildSystemManager.canonicalTarget(for: self.location.uri), - let moduleName = await workspace.buildSystemManager.moduleName(for: self.location.uri, in: canonicalTarget) + guard let canonicalTarget = await workspace.buildServerManager.canonicalTarget(for: self.location.uri), + let moduleName = await workspace.buildServerManager.moduleName(for: self.location.uri, in: canonicalTarget) else { return self } @@ -600,9 +600,9 @@ extension SwiftLanguageService { for uri: DocumentURI, in workspace: Workspace ) async throws -> [AnnotatedTestItem]? { - let targetIdentifiers = await workspace.buildSystemManager.targets(for: uri) + let targetIdentifiers = await workspace.buildServerManager.targets(for: uri) let isInTestTarget = await targetIdentifiers.asyncContains(where: { - await workspace.buildSystemManager.buildTarget(named: $0)?.tags.contains(.test) ?? true + await workspace.buildServerManager.buildTarget(named: $0)?.tags.contains(.test) ?? true }) if !targetIdentifiers.isEmpty && !isInTestTarget { // If we know the targets for the file and the file is not part of any test target, don't scan it for tests. diff --git a/Sources/SourceKitLSP/Workspace.swift b/Sources/SourceKitLSP/Workspace.swift index 88c259fa7..c83d094a3 100644 --- a/Sources/SourceKitLSP/Workspace.swift +++ b/Sources/SourceKitLSP/Workspace.swift @@ -10,8 +10,8 @@ // //===----------------------------------------------------------------------===// +package import BuildServerIntegration package import BuildServerProtocol -package import BuildSystemIntegration import Foundation import IndexStoreDB package import LanguageServerProtocol @@ -32,11 +32,11 @@ package import DocCDocumentation /// Actor that caches realpaths for `sourceFilesWithSameRealpath`. fileprivate actor SourceFilesWithSameRealpathInferrer { - private let buildSystemManager: BuildSystemManager + private let buildServerManager: BuildServerManager private var realpathCache: [DocumentURI: DocumentURI] = [:] - init(buildSystemManager: BuildSystemManager) { - self.buildSystemManager = buildSystemManager + init(buildServerManager: BuildServerManager) { + self.buildServerManager = buildServerManager } private func realpath(of uri: DocumentURI) -> DocumentURI { @@ -58,7 +58,7 @@ fileprivate actor SourceFilesWithSameRealpathInferrer { let realPaths = Set(documents.map { realpath(of: $0) }) return await orLog("Determining source files with same realpath") { var result: [DocumentURI] = [] - let filesAndDirectories = try await buildSystemManager.sourceFiles(includeNonBuildableFiles: true) + let filesAndDirectories = try await buildServerManager.sourceFiles(includeNonBuildableFiles: true) for file in filesAndDirectories.keys { if realPaths.contains(realpath(of: file)) && !documents.contains(file) { result.append(file) @@ -82,7 +82,7 @@ fileprivate actor SourceFilesWithSameRealpathInferrer { /// "initialize" request has been made. /// /// Typically a workspace is contained in a root directory. -package final class Workspace: Sendable, BuildSystemManagerDelegate { +package final class Workspace: Sendable, BuildServerManagerDelegate { /// The ``SourceKitLSPServer`` instance that created this `Workspace`. private(set) weak nonisolated(unsafe) var sourceKitLSPServer: SourceKitLSPServer? { didSet { @@ -98,8 +98,8 @@ package final class Workspace: Sendable, BuildSystemManagerDelegate { /// Tracks dynamically registered server capabilities as well as the client's capabilities. package let capabilityRegistry: CapabilityRegistry - /// The build system manager to use for documents in this workspace. - package let buildSystemManager: BuildSystemManager + /// The build server manager to use for documents in this workspace. + package let buildServerManager: BuildServerManager #if canImport(DocCDocumentation) package let doccDocumentationManager: DocCDocumentationManager @@ -142,7 +142,7 @@ package final class Workspace: Sendable, BuildSystemManagerDelegate { capabilityRegistry: CapabilityRegistry, options: SourceKitLSPOptions, hooks: Hooks, - buildSystemManager: BuildSystemManager, + buildServerManager: BuildServerManager, index uncheckedIndex: UncheckedIndex?, indexDelegate: SourceKitIndexDelegate?, indexTaskScheduler: TaskScheduler @@ -152,19 +152,19 @@ package final class Workspace: Sendable, BuildSystemManagerDelegate { self.capabilityRegistry = capabilityRegistry self.options = options self._uncheckedIndex = ThreadSafeBox(initialValue: uncheckedIndex) - self.buildSystemManager = buildSystemManager + self.buildServerManager = buildServerManager #if canImport(DocCDocumentation) - self.doccDocumentationManager = DocCDocumentationManager(buildSystemManager: buildSystemManager) + self.doccDocumentationManager = DocCDocumentationManager(buildServerManager: buildServerManager) #endif self.sourceFilesWithSameRealpathInferrer = SourceFilesWithSameRealpathInferrer( - buildSystemManager: buildSystemManager + buildServerManager: buildServerManager ) if options.backgroundIndexingOrDefault, let uncheckedIndex, - await buildSystemManager.initializationData?.prepareProvider ?? false + await buildServerManager.initializationData?.prepareProvider ?? false { self.semanticIndexManager = SemanticIndexManager( index: uncheckedIndex, - buildSystemManager: buildSystemManager, + buildServerManager: buildServerManager, updateIndexStoreTimeout: options.indexOrDefault.updateIndexStoreTimeoutOrDefault, hooks: hooks.indexHooks, indexTaskScheduler: indexTaskScheduler, @@ -184,11 +184,11 @@ package final class Workspace: Sendable, BuildSystemManagerDelegate { // Trigger an initial population of `syntacticTestIndex`. self.syntacticTestIndex = SyntacticTestIndex(determineTestFiles: { await orLog("Getting list of test files for initial syntactic index population") { - try await buildSystemManager.testFiles() + try await buildServerManager.testFiles() } ?? [] }) await indexDelegate?.addMainFileChangedCallback { [weak self] in - await self?.buildSystemManager.mainFilesChanged() + await self?.buildServerManager.mainFilesChanged() } if let semanticIndexManager { await semanticIndexManager.scheduleBuildGraphGenerationAndBackgroundIndexAllFiles( @@ -208,13 +208,13 @@ package final class Workspace: Sendable, BuildSystemManagerDelegate { documentManager: DocumentManager, rootUri: DocumentURI?, capabilityRegistry: CapabilityRegistry, - buildSystemSpec: BuildSystemSpec?, + buildServerSpec: BuildServerSpec?, toolchainRegistry: ToolchainRegistry, options: SourceKitLSPOptions, hooks: Hooks, indexTaskScheduler: TaskScheduler ) async { - struct ConnectionToClient: BuildSystemManagerConnectionToClient { + struct ConnectionToClient: BuildServerManagerConnectionToClient { func waitUntilInitialized() async { await sourceKitLSPServer?.waitUntilInitialized() } @@ -272,34 +272,34 @@ package final class Workspace: Sendable, BuildSystemManagerDelegate { } } - let buildSystemManager = await BuildSystemManager( - buildSystemSpec: buildSystemSpec, + let buildServerManager = await BuildServerManager( + buildServerSpec: buildServerSpec, toolchainRegistry: toolchainRegistry, options: options, connectionToClient: ConnectionToClient(sourceKitLSPServer: sourceKitLSPServer), - buildSystemHooks: hooks.buildSystemHooks + buildServerHooks: hooks.buildServerHooks ) logger.log( - "Created workspace at \(rootUri.forLogging) with project root \(buildSystemSpec?.projectRoot.description ?? "")" + "Created workspace at \(rootUri.forLogging) with project root \(buildServerSpec?.projectRoot.description ?? "")" ) var indexDelegate: SourceKitIndexDelegate? = nil let indexOptions = options.indexOrDefault let indexStorePath: URL? = - if let indexStorePath = await buildSystemManager.initializationData?.indexStorePath { + if let indexStorePath = await buildServerManager.initializationData?.indexStorePath { URL(fileURLWithPath: indexStorePath, relativeTo: rootUri?.fileURL) } else { nil } let indexDatabasePath: URL? = - if let indexDatabasePath = await buildSystemManager.initializationData?.indexDatabasePath { + if let indexDatabasePath = await buildServerManager.initializationData?.indexDatabasePath { URL(fileURLWithPath: indexDatabasePath, relativeTo: rootUri?.fileURL) } else { nil } - let supportsOutputPaths = await buildSystemManager.initializationData?.outputPathsProvider ?? false + let supportsOutputPaths = await buildServerManager.initializationData?.outputPathsProvider ?? false let index: UncheckedIndex? if let indexStorePath, let indexDatabasePath, let libPath = await toolchainRegistry.default?.libIndexStore { do { @@ -348,7 +348,7 @@ package final class Workspace: Sendable, BuildSystemManagerDelegate { index = nil } - await buildSystemManager.setMainFilesProvider(index) + await buildServerManager.setMainFilesProvider(index) await self.init( sourceKitLSPServer: sourceKitLSPServer, @@ -356,12 +356,12 @@ package final class Workspace: Sendable, BuildSystemManagerDelegate { capabilityRegistry: capabilityRegistry, options: options, hooks: hooks, - buildSystemManager: buildSystemManager, + buildServerManager: buildServerManager, index: index, indexDelegate: indexDelegate, indexTaskScheduler: indexTaskScheduler ) - await buildSystemManager.setDelegate(self) + await buildServerManager.setDelegate(self) // Populate the initial list of unit output paths in the index. await scheduleUpdateOfUnitOutputPathsInIndexIfNecessary() @@ -370,7 +370,7 @@ package final class Workspace: Sendable, BuildSystemManagerDelegate { package static func forTesting( options: SourceKitLSPOptions, testHooks: Hooks, - buildSystemManager: BuildSystemManager, + buildServerManager: BuildServerManager, indexTaskScheduler: TaskScheduler ) async -> Workspace { return await Workspace( @@ -379,7 +379,7 @@ package final class Workspace: Sendable, BuildSystemManagerDelegate { capabilityRegistry: CapabilityRegistry(clientCapabilities: ClientCapabilities()), options: options, hooks: testHooks, - buildSystemManager: buildSystemManager, + buildServerManager: buildServerManager, index: nil, indexDelegate: nil, indexTaskScheduler: indexTaskScheduler @@ -412,7 +412,7 @@ package final class Workspace: Sendable, BuildSystemManagerDelegate { .map { FileEvent(uri: $0, type: .changed) } // Notify all clients about the reported and inferred edits. - await buildSystemManager.filesDidChange(events) + await buildServerManager.filesDidChange(events) #if canImport(DocCDocumentation) await doccDocumentationManager.filesDidChange(events) #endif @@ -441,7 +441,7 @@ package final class Workspace: Sendable, BuildSystemManagerDelegate { } } - /// Handle a build settings change notification from the `BuildSystem`. + /// Handle a build settings change notification from the build serveer. /// This has two primary cases: /// - Initial settings reported for a given file, now we can fully open it /// - Changed settings for an already open file @@ -451,7 +451,7 @@ package final class Workspace: Sendable, BuildSystemManagerDelegate { } } - /// Handle a dependencies updated notification from the `BuildSystem`. + /// Handle a dependencies updated notification from the build server. /// We inform the respective language services as long as the given file is open /// (not queued for opening). package func filesDependenciesUpdated(_ changedFiles: Set) async { @@ -473,7 +473,7 @@ package final class Workspace: Sendable, BuildSystemManagerDelegate { await sourceKitLSPServer?.fileHandlingCapabilityChanged() await semanticIndexManager?.buildTargetsChanged(changes) await orLog("Scheduling syntactic test re-indexing") { - let testFiles = try await buildSystemManager.testFiles() + let testFiles = try await buildServerManager.testFiles() await syntacticTestIndex.listOfTestFilesDidChange(testFiles) } @@ -484,16 +484,16 @@ package final class Workspace: Sendable, BuildSystemManagerDelegate { guard await self.uncheckedIndex?.usesExplicitOutputPaths ?? false else { return } - guard await buildSystemManager.initializationData?.outputPathsProvider ?? false else { - // This can only happen if an index got injected that uses explicit output paths but the build system does not + guard await buildServerManager.initializationData?.outputPathsProvider ?? false else { + // This can only happen if an index got injected that uses explicit output paths but the build server does not // support output paths. - logger.error("The index uses explicit output paths but the build system does not support output paths") + logger.error("The index uses explicit output paths but the build server does not support output paths") return } indexUnitOutputPathsUpdateQueue.async { await orLog("Setting new list of unit output paths") { - let outputPaths = try await Set(self.buildSystemManager.outputPathsInAllTargets()) + let outputPaths = try await Set(self.buildServerManager.outputPathsInAllTargets()) await self.uncheckedIndex?.setUnitOutputPaths(outputPaths) } } @@ -511,7 +511,7 @@ package final class Workspace: Sendable, BuildSystemManagerDelegate { package func synchronize(_ request: SynchronizeRequest) async { if request.buildServerUpdates ?? false || request.index ?? false { - await buildSystemManager.waitForUpToDateBuildGraph() + await buildServerManager.waitForUpToDateBuildGraph() await indexUnitOutputPathsUpdateQueue.async {}.value } if request.index ?? false { diff --git a/Sources/sourcekit-lsp/CMakeLists.txt b/Sources/sourcekit-lsp/CMakeLists.txt index e734e738a..03a058f0c 100644 --- a/Sources/sourcekit-lsp/CMakeLists.txt +++ b/Sources/sourcekit-lsp/CMakeLists.txt @@ -2,7 +2,7 @@ add_executable(sourcekit-lsp SourceKitLSP.swift) target_link_libraries(sourcekit-lsp PRIVATE - BuildSystemIntegration + BuildServerIntegration Diagnose LanguageServerProtocol LanguageServerProtocolExtensions diff --git a/Sources/sourcekit-lsp/SourceKitLSP.swift b/Sources/sourcekit-lsp/SourceKitLSP.swift index 893bb2bd9..737856e6a 100644 --- a/Sources/sourcekit-lsp/SourceKitLSP.swift +++ b/Sources/sourcekit-lsp/SourceKitLSP.swift @@ -11,7 +11,7 @@ //===----------------------------------------------------------------------===// public import ArgumentParser -import BuildSystemIntegration +import BuildServerIntegration import Csourcekitd // Not needed here, but fixes debugging... import Diagnose import Dispatch diff --git a/Tests/BuildSystemIntegrationTests/BuildSystemManagerTests.swift b/Tests/BuildServerIntegrationTests/BuildSystemManagerTests.swift similarity index 90% rename from Tests/BuildSystemIntegrationTests/BuildSystemManagerTests.swift rename to Tests/BuildServerIntegrationTests/BuildSystemManagerTests.swift index 45aeaa364..3d0b39ed5 100644 --- a/Tests/BuildSystemIntegrationTests/BuildSystemManagerTests.swift +++ b/Tests/BuildServerIntegrationTests/BuildSystemManagerTests.swift @@ -10,8 +10,8 @@ // //===----------------------------------------------------------------------===// +@_spi(Testing) import BuildServerIntegration import BuildServerProtocol -@_spi(Testing) import BuildSystemIntegration import LanguageServerProtocol import LanguageServerProtocolExtensions import SKLogging @@ -22,7 +22,7 @@ import TSCBasic import ToolchainRegistry import XCTest -fileprivate actor TestBuildSystem: CustomBuildServer { +fileprivate actor TestBuildServer: CustomBuildServer { let inProgressRequestsTracker = CustomBuildServerInProgressRequestTracker() private let connectionToSourceKitLSP: any Connection private var buildSettingsByFile: [DocumentURI: TextDocumentSourceKitOptionsResponse] = [:] @@ -47,45 +47,45 @@ fileprivate actor TestBuildSystem: CustomBuildServer { } } -fileprivate extension BuildSystemManager { +fileprivate extension BuildServerManager { func fileBuildSettingsChanged(_ changedFiles: Set) async { handle(OnBuildTargetDidChangeNotification(changes: nil)) } } -final class BuildSystemManagerTests: XCTestCase { - /// The build system manager that we use to verify SourceKitLSPServer behavior. +final class BuildServerManagerTests: XCTestCase { + /// The build server manager that we use to verify SourceKitLSPServer behavior. /// /// - Note: Set before each test run in `setUp`. - private var manager: BuildSystemManager! = nil + private var manager: BuildServerManager! = nil - /// The build system that we use to verify SourceKitLSPServer behavior. + /// The build server that we use to verify SourceKitLSPServer behavior. /// /// - Note: Set before each test run in `setUp`. - private var buildSystem: TestBuildSystem! = nil + private var buildServer: TestBuildServer! = nil override func setUp() async throws { let dummyPath = URL(fileURLWithPath: "/") - let testBuildSystem = ThreadSafeBox(initialValue: nil) - let spec = BuildSystemSpec( + let testBuildServer = ThreadSafeBox(initialValue: nil) + let spec = BuildServerSpec( kind: .injected({ projectRoot, connectionToSourceKitLSP in - assert(testBuildSystem.value == nil, "Build system injector hook can only create a single TestBuildSystem") - let buildSystem = TestBuildSystem(projectRoot: projectRoot, connectionToSourceKitLSP: connectionToSourceKitLSP) - testBuildSystem.value = buildSystem - return LocalConnection(receiverName: "TestBuildSystem", handler: buildSystem) + assert(testBuildServer.value == nil, "Build erver injector hook can only create a single TestBuildServer") + let buildServer = TestBuildServer(projectRoot: projectRoot, connectionToSourceKitLSP: connectionToSourceKitLSP) + testBuildServer.value = buildServer + return LocalConnection(receiverName: "TestBuildServer", handler: buildServer) }), projectRoot: dummyPath, configPath: dummyPath ) - self.manager = await BuildSystemManager( - buildSystemSpec: spec, + self.manager = await BuildServerManager( + buildServerSpec: spec, toolchainRegistry: ToolchainRegistry.forTesting, options: SourceKitLSPOptions(), - connectionToClient: DummyBuildSystemManagerConnectionToClient(), - buildSystemHooks: BuildSystemHooks() + connectionToClient: DummyBuildServerManagerConnectionToClient(), + buildServerHooks: BuildServerHooks() ) - self.buildSystem = try unwrap(testBuildSystem.value) + self.buildServer = try unwrap(testBuildServer.value) } func testMainFiles() async throws { @@ -158,7 +158,7 @@ final class BuildSystemManagerTests: XCTestCase { await manager.setMainFilesProvider(mainFiles) let del = await BSMDelegate(manager) - await buildSystem.setBuildSettings(for: a, to: TextDocumentSourceKitOptionsResponse(compilerArguments: ["x"])) + await buildServer.setBuildSettings(for: a, to: TextDocumentSourceKitOptionsResponse(compilerArguments: ["x"])) // Wait for the new build settings to settle before registering for change notifications await manager.waitForUpToDateBuildGraph() await manager.registerForChangeNotifications(for: a, language: .swift) @@ -172,7 +172,7 @@ final class BuildSystemManagerTests: XCTestCase { await del.setExpected([ (a, .swift, fallbackBuildSettings(for: a, language: .swift, options: .init()), changed) ]) - await buildSystem.setBuildSettings(for: a, to: nil) + await buildServer.setBuildSettings(for: a, to: nil) try await fulfillmentOfOrThrow(changed) } @@ -186,7 +186,7 @@ final class BuildSystemManagerTests: XCTestCase { let changed = expectation(description: "changed settings") await del.setExpected([(a, .swift, FileBuildSettings(compilerArguments: ["x"], language: .swift), changed)]) - await buildSystem.setBuildSettings(for: a, to: TextDocumentSourceKitOptionsResponse(compilerArguments: ["x"])) + await buildServer.setBuildSettings(for: a, to: TextDocumentSourceKitOptionsResponse(compilerArguments: ["x"])) try await fulfillmentOfOrThrow(changed) } @@ -207,7 +207,7 @@ final class BuildSystemManagerTests: XCTestCase { await del.setExpected([ (a, .swift, FileBuildSettings(compilerArguments: ["non-fallback", "args"], language: .swift), changed) ]) - await buildSystem.setBuildSettings( + await buildServer.setBuildSettings( for: a, to: TextDocumentSourceKitOptionsResponse(compilerArguments: ["non-fallback", "args"]) ) @@ -215,7 +215,7 @@ final class BuildSystemManagerTests: XCTestCase { let revert = expectation(description: "revert to fallback settings") await del.setExpected([(a, .swift, fallbackSettings, revert)]) - await buildSystem.setBuildSettings(for: a, to: nil) + await buildServer.setBuildSettings(for: a, to: nil) try await fulfillmentOfOrThrow(revert) } @@ -234,11 +234,11 @@ final class BuildSystemManagerTests: XCTestCase { await manager.setMainFilesProvider(mainFiles) let del = await BSMDelegate(manager) - await buildSystem.setBuildSettings( + await buildServer.setBuildSettings( for: cpp1, to: TextDocumentSourceKitOptionsResponse(compilerArguments: ["C++ 1"]) ) - await buildSystem.setBuildSettings( + await buildServer.setBuildSettings( for: cpp2, to: TextDocumentSourceKitOptionsResponse(compilerArguments: ["C++ 2"]) ) @@ -297,7 +297,7 @@ final class BuildSystemManagerTests: XCTestCase { let del = await BSMDelegate(manager) let cppArg = "C++ Main File" - await buildSystem.setBuildSettings( + await buildServer.setBuildSettings( for: cpp, to: TextDocumentSourceKitOptionsResponse(compilerArguments: [cppArg, cpp.pseudoPath]) ) @@ -328,7 +328,7 @@ final class BuildSystemManagerTests: XCTestCase { (h1, .c, newArgsH1, changed1), (h2, .c, newArgsH2, changed2), ]) - await buildSystem.setBuildSettings( + await buildServer.setBuildSettings( for: cpp, to: TextDocumentSourceKitOptionsResponse(compilerArguments: [newCppArg, cpp.pseudoPath]) ) @@ -358,8 +358,8 @@ private final actor ManualMainFilesProvider: MainFilesProvider { } } -/// A `BuildSystemDelegate` setup for testing. -private actor BSMDelegate: BuildSystemManagerDelegate { +/// A `BuildServerMangerDelegate` setup for testing. +private actor BSMDelegate: BuildServerManagerDelegate { func watchFiles(_ fileWatchers: [LanguageServerProtocol.FileSystemWatcher]) async {} fileprivate typealias ExpectedBuildSettingChangedCall = ( @@ -370,7 +370,7 @@ private actor BSMDelegate: BuildSystemManagerDelegate { uri: DocumentURI, expectation: XCTestExpectation, file: StaticString, line: UInt ) - unowned let manager: BuildSystemManager + unowned let manager: BuildServerManager var expected: [ExpectedBuildSettingChangedCall] = [] /// - Note: Needed to set `expected` outside of the actor's isolation context. @@ -382,7 +382,7 @@ private actor BSMDelegate: BuildSystemManagerDelegate { self.expected = expected.map { ($0.uri, $0.language, $0.settings, $0.expectation, file, line) } } - init(_ manager: BuildSystemManager) async { + init(_ manager: BuildServerManager) async { self.manager = manager await manager.setDelegate(self) } diff --git a/Tests/BuildSystemIntegrationTests/CompilationDatabasePerfTests.swift b/Tests/BuildServerIntegrationTests/CompilationDatabasePerfTests.swift similarity index 97% rename from Tests/BuildSystemIntegrationTests/CompilationDatabasePerfTests.swift rename to Tests/BuildServerIntegrationTests/CompilationDatabasePerfTests.swift index e6729bd15..969b4e225 100644 --- a/Tests/BuildSystemIntegrationTests/CompilationDatabasePerfTests.swift +++ b/Tests/BuildServerIntegrationTests/CompilationDatabasePerfTests.swift @@ -10,7 +10,7 @@ // //===----------------------------------------------------------------------===// -import BuildSystemIntegration +import BuildServerIntegration import LanguageServerProtocol import SKTestSupport import TSCBasic diff --git a/Tests/BuildSystemIntegrationTests/CompilationDatabaseTests.swift b/Tests/BuildServerIntegrationTests/CompilationDatabaseTests.swift similarity index 81% rename from Tests/BuildSystemIntegrationTests/CompilationDatabaseTests.swift rename to Tests/BuildServerIntegrationTests/CompilationDatabaseTests.swift index 79ceae540..8a002d967 100644 --- a/Tests/BuildSystemIntegrationTests/CompilationDatabaseTests.swift +++ b/Tests/BuildServerIntegrationTests/CompilationDatabaseTests.swift @@ -10,8 +10,8 @@ // //===----------------------------------------------------------------------===// +import BuildServerIntegration import BuildServerProtocol -import BuildSystemIntegration import LanguageServerProtocol import LanguageServerProtocolExtensions import SKTestSupport @@ -186,7 +186,7 @@ final class CompilationDatabaseTests: XCTestCase { func testJSONCompilationDatabaseFromDirectory() async throws { try await withTestScratchDir { tempDir in - let dbFile = tempDir.appendingPathComponent(JSONCompilationDatabaseBuildSystem.dbName) + let dbFile = tempDir.appendingPathComponent(JSONCompilationDatabaseBuildServer.dbName) XCTAssertThrowsError(try JSONCompilationDatabase(file: dbFile)) @@ -206,10 +206,10 @@ final class CompilationDatabaseTests: XCTestCase { func testFixedCompilationDatabase() async throws { try await withTestScratchDir { tempDir in - let dbFile = tempDir.appendingPathComponent(FixedCompilationDatabaseBuildSystem.dbName) + let dbFile = tempDir.appendingPathComponent(FixedCompilationDatabaseBuildServer.dbName) XCTAssertThrowsError( - try FixedCompilationDatabaseBuildSystem( + try FixedCompilationDatabaseBuildServer( configPath: dbFile, connectionToSourceKitLSP: LocalConnection(receiverName: "Dummy SourceKit-LSP") ) @@ -221,15 +221,15 @@ final class CompilationDatabaseTests: XCTestCase { libwidget/include/ """.write(to: dbFile, atomically: true, encoding: .utf8) - let buildSystem = try XCTUnwrap( - try FixedCompilationDatabaseBuildSystem( + let buildServer = try XCTUnwrap( + try FixedCompilationDatabaseBuildServer( configPath: dbFile, connectionToSourceKitLSP: LocalConnection(receiverName: "Dummy SourceKit-LSP") ) ) let dummyFile = tempDir.appendingPathComponent("a.c") - let buildSettings = try await buildSystem.sourceKitOptions( + let buildSettings = try await buildServer.sourceKitOptions( request: TextDocumentSourceKitOptionsRequest( textDocument: TextDocumentIdentifier(URI(dummyFile)), target: .dummy, @@ -248,15 +248,15 @@ final class CompilationDatabaseTests: XCTestCase { func testInvalidCompilationDatabase() async throws { try await withTestScratchDir { tempDir in - let dbFile = tempDir.appendingPathComponent(JSONCompilationDatabaseBuildSystem.dbName) + let dbFile = tempDir.appendingPathComponent(JSONCompilationDatabaseBuildServer.dbName) try "".write(to: dbFile, atomically: true, encoding: .utf8) XCTAssertThrowsError(try JSONCompilationDatabase(file: dbFile)) } } - func testCompilationDatabaseBuildSystem() async throws { - try await checkCompilationDatabaseBuildSystem( + func testCompilationDatabaseBuildServer() async throws { + try await checkCompilationDatabaseBuildServer( """ [ { @@ -266,8 +266,8 @@ final class CompilationDatabaseTests: XCTestCase { } ] """ - ) { buildSystem in - let settings = try await buildSystem.sourceKitOptions( + ) { buildServer in + let settings = try await buildServer.sourceKitOptions( request: TextDocumentSourceKitOptionsRequest( textDocument: TextDocumentIdentifier(DocumentURI(URL(fileURLWithPath: "/a/a.swift"))), target: BuildTargetIdentifier.createCompileCommands(compiler: "swiftc"), @@ -278,19 +278,19 @@ final class CompilationDatabaseTests: XCTestCase { XCTAssertNotNil(settings) XCTAssertEqual(settings?.workingDirectory, "/a") XCTAssertEqual(settings?.compilerArguments, ["-swift-version", "4", "/a/a.swift"]) - assertNil(await buildSystem.indexStorePath) - assertNil(await buildSystem.indexDatabasePath) + assertNil(await buildServer.indexStorePath) + assertNil(await buildServer.indexDatabasePath) } } - func testCompilationDatabaseBuildSystemIndexStoreSwift0() async throws { - try await checkCompilationDatabaseBuildSystem("[]") { buildSystem in - assertNil(await buildSystem.indexStorePath) + func testCompilationDatabaseBuildServerIndexStoreSwift0() async throws { + try await checkCompilationDatabaseBuildServer("[]") { buildServer in + assertNil(await buildServer.indexStorePath) } } - func testCompilationDatabaseBuildSystemIndexStoreSwift1() async throws { - try await checkCompilationDatabaseBuildSystem( + func testCompilationDatabaseBuildServerIndexStoreSwift1() async throws { + try await checkCompilationDatabaseBuildServer( """ [ { @@ -300,20 +300,20 @@ final class CompilationDatabaseTests: XCTestCase { } ] """ - ) { buildSystem in + ) { buildServer in assertEqual( - try await buildSystem.indexStorePath?.filePath, + try await buildServer.indexStorePath?.filePath, "\(pathSeparator)b" ) assertEqual( - try await buildSystem.indexDatabasePath?.filePath, + try await buildServer.indexDatabasePath?.filePath, "\(pathSeparator)IndexDatabase" ) } } - func testCompilationDatabaseBuildSystemIndexStoreSwift2() async throws { - try await checkCompilationDatabaseBuildSystem( + func testCompilationDatabaseBuildServerIndexStoreSwift2() async throws { + try await checkCompilationDatabaseBuildServer( """ [ { @@ -333,13 +333,13 @@ final class CompilationDatabaseTests: XCTestCase { } ] """ - ) { buildSystem in - await assertEqual(buildSystem.indexStorePath, URL(fileURLWithPath: "/b")) + ) { buildServer in + await assertEqual(buildServer.indexStorePath, URL(fileURLWithPath: "/b")) } } - func testCompilationDatabaseBuildSystemIndexStoreSwift3() async throws { - try await checkCompilationDatabaseBuildSystem( + func testCompilationDatabaseBuildServerIndexStoreSwift3() async throws { + try await checkCompilationDatabaseBuildServer( """ [ { @@ -349,13 +349,13 @@ final class CompilationDatabaseTests: XCTestCase { } ] """ - ) { buildSystem in - assertEqual(await buildSystem.indexStorePath, URL(fileURLWithPath: "/b")) + ) { buildServer in + assertEqual(await buildServer.indexStorePath, URL(fileURLWithPath: "/b")) } } - func testCompilationDatabaseBuildSystemIndexStoreSwift4() async throws { - try await checkCompilationDatabaseBuildSystem( + func testCompilationDatabaseBuildServerIndexStoreSwift4() async throws { + try await checkCompilationDatabaseBuildServer( """ [ { @@ -365,13 +365,13 @@ final class CompilationDatabaseTests: XCTestCase { } ] """ - ) { buildSystem in - assertNil(await buildSystem.indexStorePath) + ) { buildServer in + assertNil(await buildServer.indexStorePath) } } - func testCompilationDatabaseBuildSystemIndexStoreClang() async throws { - try await checkCompilationDatabaseBuildSystem( + func testCompilationDatabaseBuildServerIndexStoreClang() async throws { + try await checkCompilationDatabaseBuildServer( """ [ { @@ -391,20 +391,20 @@ final class CompilationDatabaseTests: XCTestCase { } ] """ - ) { buildSystem in + ) { buildServer in assertEqual( - try await buildSystem.indexStorePath?.filePath, + try await buildServer.indexStorePath?.filePath, "\(pathSeparator)b" ) assertEqual( - try await buildSystem.indexDatabasePath?.filePath, + try await buildServer.indexDatabasePath?.filePath, "\(pathSeparator)IndexDatabase" ) } } func testIndexStorePathRelativeToWorkingDirectory() async throws { - try await checkCompilationDatabaseBuildSystem( + try await checkCompilationDatabaseBuildServer( """ [ { @@ -414,9 +414,9 @@ final class CompilationDatabaseTests: XCTestCase { } ] """ - ) { buildSystem in + ) { buildServer in assertEqual( - try await buildSystem.indexStorePath?.filePath, + try await buildServer.indexStorePath?.filePath, "\(pathSeparator)a\(pathSeparator)index-store" ) } @@ -431,18 +431,18 @@ fileprivate var pathSeparator: String { #endif } -private func checkCompilationDatabaseBuildSystem( +private func checkCompilationDatabaseBuildServer( _ compdb: String, - block: @Sendable (JSONCompilationDatabaseBuildSystem) async throws -> Void + block: @Sendable (JSONCompilationDatabaseBuildServer) async throws -> Void ) async throws { try await withTestScratchDir { tempDir in - let configPath = tempDir.appendingPathComponent(JSONCompilationDatabaseBuildSystem.dbName) + let configPath = tempDir.appendingPathComponent(JSONCompilationDatabaseBuildServer.dbName) try compdb.write(to: configPath, atomically: true, encoding: .utf8) - let buildSystem = try JSONCompilationDatabaseBuildSystem( + let buildServer = try JSONCompilationDatabaseBuildServer( configPath: configPath, toolchainRegistry: .forTesting, connectionToSourceKitLSP: LocalConnection(receiverName: "Dummy SourceKit-LSP") ) - try await block(XCTUnwrap(buildSystem)) + try await block(XCTUnwrap(buildServer)) } } diff --git a/Tests/BuildSystemIntegrationTests/CompilerCommandLineOptionMatchingTests.swift b/Tests/BuildServerIntegrationTests/CompilerCommandLineOptionMatchingTests.swift similarity index 98% rename from Tests/BuildSystemIntegrationTests/CompilerCommandLineOptionMatchingTests.swift rename to Tests/BuildServerIntegrationTests/CompilerCommandLineOptionMatchingTests.swift index 2e5a2ce47..efb68ace1 100644 --- a/Tests/BuildSystemIntegrationTests/CompilerCommandLineOptionMatchingTests.swift +++ b/Tests/BuildServerIntegrationTests/CompilerCommandLineOptionMatchingTests.swift @@ -10,7 +10,7 @@ // //===----------------------------------------------------------------------===// -@_spi(Testing) import BuildSystemIntegration +@_spi(Testing) import BuildServerIntegration import XCTest final class CompilerCommandLineOptionMatchingTests: XCTestCase { diff --git a/Tests/BuildSystemIntegrationTests/BuildServerBuildSystemTests.swift b/Tests/BuildServerIntegrationTests/ExternalBuildServerTests.swift similarity index 99% rename from Tests/BuildSystemIntegrationTests/BuildServerBuildSystemTests.swift rename to Tests/BuildServerIntegrationTests/ExternalBuildServerTests.swift index bd8a3e6d1..e933cef1a 100644 --- a/Tests/BuildSystemIntegrationTests/BuildServerBuildSystemTests.swift +++ b/Tests/BuildServerIntegrationTests/ExternalBuildServerTests.swift @@ -10,8 +10,8 @@ // //===----------------------------------------------------------------------===// +import BuildServerIntegration import BuildServerProtocol -import BuildSystemIntegration import Foundation import LanguageServerProtocol import LanguageServerProtocolExtensions @@ -26,7 +26,7 @@ import XCTest import WinSDK #endif -final class BuildServerBuildSystemTests: XCTestCase { +final class ExternalBuildServerTests: XCTestCase { func testBuildSettingsFromBuildServer() async throws { let project = try await ExternalBuildServerTestProject( files: [ @@ -524,7 +524,7 @@ final class BuildServerBuildSystemTests: XCTestCase { assertContains(try XCTUnwrap(optionsWithoutTarget).compilerArguments, "-DFIRST") } - func testDontBlockBuildServerInitializationIfBuildSystemIsUnresponsive() async throws { + func testDontBlockBuildServerInitializationIfBuildServerIsUnresponsive() async throws { // A build server that responds to the initialize request but not to any other requests. final class UnresponsiveBuildServer: CustomBuildServer { let inProgressRequestsTracker = CustomBuildServerInProgressRequestTracker() diff --git a/Tests/BuildSystemIntegrationTests/FallbackBuildSettingsTests.swift b/Tests/BuildServerIntegrationTests/FallbackBuildServerTests.swift similarity index 97% rename from Tests/BuildSystemIntegrationTests/FallbackBuildSettingsTests.swift rename to Tests/BuildServerIntegrationTests/FallbackBuildServerTests.swift index f561fc30a..d5efe8cce 100644 --- a/Tests/BuildSystemIntegrationTests/FallbackBuildSettingsTests.swift +++ b/Tests/BuildServerIntegrationTests/FallbackBuildServerTests.swift @@ -10,8 +10,8 @@ // //===----------------------------------------------------------------------===// +@_spi(Testing) import BuildServerIntegration import BuildServerProtocol -@_spi(Testing) import BuildSystemIntegration import LanguageServerProtocol import SKOptions import SKTestSupport @@ -19,7 +19,7 @@ import SourceKitLSP import TSCBasic import XCTest -final class FallbackBuildSystemTests: XCTestCase { +final class FallbackBuildServerTests: XCTestCase { func testSwift() throws { let sdk = try AbsolutePath(validating: "/my/sdk").pathString @@ -167,7 +167,7 @@ final class FallbackBuildSystemTests: XCTestCase { XCTAssertNil(fallbackBuildSettings(for: source, language: Language(rawValue: "unknown"), options: .init())) } - func testFallbackBuildSettingsWhileBuildSystemIsComputingBuildSettings() async throws { + func testFallbackBuildSettingsWhileBuildServerIsComputingBuildSettings() async throws { let fallbackResultsReceived = WrappedSemaphore(name: "Fallback results received") let project = try await SwiftPMTestProject( files: [ @@ -176,7 +176,7 @@ final class FallbackBuildSystemTests: XCTestCase { """ ], hooks: Hooks( - buildSystemHooks: BuildSystemHooks( + buildServerHooks: BuildServerHooks( preHandleRequest: { request in if request is TextDocumentSourceKitOptionsRequest { fallbackResultsReceived.waitOrXCTFail() diff --git a/Tests/BuildSystemIntegrationTests/LegacyBuildServerBuildSystemTests.swift b/Tests/BuildServerIntegrationTests/LegacyBuildServerBuildSystemTests.swift similarity index 97% rename from Tests/BuildSystemIntegrationTests/LegacyBuildServerBuildSystemTests.swift rename to Tests/BuildServerIntegrationTests/LegacyBuildServerBuildSystemTests.swift index 38866bfde..ce2589199 100644 --- a/Tests/BuildSystemIntegrationTests/LegacyBuildServerBuildSystemTests.swift +++ b/Tests/BuildServerIntegrationTests/LegacyBuildServerBuildSystemTests.swift @@ -10,8 +10,8 @@ // //===----------------------------------------------------------------------===// +import BuildServerIntegration import BuildServerProtocol -import BuildSystemIntegration import Foundation import LanguageServerProtocol import LanguageServerProtocolExtensions @@ -19,7 +19,7 @@ import SKTestSupport import TSCBasic import XCTest -final class LegacyBuildServerBuildSystemTests: XCTestCase { +final class LegacyBuildServerTests: XCTestCase { func testBuildSettingsFromBuildServer() async throws { let project = try await ExternalBuildServerTestProject( files: [ diff --git a/Tests/BuildSystemIntegrationTests/SplitShellCommandTests.swift b/Tests/BuildServerIntegrationTests/SplitShellCommandTests.swift similarity index 99% rename from Tests/BuildSystemIntegrationTests/SplitShellCommandTests.swift rename to Tests/BuildServerIntegrationTests/SplitShellCommandTests.swift index 0ef0f8606..b319cfe66 100644 --- a/Tests/BuildSystemIntegrationTests/SplitShellCommandTests.swift +++ b/Tests/BuildServerIntegrationTests/SplitShellCommandTests.swift @@ -10,7 +10,7 @@ // //===----------------------------------------------------------------------===// -import BuildSystemIntegration +import BuildServerIntegration import XCTest /// Assert that splitting `str` into its command line components results in `expected`. diff --git a/Tests/BuildSystemIntegrationTests/SwiftPMBuildSystemTests.swift b/Tests/BuildServerIntegrationTests/SwiftPMBuildServerTests.swift similarity index 83% rename from Tests/BuildSystemIntegrationTests/SwiftPMBuildSystemTests.swift rename to Tests/BuildServerIntegrationTests/SwiftPMBuildServerTests.swift index 58dc68d26..c47ece442 100644 --- a/Tests/BuildSystemIntegrationTests/SwiftPMBuildSystemTests.swift +++ b/Tests/BuildServerIntegrationTests/SwiftPMBuildServerTests.swift @@ -12,7 +12,7 @@ #if !NO_SWIFTPM_DEPENDENCY import BuildServerProtocol -@_spi(Testing) import BuildSystemIntegration +@_spi(Testing) import BuildServerIntegration import LanguageServerProtocol import LanguageServerProtocolExtensions import PackageModel @@ -46,7 +46,7 @@ private var hostTriple: Triple { } @Suite(.serialized) -struct SwiftPMBuildSystemTests { +struct SwiftPMBuildServerTests { @Test func testNoPackage() async throws { try await withTestScratchDir { tempDir in @@ -57,8 +57,8 @@ struct SwiftPMBuildSystemTests { ] ) let packageRoot = tempDir.appendingPathComponent("pkg") - let buildSystemSpec = SwiftPMBuildSystem.searchForConfig(in: packageRoot, options: try await .testDefault()) - #expect(buildSystemSpec == nil) + let buildServerSpec = SwiftPMBuildServer.searchForConfig(in: packageRoot, options: try await .testDefault()) + #expect(buildServerSpec == nil) } } @@ -81,7 +81,7 @@ struct SwiftPMBuildSystemTests { ) let packageRoot = tempDir.appendingPathComponent("pkg") await expectThrowsError( - try await SwiftPMBuildSystem( + try await SwiftPMBuildServer( projectRoot: packageRoot, toolchainRegistry: ToolchainRegistry(toolchains: []), options: SourceKitLSPOptions(), @@ -116,7 +116,7 @@ struct SwiftPMBuildSystemTests { ), backgroundIndexing: false ) - let swiftpmBuildSystem = try await SwiftPMBuildSystem( + let swiftpmBuildServer = try await SwiftPMBuildServer( projectRoot: packageRoot, toolchainRegistry: .forTesting, options: options, @@ -124,7 +124,7 @@ struct SwiftPMBuildSystemTests { testHooks: SwiftPMTestHooks() ) - let dataPath = await swiftpmBuildSystem.destinationBuildParameters.dataPath + let dataPath = await swiftpmBuildServer.destinationBuildParameters.dataPath let expectedScratchPath = packageRoot.appendingPathComponent(try #require(options.swiftPMOrDefault.scratchPath)) #expect(dataPath.asURL.isDescendant(of: expectedScratchPath)) } @@ -148,14 +148,14 @@ struct SwiftPMBuildSystemTests { ] ) let packageRoot = try tempDir.appendingPathComponent("pkg").realpath - let buildSystemManager = await BuildSystemManager( - buildSystemSpec: .swiftpmSpec(for: packageRoot), + let buildServerManager = await BuildServerManager( + buildServerSpec: .swiftpmSpec(for: packageRoot), toolchainRegistry: .forTesting, options: SourceKitLSPOptions(), - connectionToClient: DummyBuildSystemManagerConnectionToClient(), - buildSystemHooks: BuildSystemHooks() + connectionToClient: DummyBuildServerManagerConnectionToClient(), + buildServerHooks: BuildServerHooks() ) - await buildSystemManager.waitForUpToDateBuildGraph() + await buildServerManager.waitForUpToDateBuildGraph() let aswift = packageRoot @@ -164,10 +164,10 @@ struct SwiftPMBuildSystemTests { .appendingPathComponent("a.swift") let build = try await buildPath(root: packageRoot, platform: hostTriple.platformBuildPathComponent) - _ = try #require(await buildSystemManager.initializationData?.indexDatabasePath) - _ = try #require(await buildSystemManager.initializationData?.indexStorePath) + _ = try #require(await buildServerManager.initializationData?.indexDatabasePath) + _ = try #require(await buildServerManager.initializationData?.indexStorePath) let arguments = try #require( - await buildSystemManager.buildSettingsInferredFromMainFile( + await buildServerManager.buildSettingsInferredFromMainFile( for: DocumentURI(aswift), language: .swift, fallbackAfterTimeout: false @@ -216,14 +216,14 @@ struct SwiftPMBuildSystemTests { ] ) let packageRoot = try tempDir.appendingPathComponent("pkg").realpath - let buildSystemManager = await BuildSystemManager( - buildSystemSpec: .swiftpmSpec(for: packageRoot), + let buildServerManager = await BuildServerManager( + buildServerSpec: .swiftpmSpec(for: packageRoot), toolchainRegistry: .forTesting, options: SourceKitLSPOptions(), - connectionToClient: DummyBuildSystemManagerConnectionToClient(), - buildSystemHooks: BuildSystemHooks() + connectionToClient: DummyBuildServerManagerConnectionToClient(), + buildServerHooks: BuildServerHooks() ) - await buildSystemManager.waitForUpToDateBuildGraph() + await buildServerManager.waitForUpToDateBuildGraph() let aPlusSomething = packageRoot @@ -231,7 +231,7 @@ struct SwiftPMBuildSystemTests { .appendingPathComponent("lib") .appendingPathComponent("a+something.swift") - _ = try #require(await buildSystemManager.initializationData?.indexStorePath) + _ = try #require(await buildServerManager.initializationData?.indexStorePath) let pathWithPlusEscaped = "\(try aPlusSomething.filePath.replacing("+", with: "%2B"))" #if os(Windows) let urlWithPlusEscaped = try #require(URL(string: "file:///\(pathWithPlusEscaped)")) @@ -239,7 +239,7 @@ struct SwiftPMBuildSystemTests { let urlWithPlusEscaped = try #require(URL(string: "file://\(pathWithPlusEscaped)")) #endif let arguments = try #require( - await buildSystemManager.buildSettingsInferredFromMainFile( + await buildServerManager.buildSettingsInferredFromMainFile( for: DocumentURI(urlWithPlusEscaped), language: .swift, fallbackAfterTimeout: false @@ -289,14 +289,14 @@ struct SwiftPMBuildSystemTests { swiftCompilerFlags: ["-typecheck"] ) - let buildSystemManager = await BuildSystemManager( - buildSystemSpec: .swiftpmSpec(for: packageRoot), + let buildServerManager = await BuildServerManager( + buildServerSpec: .swiftpmSpec(for: packageRoot), toolchainRegistry: .forTesting, options: SourceKitLSPOptions(swiftPM: options), - connectionToClient: DummyBuildSystemManagerConnectionToClient(), - buildSystemHooks: BuildSystemHooks() + connectionToClient: DummyBuildServerManagerConnectionToClient(), + buildServerHooks: BuildServerHooks() ) - await buildSystemManager.waitForUpToDateBuildGraph() + await buildServerManager.waitForUpToDateBuildGraph() let aswift = packageRoot @@ -305,7 +305,7 @@ struct SwiftPMBuildSystemTests { .appendingPathComponent("a.swift") let arguments = try #require( - await buildSystemManager.buildSettingsInferredFromMainFile( + await buildServerManager.buildSettingsInferredFromMainFile( for: DocumentURI(aswift), language: .swift, fallbackAfterTimeout: false @@ -336,18 +336,18 @@ struct SwiftPMBuildSystemTests { ] ) let packageRoot = tempDir.appendingPathComponent("pkg") - let buildSystemManager = await BuildSystemManager( - buildSystemSpec: .swiftpmSpec(for: packageRoot), + let buildServerManager = await BuildServerManager( + buildServerSpec: .swiftpmSpec(for: packageRoot), toolchainRegistry: .forTesting, options: SourceKitLSPOptions(), - connectionToClient: DummyBuildSystemManagerConnectionToClient(), - buildSystemHooks: BuildSystemHooks() + connectionToClient: DummyBuildServerManagerConnectionToClient(), + buildServerHooks: BuildServerHooks() ) - await buildSystemManager.waitForUpToDateBuildGraph() + await buildServerManager.waitForUpToDateBuildGraph() let source = try packageRoot.appendingPathComponent("Package.swift").realpath let arguments = try #require( - await buildSystemManager.buildSettingsInferredFromMainFile( + await buildServerManager.buildSettingsInferredFromMainFile( for: DocumentURI(source), language: .swift, fallbackAfterTimeout: false @@ -377,14 +377,14 @@ struct SwiftPMBuildSystemTests { ] ) let packageRoot = try tempDir.appendingPathComponent("pkg").realpath - let buildSystemManager = await BuildSystemManager( - buildSystemSpec: .swiftpmSpec(for: packageRoot), + let buildServerManager = await BuildServerManager( + buildServerSpec: .swiftpmSpec(for: packageRoot), toolchainRegistry: .forTesting, options: SourceKitLSPOptions(), - connectionToClient: DummyBuildSystemManagerConnectionToClient(), - buildSystemHooks: BuildSystemHooks() + connectionToClient: DummyBuildServerManagerConnectionToClient(), + buildServerHooks: BuildServerHooks() ) - await buildSystemManager.waitForUpToDateBuildGraph() + await buildServerManager.waitForUpToDateBuildGraph() let aswift = packageRoot @@ -398,7 +398,7 @@ struct SwiftPMBuildSystemTests { .appendingPathComponent("b.swift") let argumentsA = try #require( - await buildSystemManager.buildSettingsInferredFromMainFile( + await buildServerManager.buildSettingsInferredFromMainFile( for: DocumentURI(aswift), language: .swift, fallbackAfterTimeout: false @@ -407,7 +407,7 @@ struct SwiftPMBuildSystemTests { expectArgumentsContain(try aswift.filePath, arguments: argumentsA) expectArgumentsContain(try bswift.filePath, arguments: argumentsA) let argumentsB = try #require( - await buildSystemManager.buildSettingsInferredFromMainFile( + await buildServerManager.buildSettingsInferredFromMainFile( for: DocumentURI(aswift), language: .swift, fallbackAfterTimeout: false @@ -443,14 +443,14 @@ struct SwiftPMBuildSystemTests { ] ) let packageRoot = try tempDir.appendingPathComponent("pkg").realpath - let buildSystemManager = await BuildSystemManager( - buildSystemSpec: .swiftpmSpec(for: packageRoot), + let buildServerManager = await BuildServerManager( + buildServerSpec: .swiftpmSpec(for: packageRoot), toolchainRegistry: .forTesting, options: SourceKitLSPOptions(), - connectionToClient: DummyBuildSystemManagerConnectionToClient(), - buildSystemHooks: BuildSystemHooks() + connectionToClient: DummyBuildServerManagerConnectionToClient(), + buildServerHooks: BuildServerHooks() ) - await buildSystemManager.waitForUpToDateBuildGraph() + await buildServerManager.waitForUpToDateBuildGraph() let aswift = packageRoot @@ -463,7 +463,7 @@ struct SwiftPMBuildSystemTests { .appendingPathComponent("libB") .appendingPathComponent("b.swift") let arguments = try #require( - await buildSystemManager.buildSettingsInferredFromMainFile( + await buildServerManager.buildSettingsInferredFromMainFile( for: DocumentURI(aswift), language: .swift, fallbackAfterTimeout: false @@ -484,7 +484,7 @@ struct SwiftPMBuildSystemTests { ) let argumentsB = try #require( - await buildSystemManager.buildSettingsInferredFromMainFile( + await buildServerManager.buildSettingsInferredFromMainFile( for: DocumentURI(bswift), language: .swift, fallbackAfterTimeout: false @@ -523,14 +523,14 @@ struct SwiftPMBuildSystemTests { ] ) let packageRoot = tempDir.appendingPathComponent("pkg") - let buildSystemManager = await BuildSystemManager( - buildSystemSpec: .swiftpmSpec(for: packageRoot), + let buildServerManager = await BuildServerManager( + buildServerSpec: .swiftpmSpec(for: packageRoot), toolchainRegistry: .forTesting, options: SourceKitLSPOptions(), - connectionToClient: DummyBuildSystemManagerConnectionToClient(), - buildSystemHooks: BuildSystemHooks() + connectionToClient: DummyBuildServerManagerConnectionToClient(), + buildServerHooks: BuildServerHooks() ) - await buildSystemManager.waitForUpToDateBuildGraph() + await buildServerManager.waitForUpToDateBuildGraph() let aswift = packageRoot @@ -543,21 +543,21 @@ struct SwiftPMBuildSystemTests { .appendingPathComponent("libB") .appendingPathComponent("b.swift") _ = try #require( - await buildSystemManager.buildSettingsInferredFromMainFile( + await buildServerManager.buildSettingsInferredFromMainFile( for: DocumentURI(aswift), language: .swift, fallbackAfterTimeout: false ) ) #expect( - await buildSystemManager.buildSettingsInferredFromMainFile( + await buildServerManager.buildSettingsInferredFromMainFile( for: DocumentURI(bswift), language: .swift, fallbackAfterTimeout: false )?.isFallback == true ) #expect( - await buildSystemManager.buildSettingsInferredFromMainFile( + await buildServerManager.buildSettingsInferredFromMainFile( for: DocumentURI(URL(string: "https://www.apple.com")!), language: .swift, fallbackAfterTimeout: false @@ -587,14 +587,14 @@ struct SwiftPMBuildSystemTests { ] ) let packageRoot = try tempDir.appendingPathComponent("pkg").realpath - let buildSystemManager = await BuildSystemManager( - buildSystemSpec: .swiftpmSpec(for: packageRoot), + let buildServerManager = await BuildServerManager( + buildServerSpec: .swiftpmSpec(for: packageRoot), toolchainRegistry: .forTesting, options: SourceKitLSPOptions(), - connectionToClient: DummyBuildSystemManagerConnectionToClient(), - buildSystemHooks: BuildSystemHooks() + connectionToClient: DummyBuildServerManagerConnectionToClient(), + buildServerHooks: BuildServerHooks() ) - await buildSystemManager.waitForUpToDateBuildGraph() + await buildServerManager.waitForUpToDateBuildGraph() let acxx = packageRoot @@ -614,11 +614,11 @@ struct SwiftPMBuildSystemTests { .appendingPathComponent("a.h") let build = buildPath(root: packageRoot, platform: try await hostTriple.platformBuildPathComponent) - _ = try #require(await buildSystemManager.initializationData?.indexStorePath) + _ = try #require(await buildServerManager.initializationData?.indexStorePath) for file in [acxx, header] { let args = try #require( - await buildSystemManager.buildSettingsInferredFromMainFile( + await buildServerManager.buildSettingsInferredFromMainFile( for: DocumentURI(file), language: .cpp, fallbackAfterTimeout: false @@ -680,14 +680,14 @@ struct SwiftPMBuildSystemTests { ] ) let packageRoot = tempDir.appendingPathComponent("pkg") - let buildSystemManager = await BuildSystemManager( - buildSystemSpec: .swiftpmSpec(for: packageRoot), + let buildServerManager = await BuildServerManager( + buildServerSpec: .swiftpmSpec(for: packageRoot), toolchainRegistry: .forTesting, options: SourceKitLSPOptions(), - connectionToClient: DummyBuildSystemManagerConnectionToClient(), - buildSystemHooks: BuildSystemHooks() + connectionToClient: DummyBuildServerManagerConnectionToClient(), + buildServerHooks: BuildServerHooks() ) - await buildSystemManager.waitForUpToDateBuildGraph() + await buildServerManager.waitForUpToDateBuildGraph() let aswift = packageRoot @@ -695,7 +695,7 @@ struct SwiftPMBuildSystemTests { .appendingPathComponent("lib") .appendingPathComponent("a.swift") let arguments = try #require( - await buildSystemManager.buildSettingsInferredFromMainFile( + await buildServerManager.buildSettingsInferredFromMainFile( for: DocumentURI(aswift), language: .swift, fallbackAfterTimeout: false @@ -739,17 +739,17 @@ struct SwiftPMBuildSystemTests { withDestinationURL: URL(fileURLWithPath: tempDir.appendingPathComponent("pkg_real").filePath) ) - let buildSystemSpec = try #require( - SwiftPMBuildSystem.searchForConfig(in: packageRoot, options: await .testDefault()) + let buildServerSpec = try #require( + SwiftPMBuildServer.searchForConfig(in: packageRoot, options: await .testDefault()) ) - let buildSystemManager = await BuildSystemManager( - buildSystemSpec: buildSystemSpec, + let buildServerManager = await BuildServerManager( + buildServerSpec: buildServerSpec, toolchainRegistry: .forTesting, options: SourceKitLSPOptions(), - connectionToClient: DummyBuildSystemManagerConnectionToClient(), - buildSystemHooks: BuildSystemHooks() + connectionToClient: DummyBuildServerManagerConnectionToClient(), + buildServerHooks: BuildServerHooks() ) - await buildSystemManager.waitForUpToDateBuildGraph() + await buildServerManager.waitForUpToDateBuildGraph() let aswiftSymlink = packageRoot @@ -760,7 +760,7 @@ struct SwiftPMBuildSystemTests { let manifest = packageRoot.appendingPathComponent("Package.swift") let argumentsFromSymlink = try #require( - await buildSystemManager.buildSettingsInferredFromMainFile( + await buildServerManager.buildSettingsInferredFromMainFile( for: DocumentURI(aswiftSymlink), language: .swift, fallbackAfterTimeout: false @@ -771,7 +771,7 @@ struct SwiftPMBuildSystemTests { // build settings for it. #expect( try await #require( - await buildSystemManager.buildSettingsInferredFromMainFile( + await buildServerManager.buildSettingsInferredFromMainFile( for: DocumentURI(aswiftReal), language: .swift, fallbackAfterTimeout: false @@ -782,7 +782,7 @@ struct SwiftPMBuildSystemTests { expectArgumentsDoNotContain(try aswiftReal.filePath, arguments: argumentsFromSymlink) let argsManifest = try #require( - await buildSystemManager.buildSettingsInferredFromMainFile( + await buildServerManager.buildSettingsInferredFromMainFile( for: DocumentURI(manifest), language: .swift, fallbackAfterTimeout: false @@ -826,21 +826,21 @@ struct SwiftPMBuildSystemTests { withDestinationURL: URL(fileURLWithPath: tempDir.appendingPathComponent("pkg_real").filePath) ) - let buildSystemSpec = try #require( - SwiftPMBuildSystem.searchForConfig(in: symlinkRoot, options: await .testDefault()) + let buildServerSpec = try #require( + SwiftPMBuildServer.searchForConfig(in: symlinkRoot, options: await .testDefault()) ) - let buildSystemManager = await BuildSystemManager( - buildSystemSpec: buildSystemSpec, + let buildServerManager = await BuildServerManager( + buildServerSpec: buildServerSpec, toolchainRegistry: .forTesting, options: SourceKitLSPOptions(), - connectionToClient: DummyBuildSystemManagerConnectionToClient(), - buildSystemHooks: BuildSystemHooks() + connectionToClient: DummyBuildServerManagerConnectionToClient(), + buildServerHooks: BuildServerHooks() ) - await buildSystemManager.waitForUpToDateBuildGraph() + await buildServerManager.waitForUpToDateBuildGraph() for file in [acpp, ah] { let args = try #require( - await buildSystemManager.buildSettingsInferredFromMainFile( + await buildServerManager.buildSettingsInferredFromMainFile( for: DocumentURI(symlinkRoot.appending(components: file)), language: .cpp, fallbackAfterTimeout: false @@ -872,14 +872,14 @@ struct SwiftPMBuildSystemTests { ] ) let packageRoot = try tempDir.appendingPathComponent("pkg").realpath - let buildSystemManager = await BuildSystemManager( - buildSystemSpec: .swiftpmSpec(for: packageRoot), + let buildServerManager = await BuildServerManager( + buildServerSpec: .swiftpmSpec(for: packageRoot), toolchainRegistry: .forTesting, options: SourceKitLSPOptions(), - connectionToClient: DummyBuildSystemManagerConnectionToClient(), - buildSystemHooks: BuildSystemHooks() + connectionToClient: DummyBuildServerManagerConnectionToClient(), + buildServerHooks: BuildServerHooks() ) - await buildSystemManager.waitForUpToDateBuildGraph() + await buildServerManager.waitForUpToDateBuildGraph() let aswift = packageRoot @@ -887,7 +887,7 @@ struct SwiftPMBuildSystemTests { .appendingPathComponent("lib") .appendingPathComponent("a.swift") let arguments = try #require( - await buildSystemManager.buildSettingsInferredFromMainFile( + await buildServerManager.buildSettingsInferredFromMainFile( for: DocumentURI(aswift), language: .swift, fallbackAfterTimeout: false @@ -927,8 +927,8 @@ struct SwiftPMBuildSystemTests { .appendingPathComponent("Sources") .appendingPathComponent("lib") - let buildSystemSpec = SwiftPMBuildSystem.searchForConfig(in: workspaceRoot, options: try await .testDefault()) - #expect(buildSystemSpec == nil) + let buildServerSpec = SwiftPMBuildServer.searchForConfig(in: workspaceRoot, options: try await .testDefault()) + #expect(buildServerSpec == nil) } } @@ -954,14 +954,14 @@ struct SwiftPMBuildSystemTests { ] ) let packageRoot = tempDir.appendingPathComponent("pkg") - let buildSystemManager = await BuildSystemManager( - buildSystemSpec: .swiftpmSpec(for: packageRoot), + let buildServerManager = await BuildServerManager( + buildServerSpec: .swiftpmSpec(for: packageRoot), toolchainRegistry: .forTesting, options: SourceKitLSPOptions(), - connectionToClient: DummyBuildSystemManagerConnectionToClient(), - buildSystemHooks: BuildSystemHooks() + connectionToClient: DummyBuildServerManagerConnectionToClient(), + buildServerHooks: BuildServerHooks() ) - await buildSystemManager.waitForUpToDateBuildGraph() + await buildServerManager.waitForUpToDateBuildGraph() let aswift = packageRoot @@ -969,9 +969,9 @@ struct SwiftPMBuildSystemTests { .appendingPathComponent("MyPlugin") .appendingPathComponent("a.swift") - _ = try #require(await buildSystemManager.initializationData?.indexStorePath) + _ = try #require(await buildServerManager.initializationData?.indexStorePath) let arguments = try #require( - await buildSystemManager.buildSettingsInferredFromMainFile( + await buildServerManager.buildSettingsInferredFromMainFile( for: DocumentURI(aswift), language: .swift, fallbackAfterTimeout: false @@ -988,7 +988,7 @@ struct SwiftPMBuildSystemTests { func testPackageWithDependencyWithoutResolving() async throws { // This package has a dependency but we haven't run `swift package resolve`. We don't want to resolve packages from // SourceKit-LSP because it has side-effects to the build directory. - // But even without the dependency checked out, we should be able to create a SwiftPMBuildSystem and retrieve the + // But even without the dependency checked out, we should be able to create a SwiftPMBuildServer and retrieve the // existing source files. let project = try await SwiftPMTestProject( files: [ @@ -1034,7 +1034,7 @@ struct SwiftPMBuildSystemTests { ], capabilities: ClientCapabilities(window: WindowClientCapabilities(workDoneProgress: true)), hooks: Hooks( - buildSystemHooks: BuildSystemHooks( + buildServerHooks: BuildServerHooks( swiftPMTestHooks: SwiftPMTestHooks(reloadPackageDidStart: { didReceiveWorkDoneProgressNotification.waitOrXCTFail() }) @@ -1083,15 +1083,15 @@ struct SwiftPMBuildSystemTests { ) let packageRoot = try tempDir.appendingPathComponent("pkg").realpath let versionSpecificManifestURL = packageRoot.appendingPathComponent("Package@swift-5.8.swift") - let buildSystemManager = await BuildSystemManager( - buildSystemSpec: .swiftpmSpec(for: packageRoot), + let buildServerManager = await BuildServerManager( + buildServerSpec: .swiftpmSpec(for: packageRoot), toolchainRegistry: .forTesting, options: SourceKitLSPOptions(), - connectionToClient: DummyBuildSystemManagerConnectionToClient(), - buildSystemHooks: BuildSystemHooks() + connectionToClient: DummyBuildServerManagerConnectionToClient(), + buildServerHooks: BuildServerHooks() ) - await buildSystemManager.waitForUpToDateBuildGraph() - let settings = await buildSystemManager.buildSettingsInferredFromMainFile( + await buildServerManager.waitForUpToDateBuildGraph() + let settings = await buildServerManager.buildSettingsInferredFromMainFile( for: DocumentURI(versionSpecificManifestURL), language: .swift, fallbackAfterTimeout: false @@ -1117,15 +1117,15 @@ struct SwiftPMBuildSystemTests { ) let packageRoot = try tempDir.appendingPathComponent("pkg").realpath let manifestURL = packageRoot.appendingPathComponent("Package.swift") - let buildSystemManager = await BuildSystemManager( - buildSystemSpec: .swiftpmSpec(for: packageRoot), + let buildServerManager = await BuildServerManager( + buildServerSpec: .swiftpmSpec(for: packageRoot), toolchainRegistry: .forTesting, options: SourceKitLSPOptions(), - connectionToClient: DummyBuildSystemManagerConnectionToClient(), - buildSystemHooks: BuildSystemHooks() + connectionToClient: DummyBuildServerManagerConnectionToClient(), + buildServerHooks: BuildServerHooks() ) - await buildSystemManager.waitForUpToDateBuildGraph() - let settings = await buildSystemManager.buildSettingsInferredFromMainFile( + await buildServerManager.waitForUpToDateBuildGraph() + let settings = await buildServerManager.buildSettingsInferredFromMainFile( for: DocumentURI(manifestURL), language: .swift, fallbackAfterTimeout: false @@ -1194,9 +1194,9 @@ fileprivate extension URL { } } -fileprivate extension BuildSystemSpec { - static func swiftpmSpec(for packageRoot: URL) -> BuildSystemSpec { - return BuildSystemSpec( +fileprivate extension BuildServerSpec { + static func swiftpmSpec(for packageRoot: URL) -> BuildServerSpec { + return BuildServerSpec( kind: .swiftPM, projectRoot: packageRoot, configPath: packageRoot.appendingPathComponent("Package.swift") diff --git a/Tests/SourceKitLSPTests/BackgroundIndexingTests.swift b/Tests/SourceKitLSPTests/BackgroundIndexingTests.swift index fcb9a7c26..9538222d1 100644 --- a/Tests/SourceKitLSPTests/BackgroundIndexingTests.swift +++ b/Tests/SourceKitLSPTests/BackgroundIndexingTests.swift @@ -10,8 +10,8 @@ // //===----------------------------------------------------------------------===// +import BuildServerIntegration import BuildServerProtocol -import BuildSystemIntegration import LanguageServerProtocol import LanguageServerProtocolExtensions import SKLogging @@ -1382,7 +1382,7 @@ final class BackgroundIndexingTests: XCTestCase { let packageInitialized = AtomicBool(initialValue: false) var testHooks = Hooks() - testHooks.buildSystemHooks.swiftPMTestHooks.reloadPackageDidStart = { + testHooks.buildServerHooks.swiftPMTestHooks.reloadPackageDidStart = { if packageInitialized.value { XCTFail("Build graph should not get reloaded when random file gets added") } @@ -1776,7 +1776,7 @@ final class BackgroundIndexingTests: XCTestCase { try SkipUnless.longTestsEnabled() let backgroundIndexingPaused = WrappedSemaphore(name: "Background indexing was paused") let hooks = Hooks( - buildSystemHooks: BuildSystemHooks( + buildServerHooks: BuildServerHooks( swiftPMTestHooks: SwiftPMTestHooks( reloadPackageDidFinish: { backgroundIndexingPaused.waitOrXCTFail() @@ -1818,7 +1818,7 @@ final class BackgroundIndexingTests: XCTestCase { func testBackgroundIndexingRunsOnSynchronizeRequestEvenIfPaused() async throws { let backgroundIndexingPaused = WrappedSemaphore(name: "Background indexing was paused") let hooks = Hooks( - buildSystemHooks: BuildSystemHooks( + buildServerHooks: BuildServerHooks( swiftPMTestHooks: SwiftPMTestHooks( reloadPackageDidFinish: { backgroundIndexingPaused.waitOrXCTFail() @@ -1854,7 +1854,7 @@ final class BackgroundIndexingTests: XCTestCase { func testPausingBackgroundIndexingDoesNotStopPreparation() async throws { let backgroundIndexingPaused = WrappedSemaphore(name: "Background indexing was paused") let hooks = Hooks( - buildSystemHooks: BuildSystemHooks( + buildServerHooks: BuildServerHooks( swiftPMTestHooks: SwiftPMTestHooks( reloadPackageDidFinish: { backgroundIndexingPaused.waitOrXCTFail() @@ -2080,7 +2080,7 @@ final class BackgroundIndexingTests: XCTestCase { } func testUseResponseFileIfTooManyArguments() async throws { - // The build system returns too many arguments to fit them into a command line invocation, so we need to use a + // The build server returns too many arguments to fit them into a command line invocation, so we need to use a // response file to invoke the indexer. final class BuildServer: CustomBuildServer { @@ -2204,10 +2204,10 @@ final class BackgroundIndexingTests: XCTestCase { ) } - func testBuildSystemUsesStandardizedFileUrlsInsteadOfRealpath() async throws { + func testBuildServerUsesStandardizedFileUrlsInsteadOfRealpath() async throws { try SkipUnless.platformIsDarwin("The realpath vs standardized path difference only exists on macOS") - final class BuildSystem: CustomBuildServer { + final class BuildServer: CustomBuildServer { let inProgressRequestsTracker = CustomBuildServerInProgressRequestTracker() private let projectRoot: URL private var testFileURL: URL { projectRoot.appendingPathComponent("test.c").standardized } @@ -2244,7 +2244,7 @@ final class BackgroundIndexingTests: XCTestCase { files: [ "test.c": "void x() {}" ], - buildServer: BuildSystem.self, + buildServer: BuildServer.self, hooks: Hooks( indexHooks: IndexHooks( updateIndexStoreTaskDidStart: { task in @@ -2530,8 +2530,8 @@ final class BackgroundIndexingTests: XCTestCase { try await project.testClient.send(SynchronizeRequest(index: true)) } - func testBuildSystemDoesNotReturnIndexUnitOutputPath() async throws { - final class BuildSystem: CustomBuildServer { + func testBuildServerDoesNotReturnIndexUnitOutputPath() async throws { + final class BuildServer: CustomBuildServer { let inProgressRequestsTracker = CustomBuildServerInProgressRequestTracker() private let projectRoot: URL @@ -2575,7 +2575,7 @@ final class BackgroundIndexingTests: XCTestCase { files: [ "test.swift": "func myTestFunc() {}" ], - buildServer: BuildSystem.self, + buildServer: BuildServer.self, enableBackgroundIndexing: true ) diff --git a/Tests/SourceKitLSPTests/BuildSystemTests.swift b/Tests/SourceKitLSPTests/BuildServerTests.swift similarity index 84% rename from Tests/SourceKitLSPTests/BuildSystemTests.swift rename to Tests/SourceKitLSPTests/BuildServerTests.swift index 4145b8a2e..c0341726a 100644 --- a/Tests/SourceKitLSPTests/BuildSystemTests.swift +++ b/Tests/SourceKitLSPTests/BuildServerTests.swift @@ -10,8 +10,8 @@ // //===----------------------------------------------------------------------===// +@_spi(Testing) import BuildServerIntegration import BuildServerProtocol -@_spi(Testing) import BuildSystemIntegration import LanguageServerProtocol import LanguageServerProtocolExtensions import SKOptions @@ -23,7 +23,7 @@ import TSCBasic import ToolchainRegistry import XCTest -fileprivate actor TestBuildSystem: CustomBuildServer { +fileprivate actor TestBuildServer: CustomBuildServer { let inProgressRequestsTracker = CustomBuildServerInProgressRequestTracker() private let connectionToSourceKitLSP: any Connection private var buildSettingsByFile: [DocumentURI: TextDocumentSourceKitOptionsResponse] = [:] @@ -48,7 +48,7 @@ fileprivate actor TestBuildSystem: CustomBuildServer { } } -final class BuildSystemTests: XCTestCase { +final class BuildServerTests: XCTestCase { /// The mock client used to communicate with the SourceKit-LSP server.p /// /// - Note: Set before each test run in `setUp`. @@ -59,10 +59,10 @@ final class BuildSystemTests: XCTestCase { /// - Note: Set before each test run in `setUp`. private var workspace: Workspace! = nil - /// The build system that we use to verify SourceKitLSPServer behavior. + /// The build server that we use to verify SourceKitLSPServer behavior. /// /// - Note: Set before each test run in `setUp`. - private var buildSystem: TestBuildSystem! = nil + private var buildServer: TestBuildServer! = nil /// Whether clangd exists in the toolchain. /// @@ -74,41 +74,41 @@ final class BuildSystemTests: XCTestCase { let server = testClient.server - let testBuildSystem = ThreadSafeBox(initialValue: nil) - let buildSystemManager = await BuildSystemManager( - buildSystemSpec: BuildSystemSpec( + let testBuildServer = ThreadSafeBox(initialValue: nil) + let buildServerManager = await BuildServerManager( + buildServerSpec: BuildServerSpec( kind: .injected({ projectRoot, connectionToSourceKitLSP in - assert(testBuildSystem.value == nil, "Build system injector hook can only create a single TestBuildSystem") - let buildSystem = TestBuildSystem( + assert(testBuildServer.value == nil, "Build server injector hook can only create a single TestBuildServer") + let buildServer = TestBuildServer( projectRoot: projectRoot, connectionToSourceKitLSP: connectionToSourceKitLSP ) - testBuildSystem.value = buildSystem - return LocalConnection(receiverName: "TestBuildSystem", handler: buildSystem) + testBuildServer.value = buildServer + return LocalConnection(receiverName: "TestBuildServer", handler: buildServer) }), projectRoot: URL(fileURLWithPath: "/"), configPath: URL(fileURLWithPath: "/") ), toolchainRegistry: .forTesting, options: try .testDefault(), - connectionToClient: DummyBuildSystemManagerConnectionToClient(), - buildSystemHooks: BuildSystemHooks() + connectionToClient: DummyBuildServerManagerConnectionToClient(), + buildServerHooks: BuildServerHooks() ) - buildSystem = try unwrap(testBuildSystem.value) + buildServer = try unwrap(testBuildServer.value) self.workspace = await Workspace.forTesting( options: try .testDefault(), testHooks: Hooks(), - buildSystemManager: buildSystemManager, + buildServerManager: buildServerManager, indexTaskScheduler: .forTesting ) await server.setWorkspaces([(workspace: workspace, isImplicit: false)]) - await workspace.buildSystemManager.setDelegate(workspace) + await workspace.buildServerManager.setDelegate(workspace) } override func tearDown() { - buildSystem = nil + buildServer = nil workspace = nil testClient = nil } @@ -131,7 +131,7 @@ final class BuildSystemTests: XCTestCase { } """ - await buildSystem.setBuildSettings(for: doc, to: TextDocumentSourceKitOptionsResponse(compilerArguments: args)) + await buildServer.setBuildSettings(for: doc, to: TextDocumentSourceKitOptionsResponse(compilerArguments: args)) let documentManager = await self.testClient.server.documentManager @@ -144,7 +144,7 @@ final class BuildSystemTests: XCTestCase { // Modify the build settings and inform the delegate. // This should trigger a new publish diagnostics and we should no longer have errors. let newSettings = TextDocumentSourceKitOptionsResponse(compilerArguments: args + ["-DFOO"]) - await buildSystem.setBuildSettings(for: doc, to: newSettings) + await buildServer.setBuildSettings(for: doc, to: newSettings) try await repeatUntilExpectedResult { guard let refreshedDiags = try? await testClient.nextDiagnosticsNotification(timeout: .seconds(1)) else { @@ -162,7 +162,7 @@ final class BuildSystemTests: XCTestCase { options: SourceKitLSPOptions.FallbackBuildSystemOptions() )!.compilerArguments - await buildSystem.setBuildSettings(for: doc, to: TextDocumentSourceKitOptionsResponse(compilerArguments: args)) + await buildServer.setBuildSettings(for: doc, to: TextDocumentSourceKitOptionsResponse(compilerArguments: args)) let text = """ #if FOO @@ -182,7 +182,7 @@ final class BuildSystemTests: XCTestCase { // Modify the build settings and inform the delegate. // This should trigger a new publish diagnostics and we should no longer have errors. let newSettings = TextDocumentSourceKitOptionsResponse(compilerArguments: args + ["-DFOO"]) - await buildSystem.setBuildSettings(for: doc, to: newSettings) + await buildServer.setBuildSettings(for: doc, to: newSettings) // No expected errors here because we fixed the settings. let diags2 = try await testClient.nextDiagnosticsNotification() @@ -214,7 +214,7 @@ final class BuildSystemTests: XCTestCase { // Modify the build settings and inform the delegate. // This should trigger a new publish diagnostics and we should see a diagnostic. let newSettings = TextDocumentSourceKitOptionsResponse(compilerArguments: args) - await buildSystem.setBuildSettings(for: doc, to: newSettings) + await buildServer.setBuildSettings(for: doc, to: newSettings) let refreshedDiags = try await testClient.nextDiagnosticsNotification() XCTAssertEqual(refreshedDiags.diagnostics.count, 1) @@ -251,8 +251,8 @@ final class BuildSystemTests: XCTestCase { XCTAssertEqual(openDiags.diagnostics.count, 1) XCTAssertEqual(text, try documentManager.latestSnapshot(doc).text) - // Swap from fallback settings to primary build system settings. - await buildSystem.setBuildSettings(for: doc, to: primarySettings) + // Swap from fallback settings to primary build server settings. + await buildServer.setBuildSettings(for: doc, to: primarySettings) // Two errors since `-DFOO` was not passed. let refreshedDiags = try await testClient.nextDiagnosticsNotification() diff --git a/Tests/SourceKitLSPTests/CompilationDatabaseTests.swift b/Tests/SourceKitLSPTests/CompilationDatabaseTests.swift index 72c5143e0..48e954924 100644 --- a/Tests/SourceKitLSPTests/CompilationDatabaseTests.swift +++ b/Tests/SourceKitLSPTests/CompilationDatabaseTests.swift @@ -10,7 +10,7 @@ // //===----------------------------------------------------------------------===// -import BuildSystemIntegration +import BuildServerIntegration import LanguageServerProtocol import SKTestSupport import SwiftExtensions @@ -57,7 +57,7 @@ final class CompilationDatabaseTests: XCTestCase { // Remove -DFOO from the compile commands. - try await project.changeFileOnDisk(FixedCompilationDatabaseBuildSystem.dbName, newMarkedContents: "") + try await project.changeFileOnDisk(FixedCompilationDatabaseBuildServer.dbName, newMarkedContents: "") // DocumentHighlight should now point to the definition in the `#else` block. diff --git a/Tests/SourceKitLSPTests/ExpectedIndexTaskTracker.swift b/Tests/SourceKitLSPTests/ExpectedIndexTaskTracker.swift index 13ddaeba6..bfc77c243 100644 --- a/Tests/SourceKitLSPTests/ExpectedIndexTaskTracker.swift +++ b/Tests/SourceKitLSPTests/ExpectedIndexTaskTracker.swift @@ -10,8 +10,8 @@ // //===----------------------------------------------------------------------===// +import BuildServerIntegration import BuildServerProtocol -import BuildSystemIntegration import LanguageServerProtocol import SKLogging import SemanticIndex @@ -23,7 +23,7 @@ enum BuildDestination { /// A string that can be used to identify the build triple in a `BuildTargetIdentifier`. /// - /// `BuildSystemManager.canonicalBuildTargetIdentifier` picks the canonical target based on alphabetical + /// `BuildServerManager.canonicalBuildTargetIdentifier` picks the canonical target based on alphabetical /// ordering. We rely on the string "destination" being ordered before "tools" so that we prefer a /// `destination` (or "target") target over a `tools` (or "host") target. var id: String { @@ -81,7 +81,7 @@ struct ExpectedPreparation { didStart: (@Sendable () -> Void)? = nil, didFinish: (@Sendable () -> Void)? = nil ) throws { - // This should match the format in `BuildTargetIdentifier(_: any SwiftBuildTarget)` inside SwiftPMBuildSystem. + // This should match the format in `BuildTargetIdentifier(_: any SwiftBuildTarget)` inside SwiftPMBuildServer. self.target = try BuildTargetIdentifier(target: target, destination: destination) self.didStart = didStart self.didFinish = didFinish diff --git a/Tests/SourceKitLSPTests/PullDiagnosticsTests.swift b/Tests/SourceKitLSPTests/PullDiagnosticsTests.swift index 1e3c6222a..b24d60b18 100644 --- a/Tests/SourceKitLSPTests/PullDiagnosticsTests.swift +++ b/Tests/SourceKitLSPTests/PullDiagnosticsTests.swift @@ -10,7 +10,7 @@ // //===----------------------------------------------------------------------===// -import BuildSystemIntegration +import BuildServerIntegration import LanguageServerProtocol import LanguageServerProtocolExtensions import LanguageServerProtocolJSONRPC @@ -147,7 +147,7 @@ final class PullDiagnosticsTests: XCTestCase { } func testNotesFromIntegratedSwiftSyntaxDiagnostics() async throws { - // Create a workspace that has compile_commands.json so that it has a build system but no compiler arguments + // Create a workspace that has compile_commands.json so that it has a build server but no compiler arguments // for test.swift so that we fall back to producing diagnostics from the built-in swift-syntax. let project = try await MultiFileTestProject(files: [ "test.swift": "func foo() 1️⃣{2️⃣", diff --git a/Tests/SourceKitLSPTests/SwiftCompileCommandsTest.swift b/Tests/SourceKitLSPTests/SwiftCompileCommandsTest.swift index 7341e372b..ba4ac1d92 100644 --- a/Tests/SourceKitLSPTests/SwiftCompileCommandsTest.swift +++ b/Tests/SourceKitLSPTests/SwiftCompileCommandsTest.swift @@ -10,7 +10,7 @@ // //===----------------------------------------------------------------------===// -import BuildSystemIntegration +import BuildServerIntegration import LanguageServerProtocol import SourceKitLSP import XCTest diff --git a/Tests/SourceKitLSPTests/SwiftPMIntegrationTests.swift b/Tests/SourceKitLSPTests/SwiftPMIntegrationTests.swift index 50cd4feac..680d3ea70 100644 --- a/Tests/SourceKitLSPTests/SwiftPMIntegrationTests.swift +++ b/Tests/SourceKitLSPTests/SwiftPMIntegrationTests.swift @@ -10,7 +10,7 @@ // //===----------------------------------------------------------------------===// -import BuildSystemIntegration +import BuildServerIntegration import Foundation import LanguageServerProtocol import SKTestSupport @@ -307,7 +307,7 @@ final class SwiftPMIntegrationTests: XCTestCase { "Test.swift": "" ], hooks: Hooks( - buildSystemHooks: BuildSystemHooks( + buildServerHooks: BuildServerHooks( swiftPMTestHooks: SwiftPMTestHooks(reloadPackageDidStart: { receivedDocumentSymbolsReply.waitOrXCTFail() }) @@ -332,7 +332,7 @@ final class SwiftPMIntegrationTests: XCTestCase { workspace: WorkspaceClientCapabilities(diagnostics: RefreshRegistrationCapability(refreshSupport: true)) ), hooks: Hooks( - buildSystemHooks: BuildSystemHooks( + buildServerHooks: BuildServerHooks( swiftPMTestHooks: SwiftPMTestHooks(reloadPackageDidStart: { receivedInitialDiagnosticsReply.waitOrXCTFail() }) diff --git a/Tests/SourceKitLSPTests/WorkspaceTestDiscoveryTests.swift b/Tests/SourceKitLSPTests/WorkspaceTestDiscoveryTests.swift index 9b68c01e7..bdc573cfd 100644 --- a/Tests/SourceKitLSPTests/WorkspaceTestDiscoveryTests.swift +++ b/Tests/SourceKitLSPTests/WorkspaceTestDiscoveryTests.swift @@ -10,7 +10,7 @@ // //===----------------------------------------------------------------------===// -@_spi(Testing) import BuildSystemIntegration +@_spi(Testing) import BuildServerIntegration import Foundation import LanguageServerProtocol import SKTestSupport @@ -699,7 +699,7 @@ final class WorkspaceTestDiscoveryTests: XCTestCase { ) } - func testInMemoryFileWithFallbackBuildSystem() async throws { + func testInMemoryFileWithFallbackBuildServer() async throws { let testClient = try await TestSourceKitLSPClient() let uri = DocumentURI(for: .swift) @@ -734,7 +734,7 @@ final class WorkspaceTestDiscoveryTests: XCTestCase { ) } - func testIndexedFileWithCompilationDbBuildSystem() async throws { + func testIndexedFileWithCompilationDbBuildServer() async throws { try SkipUnless.longTestsEnabled() let project = try await IndexedSingleSwiftFileTestProject( @@ -767,7 +767,7 @@ final class WorkspaceTestDiscoveryTests: XCTestCase { ) } - func testOnDiskFileWithCompilationDbBuildSystem() async throws { + func testOnDiskFileWithCompilationDbBuildServer() async throws { let project = try await MultiFileTestProject(files: [ "MyTests.swift": """ import XCTest @@ -779,7 +779,7 @@ final class WorkspaceTestDiscoveryTests: XCTestCase { "compile_commands.json": "[]", ]) - // When MyTests.swift is not part of the compilation database, the build system doesn't know about the file and thus + // When MyTests.swift is not part of the compilation database, the build server doesn't know about the file and thus // doesn't return any tests for it. let testsWithEmptyCompilationDatabase = try await project.testClient.send(WorkspaceTestsRequest()) XCTAssertEqual(testsWithEmptyCompilationDatabase, []) @@ -796,7 +796,7 @@ final class WorkspaceTestDiscoveryTests: XCTestCase { ]) try await project.changeFileOnDisk( - JSONCompilationDatabaseBuildSystem.dbName, + JSONCompilationDatabaseBuildServer.dbName, newMarkedContents: XCTUnwrap(String(data: JSONEncoder().encode(compilationDatabase), encoding: .utf8)) ) diff --git a/Tests/SourceKitLSPTests/WorkspaceTests.swift b/Tests/SourceKitLSPTests/WorkspaceTests.swift index c2c76e562..8675a172b 100644 --- a/Tests/SourceKitLSPTests/WorkspaceTests.swift +++ b/Tests/SourceKitLSPTests/WorkspaceTests.swift @@ -10,8 +10,8 @@ // //===----------------------------------------------------------------------===// +import BuildServerIntegration import BuildServerProtocol -import BuildSystemIntegration import Foundation import LanguageServerProtocol import SKLogging @@ -950,7 +950,7 @@ final class WorkspaceTests: XCTestCase { ) } - func testWorkspaceOptionsOverrideBuildSystem() async throws { + func testWorkspaceOptionsOverrideBuildServer() async throws { let project = try await MultiFileTestProject(files: [ ".sourcekit-lsp/config.json": """ { @@ -1001,7 +1001,7 @@ final class WorkspaceTests: XCTestCase { ) } - func testImplicitWorkspaceOptionsOverrideBuildSystem() async throws { + func testImplicitWorkspaceOptionsOverrideBuildServer() async throws { let project = try await MultiFileTestProject(files: [ "projA/.sourcekit-lsp/config.json": """ { @@ -1188,7 +1188,7 @@ final class WorkspaceTests: XCTestCase { func testSourceKitOptionsAllowingFallback() async throws { let hooks = Hooks( - buildSystemHooks: BuildSystemHooks( + buildServerHooks: BuildServerHooks( swiftPMTestHooks: SwiftPMTestHooks( reloadPackageDidStart: { // Essentially make sure that the package never loads, so we are forced to return fallback arguments. @@ -1299,7 +1299,7 @@ final class WorkspaceTests: XCTestCase { try XCTAssertEqual(XCTUnwrap(prepareUpToDateAgain).didPrepareTarget, false) } - func testBuildSystemUsesStandardizedFileUrlsInsteadOfRealpath() async throws { + func testBuildServerUsesStandardizedFileUrlsInsteadOfRealpath() async throws { try SkipUnless.platformIsDarwin("The realpath vs standardized path difference only exists on macOS") // Explicitly create a directory at /tmp (which is a standardized path but whose realpath is /private/tmp) @@ -1358,7 +1358,7 @@ final class WorkspaceTests: XCTestCase { try await testClient.send(SynchronizeRequest(index: true)) // Check that we can infer build settings for the header from its main file. indexstore-db stores this main file - // path as `/private/tmp` while the build system only knows about it as `/tmp`. + // path as `/private/tmp` while the build server only knows about it as `/tmp`. let options = try await testClient.send( SourceKitOptionsRequest( textDocument: TextDocumentIdentifier(scratchDirectory.appendingPathComponent("test.h")), diff --git a/Tests/SwiftSourceKitPluginTests/PluginSwiftPMTestProject.swift b/Tests/SwiftSourceKitPluginTests/PluginSwiftPMTestProject.swift index e3ee2f649..2315fce0b 100644 --- a/Tests/SwiftSourceKitPluginTests/PluginSwiftPMTestProject.swift +++ b/Tests/SwiftSourceKitPluginTests/PluginSwiftPMTestProject.swift @@ -10,7 +10,7 @@ // //===----------------------------------------------------------------------===// -import BuildSystemIntegration +import BuildServerIntegration import Foundation import LanguageServerProtocol import SKTestSupport @@ -26,25 +26,25 @@ final class PluginSwiftPMTestProject { private let fileData: [String: MultiFileTestProject.FileData] - private var _buildSystemManager: BuildSystemManager? - private var buildSystemManager: BuildSystemManager { + private var _buildServerManager: BuildServerManager? + private var buildServerManager: BuildServerManager { get async throws { - if let _buildSystemManager { - return _buildSystemManager + if let _buildServerManager { + return _buildServerManager } - let buildSystemManager = await BuildSystemManager( - buildSystemSpec: BuildSystemSpec( + let buildServerManager = await BuildServerManager( + buildServerSpec: BuildServerSpec( kind: .swiftPM, projectRoot: scratchDirectory, configPath: scratchDirectory.appendingPathComponent("Package.swift") ), toolchainRegistry: .forTesting, options: try .testDefault(backgroundIndexing: false), - connectionToClient: DummyBuildSystemManagerConnectionToClient(), - buildSystemHooks: BuildSystemHooks() + connectionToClient: DummyBuildServerManagerConnectionToClient(), + buildServerHooks: BuildServerHooks() ) - _buildSystemManager = buildSystemManager - return buildSystemManager + _buildServerManager = buildServerManager + return buildServerManager } } @@ -98,8 +98,8 @@ final class PluginSwiftPMTestProject { } package func compilerArguments(for fileName: String) async throws -> [String] { - try await buildSystemManager.waitForUpToDateBuildGraph() - let buildSettings = try await buildSystemManager.buildSettingsInferredFromMainFile( + try await buildServerManager.waitForUpToDateBuildGraph() + let buildSettings = try await buildServerManager.buildSettingsInferredFromMainFile( for: try uri(for: fileName), language: .swift, fallbackAfterTimeout: false diff --git a/config.schema.json b/config.schema.json index 17a6d5965..d22dfee11 100644 --- a/config.schema.json +++ b/config.schema.json @@ -23,8 +23,8 @@ "type" : "string" }, "buildSettingsTimeout" : { - "description" : "Number of milliseconds to wait for build settings from the build system before using fallback build settings.", - "markdownDescription" : "Number of milliseconds to wait for build settings from the build system before using fallback build settings.", + "description" : "Number of milliseconds to wait for build settings from the build server before using fallback build settings.", + "markdownDescription" : "Number of milliseconds to wait for build settings from the build server before using fallback build settings.", "type" : "integer" }, "cancelTextDocumentRequestsOnEditAndClose" : { @@ -82,8 +82,8 @@ "type" : "array" }, "fallbackBuildSystem" : { - "description" : "Dictionary with the following keys, defining options for files that aren't managed by any build system.", - "markdownDescription" : "Dictionary with the following keys, defining options for files that aren't managed by any build system.", + "description" : "Dictionary with the following keys, defining options for files that aren't managed by any build server.", + "markdownDescription" : "Dictionary with the following keys, defining options for files that aren't managed by any build server.", "properties" : { "cCompilerFlags" : { "description" : "Extra arguments passed to the compiler for C files.",