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
4 changes: 4 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@ jobs:
run: scripts/smoke-test.sh
- name: Architecture rules
run: swift test --package-path Architecture
- name: Build benchmarks
env:
BENCHMARK_DISABLE_JEMALLOC: "true"
run: swift build --package-path Benchmarks

actionlint:
name: Workflow lint
Expand Down
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 plugin'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
2 changes: 0 additions & 2 deletions .llm-check.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,5 @@ excludes:
- Benchmarks
- docs
- site
# Symlink to Plugins/SchemeGeneratorPlugin/Core, read once at its real path.
- Tests/SchemeGeneratorTests/Core
# Folders ending in Tests hold test code.
testSuffixes: [Tests]
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
4 changes: 2 additions & 2 deletions Architecture/Tests/ArchitectureTests/ArchitectureRules.swift
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,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
14 changes: 1 addition & 13 deletions Architecture/Tests/ArchitectureTests/Detect.swift
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import LLMCheck
import SwiftSyntax

/// The detectors, separate from the codebase so `DetectorTests` can run them on snippets.
/// The repository-specific detectors (the shared ones are swift-llm-check built-ins), separate from the codebase so `DetectorTests` can run them on snippets.
enum Detect {
/// Types whose every use is I/O, process state or plugin output.
static let impureTypes: Set<String> = [
Expand Down Expand Up @@ -41,16 +41,4 @@ enum Detect {
return function?.name.text != "fatalError"
}
}

/// `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)
}
}
}
16 changes: 0 additions & 16 deletions Architecture/Tests/ArchitectureTests/DetectorTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -55,20 +55,4 @@ import Testing
""", at: "Plugins/SchemeGeneratorPlugin/SchemeGenerator.swift"))
#expect(found.map(\.location.line) == [1, 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])
}
}
1 change: 1 addition & 0 deletions Benchmarks/Benchmarks/SchemeGeneratorBenchmarks/Core
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import Benchmark
import Foundation

// The plugin's work per run, minus the disk: hash the product list, plan which schemes to write, render each one.
// A modular app has tens to hundreds of products; 1,000 shows how the cost grows.

func products(_ count: Int) -> [String] { (0..<count).map { "Feature\($0)Module" } }

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 hundred = products(100)
let thousand = products(1_000)

Benchmark("Render scheme, one product", configuration: .init(scalingFactor: .kilo)) { benchmark in
for _ in benchmark.scaledIterations { blackHole(XcschemeTemplate.render(productName: "FeatureModule")) }
}

Benchmark("Render schemes, 1000 products") { benchmark in
for name in thousand { blackHole(XcschemeTemplate.render(productName: name)) }
}

Benchmark("Render and encode schemes, 1000 products") { benchmark in
for name in thousand { blackHole(XcschemeTemplate.renderData(productName: name)) }
}

Benchmark("Hash product names, 100 products", configuration: .init(scalingFactor: .kilo)) { benchmark in
for _ in benchmark.scaledIterations { blackHole(ProductNamesHash.hash(hundred)) }
}

Benchmark("Plan schemes, 1000 products") { benchmark in
// A third exist already, a few are obsolete, overwrite and removal on: every branch of the plan.
let existing = Array(thousand.prefix(333)) + (0..<20).map { "Obsolete\($0)" }
blackHole(
SchemePlan(
productNames: thousand, existingSchemes: existing, excludedSchemes: ["Obsolete0"],
overwriteAlreadyGeneratedSchemes: true, removeNotGeneratedSchemes: true))
}

Benchmark("Read scheme names, 1000 files") { benchmark in
let files = thousand.map { SchemeNaming.fileName(scheme: $0) } + ["README.md", ".DS_Store"]
blackHole(files.compactMap(SchemeNaming.schemeName(fileName:)))
}

Benchmark("Full run without disk, 1000 products") { benchmark in
let existing = Array(thousand.prefix(500))
blackHole(ProductNamesHash.hash(thousand))
let plan = SchemePlan(
productNames: thousand, existingSchemes: existing, excludedSchemes: [],
overwriteAlreadyGeneratedSchemes: true, removeNotGeneratedSchemes: true)
for name in plan.toWrite { blackHole(XcschemeTemplate.renderData(productName: name)) }
}
}
31 changes: 31 additions & 0 deletions Benchmarks/Package.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// swift-tools-version: 6.1
import PackageDescription

// SchemeGeneratorPlugin's benchmarks, on ordo-one/package-benchmark (https://www.swift.org/blog/benchmarks/). A
// separate package so the plugin never depends on it. A plugin target cannot be imported, so the benchmark target
// compiles the plugin's pure core itself: Benchmarks/SchemeGeneratorBenchmarks/Core is a symlink to
// Plugins/SchemeGeneratorPlugin/Core. Run from the repository root: `swift package --package-path Benchmarks benchmark`.
let package = Package(
name: "Benchmarks",
platforms: [.macOS(.v15)],
dependencies: [
.package(url: "https://github.com/ordo-one/package-benchmark.git", from: "1.38.0")
],
targets: [
.executableTarget(
name: "SchemeGeneratorBenchmarks",
dependencies: [
.product(name: "Benchmark", package: "package-benchmark")
],
path: "Benchmarks/SchemeGeneratorBenchmarks",
swiftSettings: [.swiftLanguageMode(.v5)],
plugins: [
.plugin(name: "BenchmarkPlugin", package: "package-benchmark")
]
),
// Reads two `benchmark --format markdown` outputs and prints each benchmark's p50 before and after.
.executableTarget(name: "p50", path: "Tools/P50"),
// Reads an exported Time Profiler table and prints the hottest functions (scripts/profile.sh).
.executableTarget(name: "hotspots", path: "Tools/Hotspots"),
]
)
86 changes: 86 additions & 0 deletions Benchmarks/Tools/Hotspots/main.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import Foundation

// Usage: swift run --package-path Benchmarks hotspots profile.xml [count]
// profile.xml is `xcrun xctrace export --xpath '…/table[@schema="time-profile"]'` (scripts/profile.sh writes it).
// Prints the functions with the most samples of their own (self) and the library functions with the most samples
// under them (inclusive). package-benchmark's ARC counting hooks are left out: they exist only while measuring.

/// Reads the rows of an exported time-profile table. Frames and backtraces are written once and then referenced
/// by id, so both are remembered.
final class ProfileReader: NSObject, XMLParserDelegate {
var frameNames: [String: String] = [:]
var backtraces: [String: [String]] = [:]
var samples: [[String]] = []
private var current: [String]?
private var currentID: String?

func parser(
_ parser: XMLParser, didStartElement element: String, namespaceURI: String?, qualifiedName: String?,
attributes: [String: String] = [:]
) {
switch element {
case "tagged-backtrace", "backtrace":
if let ref = attributes["ref"] {
samples.append(backtraces[ref] ?? [])
} else {
current = []
currentID = attributes["id"]
}
case "frame" where current != nil:
if let ref = attributes["ref"] {
current?.append(frameNames[ref] ?? "?")
} else {
let name = attributes["name"] ?? "?"
if let id = attributes["id"] { frameNames[id] = name }
current?.append(name)
}
default:
break
}
}

func parser(_ parser: XMLParser, didEndElement element: String, namespaceURI: String?, qualifiedName: String?) {
guard element == "tagged-backtrace" || element == "backtrace", let frames = current else { return }
if let currentID { backtraces[currentID] = frames }
samples.append(frames)
current = nil
currentID = nil
}
}

let arguments = CommandLine.arguments
guard arguments.count >= 2, let parser = XMLParser(contentsOf: URL(fileURLWithPath: arguments[1])) else {
print("usage: hotspots <profile.xml> [count]")
exit(2)
}
let count = arguments.count > 2 ? Int(arguments[2]) ?? 20 : 20
let reader = ProfileReader()
parser.delegate = reader
guard parser.parse() else {
print("could not read \(arguments[1]): \(parser.parserError.map { "\($0)" } ?? "unknown error")")
exit(1)
}

let measuring = /ARCStatsProducer|_swift_(retain|release)_(adapter|hook)|MallocInterposer/
func short(_ name: String) -> String { String(name.prefix { $0 != "(" }.suffix(110)) }

var selfSamples: [String: Int] = [:]
var inclusiveSamples: [String: Int] = [:]
var total = 0
for frames in reader.samples where !frames.isEmpty {
guard !frames.contains(where: { $0.contains(measuring) }) else { continue }
total += 1
selfSamples[short(frames[0]), default: 0] += 1
for name in Set(frames.map(short)) where name.contains(/SchemeGenerator|SchemePlan|XcschemeTemplate|ProductNamesHash|SchemeNaming/) {
inclusiveSamples[name, default: 0] += 1
}
}
func report(_ title: String, _ counts: [String: Int], of total: Int) {
print(title)
for (name, samples) in counts.sorted(by: { $0.value > $1.value }).prefix(count) {
print(String(format: "%5.1f%% ", 100 * Double(samples) / Double(max(total, 1))) + name)
}
}
print("\(total) samples")
report("Self", selfSamples, of: total)
report("Inclusive (SchemeGeneratorPlugin core)", inclusiveSamples, of: total)
54 changes: 54 additions & 0 deletions Benchmarks/Tools/P50/main.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import Foundation

// Usage: swift run --package-path Benchmarks p50 before.md after.md
// Each file is the output of `swift package --package-path Benchmarks benchmark --format markdown --no-progress`.

/// A benchmark's p50 wall clock in microseconds and p50 malloc count.
struct Medians {
var wallClock: Double?
var mallocs: Double?
}

func medians(inFile path: String) throws -> [(name: String, medians: Medians)] {
let text = try String(contentsOfFile: path, encoding: .utf8)
// A row: | Time (wall clock) (μs) * | p0 | p25 | p50 | … The unit is absent for plain counts.
let row =
/^\|\s*(Malloc \(total\)|Time \(wall clock\))\s*(?:\(([^)]*)\))?\s*\*?\s*\|\s*[\d,]+\s*\|\s*[\d,]+\s*\|\s*([\d,]+)/
let scale: [String: Double] = ["ns": 1e-3, "μs": 1, "us": 1, "ms": 1e3, "s": 1e6, "K": 1e3, "M": 1e6]
var result: [(name: String, medians: Medians)] = []
for line in text.split(separator: "\n") {
if line.hasPrefix("### ") {
let name = line.dropFirst(4).replacingOccurrences(of: " metrics", with: "")
result.append((name, Medians()))
} else if let match = line.firstMatch(of: row), !result.isEmpty {
let value =
Double(match.3.replacingOccurrences(of: ",", with: ""))! * (match.2.map { scale[String($0)] ?? 1 } ?? 1)
if match.1 == "Malloc (total)" {
result[result.count - 1].medians.mallocs = result[result.count - 1].medians.mallocs ?? value
} else {
result[result.count - 1].medians.wallClock = result[result.count - 1].medians.wallClock ?? value
}
}
}
return result
}

let arguments = CommandLine.arguments
guard arguments.count == 3 else {
print("usage: p50 <before.md> <after.md>")
exit(2)
}
let before = Dictionary(
try medians(inFile: arguments[1]).map { ($0.name, $0.medians) }, uniquingKeysWith: { a, _ in a })
func cell(_ old: Double?, _ new: Double?, _ format: String) -> String {
guard let new else { return "" }
guard let old else { return String(format: format, new) }
return String(format: "\(format) → \(format) (%.2fx)", old, new, new / old)
}
print("| Benchmark | Wall clock p50 (µs) | Mallocs p50 |")
print("|---|---|---|")
for (name, after) in try medians(inFile: arguments[2]) {
let old = before[name]
print(
"| \(name) | \(cell(old?.wallClock, after.wallClock, "%.1f")) | \(cell(old?.mallocs, after.mallocs, "%.0f")) |")
}
23 changes: 23 additions & 0 deletions Benchmarks/scripts/profile.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
#!/bin/sh
# Profiles one benchmark with Instruments' Time Profiler and prints its hottest functions.
# Usage, from the repository root: Benchmarks/scripts/profile.sh 'Render schemes, 1000 products' [count]
# The name is the benchmark's, matched exactly. The trace is kept in Benchmarks/.build/profiles to open in Instruments.
set -eu

name=$1
count=${2:-20}
package=$(cd "$(dirname "$0")/.." && pwd)
swift build --package-path "$package" -c release --product SchemeGeneratorBenchmarks
swift build --package-path "$package" -c release --product hotspots
bin=$(swift build --package-path "$package" -c release --show-bin-path)

out="$package/.build/profiles"
mkdir -p "$out"
trace="$out/$(echo "$name" | tr -c 'A-Za-z0-9' '-').trace"
rm -rf "$trace"
# Instruments symbolicates only a binary launched by its absolute path.
xcrun xctrace record --quiet --template 'Time Profiler' --output "$trace" --launch -- \
"$bin/SchemeGeneratorBenchmarks" --filter "^$name\$"
xcrun xctrace export --input "$trace" \
--xpath '/trace-toc/run[@number="1"]/data/table[@schema="time-profile"]' > "$trace.xml"
"$bin/hotspots" "$trace.xml" "$count"
Loading
Loading