Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions .github/copilot-instructions.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,10 @@ diff Package.swift Package_generated.swift
| Config load | `ConfigLoader.swift` | Finds `packageGenerator.{yaml,yml,json}`, converts YAML via `yaml-converter` subprocess, decodes into `ConfigurationV2` |
| 2 — Discovery | `TargetResolution.swift` | `resolveTargetPaths` (shortest-path logic), `linkTestTargets` (strips "Tests" suffix), `discoverExternalDeps` (reads SPM graph), `runCLI` (invokes `package-generator-cli`) |
| 3 — Import Analysis | `ImportAnalysis.swift` | `filterImports` — drops self-imports and explicit exclusions; Apple SDK filtering is intentionally **deferred** to render phase |
| 4 — Code Generation | `CodeGeneration.swift` | `renderSingleTarget`, `generateProductsSection`, `generateTargetsSection`, `writeOutput` |
| 5 — Advanced Features | `AdvancedFeatures.swift` | `generateExportedFiles`, `detectUnusedTargets`, `computeDependencyWeight` |
| 4 — Code Generation | `TargetRendering.swift`, `ProductGeneration.swift`, `CodeGeneration.swift` | pure `renderSingleTarget`, `generateTargetsSection`, `generateProductsSection`, `renderPackageContent`; `writeOutput` writes the file |
| 5 — Advanced Features | `AdvancedFeatures.swift`, `DependencyGraph.swift` | `generateExportedFiles`, `detectUnusedTargets`; pure `computeDependencyWeight`, `analyzeDependencyGraph` |

Files with no `PackagePlugin` import are symlinked into `Tests/PackageGeneratorTests/Shared` (and `Benchmarks/Benchmarks/GeneratorBenchmarks/Shared`) so the tests and benchmarks compile them; they report warnings through a closure instead of `Diagnostics`.

Entry point: `Plugin.swift` → `PackageGeneratorV2.generate(config:context:)`

Expand Down Expand Up @@ -91,7 +93,7 @@ additionalDependencies:
- '.product(name: "PreviewSnapshots", package: "swiftui-preview-snapshots")'
```

### Dependency Resolution Priority (in `renderSingleTarget`)
### Dependency Resolution Priority (in `renderSingleTarget`, `TargetRendering.swift`)
1. `externalDeps` map → `.product(name:package:)` reference
2. `allLocalTargetNames` set → `"TargetName"` string literal
3. Apple SDK built-in list (`AppleSDKs.swift`) → silently skipped
Expand Down
6 changes: 6 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,9 @@ jobs:
run: swift test
- name: Architecture rules
run: swift test --package-path Architecture
- name: Build benchmarks
# Built, not run: shared runners are too noisy to compare timings. jemalloc is off so the runner needs no
# Homebrew package; run them locally as docs/performance.md describes.
env:
BENCHMARK_DISABLE_JEMALLOC: "true"
run: swift build --package-path Benchmarks
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ struct ArchitectureRules {

@Test func testSourcesLinkThePluginFiles() throws {
let sources = try SharedSource.all(in: repository())
#expect(sources.count >= 3)
#expect(sources.count >= 10)
expectNone(Detect.unlinkedTestSources(sources), rule: .testSourcesLinkThePluginFiles)
}

Expand Down
4 changes: 2 additions & 2 deletions Architecture/Tests/ArchitectureTests/Detect.swift
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,9 @@ enum Detect {
return directories + toolPaths
}

/// `appleDefaultSDKs` referenced inside a function named `filterImports`.
/// `appleDefaultSDKs` or `appleDefaultSDKSet` referenced inside a function named `filterImports`.
static func earlySDKFiltering(in scope: Scope) -> [Match<Syntax>] {
scope.references(to: "appleDefaultSDKs").filter { match in
scope.references(to: "appleDefaultSDKs", "appleDefaultSDKSet").filter { match in
sequence(first: match.node, next: \.parent).contains {
$0.as(FunctionDeclSyntax.self)?.name.text == "filterImports"
}
Expand Down
6 changes: 3 additions & 3 deletions Architecture/Tests/ArchitectureTests/DetectorTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -72,13 +72,13 @@ import Testing
in: scope(
"""
func filterImports(rawImports: [String]) -> [String] {
rawImports.filter { !appleDefaultSDKs.contains($0) }
rawImports.filter { !appleDefaultSDKs.contains($0) && !appleDefaultSDKSet.contains($0) }
}
func renderSingleTarget() {
let appleExclusions = Set(appleDefaultSDKs)
let skipped = appleDefaultSDKSet.contains(dep)
}
"""))
#expect(found.map(\.location.line) == [2])
#expect(found.map(\.location.line) == [2, 2])
}

@Test func xcTestImportsAreFound() {
Expand Down
17 changes: 9 additions & 8 deletions Architecture/Tests/ArchitectureTests/Rules.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@ import LLMCheck
extension Rule {
static let testSourcesLinkThePluginFiles = Rule(
id: "test-sources-link-the-plugin-files",
title: "Every Swift file in `Tests/PackageGeneratorTests/Shared` is a symbolic link into `Plugins/PackageGenerator`.",
title: "Every Swift file in the tests' and benchmarks' `Shared` folders is a symbolic link into `Plugins/PackageGenerator`.",
category: .structure,
rationale: """
A `.plugin` target cannot be imported, so the test target compiles the plugin's own files through \
symbolic links (CODING_STANDARDS.md, "The tests compile the real files"). A copy, or a link to anywhere \
else, would let the tests pass against code the plugin no longer runs.
A `.plugin` target cannot be imported, so the test target and the benchmarks compile the plugin's own \
files through symbolic links in `Tests/PackageGeneratorTests/Shared` and \
`Benchmarks/Benchmarks/GeneratorBenchmarks/Shared` (CODING_STANDARDS.md, "The tests compile the real \
files"). A copy, or a link to anywhere else, would test and measure code the plugin no longer runs.
""",
howToFix: """
Replace the file with a relative link: \
Expand All @@ -23,8 +24,8 @@ extension Rule {
title: "A plugin file the tests link imports only Foundation.",
category: .structure,
rationale: """
The generator's pure core (CODING_STANDARDS.md, "Pure core, thin shell") is compiled by the plugin and by \
the test target, which cannot import `PackagePlugin`. Yams, the package's only dependency, belongs to \
The generator's pure core (CODING_STANDARDS.md, "Pure core, thin shell") is compiled by the plugin, the \
test target and the benchmarks; the last two cannot import `PackagePlugin`. Yams, the package's only dependency, belongs to \
`yaml-converter`, not the plugin.
""",
howToFix: """
Expand Down Expand Up @@ -76,7 +77,7 @@ extension Rule {

static let appleSDKFilteringIsDeferred = Rule(
id: "apple-sdk-filtering-is-deferred",
title: "`filterImports` does not consult `appleDefaultSDKs`.",
title: "`filterImports` does not consult `appleDefaultSDKs` or `appleDefaultSDKSet`.",
category: .output,
rationale: """
Imports are matched to external products and local targets before Apple SDKs are skipped. Filtering SDK \
Expand All @@ -92,7 +93,7 @@ extension Rule {
rawImports.filter { !appleDefaultSDKs.contains($0) }
""",
goodExample: """
} else if appleSDKs.contains(dep) {
} else if appleDefaultSDKSet.contains(dep) {
// Known Apple SDK: skip silently, after externalDeps and local targets were checked.
"""
)
Expand Down
36 changes: 20 additions & 16 deletions Architecture/Tests/ArchitectureTests/Support.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,33 +5,37 @@ import LLMCheck
/// shared by all suites, which Swift Testing runs in parallel.
func repository() throws -> Codebase { try Codebase() }

/// Where the test target compiles the plugin's pure files from. A `.plugin` target cannot be imported.
let sharedTestSourcesFolder = "Tests/PackageGeneratorTests/Shared"
/// Where the test target and the benchmarks compile the plugin's pure files from. A `.plugin` target cannot be
/// imported.
let sharedSourceFolders = ["Tests/PackageGeneratorTests/Shared", "Benchmarks/Benchmarks/GeneratorBenchmarks/Shared"]

/// A Swift file in `sharedTestSourcesFolder`, and where it points when it is a symbolic link.
/// A Swift file in one of `sharedSourceFolders`, and where it points when it is a symbolic link.
struct SharedSource: Sendable {
/// From the repository root, like `Tests/PackageGeneratorTests/Shared/ParsedPackage.swift`.
let relativePath: String
/// The link's destination from the repository root, like `Plugins/PackageGenerator/ParsedPackage.swift`, or `nil`
/// when the file is a regular file.
let destination: String?

/// The Swift files in `sharedTestSourcesFolder` of `codebase`, read from the file system: `Codebase` excludes the
/// folder so that the rules read each file once, under its real path.
/// The Swift files in `sharedSourceFolders` of `codebase`, read from the file system: `Codebase` excludes the
/// folders so that the rules read each file once, under its real path.
static func all(in codebase: Codebase) throws -> [SharedSource] {
let fileManager = FileManager.default
let folder = codebase.root.appendingPathComponent(sharedTestSourcesFolder)
return try fileManager.contentsOfDirectory(atPath: folder.path).sorted()
.filter { $0.hasSuffix(".swift") }
.map { name in
let link = folder.appendingPathComponent(name)
let target = try? fileManager.destinationOfSymbolicLink(atPath: link.path)
let destination = target.map {
URL(fileURLWithPath: $0, relativeTo: folder).standardizedFileURL.path
.replacingOccurrences(of: codebase.root.standardizedFileURL.path + "/", with: "")
let root = codebase.root.standardizedFileURL.path + "/"
return try sharedSourceFolders.flatMap { relativeFolder in
let folder = codebase.root.appendingPathComponent(relativeFolder)
return try fileManager.contentsOfDirectory(atPath: folder.path).sorted()
.filter { $0.hasSuffix(".swift") }
.map { name in
let link = folder.appendingPathComponent(name)
let target = try? fileManager.destinationOfSymbolicLink(atPath: link.path)
let destination = target.map {
URL(fileURLWithPath: $0, relativeTo: folder).standardizedFileURL.path
.replacingOccurrences(of: root, with: "")
}
return SharedSource(relativePath: "\(relativeFolder)/\(name)", destination: destination)
}
return SharedSource(relativePath: "\(sharedTestSourcesFolder)/\(name)", destination: destination)
}
}
}
}

Expand Down
161 changes: 161 additions & 0 deletions Benchmarks/Benchmarks/GeneratorBenchmarks/GeneratorBenchmarks.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
import Benchmark
import Foundation

// The plugin's PackagePlugin-free files are compiled into this target through the links in `Shared/`. What they
// measure is the part of a run the plugin does itself; scanning sources for imports is package-generator-cli's work.

/// A synthetic modular app: `groups` folders of `perGroup` library targets, each with a test target, so
/// `2 × groups × perGroup` targets. Imports mix local targets, external products, Apple SDKs and an unknown module,
/// like a real heavily modularized app.
struct SyntheticProject {
let config: ConfigurationV2
/// The configuration as the plugin reads it from disk, with some parameters in the legacy `targetsParameters`.
let configJSON: Data
/// What package-generator-cli reports for each target: unsorted, with self-imports and an excluded import.
let rawImports: [(name: String, isTest: Bool, imports: [String])]
/// `ParsedPackage`s after `filterImports`, as `PackageGeneratorV2` builds them.
let packages: [ParsedPackage]
let externalDeps: [String: String]

init(groups: Int = 25, perGroup: Int = 20) {
var random = SplitMix64(seed: 42)
let externalProducts = (0..<40).map { "Vendor\($0)" }
externalDeps = Dictionary(
uniqueKeysWithValues: externalProducts.enumerated().map { index, product in
(product, ".product(name: \"\(product)\", package: \"vendor-package-\(index % 12)\")")
})
let sdks = ["Foundation", "SwiftUI", "UIKit", "Combine", "CoreData", "MapKit", "Charts", "OSLog", "os"]
let exclusions = ConfigurationV2.Exclusions(imports: ["LegacyAnalytics"], targets: [])

var directoryGroups: [ConfigurationV2.DirectoryGroup] = []
var rawImports: [(name: String, isTest: Bool, imports: [String])] = []
var legacyParameters: [String: [String]] = [:]
var localNames: [String] = []

for group in 0..<groups {
var specs: [ConfigurationV2.TargetSpec] = []
for index in 0..<perGroup {
let name = "Feature\(group)Module\(index)"
let testName = name + "Tests"

var imports = [name, "LegacyAnalytics", "Module\(group)Unknown"]
imports += (0..<min(8, localNames.count)).map { _ in localNames[random.next(below: localNames.count)] }
imports += (0..<3).map { _ in externalProducts[random.next(below: externalProducts.count)] }
imports += (0..<3).map { _ in sdks[random.next(below: sdks.count)] }
imports.shuffle(using: &random)
var seen = Set<String>()
rawImports.append((name, false, imports.filter { seen.insert($0).inserted }))
rawImports.append((testName, true, [name, "XCTest", "Foundation", externalProducts[index % 40]]))

specs.append(
.init(
name: name,
path: "Sources/Feature\(group)/\(name)",
exclude: index % 4 == 0 ? ["README.md", "__Snapshots__"] : nil,
parameters: index % 3 == 0 ? ["resources: [.process(\"Resources\")]"] : nil,
additionalDependencies: index % 5 == 0
? [".product(name: \"Dependencies\", package: \"swift-dependencies\")"] : nil))
specs.append(.init(name: testName, type: .test, path: "Tests/Feature\(group)/\(testName)"))
if index % 2 == 0 {
legacyParameters[name] = ["swiftSettings: [.enableUpcomingFeature(\"ExistentialAny\")]"]
}
localNames.append(name)
}
directoryGroups.append(.init(path: "Sources/Feature\(group)", targets: specs))
}

config = ConfigurationV2(
pragmaMark: true, spaces: 2, leafInfo: true, unusedThreshold: 0,
packageDirectoryTargets: directoryGroups,
mappers: .init(imports: ["Vendor0": ".product(name: \"Vendor0\", package: \"vendor-zero\")"]),
exclusions: exclusions)

var object = try! JSONSerialization.jsonObject(with: JSONEncoder().encode(config)) as! [String: Any]
object["targetsParameters"] = legacyParameters
configJSON = try! JSONSerialization.data(withJSONObject: object)

self.rawImports = rawImports
let specs = Dictionary(
uniqueKeysWithValues: directoryGroups.flatMap(\.targets).map { ($0.name, $0) })
packages = rawImports.map { entry in
let spec = specs[entry.name]!
return ParsedPackage(
name: entry.name,
isTest: entry.isTest,
dependencies: filterImports(rawImports: entry.imports, targetName: entry.name, exclusions: exclusions),
path: spec.path!,
fullPath: "/project/" + spec.path!,
exclude: spec.exclude ?? [],
parameters: spec.parameters,
additionalDependencies: spec.additionalDependencies)
}
}
}

/// A seeded generator, so every run measures the same project.
struct SplitMix64: RandomNumberGenerator {
var state: UInt64
init(seed: UInt64) { state = seed }
mutating func next() -> UInt64 {
state &+= 0x9E37_79B9_7F4A_7C15
var z = state
z = (z ^ (z >> 30)) &* 0xBF58_476D_1CE4_E5B9
z = (z ^ (z >> 27)) &* 0x94D0_49BB_1331_11EB
return z ^ (z >> 31)
}
mutating func next(below upperBound: Int) -> Int { Int(next() % UInt64(upperBound)) }
}

let benchmarks: @Sendable () -> Void = {
Benchmark.defaultConfiguration = .init(
metrics: [.wallClock, .cpuTotal, .mallocCountTotal, .peakMemoryResident, .retainCount],
// Exact counts and microseconds, so a change of a few percent shows up in a comparison.
timeUnits: .microseconds,
units: [.mallocCountTotal: .count, .retainCount: .count],
maxDuration: .seconds(2),
maxIterations: 1_000
)

let project = SyntheticProject()
let plain = ConfigurationV2(packageDirectoryTargets: project.config.packageDirectoryTargets)

Benchmark("Decode config, 1,000 targets") { _ in
blackHole(try JSONDecoder().decode(ConfigurationV2.self, from: project.configJSON))
}

Benchmark("Filter imports, 1,000 targets") { _ in
for entry in project.rawImports {
blackHole(
filterImports(
rawImports: entry.imports, targetName: entry.name, exclusions: project.config.exclusions))
}
}

Benchmark("Dependency graph, 1,000 targets") { _ in
blackHole(computeDependencyWeight(project.packages))
blackHole(analyzeDependencyGraph(project.packages))
}

Benchmark("Render products, 1,000 targets") { _ in
blackHole(generateProductsSection(parsedPackages: project.packages, config: project.config))
}

Benchmark("Render Package.swift, 1,000 targets") { _ in
let weights = computeDependencyWeight(project.packages)
var warnings = 0
blackHole(
renderPackageContent(
project.packages, config: project.config, externalDeps: project.externalDeps, leafWeights: weights,
warn: { _ in warnings += 1 }))
blackHole(warnings)
}

Benchmark("Render Package.swift, 1,000 targets, default settings") { _ in
var warnings = 0
blackHole(
renderPackageContent(
project.packages, config: plain, externalDeps: project.externalDeps, leafWeights: [:],
warn: { _ in warnings += 1 }))
blackHole(warnings)
}
}
Loading
Loading