Skip to content
Open
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
2 changes: 1 addition & 1 deletion .claude/rules/generator-design.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ paths:
- **No hand-kept list of system frameworks.** Where logic or wording must tell system modules from the user's, use a signal SafeDI has (the modules it read, or was given module info for), or drop the feature. A curated list is always incomplete and goes stale with every SDK.
- **Runtime speed of generated code over compile time.** Generated trees run in adopters' apps; compile time costs only developers, and release compile time matters least. Never make a tree slower in order to compile faster (heap-allocated payloads) without a runtime measurement beside the compile numbers, and rank compile-cost work by debug builds. A small constant cost per tree build, such as one allocation per seam, is fine: trees are not built in tight loops. Seams alone never inline local functions (`LocalFunctionInlining`).
- **A cost every build pays needs the case's frequency.** More `generate` time is paid by every user on every build; a rare compile error with a documented fix is paid once by the few who hit it. Measure how often the case occurs in a real app before trading API, capability or build time for it, and keep it documented when it is rare, fails at compile time (never with a wrong value) and has an easy fix. Where SafeDI cannot see something (isolation, another module's sources), a documented opt-in or spelling comes before generator work. Erasure (`fulfilledByType:`, `erasedToConcreteExistential:`, `ErasedInstantiator`) is first-class: a real app's tree that does not use it yet is no evidence a shape is rare.
- **Isolation comes from the spelling.** A function moved out of `mock()` into a mocked type's own extension, spelled with its `mockAttributes`, has that type's `mock()` as its witness. A caller calls it only where its mock spells the same text or the type spells none, the initializer is not spelled `nonisolated`, no `@Sendable` function encloses the call, and the module writes the type's own `mock()`. The spelling does not cover a `@Sendable` function, a value sent into an actor's initializer, a public mock's configurations or an unmocked type in a public mock's tree. Inference, name guessing and a module-wide setting were tried and dropped.
- **Isolation comes from the spelling.** A function moved out of `mock()` into a mocked type's own extension, spelled with its `mockAttributes`, has that type's `mock()` as its witness. A caller calls it only where its mock spells the same text or the type spells none, the initializer is not spelled `nonisolated`, no `@Sendable` function encloses the call, and the module writes the type's own `mock()`. The spelling does not cover a `@Sendable` function, a value sent into an actor's initializer, a public mock's configurations or an unmocked type in a public mock's tree. Inference, name guessing and a module-wide setting were dropped; initializer attributes count as spelled.
- **Measure the compile cost of a change to generated code.** Before review of a change that alters what seams, public mocks or builders emit, run `Scripts/compile-time-check.py BASE_TOOL HEAD_TOOL BUILD DIRECTORY --base-build BASE_BUILD` with tools built from the change and from the commit it is based on: it generates wide graphs (40 and 200 screens) with each tool and fails when a module's generated lines grow by a quarter or `swiftc`'s CPU time on it by half. A change that grows either on purpose says so, with the table, in its pull request. CI times no compile: "Check Generate Time on Linux" runs the script's self-test and its `--lines` mode, which reports a module's generated lines more than 5% from `Scripts/compile-time-baseline.txt` (a warning, `--warn-only`, until the generator's output settles; then a failure). A change that alters generated output rewrites the file with `--write-baseline` from its own tool, in a commit of its own, and says why in a comment above each moved number.
- **No function the compiler takes long over.** "Check Function Compile Time on Linux" (`Scripts/function-compile-time-check.py`) fails when one function of SafeDICore takes over 10 s in the optimizer or 5 s in the type checker in a release build: the optimizer's cost grows faster than a function's length. Split the function (a block of a long initializer into a private static function, a long joined expression into sequential appends); never turn the optimizer off for it, since the generator's hot path runs through such code. `Scripts/function-compile-time-waivers.txt` lists the functions known to be over, each with a ceiling and what removes it; never add a line for new code.
- **`generate` time grows with the code it generates.** "Growth" in `CLAUDE.md` is the requirement: at most linear in every dimension of the input, proved by a growth row or a counted step in the change that adds the iteration. A step that runs once per place, fill, builder or scope must not build or scan a collection holding every place's, fill's or name's entries: build it once and share it (`GenerationWork.Shared`), or ask each set in turn (`NamesConsultedInTurn`) instead of joining them. Each such step counts its work where each taker takes what it consults (`GenerationWork.taking(_:by:)`): a plain collection counts every element, so rebuilding or scanning it for each taker counts that work whatever the step reports. `SafeDIToolSeamGenerationWorkTests` fails when a counted step's work grows more than 1.1 times as fast as the paths to the places of shape E: its places in the seam's own tree, in the fills of a seam it calls at each path, and there with every path opening types of its own, so that the names grow with the paths. A new step of that kind is counted there too. The observer is task-local, and every task that emits a scope's code inherits it, so it sees every step; `identifierSafeNames` counts only for a seam's signature. Two sites still do such work, uncounted: a call walks the enums of the inner seams on each of its places' routes, once for each place (`InnerScopeReaders.labelsSomeInnerRouteLacks(of:)`), so its work grows with its places times the inner seams' places; and a call nested in a fill of another call copies the enclosing calls' fill map and fill names.
Expand Down
2 changes: 2 additions & 0 deletions Documentation/Manual.md
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,8 @@ The `@Instantiable` macro checks a type’s own initializer, or the hand-written

A [public mock](#public-mocks) builds each type of its tree through a function SafeDI generates in that type’s extension, which repeats the attributes the type’s initializer, `instantiate(…)` or hand-written mock spells, exactly as written, so that function has the same isolation. It leaves out `@_spi`, `@backDeployed` and `@objc`, which that function cannot take. An attached macro there expands on that function too; if the macro cannot, give the type a hand-written `mock()` without it, which the public mock then builds the type with.

A builder in a mock’s overrides that replaces how a type is built is typed with the type’s `mockAttributes`, such as `@MainActor`, so that a closure you pass for it, such as `.init({ .mock() })` in a preview, runs in that isolation, in either of two cases: every mock in the module that builds the type spells the same `mockAttributes`, or the type’s initializer or `instantiate()`, and its hand-written mock where it has one, spell them too, such as a `@MainActor init` beside a `@MainActor static func mock`. In the second case the builder takes only the attributes each of those spells. SafeDI reads isolation only from `mockAttributes` and from what those constructions spell, never from a type’s declaration or its superclass, so spell it where you want the builder isolated. Otherwise a builder keeps no attributes, as it does where a `Sendable` wrapper such as `SendableInstantiator`, a public mock or a seam builds a type whose construction spells none, since the generated code calls the builder outside that isolation there. An attribute a closure type cannot take, such as `@available(…)`, stays on the declarations.

`generatedAttributes` is the shorthand for giving both the same text, and cannot be combined with either of the other two.

```swift
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,50 @@ extension DependencyTreeGenerator {
additionalMocksToGenerate: Set<String>,
storesPublicMockPlans: Bool,
publicMockContext: PublicMockContext?,
) async throws -> MockGenerationResult {
// Which builders spell their type's `mockAttributes` is a fact of the whole module, read by every mock's lowering.
let builderAttributesByType = MockBuilderIsolation.builderAttributes(among: typeDescriptionToFulfillingInstantiableMap, additionalMocksToGenerate: additionalMocksToGenerate).builderAttributesByType
guard !builderAttributesByType.isEmpty else {
return try await generateMockCodeChoosingRecords(
mockConditionalCompilation: mockConditionalCompilation,
currentModuleSourceFilePaths: currentModuleSourceFilePaths,
additionalMocksToGenerate: additionalMocksToGenerate,
storesPublicMockPlans: storesPublicMockPlans,
publicMockContext: publicMockContext,
)
}
return try await bindingBuilderAttributes(builderAttributesByType) {
try await generateMockCodeChoosingRecords(
mockConditionalCompilation: mockConditionalCompilation,
currentModuleSourceFilePaths: currentModuleSourceFilePaths,
additionalMocksToGenerate: additionalMocksToGenerate,
storesPublicMockPlans: storesPublicMockPlans,
publicMockContext: publicMockContext,
)
}
}

/// Runs `body` with `builderAttributesByType` bound for the mocks' lowering (`MockBuilderIsolation`). The async
/// `withValue` call stays out of line and unoptimized: Swift 6.2.4's release builds abort in `swift_task_dealloc`
/// ("freed pointer was not the last allocation") where it is inlined into a frame beside the nested async `withValue`
/// calls `generateMockCodeChoosingRecords` makes, as the graph fuzzer's long run's and fold checks' bindings do.
@inline(never) @_optimize(none)
private func bindingBuilderAttributes<Result>(_ builderAttributesByType: [TypeDescription: String], _ body: () async throws -> Result) async rethrows -> Result {
try await MockBuilderIsolation.$builderAttributesByType.withValue(builderAttributesByType) {
try await body()
}
}

/// `generateMockCode(mockConditionalCompilation:currentModuleSourceFilePaths:additionalMocksToGenerate:storesPublicMockPlans:publicMockContext:)`
/// with the module's isolated builders set, kept out of line so that its nested async `withValue` calls are never inlined
/// into one frame with `bindingBuilderAttributes(_:_:)`'s (Swift 6.2.4, "freed pointer was not the last allocation").
@inline(never)
private func generateMockCodeChoosingRecords(
mockConditionalCompilation: String?,
currentModuleSourceFilePaths: Set<String>?,
additionalMocksToGenerate: Set<String>,
storesPublicMockPlans: Bool,
publicMockContext: PublicMockContext?,
) async throws -> MockGenerationResult {
// The roots of the mock roots' worlds are recorded where a test observes node records or the mock worlds' sharing, or
// mocks are laid out from them (`NodeRecordsObservation.laysOutMockRoots`), which a run lays out alike whether or not a
Expand Down
Loading
Loading