sdk: SwiftBuild support (#229)
- Commit
0108899e0466871d501cd2a21921d95639b0a6a2- Author
- Kabir Oberai <[email protected]>
- When
- 2026-09-20 06:47 UTC (2 months ago)
- Parents
e36ba50
## What does this PR do? Adds support for SwiftBuild on Swift 6.4. We now point SwiftBuild to iPhoneOS.platform and rely on the real [SWBApplePlatform](https://github.com/swiftlang/swift-build/tree/b30ee3c00abf34857084c26bb873c3da06348134/Sources/SWBApplePlatform). We also do a little futzing to convince SWB to use our Darwin-compatible toolset (lld, librarian, resource dirs). We explicitly _don't_ pass in a Swift SDK because that would downgrade SWB to using one of the generic platform plugins instead of ApplePlatform. This also gets us a lot closer to parity with Xcode's behavior when building for Apple platforms; we get the same build flags and everything. We can probably achieve identical bundling too, if we take control of the PIF. One other change: since we need to pass custom env vars and such, we can't rely on sourcekit-lsp's built-in SwiftPM integration anymore. We thus create a custom BSP server that trampolines to SwiftPM's build server with the right flags set. This effectively makes SwiftPM an implementation detail, so we can start messing with the PIF. ## How was it tested? - [x] Build with Swift 6.3 on macOS - [x] Build with Swift 6.4 on macOS - [x] Build with Swift 6.3 on Linux - [x] Build with Swift 6.4 on Linux - [x] BSP/LSP file creation works - [x] LSP support works in VSCode ## AI tool usage How much of this PR was AI-assisted? (check one) - [ ] **0** - No AI was used to write code - [x] **1** - I was assisted by AI. I reviewed the finished result. - [ ] **2** - I set the AI going and left it to it; nobody has read the result - no review, or AI review only <!-- If an AI agent is filling this in: declare the level honestly, and open as a draft if it is #2. Do not lower the declared level to get the PR reviewed. --> <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **New Features** - Added a `dev build-server` command for Build Server Protocol integration. - Projects automatically select the appropriate Swift build system when supported. - Packaging supports output layouts for Swift Package Manager and Swift Build. - Added options to skip language-server configuration when needed. - **Documentation** - Updated project templates and tutorials to use `.bsp/xtool.json` for IDE features such as syntax highlighting and documentation lookup. - **Improvements** - Enhanced SDK generation and compatibility across supported toolchains and platforms. - Improved automatic language-server configuration while preserving existing configuration files. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
Diff
Documentation/xtool.docc/First-app-code/template-1a.sh
diff --git a/Documentation/xtool.docc/First-app-code/template-1a.sh b/Documentation/xtool.docc/First-app-code/template-1a.shindex fffe566..901c770 100644--- a/Documentation/xtool.docc/First-app-code/template-1a.sh+++ b/Documentation/xtool.docc/First-app-code/template-1a.sh@@ -3,7 +3,7 @@ Creating package: Hello Creating Package.swift Creating xtool.yml Creating .gitignore-Creating .sourcekit-lsp/config.json+Creating .bsp/xtool.json Creating Sources/Hello/HelloApp.swift Creating Sources/Hello/ContentView.swift
Documentation/xtool.docc/First-app-code/template-1b.sh
diff --git a/Documentation/xtool.docc/First-app-code/template-1b.sh b/Documentation/xtool.docc/First-app-code/template-1b.shindex 87fdcbf..fc0c010 100644--- a/Documentation/xtool.docc/First-app-code/template-1b.sh+++ b/Documentation/xtool.docc/First-app-code/template-1b.sh@@ -3,7 +3,7 @@ Creating package: Hello Creating Package.swift Creating xtool.yml Creating .gitignore-Creating .sourcekit-lsp/config.json+Creating .bsp/xtool.json Creating Sources/Hello/HelloApp.swift Creating Sources/Hello/ContentView.swift
Documentation/xtool.docc/First-app-code/template-2a.sh
diff --git a/Documentation/xtool.docc/First-app-code/template-2a.sh b/Documentation/xtool.docc/First-app-code/template-2a.shindex 9cecda4..67f9a3b 100644--- a/Documentation/xtool.docc/First-app-code/template-2a.sh+++ b/Documentation/xtool.docc/First-app-code/template-2a.sh@@ -3,7 +3,7 @@ Creating package: Hello Creating Package.swift Creating xtool.yml Creating .gitignore-Creating .sourcekit-lsp/config.json+Creating .bsp/xtool.json Creating Sources/Hello/HelloApp.swift Creating Sources/Hello/ContentView.swift @@ -12,7 +12,7 @@ Finished generating project Hello. Developer$ Hello$ -rw-rw-r-- 1 user user 187 .gitignore-drwxrwxr-x 2 user user 4096 .sourcekit-lsp+drwxrwxr-x 2 user user 4096 .bsp -rw-rw-r-- 1 user user 463 Package.swift drwxrwxr-x 3 user user 4096 Sources -rw-rw-r-- 1 user user 39 xtool.yml
Documentation/xtool.docc/First-app-code/template-2b.sh
diff --git a/Documentation/xtool.docc/First-app-code/template-2b.sh b/Documentation/xtool.docc/First-app-code/template-2b.shindex d138eef..15aeacc 100644--- a/Documentation/xtool.docc/First-app-code/template-2b.sh+++ b/Documentation/xtool.docc/First-app-code/template-2b.sh@@ -3,7 +3,7 @@ Creating package: Hello Creating Package.swift Creating xtool.yml Creating .gitignore-Creating .sourcekit-lsp/config.json+Creating .bsp/xtool.json Creating Sources/Hello/HelloApp.swift Creating Sources/Hello/ContentView.swift @@ -12,7 +12,7 @@ Finished generating project Hello. Developer$ cd Hello Hello$ ls -la -rw-rw-r-- 1 user user 187 .gitignore-drwxrwxr-x 2 user user 4096 .sourcekit-lsp+drwxrwxr-x 2 user user 4096 .bsp -rw-rw-r-- 1 user user 463 Package.swift drwxrwxr-x 3 user user 4096 Sources -rw-rw-r-- 1 user user 39 xtool.yml
Documentation/xtool.docc/First-app-code/template-3a.sh
diff --git a/Documentation/xtool.docc/First-app-code/template-3a.sh b/Documentation/xtool.docc/First-app-code/template-3a.shindex 225d90b..598d49f 100644--- a/Documentation/xtool.docc/First-app-code/template-3a.sh+++ b/Documentation/xtool.docc/First-app-code/template-3a.sh@@ -3,7 +3,7 @@ Creating package: Hello Creating Package.swift Creating xtool.yml Creating .gitignore-Creating .sourcekit-lsp/config.json+Creating .bsp/xtool.json Creating Sources/Hello/HelloApp.swift Creating Sources/Hello/ContentView.swift @@ -12,7 +12,7 @@ Finished generating project Hello. Developer$ cd Hello Hello$ ls -la -rw-rw-r-- 1 user user 187 .gitignore-drwxrwxr-x 2 user user 4096 .sourcekit-lsp+drwxrwxr-x 2 user user 4096 .bsp -rw-rw-r-- 1 user user 463 Package.swift drwxrwxr-x 3 user user 4096 Sources -rw-rw-r-- 1 user user 39 xtool.yml
Documentation/xtool.docc/First-app-code/template-3b.sh
diff --git a/Documentation/xtool.docc/First-app-code/template-3b.sh b/Documentation/xtool.docc/First-app-code/template-3b.shindex e8c9c6b..59ca74b 100644--- a/Documentation/xtool.docc/First-app-code/template-3b.sh+++ b/Documentation/xtool.docc/First-app-code/template-3b.sh@@ -3,7 +3,7 @@ Creating package: Hello Creating Package.swift Creating xtool.yml Creating .gitignore-Creating .sourcekit-lsp/config.json+Creating .bsp/xtool.json Creating Sources/Hello/HelloApp.swift Creating Sources/Hello/ContentView.swift @@ -12,7 +12,7 @@ Finished generating project Hello. Developer$ cd Hello Hello$ ls -la -rw-rw-r-- 1 user user 187 .gitignore-drwxrwxr-x 2 user user 4096 .sourcekit-lsp+drwxrwxr-x 2 user user 4096 .bsp -rw-rw-r-- 1 user user 463 Package.swift drwxrwxr-x 3 user user 4096 Sources -rw-rw-r-- 1 user user 39 xtool.yml
Documentation/xtool.docc/First-app-code/template-4a.sh
diff --git a/Documentation/xtool.docc/First-app-code/template-4a.sh b/Documentation/xtool.docc/First-app-code/template-4a.shindex 1cb630e..8e5184a 100644--- a/Documentation/xtool.docc/First-app-code/template-4a.sh+++ b/Documentation/xtool.docc/First-app-code/template-4a.sh@@ -3,7 +3,7 @@ Creating package: Hello Creating Package.swift Creating xtool.yml Creating .gitignore-Creating .sourcekit-lsp/config.json+Creating .bsp/xtool.json Creating Sources/Hello/HelloApp.swift Creating Sources/Hello/ContentView.swift @@ -12,7 +12,7 @@ Finished generating project Hello. Developer$ cd Hello Hello$ ls -la -rw-rw-r-- 1 user user 187 .gitignore-drwxrwxr-x 2 user user 4096 .sourcekit-lsp+drwxrwxr-x 2 user user 4096 .bsp -rw-rw-r-- 1 user user 463 Package.swift drwxrwxr-x 3 user user 4096 Sources -rw-rw-r-- 1 user user 39 xtool.yml
Documentation/xtool.docc/First-app-code/template-4b.sh
diff --git a/Documentation/xtool.docc/First-app-code/template-4b.sh b/Documentation/xtool.docc/First-app-code/template-4b.shindex 4f7dd50..e318484 100644--- a/Documentation/xtool.docc/First-app-code/template-4b.sh+++ b/Documentation/xtool.docc/First-app-code/template-4b.sh@@ -3,7 +3,7 @@ Creating package: Hello Creating Package.swift Creating xtool.yml Creating .gitignore-Creating .sourcekit-lsp/config.json+Creating .bsp/xtool.json Creating Sources/Hello/HelloApp.swift Creating Sources/Hello/ContentView.swift @@ -12,7 +12,7 @@ Finished generating project Hello. Developer$ cd Hello Hello$ ls -la -rw-rw-r-- 1 user user 187 .gitignore-drwxrwxr-x 2 user user 4096 .sourcekit-lsp+drwxrwxr-x 2 user user 4096 .bsp -rw-rw-r-- 1 user user 463 Package.swift drwxrwxr-x 3 user user 4096 Sources -rw-rw-r-- 1 user user 39 xtool.yml@@ -21,5 +21,9 @@ Hello$ cat xtool.yml version: 1 bundleID: com.example.Hello -Hello$ cat .sourcekit-lsp/config.json-{ "swiftPM": { "swiftSDK": "arm64-apple-ios" } }+Hello$ cat .bsp/xtool.json+{+ "name": "xtool",+ ...+ "argv": ["/usr/bin/env", "xtool", "dev", "build-server"]+}
Documentation/xtool.docc/First-app.tutorial
diff --git a/Documentation/xtool.docc/First-app.tutorial b/Documentation/xtool.docc/First-app.tutorialindex 396c221..f9ed39b 100644--- a/Documentation/xtool.docc/First-app.tutorial+++ b/Documentation/xtool.docc/First-app.tutorial@@ -30,9 +30,9 @@ } @Step {- Read `.sourcekit-lsp/config.json`.+ Read `.bsp/xtool.json`. - This file tells SourceKit to build for the `arm64-apple-ios` system defined in `darwin.artifactbundle`. This is the [Swift SDK](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0387-cross-compilation-destinations.md) that we built during the setup process. It contains the necessary modules for building iOS apps, such as UIKit and SwiftUI, as well as tools for building and manipulating iOS binaries. Under the hood, xtool also calls `swift build` with `--swift-sdk arm64-apple-ios` for the same reason.+ This file tells your IDE to ask xtool for build information (via the Build Server Protocol). It enables features like syntax highlighting and documentation lookup. @Code(name: "Terminal", file: "template-4b.sh", previousFile: "template-4a.sh") {} }
Sources/PackLib/BuildSettings.swift
diff --git a/Sources/PackLib/BuildSettings.swift b/Sources/PackLib/BuildSettings.swiftindex 4ba0efc..8d1a4a5 100644--- a/Sources/PackLib/BuildSettings.swift+++ b/Sources/PackLib/BuildSettings.swift@@ -1,37 +1,73 @@ import Foundation import Subprocess import XUtils+import Superutils public struct BuildSettings: Sendable { private static let customBinDir = // this is the same option used by SwiftPM itself for dev builds ProcessInfo.processInfo.environment["SWIFTPM_CUSTOM_BIN_DIR"].map { FilePath($0) } - private static let envURL = URL(fileURLWithPath: "/usr/bin/env")-- public let packagePath: String+ public var packagePath: String public let configuration: BuildConfiguration public let triple: String- public let sdkOptions: [String]- public let options: [String]+ public let buildSystem: BuildSystem+ public let customOptions: [String]++ public var sdkOptions: [String]+ public var sdkEnvironment: [Environment.Key: String?]++ private var configOptions: [String] {+ return [+ "--configuration", configuration.rawValue,+ "--build-system", buildSystem.pmName,+ "--package-path", packagePath,+ ]+ }++ private var resolvedBaseOptions: [String] {+ configOptions + sdkOptions + customOptions+ } public init( configuration: BuildConfiguration, triple: String,+ buildSystem: BuildSystem? = nil, packagePath: String = ".", options: [String] = [] ) async throws { self.packagePath = packagePath self.configuration = configuration- self.options = options+ self.customOptions = options self.triple = triple+ self.buildSystem = if let buildSystem { buildSystem } else { try await .default() }++ self.sdkEnvironment = [+ // xcrun passes an SDKROOT that messes with our sdk configuration+ "SDKROOT": nil,+ ] - // on macOS we don't explicitly install a Swift SDK but- // SwiftPM vends "implicit" Darwin SDKs as of Swift 6.1,- // i.e. we can pass `--swift-sdk arm64-apple-ios` and it- // just works. See:- // https://github.com/swiftlang/swift-package-manager/pull/6828- self.sdkOptions = ["--swift-sdk", triple]+ switch self.buildSystem {+ case .swiftPM:+ // on macOS we don't explicitly install a Swift SDK but+ // SwiftPM vends "implicit" Darwin SDKs as of Swift 6.1,+ // i.e. we can pass `--swift-sdk arm64-apple-ios` and it+ // just works. See:+ // https://github.com/swiftlang/swift-package-manager/pull/6828+ self.sdkOptions = ["--swift-sdk", triple]+ case .swiftBuild:+ self.sdkOptions = ["--triple", triple]+ #if !os(macOS)+ let darwinSDK = try DarwinSDK.current()+ .orThrow(StringError("No Darwin SDK configured. Please run `xtool setup`."))+ self.sdkOptions += [+ "--toolset", "\(darwinSDK.bundle.path)/toolset-swb.json",+ ]+ self.sdkEnvironment.merge([+ "XCODE_EXTRA_PLATFORM_FOLDERS": "\(darwinSDK.bundle.path)/Developer/Platforms",+ ]) { $1 }+ #endif+ } } #if os(macOS)@@ -44,15 +80,40 @@ public struct BuildSettings: Sendable { return result.standardOutput?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" } - private static let swiftURL = Task {+ private static let _swiftURL = Task { try await FilePath(xcrun(["-f", "swift"])) }++ public static func swiftURL() async throws -> FilePath {+ try await _swiftURL.value+ }++ private static let _swiftcURL = Task {+ try await FilePath(xcrun(["-f", "swiftc"]))+ }++ public static func swiftcURL() async throws -> FilePath {+ try await _swiftcURL.value+ }+ #else+ public static func swiftURL() async throws -> FilePath {+ try await FilePath(ToolRegistry.locate("swift")).orThrow(StringError("Got bad path for swift executable"))+ }++ public static func swiftcURL() async throws -> FilePath {+ try await FilePath(ToolRegistry.locate("swiftc")).orThrow(StringError("Got bad path for swiftc executable"))+ } #endif + public func withPackagePath(_ path: String) -> Self {+ var copy = self+ copy.packagePath = path+ return copy+ }+ public func swiftPMInvocation( forTool tool: String, arguments: [String],- packagePathOverride: String? = nil ) async throws -> Subprocess.Configuration { let executable: Executable let baseArguments: [String]@@ -65,35 +126,71 @@ public struct BuildSettings: Sendable { // to add SDKROOT=.../MacOSX.sdk to our invocations. We avoid this by // 1) invoking the real swift executable (located with `xcrun -f`) and // 2) explicitly removing SDKROOT from the env, as it may be inherited- // through the `swift run pack` invocation.- executable = .path(try await Self.swiftURL.value)+ // through a parent process (e.g. `swift run xtool`).+ executable = .path(try await Self.swiftURL()) #else executable = .name("swift") #endif baseArguments = [tool] } - let extraArguments: [String] = [- "--package-path", packagePathOverride ?? packagePath,- "--configuration", configuration.rawValue,- ]-- var rawEnv = ProcessInfo.processInfo.environment- rawEnv.removeValue(forKey: "SDKROOT")- let env = Dictionary(uniqueKeysWithValues: rawEnv.map {- (Environment.Key(rawValue: $0)!, $1)- })- return Configuration( executable,- arguments: .init(baseArguments + extraArguments + sdkOptions + options + arguments),- environment: .custom(env),+ arguments: .init(baseArguments + resolvedBaseOptions + arguments),+ environment: .inherit.updating(sdkEnvironment), platformOptions: .withGracefulShutDown, ) }++ // loosely based on+ // https://github.com/swiftlang/sourcekit-lsp/blob/c55899a/Sources/BuildServerIntegration/ExternalBuildServerAdapter.swift#L92+ private var baseBuildServerArguments: [String] {+ return [+ "experimental-build-server",+ "--disable-automatic-resolution",+ "--scratch-path", ".build/index-build",+ // this requires Swift 6.4 but we need 6.4 on Linux anyway, for the platform toolset fixes+ "--experimental-skip-acquiring-lock",+ ]+ }++ public var buildServerArguments: [String] {+ ["package"] + baseBuildServerArguments + resolvedBaseOptions+ }++ public func buildServerInvocation() async throws -> Subprocess.Configuration {+ try await swiftPMInvocation(forTool: "package", arguments: baseBuildServerArguments)+ } } public enum BuildConfiguration: String, CaseIterable, Sendable { case debug case release++ var swiftBuildValue: String {+ switch self {+ case .debug: "Debug"+ case .release: "Release"+ }+ }+}++public enum BuildSystem: Sendable {+ case swiftPM+ case swiftBuild++ public static func `default`() async throws -> Self {+ if try await SwiftVersion.current.supportsSwiftBuild {+ return .swiftBuild+ } else {+ return .swiftPM+ }+ }++ var pmName: String {+ switch self {+ case .swiftPM: "native"+ case .swiftBuild: "swiftbuild"+ }+ } }
Sources/PackLib/PackSchema.swift
diff --git a/Sources/PackLib/PackSchema.swift b/Sources/PackLib/PackSchema.swiftindex 406ef24..297c424 100644--- a/Sources/PackLib/PackSchema.swift+++ b/Sources/PackLib/PackSchema.swift@@ -22,6 +22,9 @@ public struct PackSchemaBase: Codable, Sendable { public var extensions: [Extension]? + /// Skip auto-creating the LSP support file if it's missing.+ public var skipLSP: Bool?+ public struct Extension: Codable, Sendable { public var product: String public var bundleID: String?
Sources/PackLib/Packer.swift
diff --git a/Sources/PackLib/Packer.swift b/Sources/PackLib/Packer.swiftindex 3ae811f..d41cb7f 100644--- a/Sources/PackLib/Packer.swift+++ b/Sources/PackLib/Packer.swift@@ -55,20 +55,21 @@ public struct Packer: Sendable { try Data().write(to: sources.appendingPathComponent("stub.c", isDirectory: false)) } - let buildConfig = try await buildSettings.swiftPMInvocation(- forTool: "build",- arguments: [- "--package-path", packageDir.path,- "--scratch-path", ".build",- // resolving can cause SwiftPM to overwrite the root package deps- // with just the deps needed for the builder package (which is to- // say, any "dev dependencies" of the root package may be removed.)- // fortunately we've already resolved the root package by this point- // in order to dump the plan, so we can skip resolution here to skirt- // the issue.- "--disable-automatic-resolution",- ]- )+ let buildConfig = try await buildSettings+ .withPackagePath(packageDir.path)+ .swiftPMInvocation(+ forTool: "build",+ arguments: [+ "--scratch-path", ".build",+ // resolving can cause SwiftPM to overwrite the root package deps+ // with just the deps needed for the builder package (which is to+ // say, any "dev dependencies" of the root package may be removed.)+ // fortunately we've already resolved the root package by this point+ // in order to dump the plan, so we can skip resolution here to skirt+ // the issue.+ "--disable-automatic-resolution",+ ],+ ) try await Subprocess.run( buildConfig, output: .currentStandardOutput,@@ -84,8 +85,16 @@ public struct Packer: Sendable { let outputURL = output.url + let binPath: String+ switch buildSettings.buildSystem {+ case .swiftPM:+ binPath = "\(buildSettings.triple)/\(buildSettings.configuration.rawValue)"+ case .swiftBuild:+ let platformName = buildSettings.triple.contains("simulator") ? "iphonesimulator" : "iphoneos"+ binPath = "out/Products/\(buildSettings.configuration.swiftBuildValue)-\(platformName)"+ } let binDir = URL(- fileURLWithPath: ".build/\(buildSettings.triple)/\(buildSettings.configuration.rawValue)",+ fileURLWithPath: ".build/\(binPath)", isDirectory: true )
Sources/PackLib/Planner.swift
diff --git a/Sources/PackLib/Planner.swift b/Sources/PackLib/Planner.swiftindex 11501af..f718769 100644--- a/Sources/PackLib/Planner.swift+++ b/Sources/PackLib/Planner.swift@@ -244,10 +244,9 @@ public struct Planner: Sendable { } private func _dumpAction(arguments: [String], path: String) async throws -> Data {- let dumpConfig = try await buildSettings.swiftPMInvocation(+ let dumpConfig = try await buildSettings.withPackagePath(path).swiftPMInvocation( forTool: "package", arguments: arguments,- packagePathOverride: path ) return try await Subprocess.run( dumpConfig,
Sources/PackLib/SwiftVersion.swift
diff --git a/Sources/PackLib/SwiftVersion.swift b/Sources/PackLib/SwiftVersion.swiftnew file mode 100644index 0000000..83c31e6--- /dev/null+++ b/Sources/PackLib/SwiftVersion.swift@@ -0,0 +1,50 @@+import Subprocess+import Version+import XUtils++public struct SwiftVersion: Sendable {+ public var version: Version++ public var supportsSwiftBuild: Bool {+ version >= Version(6, 4, 0)+ }+}++extension SwiftVersion {+ private static let cached = Task<Self, Error> {+ let outputString: String?+ do {+ outputString = try await Subprocess.run(+ .path(try await BuildSettings.swiftURL()),+ arguments: ["--version"],+ output: .string(limit: .max)+ )+ .checkSuccess()+ .standardOutput+ } catch {+ throw StringError("Failed to obtain Swift version")+ }+ var output = outputString?[...] ?? ""+ if output.hasPrefix("Apple ") {+ output = output.dropFirst("Apple ".count)+ }+ guard output.hasPrefix("Swift version ") else {+ throw StringError("Could not parse Swift version: '\(output)'")+ }+ output = output.dropFirst("Swift version ".count)+ guard let space = output.firstIndex(of: " ") else {+ throw StringError("Could not parse Swift version: '\(output)'")+ }+ output = output[..<space]+ guard let version = Version(tolerant: output) else {+ throw StringError("Could not parse Swift version: '\(output)'")+ }+ return SwiftVersion(version: version)+ }++ public static var current: Self {+ get async throws {+ try await cached.value+ }+ }+}
Sources/XToolSupport/DevBSPCommand.swift
diff --git a/Sources/XToolSupport/DevBSPCommand.swift b/Sources/XToolSupport/DevBSPCommand.swiftnew file mode 100644index 0000000..12940a8--- /dev/null+++ b/Sources/XToolSupport/DevBSPCommand.swift@@ -0,0 +1,32 @@+import ArgumentParser+import Foundation+import XKit+import PackLib+import Subprocess++struct DevBSPCommand: AsyncParsableCommand {+ static let configuration = CommandConfiguration(+ commandName: "build-server",+ abstract: "Run build server",+ )++ @Option+ var triple: String?++ func run() async throws {+ guard try await SwiftVersion.current.supportsSwiftBuild else {+ throw Console.Error("`xtool dev build-server` requires Swift 6.4 or later")+ }+ let settings = try await BuildSettings(+ configuration: .debug,+ triple: triple ?? PackOperation.defaultTriple+ )+ try await Subprocess.run(+ settings.buildServerInvocation(),+ input: .standardInput,+ output: .currentStandardOutput,+ error: .currentStandardError,+ )+ .checkSuccess()+ }+}
Sources/XToolSupport/DevCommand.swift
diff --git a/Sources/XToolSupport/DevCommand.swift b/Sources/XToolSupport/DevCommand.swiftindex f9a43e0..4e613bc 100644--- a/Sources/XToolSupport/DevCommand.swift+++ b/Sources/XToolSupport/DevCommand.swift@@ -27,6 +27,15 @@ struct PackOperation { @discardableResult func run() async throws -> URL {+ // TODO: support running inside a child directory++ let contents = try FileManager.default.contentsOfDirectory(atPath: ".")+ guard contents.contains("Package.swift")+ || contents.contains(where: { $0.hasPrefix("Package@") && $0.hasSuffix(".swift") })+ else {+ throw Console.Error("Could not find Package.swift in this directory.")+ }+ try await EnsureSDKOperation(quiet: true).run() print("Planning...")@@ -43,6 +52,8 @@ struct PackOperation { """) } + await LSPConfig.tryEnsure(using: schema)+ let buildSettings = try await BuildSettings( configuration: buildOptions.configuration, triple: triple ?? Self.defaultTriple,@@ -276,6 +287,7 @@ struct DevCommand: AsyncParsableCommand { DevXcodeCommand.self, DevBuildCommand.self, DevRunCommand.self,+ DevBSPCommand.self, ], defaultSubcommand: DevRunCommand.self )
Sources/XToolSupport/LSPConfig.swift
diff --git a/Sources/XToolSupport/LSPConfig.swift b/Sources/XToolSupport/LSPConfig.swiftnew file mode 100644index 0000000..b7482b5--- /dev/null+++ b/Sources/XToolSupport/LSPConfig.swift@@ -0,0 +1,90 @@+import Foundation+import PackLib++enum LSPConfig {+ static let bsp: (String, String) = (+ ".bsp/xtool.json",+ """+ {+ "name": "xtool",+ "version": "1.0",+ "bspVersion": "2.2.0",+ "languages": ["c", "cpp", "objective-c", "objective-cpp", "swift"],+ "argv": ["/usr/bin/env", "xtool", "dev", "build-server"]+ }+ """+ )++ static let legacyLSP: (String, String) = (+ ".sourcekit-lsp/config.json",+ """+ {+ "swiftPM": {+ "swiftSDK": "arm64-apple-ios"+ }+ }+ """+ )++ nonisolated(nonsending) static func tryEnsure(+ using schema: PackSchema,+ quiet: Bool = false,+ currentDirectory directory: URL = URL(filePath: FileManager.default.currentDirectoryPath)+ ) async {+ do {+ try await ensure(using: schema, quiet: quiet, currentDirectory: directory)+ } catch {+ print("warning: failed to validate LSP configuration: \(error)")+ }+ }++ nonisolated(nonsending) static func ensure(+ using schema: PackSchema,+ quiet: Bool = false,+ currentDirectory directory: URL = URL(filePath: FileManager.default.currentDirectoryPath)+ ) async throws {+ if schema.skipLSP == true {+ return+ }++ if try await SwiftVersion.current.supportsSwiftBuild {+ try await ensure(primary: bsp, secondary: legacyLSP, quiet: quiet, currentDirectory: directory)+ } else {+ try await ensure(primary: legacyLSP, secondary: bsp, quiet: quiet, currentDirectory: directory)+ }+ }++ // creates the primary LSP-support file if it doesn't exist, and cleans up old files+ private nonisolated(nonsending) static func ensure(+ primary: (String, String),+ secondary: (String, String),+ quiet: Bool,+ currentDirectory directory: URL+ ) async throws {+ let primaryURL = directory.appendingPathComponent(primary.0)+ if FileManager.default.fileExists(atPath: primaryURL.path) {+ return+ }++ try? FileManager.default.createDirectory(+ at: primaryURL.deletingLastPathComponent(),+ withIntermediateDirectories: true+ )+ try Data((primary.1 + "\n").utf8).write(to: primaryURL)++ let secondaryURL = directory.appendingPathComponent(secondary.0)+ if let secondaryData = try? await Data(reading: secondaryURL),+ let secondaryString = String(data: secondaryData, encoding: .utf8),+ secondaryString.trimmingCharacters(in: .whitespacesAndNewlines) == secondary.1 {+ try? FileManager.default.removeItem(at: secondaryURL)+ }++ if !quiet {+ print("""+ [LSP] Created \(primary.0) for enhanced IDE support. You may+ need to restart your editor for the change to take effect.+ You can disable this with `skipLSP: true` in xtool.yml.+ """)+ }+ }+}
Sources/XToolSupport/NewCommand.swift
diff --git a/Sources/XToolSupport/NewCommand.swift b/Sources/XToolSupport/NewCommand.swiftindex 68f192b..29d0ab7 100644--- a/Sources/XToolSupport/NewCommand.swift+++ b/Sources/XToolSupport/NewCommand.swift@@ -120,17 +120,6 @@ struct NewCommand: AsyncParsableCommand { """ ), - (- ".sourcekit-lsp/config.json",- """- {- "swiftPM": {- "swiftSDK": "arm64-apple-ios"- }- }- """- ),- ( "Sources/\(moduleName)/\(moduleName)App.swift", """@@ -177,6 +166,12 @@ struct NewCommand: AsyncParsableCommand { try "\(contents)\n".write(to: url, atomically: true, encoding: .utf8) } + await LSPConfig.tryEnsure(+ using: .default,+ quiet: true,+ currentDirectory: baseURL,+ )+ print("\nFinished generating project \(name). Next steps:") print("- Enter the directory with `cd \(name)`") print("- Build and run with `xtool dev`")
Sources/XToolSupport/SDKBuilder.swift
diff --git a/Sources/XToolSupport/SDKBuilder.swift b/Sources/XToolSupport/SDKBuilder.swiftindex be4fb0b..15b0588 100644--- a/Sources/XToolSupport/SDKBuilder.swift+++ b/Sources/XToolSupport/SDKBuilder.swift@@ -5,6 +5,7 @@ import Subprocess import XKit // HTTPClient, stdoutSafe import XUtils // System.File{Path,Descriptor} +// swiftlint:disable:next type_body_length struct SDKBuilder { enum Arch: String { case x86_64@@ -75,7 +76,7 @@ struct SDKBuilder { let mode: Mode // bump this when the sdk builder logic changes- static let sdkEpoch = 1+ static let sdkEpoch = 2 // tag from https://github.com/xtool-org/darwin-tools-linux-llvm static let darwinToolsVersion = "1.0.1"@@ -93,6 +94,7 @@ struct SDKBuilder { """ } + // swiftlint:disable:next function_body_length func buildSDK() async throws { let sdkVersion = Self.currentSDKVersion @@ -174,6 +176,9 @@ struct SDKBuilder { "linker": { "path": "ld64.lld" },+ "librarian": {+ "path": "llvm-lib"+ }, "swiftCompiler": { "extraCLIOptions": [ "-Xfrontend", "-enable-cross-import-overlays",@@ -187,6 +192,26 @@ struct SDKBuilder { encoding: .utf8 ) + // this toolset works with the swiftbuild system on Linux+ // note that we need Swift 6.4+ because 6.3 has bugs in+ // resolving the librarian and linker paths.+ try """+ {+ "schemaVersion": "1.0",+ "rootPath": "toolset/bin",+ "linker": {+ "path": "ld64.lld"+ },+ "librarian": {+ "path": "llvm-lib"+ }+ }+ """.write(+ to: output.appendingPathComponent("toolset-swb.json"),+ atomically: false,+ encoding: .utf8+ )+ let sdkDefinition = SDKDefinition( schemaVersion: "4.0", targetTriples: [@@ -207,6 +232,7 @@ struct SDKBuilder { .write(to: output.appendingPathComponent("darwin-sdk-version.txt")) } + // swiftlint:disable:next function_body_length private func installToolset(in output: URL) async throws { let toolsetDir = output.appendingPathComponent("toolset") @@ -253,6 +279,109 @@ struct SDKBuilder { try await execution.standardInputWriter.finish() } .checkSuccess()++ // swift-build assumes we have an Apple-flavored librarian for Apple platforms+ // (https://github.com/swiftlang/swift-build/blob/b2433e74e/Sources/SWBCore/SpecImplementations/Tools/LinkerTools.swift#L1735)+ // but allows us to override this assumption if we explicitly provide the name llvm-lib (look a few lines above in that file)+ try FileManager.default.moveItem(+ at: toolsetDir.appending(path: "bin/libtool"),+ to: toolsetDir.appending(path: "bin/llvm-lib")+ )++ let ld64 = toolsetDir.appending(path: "bin/ld64.lld")+ let origBins = toolsetDir.appending(path: "bin/orig")+ let origLD64 = origBins.appending(path: "ld64.lld")+ try FileManager.default.createDirectory(at: origBins, withIntermediateDirectories: false)+ try FileManager.default.moveItem(at: ld64, to: origLD64)++ // this terrible hack works around the fact that lld doesn't support the -r option,+ // which merges multiple object files into one (used by SPM's SWB backend to combine+ // per-file MachOs into a single one for the module, on Darwin).+ //+ // so instead, we write a trampoline that intercepts `ld64.lld -r` and instead runs+ // libtool to build a static archive.+ try """+ #!/bin/sh++ set -eu++ case "$0" in+ */*) script_path="$0" ;;+ *) script_path="$(command -v "$0")" ;;+ esac+ case "$script_path" in+ /*) script_dir="${script_path%/*}"; [ -n "$script_dir" ] || script_dir="/" ;;+ */*) script_dir="${script_path%/*}" ;;+ *) script_dir="." ;;+ esac+ bin_dir="$(CDPATH= cd -P "$script_dir" && pwd -P)"++ find_argument_value() {+ argument_name="$1"+ shift++ while [ "$#" -gt 0 ]; do+ if [ "$1" = "$argument_name" ]; then+ shift+ if [ "$#" -gt 0 ]; then+ argument_value="$1"+ return 0+ fi+ return 1+ fi+ shift+ done++ return 1+ }++ relocatable=+ for argument do+ if [ "$argument" = "-r" ]; then+ relocatable=1+ fi+ done++ if [ -n "$relocatable" ]; then+ missing_argument=++ if find_argument_value -filelist "$@"; then+ filelist="$argument_value"+ else+ missing_argument=1+ fi+ if find_argument_value -dependency_info "$@"; then+ dependency_info="$argument_value"+ else+ missing_argument=1+ fi+ if find_argument_value -o "$@"; then+ output="$argument_value"+ else+ missing_argument=1+ fi++ if [ -n "$missing_argument" ]; then+ echo "ld64.lld trampoline could not process arguments." >&2+ echo "Please file an issue at https://github.com/xtool-org/xtool/issues" >&2+ echo " Arguments: $@" >&2+ exit 2+ fi++ exec "$bin_dir/llvm-lib" -static \+ -filelist "$filelist" \+ -dependency_info "$dependency_info" \+ -o "$output"+ fi++ exec "$bin_dir/orig/ld64.lld" "$@"+ """.write(+ to: ld64,+ atomically: false,+ encoding: .utf8+ )+ // set -x+ try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: ld64.path) } private func installMacros(in output: URL) async throws {@@ -418,6 +547,8 @@ struct SDKBuilder { let lib = "../../../../../Library" let platformDir = dev.appending(path: "Platforms/\(platform).platform") + try patchPlatformManifest(path: platformDir.appending(path: "Info.plist"))+ /* XCTest and Testing.framework are located in *.platform/Developer/{Library/Frameworks,usr/lib} rather than inside the SDK. These search paths are explicitly included when building tests, which presumably ensures that normal@@ -507,6 +638,26 @@ struct SDKBuilder { }.value } + private func patchPlatformManifest(path: URL) throws {+ let data = try Data(contentsOf: path)+ guard var plist = try PropertyListSerialization.propertyList(from: data, options: [], format: nil) as? [String: Any] else {+ throw Console.Error("Could not read '\(path.path)'")+ }++ var defaultProperties = (plist["DefaultProperties"] as? [String: Any]) ?? [:]+ defaultProperties["SWIFT_RESOURCE_DIR"] = "$(PLATFORM_DIR)/../../Toolchains/XcodeDefault.xctoolchain/usr/lib/swift"+ defaultProperties["CLANG_RESOURCE_DIR"] = "$(SWIFT_RESOURCE_DIR)/clang"+ defaultProperties["ALTERNATE_LINKER"] = "lld"+ // stub out codesign as /bin/true (SwiftBuild often emits CodeSign tasks, e.g. when+ // building for sim). we sign post-build.+ defaultProperties["CODESIGN"] = "true"+ plist["DefaultProperties"] = defaultProperties++ let newData = try PropertyListSerialization.data(fromPropertyList: plist, format: .xml, options: 0)+ // a non-atomic write would modify the shared inode that's hard-linked from Xcode.app+ try newData.write(to: path, options: .atomic)+ }+ // returns the number of files we actually want to keep, // useful for computing progress % during fs traversal private func _extractXIP(inputPath: String, outDir: String) async throws -> Int {@@ -650,13 +801,16 @@ struct SDKEntry { E("clang"), ]), E("Platforms", ["iPhoneOS", "MacOSX", "iPhoneSimulator"].map {- E("\($0).platform/Developer", [- E("SDKs"),- E("Library", [- E("Frameworks"),- E("PrivateFrameworks"),- ]),- E("usr/lib"),+ E("\($0).platform", [+ E("Info.plist"),+ E("Developer", [+ E("SDKs"),+ E("Library", [+ E("Frameworks"),+ E("PrivateFrameworks"),+ ]),+ E("usr/lib"),+ ]) ]) }), ])
Sources/XToolSupport/SDKCommand.swift
diff --git a/Sources/XToolSupport/SDKCommand.swift b/Sources/XToolSupport/SDKCommand.swiftindex 30ebad2..af04b62 100644--- a/Sources/XToolSupport/SDKCommand.swift+++ b/Sources/XToolSupport/SDKCommand.swift@@ -151,40 +151,6 @@ extension DarwinSDK { } } -private enum SwiftVersion {}-extension SwiftVersion {- static func current() async throws -> Version {- let outputString: String?- do {- outputString = try await Subprocess.run(- .name("swift"),- arguments: ["--version"],- output: .string(limit: .max)- )- .checkSuccess()- .standardOutput- } catch {- throw Console.Error("Failed to obtain Swift version")- }- var output = outputString?[...] ?? ""- if output.hasPrefix("Apple ") {- output = output.dropFirst("Apple ".count)- }- guard output.hasPrefix("Swift version ") else {- throw Console.Error("Could not parse Swift version: '\(output)'")- }- output = output.dropFirst("Swift version ".count)- guard let space = output.firstIndex(of: " ") else {- throw Console.Error("Could not parse Swift version: '\(output)'")- }- output = output[..<space]- guard let version = Version(tolerant: output) else {- throw Console.Error("Could not parse Swift version: '\(output)'")- }- return version- }-}- struct EnsureSDKOperation { let quiet: Bool