File: LibraryPluginProvider.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 (201 lines) | stat: -rw-r--r-- 6,785 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
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2024 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#if swift(>=6.0)
public import SwiftSyntaxMacros
@_spi(PluginMessage) public import SwiftCompilerPluginMessageHandling
private import _SwiftLibraryPluginProviderCShims
// NOTE: Do not use '_SwiftSyntaxCShims' for 'dlopen' and 'LoadLibraryW' (Windows)
// because we don't want other modules depend on 'WinSDK'.
#if canImport(Darwin)
private import Darwin
#elseif canImport(Glibc)
private import Glibc
#elseif canImport(Musl)
private import Musl
#endif
#else
import SwiftSyntaxMacros
@_spi(PluginMessage) import SwiftCompilerPluginMessageHandling
@_implementationOnly import _SwiftLibraryPluginProviderCShims
#if canImport(Darwin)
@_implementationOnly import Darwin
#elseif canImport(Glibc)
@_implementationOnly import Glibc
#elseif canImport(Musl)
@_implementationOnly import Musl
#endif
#endif

/// Singleton 'PluginProvider' that can serve shared library plugins.
@_spi(PluginMessage)
public class LibraryPluginProvider: PluginProvider {
  struct LoadedLibraryPlugin {
    var libraryPath: String
    var handle: UnsafeMutableRawPointer
  }

  struct MacroRef: Hashable {
    var moduleName: String
    var typeName: String
  }

  /// Loaded dynamic link library handles associated with the module name.
  var loadedLibraryPlugins: [String: LoadedLibraryPlugin] = [:]

  /// Resolved macros cache.
  var resolvedMacros: [MacroRef: Macro.Type] = [:]

  private init() {}

  /// Singleton.
  @MainActor
  public static let shared: LibraryPluginProvider = LibraryPluginProvider()

  public var features: [PluginFeature] {
    [.loadPluginLibrary]
  }

  public func loadPluginLibrary(libraryPath: String, moduleName: String) throws {
    if let loaded = loadedLibraryPlugins[moduleName] {
      guard loaded.libraryPath == libraryPath else {
        // NOTE: Should be unreachable. Compiler should not load different
        // library for the same module name.
        throw LibraryPluginError(
          message:
            "library plugin for module '\(moduleName)' is already loaded from different path '\(loaded.libraryPath)'"
        )
      }
      return
    }

    let dlHandle = try _loadLibrary(libraryPath)

    loadedLibraryPlugins[moduleName] = LoadedLibraryPlugin(
      libraryPath: libraryPath,
      handle: dlHandle
    )
  }

  public func resolveMacro(moduleName: String, typeName: String) throws -> SwiftSyntaxMacros.Macro.Type {
    let macroRef = MacroRef(moduleName: moduleName, typeName: typeName)
    if let resolved = resolvedMacros[macroRef] {
      return resolved
    }

    // Find 'dlopen'ed library for the module name.
    guard let plugin = loadedLibraryPlugins[moduleName] else {
      // NOTE: Should be unreachable. Compiler should not use this server
      // unless the plugin loading succeeded.
      throw LibraryPluginError(message: "plugin not loaded for module '\(moduleName)'")
    }

    // Lookup the type metadata.
    guard let type = _findAnyType(moduleName, typeName) else {
      throw LibraryPluginError(
        message: "type '\(moduleName).\(typeName)' could not be found in library plugin '\(plugin.libraryPath)'"
      )
    }

    // The type must be a 'Macro' type.
    guard let macro = type as? Macro.Type else {
      throw LibraryPluginError(
        message:
          "type '\(moduleName).\(typeName)' is not a valid macro implementation type in library plugin '\(plugin.libraryPath)'"
      )
    }

    // Cache the resolved type.
    resolvedMacros[macroRef] = macro
    return macro
  }
}

#if os(Windows)
private func _loadLibrary(_ path: String) throws -> UnsafeMutableRawPointer {
  // Create NULL terminated UTF16 string.
  let utf16Path = UnsafeMutableBufferPointer<UInt16>.allocate(capacity: path.utf16.count + 1)
  defer { utf16Path.deallocate() }
  let end = utf16Path.initialize(fromContentsOf: path.utf16)
  utf16Path.initializeElement(at: end, to: 0)

  guard let dlHandle = swiftlibrarypluginprovider_LoadLibraryW(utf16Path.baseAddress) else {
    // FIXME: Format the error code to string.
    throw LibraryPluginError(message: "loader error: \(swiftlibrarypluginprovider_GetLastError())")
  }
  return UnsafeMutableRawPointer(dlHandle)
}
#else
private func _loadLibrary(_ path: String) throws -> UnsafeMutableRawPointer {
  guard let dlHandle = dlopen(path, RTLD_LAZY | RTLD_LOCAL) else {
    throw LibraryPluginError(message: "loader error: \(String(cString: dlerror()))")
  }
  return dlHandle
}
#endif

private func _findAnyType(_ moduleName: String, _ typeName: String) -> Any.Type? {
  // Create a mangled name for struct, enum, and class. And use a runtime
  // function to find the type. Note that this simple mangling works even if the
  // actual symbol name doesn't match with it. i.e. We don't need to perform
  // punycode encodings or word substitutions.
  // FIXME: This is process global. Can we limit it to a specific .dylib ?
  for suffix in [ /*struct*/"V", /*enum*/ "O", /*class*/ "C"] {
    let mangled = "\(moduleName.utf8.count)\(moduleName)\(typeName.utf8.count)\(typeName)\(suffix)"
    if let type = _typeByName(mangled) {
      return type
    }
  }
  return nil
}

private struct LibraryPluginError: Error, CustomStringConvertible {
  var description: String
  init(message: String) {
    self.description = message
  }
}

// Compatibility shim for SE-0370
#if swift(<5.8)
extension UnsafeMutableBufferPointer {
  private func initialize(fromContentsOf source: some Collection<Element>) -> Index {
    let count = source.withContiguousStorageIfAvailable {
      guard let sourceAddress = $0.baseAddress, !$0.isEmpty else {
        return 0
      }
      precondition(
        $0.count <= self.count,
        "buffer cannot contain every element from source."
      )
      baseAddress?.initialize(from: sourceAddress, count: $0.count)
      return $0.count
    }
    if let count {
      return startIndex.advanced(by: count)
    }

    var (iterator, copied) = self.initialize(from: source)
    precondition(
      iterator.next() == nil,
      "buffer cannot contain every element from source."
    )
    return startIndex.advanced(by: copied)
  }

  private func initializeElement(at index: Index, to value: Element) {
    precondition(startIndex <= index && index < endIndex)
    let p = baseAddress!.advanced(by: index)
    p.initialize(to: value)
  }
}
#endif