File: PackagePIFProjectBuilder.swift

package info (click to toggle)
swiftlang 6.2.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,856,264 kB
  • sloc: cpp: 9,995,718; ansic: 2,234,019; asm: 1,092,167; python: 313,940; objc: 82,726; f90: 80,126; lisp: 38,373; pascal: 25,580; sh: 20,378; ml: 5,058; perl: 4,751; makefile: 4,725; awk: 3,535; javascript: 3,018; xml: 918; fortran: 664; cs: 573; ruby: 396
file content (567 lines) | stat: -rw-r--r-- 25,282 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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2025 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
//
//===----------------------------------------------------------------------===//

import Foundation
import TSCUtility

import struct Basics.AbsolutePath
import struct Basics.Diagnostic
import class Basics.ObservabilitySystem
import struct Basics.SourceControlURL

import class PackageModel.Manifest
import struct PackageModel.Platform
import class PackageModel.Product
import struct PackageModel.Resource
import struct PackageModel.ToolsVersion

import struct PackageGraph.ModulesGraph
import struct PackageGraph.ResolvedModule
import struct PackageGraph.ResolvedPackage

import struct PackageLoading.FileRuleDescription
import struct PackageLoading.TargetSourcesBuilder

import struct SwiftBuild.Pair
import enum SwiftBuild.ProjectModel
import struct SwiftBuild.SwiftBuildFileType

/// Helper type to create PIF **project** and **targets** for a given package.
struct PackagePIFProjectBuilder {
    let pifBuilder: PackagePIFBuilder
    let package: PackageGraph.ResolvedPackage
    let packageManifest: PackageModel.Manifest
    let modulesGraph: PackageGraph.ModulesGraph

    var project: ProjectModel.Project

    let binaryGroupKeyPath: WritableKeyPath<ProjectModel.Group, ProjectModel.Group>
    var binaryGroup: ProjectModel.Group {
        get { self.project.mainGroup[keyPath: self.binaryGroupKeyPath] }
        set { self.project.mainGroup[keyPath: self.binaryGroupKeyPath] = newValue }
    }

    let additionalFilesGroupKeyPath: WritableKeyPath<ProjectModel.Group, ProjectModel.Group>
    var additionalFilesGroup: ProjectModel.Group {
        get { self.project.mainGroup[keyPath: self.additionalFilesGroupKeyPath] }
        set { self.project.mainGroup[keyPath: self.additionalFilesGroupKeyPath] = newValue }
    }

    let declaredPlatforms: [PackageModel.Platform]?
    let deploymentTargets: [PackageModel.Platform: String?]

    /// Current set of names of any package products that are explicitly declared dynamic libraries.
    private let dynamicLibraryProductNames: Set<String>

    /// FIXME: We should eventually clean this up but right now we have to carry over this
    /// bit of information from processing the *products* to processing the *targets*.
    var mainModuleTargetNamesWithResources: Set<String> = []

    var builtModulesAndProducts: [PackagePIFBuilder.ModuleOrProduct]

    func log(
        _ severity: Diagnostic.Severity,
        indent: UInt = 0,
        _ message: String,
        sourceFile: StaticString = #fileID,
        sourceLine: UInt = #line
    ) {
        self.pifBuilder.observabilityScope.logPIF(
            severity,
            indent: indent,
            message,
            sourceFile: sourceFile,
            sourceLine: sourceLine
        )
    }

    init(createForPackage package: PackageGraph.ResolvedPackage, builder: PackagePIFBuilder) {
        // Create a PIF project using an identifier that's based on the normalized absolute path of the package.
        // We use the package manifest path as the project path, and the package path as the project's base source
        // directory.
        // FIXME: The PIF creation should ideally be done on a background thread.
        var pifProject = ProjectModel.Project(
            id: "PACKAGE:\(package.identity)",
            path: package.manifest.path.pathString,
            projectDir: package.path.pathString,
            name: package.name,
            developmentRegion: package.manifest.defaultLocalization
        )

        let additionalFilesGroupKeyPath = pifProject.mainGroup.addGroup { id in
            ProjectModel.Group(
                id: id,
                path: "/",
                pathBase: .absolute,
                name: "AdditionalFiles"
            )
        }
        let binaryGroupKeyPath = pifProject.mainGroup.addGroup { id in
            ProjectModel.Group(
                id: id,
                path: "/",
                pathBase: .absolute,
                name: "Binaries"
            )
        }

        // Test modules have a higher minimum deployment target by default,
        // so we favor non-test modules as representative for the package's deployment target.
        let firstModule = package.modules.first { $0.type != .test } ?? package.modules.first

        let moduleDeploymentTargets = firstModule?.deploymentTargets(using: builder.delegate)

        // The deployment targets are passed through to the eventual `ModuleOrProduct` values,
        // so that querying them yields reasonable results for those build settings.
        var deploymentTargets: [PackageModel.Platform: String?] = [
            .macOS: moduleDeploymentTargets?[.macOS],
            .macCatalyst: moduleDeploymentTargets?[.macCatalyst],
            .iOS: moduleDeploymentTargets?[.iOS],
            .tvOS: moduleDeploymentTargets?[.tvOS],
            .watchOS: moduleDeploymentTargets?[.watchOS],
            .driverKit: moduleDeploymentTargets?[.driverKit],
        ]
        deploymentTargets[.visionOS] = moduleDeploymentTargets?[.visionOS]
        let declaredPlatforms = firstModule?.declaredPlatforms

        // Compute the names of all explicitly dynamic library products, we need to avoid
        // name clashes with any package targets we could decide to build dynamically.
        let allPackages = builder.modulesGraph.packages
        let dynamicLibraryProductNames = Set(
            allPackages
                .flatMap(\.products)
                .filter { $0.type == .library(.dynamic) }
                .map(\.name)
        )

        self.pifBuilder = builder
        self.package = package
        self.packageManifest = self.pifBuilder.packageManifest
        self.modulesGraph = self.pifBuilder.modulesGraph
        self.project = pifProject
        self.binaryGroupKeyPath = binaryGroupKeyPath
        self.additionalFilesGroupKeyPath = additionalFilesGroupKeyPath
        self.declaredPlatforms = declaredPlatforms
        self.deploymentTargets = deploymentTargets
        self.dynamicLibraryProductNames = dynamicLibraryProductNames
        self.builtModulesAndProducts = []
    }

    // MARK: - Handling Resources

    mutating func addResourceBundle(
        for module: PackageGraph.ResolvedModule,
        targetKeyPath: WritableKeyPath<ProjectModel.Project, ProjectModel.Target>,
        generatedResourceFiles: [String]
    ) throws -> (PackagePIFBuilder.EmbedResourcesResult, PackagePIFBuilder.ModuleOrProduct?) {
        if module.resources.isEmpty && generatedResourceFiles.isEmpty {
            return (PackagePIFBuilder.EmbedResourcesResult(
                bundleName: nil,
                shouldGenerateBundleAccessor: false,
                shouldGenerateEmbedInCodeAccessor: false
            ), nil)
        }

        let bundleName = self.resourceBundleName(forModuleName: module.name)
        let resourceBundleGUID = self.pifTargetIdForResourceBundle(module.name)
        let resourcesTargetKeyPath = try self.project.addTarget { _ in
            ProjectModel.Target(
                id: resourceBundleGUID,
                productType: .bundle,
                name: bundleName,
                productName: bundleName
            )
        }
        var resourcesTarget: ProjectModel.Target { self.project[keyPath: resourcesTargetKeyPath] }

        self.project[keyPath: targetKeyPath].common.addDependency(
            on: resourcesTarget.id,
            platformFilters: [],
            linkProduct: false
        )
        self.log(.debug, indent: 1, "Added dependency on resource target '\(resourcesTarget.id)'")

        for pluginModule in module.pluginsAppliedToModule {
            self.project[keyPath: resourcesTargetKeyPath].common.addDependency(
                on: pluginModule.pifTargetGUID,
                platformFilters: [],
                linkProduct: false
            )
        }

        self.log(
            .debug,
            indent: 1,
            "Created target '\(resourcesTarget.id)' of type '\(resourcesTarget.productType)' " +
            "with name '\(resourcesTarget.name)' and product name '\(resourcesTarget.productName)'"
        )

        var settings: ProjectModel.BuildSettings = self.package.underlying.packageBaseBuildSettings
        settings[.TARGET_NAME] = bundleName
        settings[.PRODUCT_NAME] = "$(TARGET_NAME)"
        settings[.PRODUCT_MODULE_NAME] = bundleName
        settings[.PRODUCT_BUNDLE_IDENTIFIER] = "\(self.package.identity).\(module.name).resources"
            .spm_mangledToBundleIdentifier()
        settings[.EXECUTABLE_NAME] = ""
        settings[.GENERATE_INFOPLIST_FILE] = "YES"
        settings[.PACKAGE_RESOURCE_TARGET_KIND] = "resource"

        settings[.COREML_COMPILER_CONTAINER] = "swift-package"
        settings[.COREML_CODEGEN_LANGUAGE] = "None"

        self.project[keyPath: resourcesTargetKeyPath].common.addBuildConfig { id in
            BuildConfig(id: id, name: "Debug", settings: settings)
        }
        self.project[keyPath: resourcesTargetKeyPath].common.addBuildConfig { id in
            BuildConfig(id: id, name: "Release", settings: settings)
        }

        let result = self.processResources(
            for: module,
            sourceModuleTargetKeyPath: targetKeyPath,
            resourceBundleTargetKeyPath: resourcesTargetKeyPath,
            generatedResourceFiles: generatedResourceFiles
        )

        let resourceBundle = PackagePIFBuilder.ModuleOrProduct(
            type: .resourceBundle,
            name: bundleName,
            moduleName: bundleName,
            pifTarget: .target(resourcesTarget),
            indexableFileURLs: [],
            headerFiles: [],
            linkedPackageBinaries: [],
            swiftLanguageVersion: nil,
            declaredPlatforms: [],
            deploymentTargets: [:]
        )

        return (result, resourceBundle)
    }

    mutating func processResources(
        for module: PackageGraph.ResolvedModule,
        sourceModuleTargetKeyPath: WritableKeyPath<ProjectModel.Project, ProjectModel.Target>,
        resourceBundleTargetKeyPath: WritableKeyPath<ProjectModel.Project, ProjectModel.Target>?,
        generatedResourceFiles: [String]
    ) -> PackagePIFBuilder.EmbedResourcesResult {
        if module.resources.isEmpty && generatedResourceFiles.isEmpty {
            return PackagePIFBuilder.EmbedResourcesResult(
                bundleName: nil,
                shouldGenerateBundleAccessor: false,
                shouldGenerateEmbedInCodeAccessor: false
            )
        }
        // If resourceBundleTarget is nil, we add resources to the sourceModuleTarget instead.
        let targetForResourcesKeyPath: WritableKeyPath<ProjectModel.Project, ProjectModel.Target> =
            resourceBundleTargetKeyPath ?? sourceModuleTargetKeyPath
        
        // Generated resources get a default treatment for rule and localization.
        let generatedResources = generatedResourceFiles.compactMap {
            PackagePIFBuilder.Resource(path: $0, rule: .process(localization: nil))
        }

        let resources = module.resources.map { PackagePIFBuilder.Resource($0) } + generatedResources
        let shouldGenerateBundleAccessor = resources.anySatisfy { $0.rule != .embedInCode }
        let shouldGenerateEmbedInCodeAccessor = resources.anySatisfy { $0.rule == .embedInCode }

        for resource in resources {
            let resourcePath = resource.path
            // Add a file reference for the resource. We use an absolute path, as for all the other files,
            // but we should be able to optimize this later by making it group-relative.
            let ref = self.project.mainGroup.addFileReference { id in
                ProjectModel.FileReference(id: id, path: resourcePath, pathBase: .absolute)
            }

            // CoreData files should also be in the actual target because they
            // can end up generating code during the build.
            // The build system will only perform codegen tasks for the main target in this case.
            let isCoreDataFile = [SwiftBuild.SwiftBuildFileType.xcdatamodeld, .xcdatamodel]
                .contains { $0.fileTypes.contains(resourcePath.pathExtension) }

            if isCoreDataFile {
                self.project[keyPath: sourceModuleTargetKeyPath].addSourceFile { id in
                    BuildFile(id: id, fileRef: ref)
                }
                self.log(.debug, indent: 2, "Added core data resource as source file '\(resourcePath)'")
            }

            // Core ML files need to be included in the source module as well, because there is code generation.
            let coreMLFileTypes: [SwiftBuild.SwiftBuildFileType] = [.mlmodel, .mlpackage]
            let isCoreMLFile = coreMLFileTypes.contains { $0.fileTypes.contains(resourcePath.pathExtension) }

            if isCoreMLFile {
                self.project[keyPath: sourceModuleTargetKeyPath].addSourceFile { id in
                    BuildFile(id: id, fileRef: ref, generatedCodeVisibility: .public)
                }
                self.log(.debug, indent: 2, "Added coreml resource as source file '\(resourcePath)'")
            }

            // Metal source code needs to be added to the source build phase.
            let isMetalFile = SwiftBuild.SwiftBuildFileType.metal.fileTypes.contains(resourcePath.pathExtension)

            if isMetalFile {
                self.project[keyPath: targetForResourcesKeyPath].addSourceFile { id in
                    BuildFile(id: id, fileRef: ref)
                }
            } else {
                // FIXME: Handle additional rules here (e.g. `.copy`).
                self.project[keyPath: targetForResourcesKeyPath].addResourceFile { id in
                    BuildFile(
                        id: id,
                        fileRef: ref,
                        platformFilters: [],
                        resourceRule: resource.rule == .embedInCode ? .embedInCode : .process
                    )
                }
            }

            // Asset Catalogs need to be included in the sources modules for generated asset symbols.
            let isAssetCatalog = resourcePath.pathExtension == "xcassets"
            if isAssetCatalog {
                self.project[keyPath: sourceModuleTargetKeyPath].addSourceFile { id in
                    BuildFile(id: id, fileRef: ref)
                }
                self.log(.debug, indent: 2, "Added asset catalog as source file '\(resourcePath)'")
            }

            // String Catalogs can also generate symbols.
            if SwiftBuild.SwiftBuildFileType.xcstrings.fileTypes.contains(resourcePath.pathExtension) {
                self.project[keyPath: sourceModuleTargetKeyPath].addSourceFile { id in
                    BuildFile(id: id, fileRef: ref)
                }
                self.log(.debug, indent: 2, "Added string catalog as source file '\(resourcePath)'")
            }

            self.log(.debug, indent: 2, "Added resource file '\(resourcePath)'")
        }

        let resourceBundleTargetName: String?
        if let resourceBundleTargetKeyPath {
            let resourceBundleTarget = self.project[keyPath: resourceBundleTargetKeyPath]
            resourceBundleTargetName = resourceBundleTarget.name
        } else {
            resourceBundleTargetName = nil
        }
        
        return PackagePIFBuilder.EmbedResourcesResult(
            bundleName: resourceBundleTargetName,
            shouldGenerateBundleAccessor: shouldGenerateBundleAccessor,
            shouldGenerateEmbedInCodeAccessor: shouldGenerateEmbedInCodeAccessor
        )
    }

    func resourceBundleTargetKeyPath(
        forModuleName name: String
    ) -> WritableKeyPath<ProjectModel.Project, ProjectModel.Target>? {
        let resourceBundleGUID = self.pifTargetIdForResourceBundle(name)
        let targetKeyPath = self.project.findTarget(id: resourceBundleGUID)
        return targetKeyPath
    }

    func pifTargetIdForResourceBundle(_ name: String) -> GUID {
        GUID("PACKAGE-RESOURCE:\(name)")
    }

    func resourceBundleName(forModuleName name: String) -> String {
        "\(self.package.name)_\(name)"
    }

    // MARK: - Plugin Helpers

    /// Helper function that compiles the plugin-generated files for a target,
    /// optionally also adding the corresponding plugin-provided commands to the PIF target.
    ///
    /// The reason we might not add them is that some targets are derivatives of other targets — in such cases,
    /// only the primary target adds the build tool commands to the PIF target.
    mutating func computePluginGeneratedFiles(
        module: PackageGraph.ResolvedModule,
        targetKeyPath: WritableKeyPath<ProjectModel.Project, ProjectModel.Target>,
        addBuildToolPluginCommands: Bool
    ) -> (sourceFilePaths: [AbsolutePath], resourceFilePaths: [String]) {
        guard let pluginResults = pifBuilder.buildToolPluginResultsByTargetName[module.name] else {
            // We found no results for the target.
            return (sourceFilePaths: [], resourceFilePaths: [])
        }

        var sourceFilePaths: [AbsolutePath] = []
        var resourceFilePaths: [AbsolutePath] = []

        for pluginResult in pluginResults {
            // Process the results of applying any build tool plugins on the target.
            // If we've been asked to add build tool commands for the result, we do so now.
            if addBuildToolPluginCommands {
                for command in pluginResult.buildCommands {
                    self.addBuildToolCommand(command, to: targetKeyPath)
                }
            }

            // Process all the paths of derived output paths using the same rules as for source.
            let result = self.process(
                pluginGeneratedFilePaths: pluginResult.allDerivedOutputPaths,
                forModule: module,
                toolsVersion: self.package.manifest.toolsVersion
            )

            sourceFilePaths.append(contentsOf: result.sourceFilePaths)
            resourceFilePaths.append(contentsOf: result.resourceFilePaths.map(\.path))
        }
        return (
            sourceFilePaths: sourceFilePaths,
            resourceFilePaths: resourceFilePaths.map(\.pathString)
        )
    }

    /// Helper function for adding build tool commands to the right PIF target depending on whether they generate
    /// sources or resources.
    mutating func addBuildToolCommands(
        module: PackageGraph.ResolvedModule,
        sourceModuleTargetKeyPath: WritableKeyPath<ProjectModel.Project, ProjectModel.Target>,
        resourceBundleTargetKeyPath: WritableKeyPath<ProjectModel.Project, ProjectModel.Target>,
        sourceFilePaths: [AbsolutePath],
        resourceFilePaths: [String]
    ) {
        guard let pluginResults = pifBuilder.buildToolPluginResultsByTargetName[module.name] else {
            return
        }

        for pluginResult in pluginResults {
            for command in pluginResult.buildCommands {
                let producesResources = Set(command.outputPaths).intersection(resourceFilePaths).hasContent

                if producesResources {
                    self.addBuildToolCommand(command, to: resourceBundleTargetKeyPath)
                } else {
                    self.addBuildToolCommand(command, to: sourceModuleTargetKeyPath)
                }
            }
        }
    }

    /// Adds build rules to `pifTarget` for any build tool   commands from invocation results.
    /// Returns the absolute paths of any generated source files that should be added to the sources build phase of the
    /// PIF target.
    mutating func addBuildToolCommands(
        from pluginInvocationResults: [PackagePIFBuilder.BuildToolPluginInvocationResult],
        targetKeyPath: WritableKeyPath<ProjectModel.Project, ProjectModel.Target>,
        addBuildToolPluginCommands: Bool
    ) -> [String] {
        var generatedSourceFileAbsPaths: [String] = []
        for result in pluginInvocationResults {
            // Create build rules for all the commands in the result.
            if addBuildToolPluginCommands {
                for command in result.buildCommands {
                    self.addBuildToolCommand(command, to: targetKeyPath)
                }
            }
            // Add the paths of the generated source files, so that they can be added to the Sources build phase.
            generatedSourceFileAbsPaths.append(contentsOf: result.allDerivedOutputPaths.map(\.pathString))
        }
        return generatedSourceFileAbsPaths
    }

    /// Adds a single plugin-created build command to a PIF target.
    mutating func addBuildToolCommand(
        _ command: PackagePIFBuilder.CustomBuildCommand,
        to targetKeyPath: WritableKeyPath<ProjectModel.Project, ProjectModel.Target>
    ) {
        var commandLine = [command.executable] + command.arguments
        if let sandbox = command.sandboxProfile, !pifBuilder.delegate.isPluginExecutionSandboxingDisabled {
            commandLine = try! sandbox.apply(to: commandLine, fileSystem: self.pifBuilder.fileSystem)
        }

        self.project[keyPath: targetKeyPath].customTasks.append(
            ProjectModel.CustomTask(
                commandLine: commandLine,
                environment: command.environment.map { Pair($0, $1) }.sorted(by: <),
                workingDirectory: command.workingDir?.pathString,
                executionDescription: command.displayName ?? "Performing build tool plugin command",
                inputFilePaths: [command.executable] + command.inputPaths.map(\.pathString),
                outputFilePaths: command.outputPaths,
                enableSandboxing: false,
                preparesForIndexing: true
            )
        )
    }

    /// Processes the paths of plugin-generated files for a particular package target,
    /// returning paths of those that should be treated as sources vs resources.
    private func process(
        pluginGeneratedFilePaths: [AbsolutePath],
        forModule module: PackageGraph.ResolvedModule,
        toolsVersion: PackageModel.ToolsVersion?
    ) -> (sourceFilePaths: [AbsolutePath], resourceFilePaths: [Resource]) {
        precondition(module.isSourceModule)

        // If we have no tools version, all files are treated as *source* files.
        guard let toolsVersion else {
            return (sourceFilePaths: pluginGeneratedFilePaths, resourceFilePaths: [])
        }

        // FIXME: Will be fixed by <rdar://144802163> (SwiftPM PIFBuilder — adopt ObservabilityScope as the logging API).
        let observabilityScope = ObservabilitySystem.NOOP

        // Use the `TargetSourcesBuilder` from libSwiftPM to split the generated files into sources and resources.
        let (generatedSourcePaths, generatedResourcePaths) = TargetSourcesBuilder.computeContents(
            for: pluginGeneratedFilePaths,
            toolsVersion: toolsVersion,
            additionalFileRules: Self.additionalFileRules,
            defaultLocalization: module.defaultLocalization,
            targetName: module.name,
            targetPath: module.path,
            observabilityScope: observabilityScope
        )

        // FIXME: We are not handling resource rules here, but the same is true for non-generated resources.
        // (Today, everything gets essentially treated as `.processResource` even if it may have been declared as
        // `.copy` in the manifest.)
        return (generatedSourcePaths, generatedResourcePaths)
    }

    private static let additionalFileRules: [FileRuleDescription] =
        FileRuleDescription.xcbuildFileTypes + [
            FileRuleDescription(
                rule: .compile,
                toolsVersion: .v5_5,
                fileTypes: ["docc"]
            ),
            FileRuleDescription(
                rule: .processResource(localization: .none),
                toolsVersion: .v5_7,
                fileTypes: ["mlmodel", "mlpackage"]
            ),
            FileRuleDescription(
                rule: .processResource(localization: .none),
                toolsVersion: .v5_7,
                fileTypes: ["rkassets"] // visionOS
            ),
        ]

    // MARK: - General Helpers

    func installPath(for product: PackageModel.Product) -> String {
        if let customInstallPath = pifBuilder.delegate.customInstallPath(product: product) {
            customInstallPath
        } else {
            "/usr/local/lib"
        }
    }

    /// Always create a dynamic variant for targets, for automatic resolution of diamond problems,
    /// unless there is a potential name clash with an explicitly *dynamic library* product.
    ///
    /// Swift Build will emit a diagnostic if such a package target is part of a diamond.
    func shouldOfferDynamicTarget(_ targetName: String) -> Bool {
        !self.dynamicLibraryProductNames.contains(targetName)
    }
}