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
41 changes: 41 additions & 0 deletions .github/workflows/pages.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
name: Pages

# Publishes site/, the project's landing page, to GitHub Pages when it changes on main.
on:
push:
branches: [main]
paths: [site/**, .github/workflows/pages.yml]
workflow_dispatch:

permissions:
contents: read

concurrency:
group: pages
cancel-in-progress: false

jobs:
deploy:
name: Deploy
runs-on: ubuntu-latest
timeout-minutes: 10
permissions:
pages: write
id-token: write
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
persist-credentials: false
- name: Configure Pages
uses: actions/configure-pages@v5
- name: Upload site
uses: actions/upload-pages-artifact@v3
with:
path: site
- name: Deploy
id: deployment
uses: actions/deploy-pages@v4
10 changes: 7 additions & 3 deletions .llm-check.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,15 @@
# A name matches any folder or file; a path with a slash matches from the root.
excludes:
- Architecture
- Benchmarks
# The benchmarks' own code; their `Shared` folder stays, for `test-sources-link-the-plugin-files`.
- Benchmarks/Package.swift
- Benchmarks/Tools
- Benchmarks/Benchmarks/GeneratorBenchmarks/GeneratorBenchmarks.swift
- docs
- Examples
- site
# Symbolic links to files in Plugins/PackageGenerator; the rules read the originals.
- Tests/PackageGeneratorTests/Shared
# Folders ending in Tests hold test code.
testSuffixes: [Tests]
# Read the `Shared` links into Plugins/PackageGenerator, so a rule can require links and not copies. The plugin files
# are then also read under the link paths, which only the test rules see; neither finds anything in plugin code.
symbolicLinks: follow
2 changes: 1 addition & 1 deletion Architecture/Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ let package = Package(
name: "Architecture",
platforms: [.macOS(.v14)],
dependencies: [
.package(url: "https://github.com/mackoj/swift-llm-check.git", from: "0.4.1"),
.package(url: "https://github.com/mackoj/swift-llm-check.git", from: "0.5.0"),
.package(url: "https://github.com/swiftlang/swift-syntax.git", "601.0.0"..<"700.0.0"),
],
targets: [
Expand Down
24 changes: 18 additions & 6 deletions Architecture/Tests/ArchitectureTests/ArchitectureRules.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,26 @@ struct ArchitectureRules {
static func plugin() throws -> Scope { try repository().productionCode.in("Plugins/PackageGenerator") }
static func tests() throws -> Scope { try repository().testCode.in("Tests") }

/// The Swift files in `sharedSourceFolders`, links included (`symbolicLinks: follow`).
static func shared() throws -> [SourceFile] { try repository().allCode.in(sharedSourceFolders).files }

@Test func testSourcesLinkThePluginFiles() throws {
let sources = try SharedSource.all(in: repository())
#expect(sources.count >= 3)
expectNone(Detect.unlinkedTestSources(sources), rule: .testSourcesLinkThePluginFiles)
let sources = try Self.shared()
#expect(sources.count >= 10)
// `SourceFile` is not a `Finding` in swift-llm-check 0.5.0, so each offending file becomes a `Violation`.
let unlinked = sources.filter { $0.symbolicLinkDestination?.hasPrefix("Plugins/PackageGenerator/") != true }
expectNone(
unlinked.map { file in
Violation(
location: Location(filePath: file.path, relativePath: file.relativePath, line: 1, column: 1),
snippet: file.symbolicLinkDestination.map { "\(file.relativePath) -> \($0)" }
?? "\(file.relativePath) is a regular file")
},
rule: .testSourcesLinkThePluginFiles)
}

@Test func coreFilesImportOnlyFoundation() throws {
let linked = try SharedSource.all(in: repository()).compactMap(\.destination)
let linked = Array(Set(try Self.shared().compactMap(\.symbolicLinkDestination))).sorted()
#expect(linked.count >= 3)
expectNone(Detect.coreImports(in: try Self.plugin(), files: linked), rule: .coreFilesImportOnlyFoundation)
}
Expand Down Expand Up @@ -44,11 +56,11 @@ struct ArchitectureRules {
@Test func testsUseSwiftTesting() throws {
let tests = try Self.tests()
#expect(tests.containing("import Testing").relativePaths.count >= 1)
expectNone(Detect.xcTestImports(in: tests), rule: .testsUseSwiftTesting)
expectNone(tests.xcTestImports, rule: .testsUseSwiftTesting)
}

@Test func testsAreNotDisabled() throws {
expectNone(Detect.disabledTests(in: try Self.tests()), rule: .testsAreNotDisabled)
expectNone(try Self.tests().disabledTests, rule: .testsAreNotDisabled)
}
}

Expand Down
31 changes: 2 additions & 29 deletions Architecture/Tests/ArchitectureTests/Detect.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,6 @@ import SwiftSyntax

/// The detectors, separate from the codebase so `DetectorTests` can run them on snippets.
enum Detect {
/// Shared test sources that are regular files, or links that do not point into `Plugins/PackageGenerator`.
static func unlinkedTestSources(_ sources: [SharedSource]) -> [Violation] {
sources.filter { source in
guard let destination = source.destination else { return true }
return !destination.hasPrefix("Plugins/PackageGenerator/")
}
.map { source in
Violation(
location: Location(
filePath: source.relativePath, relativePath: source.relativePath, line: 1, column: 1),
snippet: source.destination.map { "\(source.relativePath) -> \($0)" }
?? "\(source.relativePath) is a regular file")
}
}

/// Imports other than Foundation in `files`, the plugin files that the tests link.
static func coreImports(in plugin: Scope, files: [String]) -> [Match<ImportDeclSyntax>] {
guard !files.isEmpty else { return [] }
Expand All @@ -44,27 +29,15 @@ 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"
}
}
}

/// `import XCTest`.
static func xcTestImports(in scope: Scope) -> [Match<ImportDeclSyntax>] {
scope.imports(of: "XCTest")
}

/// The `.disabled(…)` trait, wherever a test or suite takes it.
static func disabledTests(in scope: Scope) -> [Match<FunctionCallExprSyntax>] {
scope.calls(named: "disabled").filter { call in
call.node.receiver == nil && call.node.calledExpression.is(MemberAccessExprSyntax.self)
}
}

private static func memberAccesses(named names: Set<String>, in scope: Scope) -> [Match<MemberAccessExprSyntax>] {
scope.containing(Array(names)).nodes(of: MemberAccessExprSyntax.self) {
$0.node.base != nil && names.contains($0.node.declName.baseName.text)
Expand Down
31 changes: 3 additions & 28 deletions Architecture/Tests/ArchitectureTests/DetectorTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,6 @@ import Testing
Scope(files: [SourceFile(path: path, source: source)])
}

@Test func unlinkedTestSourcesAreFound() {
let found = Detect.unlinkedTestSources([
SharedSource(relativePath: "Tests/T/Shared/A.swift", destination: "Plugins/PackageGenerator/A.swift"),
SharedSource(relativePath: "Tests/T/Shared/B.swift", destination: nil),
SharedSource(relativePath: "Tests/T/Shared/C.swift", destination: "Sources/Other/C.swift"),
])
#expect(found.map(\.location.relativePath) == ["Tests/T/Shared/B.swift", "Tests/T/Shared/C.swift"])
}

@Test func coreImportsAreFound() {
let plugin = Scope(files: [
SourceFile(path: "Plugins/PackageGenerator/Core.swift", source: "import Foundation\nimport PackagePlugin"),
Expand Down Expand Up @@ -72,28 +63,12 @@ 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])
}

@Test func xcTestImportsAreFound() {
let found = Detect.xcTestImports(in: scope("import XCTest\nimport Testing", at: "Tests/T/A.swift"))
#expect(found.map(\.location.line) == [1])
}

@Test func disabledTestsAreFound() {
let found = Detect.disabledTests(
in: scope(
"""
@Test(.disabled("flaky")) func a() {}
@Suite(.disabled()) struct B {}
@Test func c() { rule.disabled() }
""", at: "Tests/T/A.swift"))
#expect(found.map(\.location.line) == [1, 2])
#expect(found.map(\.location.line) == [2, 2])
}
}
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
33 changes: 3 additions & 30 deletions Architecture/Tests/ArchitectureTests/Support.swift
Original file line number Diff line number Diff line change
@@ -1,39 +1,12 @@
import Foundation
import LLMCheck

/// The PackageGeneratorPlugin repository, rooted where `.llm-check.yaml` is. Its file list and every parsed file are
/// 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"

/// A Swift file in `sharedTestSourcesFolder`, 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.
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: "")
}
return SharedSource(relativePath: "\(sharedTestSourcesFolder)/\(name)", destination: destination)
}
}
}
/// 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"]

extension RuleCategory {
static let structure = RuleCategory(
Expand Down
Loading
Loading