Skip to content
Closed
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
5 changes: 5 additions & 0 deletions .github/actionlint.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Every job runs on GitHub-hosted runners.
self-hosted-runner:
labels: []
# The repository defines no configuration variables, so any `vars.*` reference is a typo.
config-variables: []
52 changes: 52 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
name: CI

on:
push:
branches: [main]
pull_request:

permissions:
contents: read

concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true

jobs:
host:
name: macOS host
runs-on: macos-15
timeout-minutes: 30
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
# Everything is simulator-only, so this builds an empty module: it checks the package and its guards.
- name: Build
run: swift build --build-tests
- name: Test
run: swift test
- name: Architecture rules
run: swift test --package-path Architecture

simulators:
name: Simulators
runs-on: macos-15
timeout-minutes: 45
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- name: Test on an iOS simulator
run: |
udid=$(xcrun simctl list devices available --json \
| jq -r '[.devices | to_entries[] | select(.key | contains("iOS")) | .value[] | select(.name | startswith("iPhone"))][0].udid')
echo "Testing on $udid"
xcodebuild test -scheme EnvironmentVariationPreview -destination "id=$udid" -quiet
- name: Build for tvOS, watchOS and visionOS simulators
run: |
for platform in "tvOS Simulator" "watchOS Simulator" "visionOS Simulator"; do
echo "::group::$platform"
xcodebuild build -scheme EnvironmentVariationPreview -destination "generic/platform=$platform" -quiet
echo "::endgroup::"
done
43 changes: 43 additions & 0 deletions .github/workflows/soundness.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
name: Soundness

on:
pull_request:
push:
branches: [main]

permissions:
contents: read

concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true

jobs:
actionlint:
name: Workflow lint
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
persist-credentials: false

- name: Run actionlint
run: pipx run --spec actionlint-py==1.7.12.25 actionlint

zizmor:
name: Workflow security audit
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
persist-credentials: false

- name: Run zizmor
env:
# Online audits (impostor commits, known-vulnerable actions) read public repositories.
GH_TOKEN: ${{ github.token }}
run: pipx run --spec zizmor==1.30.1 zizmor --format github .github/workflows
6 changes: 6 additions & 0 deletions .github/zizmor.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
rules:
unpinned-uses:
config:
policies:
# Setting policies replaces zizmor's defaults, so keep the default for GitHub's own actions.
"actions/*": ref-pin
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
.DS_Store
/.build
.build/
/Packages
/*.xcodeproj
xcuserdata/
DerivedData/
.swiftpm/config/registries.json
.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata
.netrc
/Architecture/Package.resolved
/Benchmarks/Package.resolved
9 changes: 9 additions & 0 deletions .llm-check.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# swift-llm-check: what the rules in Architecture/ read. `Codebase()` finds the repository root here.
# A name matches any folder or file; a path with a slash matches from the root.
excludes:
- Architecture
- Benchmarks
- docs
- site
# Folders ending in Tests hold test code.
testSuffixes: [Tests]
30 changes: 30 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Agent notes

`EnvironmentVariationPreview` is a SwiftUI library, not an app: one view modifier, `.environmentVariations([...])`,
that renders a view once per environment value (color scheme, dynamic type, layout direction, locale…) with a caption.
It compiles only for the simulator. Usage is in `README.md`.

Read `CODING_STANDARDS.md` before writing code.

## How to work
- **Smallest diff.** Every changed line traces to the request. Match the surrounding file's idioms (two-space indent,
DocC comments on public API).
- **Test first.** A bug gets a failing test; a new environment value gets a description test.
- A new environment value is a new `EnvironmentValueItem` case plus its branch in `apply(to:)` and in `description`.

## Docs travel with code
- `README.md` is the user documentation; DocC comments are the API reference (Swift Package Index, see `.spi.yml`).
- `site/index.html` is the landing page (GitHub Pages, `.github/workflows/pages.yml`). Its code samples and install
snippet repeat the README: update them in the same change.

## Build and test
- Host: `swift build --build-tests && swift test` builds an empty module (everything is simulator-only), which checks
the package resolves and the guards are intact.
- Simulator: `xcodebuild test -scheme EnvironmentVariationPreview -destination 'platform=iOS Simulator,name=<iPhone>'`
runs the real tests. CI also builds for tvOS, watchOS and visionOS simulators.
- Architecture rules: `swift test --package-path Architecture` (macOS only) runs the mechanical part of
`CODING_STANDARDS.md` as [swift-llm-check](https://github.com/mackoj/swift-llm-check) rules, listed in
`docs/architecture-rules.md`. A failure prints the rule, why it exists and how to fix it: fix the code, never add a
baseline. A new or changed rule needs a `DetectorTests` case and
`LLM_CHECK_RECORD=1 swift test --package-path Architecture` to regenerate the document.
- Releases: tags are bare semver (`1.1.4`, no `v`), created with `gh release create`.
23 changes: 23 additions & 0 deletions Architecture/Package.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// swift-tools-version: 6.0
import PackageDescription

// EnvironmentVariationPreview's mechanical rules (CODING_STANDARDS.md) as tests, written with swift-llm-check.
// Test-only and macOS-only, so the library never builds it and its swift-tools-version 5.7.1 floor is unaffected.
// Run from the repository root: `swift test --package-path Architecture`.
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/swiftlang/swift-syntax.git", "601.0.0"..<"700.0.0"),
],
targets: [
.testTarget(
name: "ArchitectureTests",
dependencies: [
.product(name: "LLMCheck", package: "swift-llm-check"),
.product(name: "SwiftSyntax", package: "swift-syntax"),
]
)
]
)
61 changes: 61 additions & 0 deletions Architecture/Tests/ArchitectureTests/ArchitectureRules.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import LLMCheck
import Testing

/// The rules, run on the repository. A failure prints the rule, why it exists and how to fix it.
@Suite("Architecture rules")
struct ArchitectureRules {
static func sources() throws -> Scope { try repository().productionCode.in("/Sources") }

@Test func sourcesAreSimulatorOnly() throws {
let sources = try Self.sources()
#expect(sources.relativePaths.count > 5)
expectNone(Detect.codeOutsideSimulatorGuard(in: sources), rule: .sourcesAreSimulatorOnly)
}

@Test func importsStayWithinBudget() throws {
expectNone(Detect.importsOverBudget(in: try Self.sources()), rule: .importsStayWithinBudget)
}

@Test func availabilityNamesThePackageFloor() throws {
let found = Detect.availabilityOffTheFloor(in: try Self.sources(), floor: packageFloor)
expectNone(found, rule: .availabilityNamesThePackageFloor)
}

@Test func publicTypesDeclareAvailability() throws {
let sources = try Self.sources()
#expect(sources.declarations.withModifier("public").count > 10)
expectNone(Detect.publicDeclarationsWithoutAvailability(in: sources), rule: .publicTypesDeclareAvailability)
}

@Test func anyViewStaysInApply() throws {
let sources = try Self.sources()
#expect(sources.references(to: "AnyView").count > 40)
expectNone(Detect.anyViewOutsideApply(in: sources), rule: .anyViewStaysInApply)
}

@Test func erasedPayloadsNameTheirType() throws {
expectNone(Detect.erasedPayloadsWithoutTypeComment(in: try Self.sources()), rule: .erasedPayloadsNameTheirType)
}

@Test func descriptionsNameTheirCase() throws {
let sources = try Self.sources()
#expect(sources.containing("var description").relativePaths.count >= 2)
expectNone(Detect.descriptionsNamingAnotherCase(in: sources), rule: .descriptionsNameTheirCase)
}
}

/// Keeps `docs/architecture-rules.md` in step with the rules. Regenerate with
/// `LLM_CHECK_RECORD=1 swift test --package-path Architecture`.
@Test func rulesDocumentIsUpToDate() throws {
let catalog = RuleCatalog(allRules)
#expect(catalog.duplicateIDs.isEmpty)
try expectFile(
"docs/architecture-rules.md", in: repository(),
matches: catalog.markdown(
title: "Architecture rules",
introduction: """
The mechanical part of `CODING_STANDARDS.md`, enforced by the `Architecture/` package with \
[swift-llm-check](https://github.com/mackoj/swift-llm-check): \
`swift test --package-path Architecture` (macOS). Generated from its rules; do not edit by hand.
"""))
}
125 changes: 125 additions & 0 deletions Architecture/Tests/ArchitectureTests/Detect.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
import Foundation
import LLMCheck
import SwiftSyntax

/// The detectors, separate from the codebase so `DetectorTests` can run them on snippets.
enum Detect {
/// Top-level code outside one whole-file `#if targetEnvironment(simulator)` with no `#else`. A file that is not
/// guarded at all is reported at its first statement; a guarded file at whatever sits beside the guard.
static func codeOutsideSimulatorGuard(in scope: Scope) -> [Match<Syntax>] {
scope.files.flatMap { file -> [Match<Syntax>] in
file.syntax.statements.compactMap { statement in
if let guarded = statement.item.as(IfConfigDeclSyntax.self), isSimulatorGuard(guarded) { return nil }
return Match(node: Syntax(statement), file: file)
}
}
}

private static func isSimulatorGuard(_ node: IfConfigDeclSyntax) -> Bool {
node.clauses.count == 1 && node.clauses.first?.condition?.trimmedDescription == "targetEnvironment(simulator)"
}

/// What the library may import.
static let allowedModules: Set<String> = ["Foundation", "SwiftUI", "CoreData"]

/// Imports of any other module.
static func importsOverBudget(in scope: Scope) -> [Match<ImportDeclSyntax>] {
scope.imports.filter { !allowedModules.contains($0.node.moduleName) }
}

/// Platform names that make an `@available` a statement about the floor.
static let platformNames = ["iOS", "macOS", "tvOS", "watchOS", "visionOS", "macCatalyst"]

/// `@available(…)` attributes that name a platform but not exactly the package floor.
static func availabilityOffTheFloor(in scope: Scope, floor: String) -> [Match<AttributeSyntax>] {
scope.containing("@available").nodes(of: AttributeSyntax.self) { match in
guard match.node.attributeName.trimmedDescription == "available",
let arguments = match.node.arguments?.trimmedDescription
else { return false }
let namesPlatform = arguments.split(whereSeparator: { !$0.isLetter }).contains {
platformNames.contains(String($0))
}
return namesPlatform && arguments != floor
}
}

/// Public types without `@available`, and public members of extensions when neither has it.
static func publicDeclarationsWithoutAvailability(in scope: Scope) -> [Declaration] {
scope.declarations.filter { declaration in
guard declaration.hasModifier("public"), !declaration.hasAttribute("available") else { return false }
switch declaration.kind {
case .struct, .class, .enum, .actor, .protocol:
return true
case .function, .initializer, .variable:
guard let parent = declaration.parent, parent.kind == .extension else { return false }
return !parent.hasAttribute("available")
default:
return false
}
}
}

/// `AnyView` anywhere but inside `EnvironmentValueItem.apply`.
static func anyViewOutsideApply(in scope: Scope) -> [Match<Syntax>] {
scope.references(to: "AnyView").filter { !$0.declarationNames.contains("EnvironmentValueItem.apply") }
}

/// Enum cases with an `Any` or `Any?` parameter and no `// TypeName` comment after them on the same line. A type
/// name is UpperCamelCase, so `// TODO` is not one.
static func erasedPayloadsWithoutTypeComment(in scope: Scope) -> [Match<EnumCaseDeclSyntax>] {
scope.containing("case").nodes(of: EnumCaseDeclSyntax.self) { match in
let erased = match.node.elements.contains { element in
element.parameterClause?.parameters.contains {
["Any", "Any?"].contains($0.type.trimmedDescription)
} ?? false
}
guard erased else { return false }
let trailing = match.node.lastToken(viewMode: .sourceAccurate)?.trailingTrivia ?? []
return !trailing.contains { piece in
guard case .lineComment(let text) = piece else { return false }
let name = text.dropFirst(2).trimmingCharacters(in: .whitespaces)
return name.first?.isUppercase == true && name.contains(where: \.isLowercase)
&& name.allSatisfy { $0.isLetter || $0.isNumber || $0 == "." }
}
}
}

/// In the `switch` of a `description` property, `case .name(…)` whose first string literal does not start with
/// `"name: "`. Cases without a payload (`case .regular:`) are not checked.
static func descriptionsNamingAnotherCase(in scope: Scope) -> [Match<SwitchCaseSyntax>] {
scope.containing("description").nodes(of: SwitchCaseSyntax.self) { match in
guard isInDescription(match.node), let name = payloadCaseName(match.node) else { return false }
guard let literal = match.node.statements.firstDescendant(of: StringLiteralExprSyntax.self),
let first = literal.segments.first?.as(StringSegmentSyntax.self)
else { return true }
return !first.content.text.hasPrefix("\(name): ")
}
}

private static func isInDescription(_ node: some SyntaxProtocol) -> Bool {
sequence(first: Syntax(node), next: \.parent).contains {
$0.as(PatternBindingSyntax.self)?.pattern.trimmedDescription == "description"
}
}

/// `name` for `case .name(let value):`; nil for anything else.
private static func payloadCaseName(_ node: SwitchCaseSyntax) -> String? {
guard let item = node.label.as(SwitchCaseLabelSyntax.self)?.caseItems.first,
let pattern = item.pattern.as(ExpressionPatternSyntax.self),
let call = pattern.expression.as(FunctionCallExprSyntax.self),
let member = call.calledExpression.as(MemberAccessExprSyntax.self), member.base == nil
else { return nil }
return member.declName.baseName.text
}
}

extension SyntaxProtocol {
/// The first node of a type under this one, in source order.
fileprivate func firstDescendant<Node: SyntaxProtocol>(of type: Node.Type) -> Node? {
for child in children(viewMode: .sourceAccurate) {
if let node = child.as(Node.self) { return node }
if let node = child.firstDescendant(of: type) { return node }
}
return nil
}
}
Loading
Loading