File: Toolchain.swift

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (354 lines) | stat: -rw-r--r-- 11,839 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

import LSPLogging
import LanguageServerProtocol
import RegexBuilder
import SKSupport
import SwiftExtensions

import enum PackageLoading.Platform
import struct TSCBasic.AbsolutePath
import protocol TSCBasic.FileSystem
import class TSCBasic.Process
import var TSCBasic.localFileSystem

/// A Swift version consisting of the major and minor component.
public struct SwiftVersion: Sendable, Comparable, CustomStringConvertible {
  public let major: Int
  public let minor: Int

  public static func < (lhs: SwiftVersion, rhs: SwiftVersion) -> Bool {
    return (lhs.major, lhs.minor) < (rhs.major, rhs.minor)
  }

  public init(_ major: Int, _ minor: Int) {
    self.major = major
    self.minor = minor
  }

  public var description: String {
    return "\(major).\(minor)"
  }
}

fileprivate enum SwiftVersionParsingError: Error, CustomStringConvertible {
  case failedToFindSwiftc
  case failedToParseOutput(output: String?)

  var description: String {
    switch self {
    case .failedToFindSwiftc:
      return "Default toolchain does not contain a swiftc executable"
    case .failedToParseOutput(let output):
      return """
        Failed to parse Swift version. Output of swift --version:
        \(output ?? "<empty>")
        """
    }
  }
}

/// A Toolchain is a collection of related compilers and libraries meant to be used together to
/// build and edit source code.
///
/// This can be an explicit toolchain, such as an xctoolchain directory on Darwin, or an implicit
/// toolchain, such as the contents from `/usr/bin`.
public final class Toolchain: Sendable {

  /// The unique toolchain identifier.
  ///
  /// For an xctoolchain, this is a reverse domain name e.g. "com.apple.dt.toolchain.XcodeDefault".
  /// Otherwise, it is typically derived from `path`.
  public let identifier: String

  /// The human-readable name for the toolchain.
  public let displayName: String

  /// The path to this toolchain, if applicable.
  ///
  /// For example, this may be the path to an ".xctoolchain" directory.
  public let path: AbsolutePath?

  // MARK: Tool Paths

  /// The path to the Clang compiler if available.
  public let clang: AbsolutePath?

  /// The path to the Swift driver if available.
  public let swift: AbsolutePath?

  /// The path to the Swift compiler if available.
  public let swiftc: AbsolutePath?

  /// The path to the swift-format executable, if available.
  public let swiftFormat: AbsolutePath?

  /// The path to the clangd language server if available.
  public let clangd: AbsolutePath?

  /// The path to the Swift language server if available.
  public let sourcekitd: AbsolutePath?

  /// The path to the indexstore library if available.
  public let libIndexStore: AbsolutePath?

  private let swiftVersionTask = ThreadSafeBox<Task<SwiftVersion, any Error>?>(initialValue: nil)

  /// The Swift version installed in the toolchain. Throws an error if the version could not be parsed or if no Swift
  /// compiler is installed in the toolchain.
  public var swiftVersion: SwiftVersion {
    get async throws {
      let task = swiftVersionTask.withLock { task in
        if let task {
          return task
        }
        let newTask = Task { () -> SwiftVersion in
          guard let swiftc else {
            throw SwiftVersionParsingError.failedToFindSwiftc
          }

          let process = Process(args: swiftc.pathString, "--version")
          try process.launch()
          let result = try await process.waitUntilExit()
          let output = String(bytes: try result.output.get(), encoding: .utf8)
          let regex = Regex {
            "Swift version "
            Capture { OneOrMore(.digit) }
            "."
            Capture { OneOrMore(.digit) }
          }
          guard let match = output?.firstMatch(of: regex) else {
            throw SwiftVersionParsingError.failedToParseOutput(output: output)
          }
          guard let major = Int(match.1), let minor = Int(match.2) else {
            throw SwiftVersionParsingError.failedToParseOutput(output: output)
          }
          return SwiftVersion(major, minor)
        }
        task = newTask
        return newTask
      }

      return try await task.value
    }
  }

  public init(
    identifier: String,
    displayName: String,
    path: AbsolutePath? = nil,
    clang: AbsolutePath? = nil,
    swift: AbsolutePath? = nil,
    swiftc: AbsolutePath? = nil,
    swiftFormat: AbsolutePath? = nil,
    clangd: AbsolutePath? = nil,
    sourcekitd: AbsolutePath? = nil,
    libIndexStore: AbsolutePath? = nil
  ) {
    self.identifier = identifier
    self.displayName = displayName
    self.path = path
    self.clang = clang
    self.swift = swift
    self.swiftc = swiftc
    self.swiftFormat = swiftFormat
    self.clangd = clangd
    self.sourcekitd = sourcekitd
    self.libIndexStore = libIndexStore
  }

  /// Returns `true` if this toolchain has strictly more tools than `other`.
  ///
  /// ### Examples
  /// - A toolchain that contains both `swiftc` and  `clangd` is a superset of one that only contains `swiftc`.
  /// - A toolchain that contains only `swiftc`, `clangd` is not a superset of a toolchain that contains `swiftc` and
  ///   `libIndexStore`. These toolchains are not comparable.
  /// - Two toolchains that both contain `swiftc` and `clangd` are supersets of each other.
  func isSuperset(of other: Toolchain) -> Bool {
    func isSuperset(for tool: KeyPath<Toolchain, AbsolutePath?>) -> Bool {
      if self[keyPath: tool] == nil && other[keyPath: tool] != nil {
        // This toolchain doesn't contain the tool but the other toolchain does. It is not a superset.
        return false
      } else {
        return true
      }
    }
    return isSuperset(for: \.clang) && isSuperset(for: \.swift) && isSuperset(for: \.swiftc)
      && isSuperset(for: \.clangd) && isSuperset(for: \.sourcekitd) && isSuperset(for: \.libIndexStore)
  }

  /// Same as `isSuperset` but returns `false` if both toolchains have the same set of tools.
  func isProperSuperset(of other: Toolchain) -> Bool {
    return self.isSuperset(of: other) && !other.isSuperset(of: self)
  }
}

extension Toolchain {
  /// Create a toolchain for the given path, if it contains at least one tool, otherwise return nil.
  ///
  /// This initializer looks for a toolchain using the following basic layout:
  ///
  /// ```
  /// bin/clang
  ///    /clangd
  ///    /swiftc
  /// lib/sourcekitd.framework/sourcekitd
  ///    /libsourcekitdInProc.{so,dylib}
  ///    /libIndexStore.{so,dylib}
  /// ```
  ///
  /// The above directory layout can found relative to `path` in the following ways:
  /// * `path` (=bin), `path/../lib`
  /// * `path/bin`, `path/lib`
  /// * `path/usr/bin`, `path/usr/lib`
  ///
  /// If `path` contains an ".xctoolchain", we try to read an Info.plist file to provide the
  /// toolchain identifier, etc.  Otherwise this information is derived from the path.
  convenience public init?(_ path: AbsolutePath, _ fileSystem: FileSystem = localFileSystem) {
    // Properties that need to be initialized
    let identifier: String
    let displayName: String
    let toolchainPath: AbsolutePath?
    var clang: AbsolutePath? = nil
    var clangd: AbsolutePath? = nil
    var swift: AbsolutePath? = nil
    var swiftc: AbsolutePath? = nil
    var swiftFormat: AbsolutePath? = nil
    var sourcekitd: AbsolutePath? = nil
    var libIndexStore: AbsolutePath? = nil

    if let (infoPlist, xctoolchainPath) = containingXCToolchain(path, fileSystem) {
      identifier = infoPlist.identifier
      displayName = infoPlist.displayName ?? xctoolchainPath.basenameWithoutExt
      toolchainPath = xctoolchainPath
    } else {
      identifier = path.pathString
      displayName = path.basename
      toolchainPath = path
    }

    // Find tools in the toolchain

    var foundAny = false
    let searchPaths = [path, path.appending(components: "bin"), path.appending(components: "usr", "bin")]
    for binPath in searchPaths {
      let libPath = binPath.parentDirectory.appending(component: "lib")

      guard fileSystem.isDirectory(binPath) || fileSystem.isDirectory(libPath) else { continue }

      let execExt = Platform.current?.executableExtension ?? ""

      let clangPath = binPath.appending(component: "clang\(execExt)")
      if fileSystem.isExecutableFile(clangPath) {
        clang = clangPath
        foundAny = true
      }
      let clangdPath = binPath.appending(component: "clangd\(execExt)")
      if fileSystem.isExecutableFile(clangdPath) {
        clangd = clangdPath
        foundAny = true
      }

      let swiftPath = binPath.appending(component: "swift\(execExt)")
      if fileSystem.isExecutableFile(swiftPath) {
        swift = swiftPath
        foundAny = true
      }

      let swiftcPath = binPath.appending(component: "swiftc\(execExt)")
      if fileSystem.isExecutableFile(swiftcPath) {
        swiftc = swiftcPath
        foundAny = true
      }

      let swiftFormatPath = binPath.appending(component: "swift-format\(execExt)")
      if fileSystem.isExecutableFile(swiftFormatPath) {
        swiftFormat = swiftFormatPath
        foundAny = true
      }

      // If 'currentPlatform' is nil it's most likely an unknown linux flavor.
      let dylibExt: String
      if let dynamicLibraryExtension = Platform.current?.dynamicLibraryExtension {
        dylibExt = dynamicLibraryExtension
      } else {
        logger.fault("Could not determine host OS. Falling back to using '.so' as dynamic library extension")
        dylibExt = ".so"
      }

      let sourcekitdPath = libPath.appending(components: "sourcekitd.framework", "sourcekitd")
      if fileSystem.isFile(sourcekitdPath) {
        sourcekitd = sourcekitdPath
        foundAny = true
      } else {
        #if os(Windows)
        let sourcekitdPath = binPath.appending(component: "sourcekitdInProc\(dylibExt)")
        #else
        let sourcekitdPath = libPath.appending(component: "libsourcekitdInProc\(dylibExt)")
        #endif
        if fileSystem.isFile(sourcekitdPath) {
          sourcekitd = sourcekitdPath
          foundAny = true
        }
      }

      #if os(Windows)
      let libIndexStorePath = binPath.appending(components: "libIndexStore\(dylibExt)")
      #else
      let libIndexStorePath = libPath.appending(components: "libIndexStore\(dylibExt)")
      #endif
      if fileSystem.isFile(libIndexStorePath) {
        libIndexStore = libIndexStorePath
        foundAny = true
      }

      if foundAny {
        break
      }
    }
    if !foundAny {
      return nil
    }

    self.init(
      identifier: identifier,
      displayName: displayName,
      path: toolchainPath,
      clang: clang,
      swift: swift,
      swiftc: swiftc,
      swiftFormat: swiftFormat,
      clangd: clangd,
      sourcekitd: sourcekitd,
      libIndexStore: libIndexStore
    )
  }
}

/// Find a containing xctoolchain with plist, if available.
func containingXCToolchain(
  _ path: AbsolutePath,
  _ fileSystem: FileSystem
) -> (XCToolchainPlist, AbsolutePath)? {
  var path = path
  while !path.isRoot {
    if path.extension == "xctoolchain" {
      if let infoPlist = orLog("", { try XCToolchainPlist(fromDirectory: path, fileSystem) }) {
        return (infoPlist, path)
      }
      return nil
    }
    path = path.parentDirectory
  }
  return nil
}