diff --git a/.claude/rules/generator-design.md b/.claude/rules/generator-design.md index 1f0955c368..99344d60dc 100644 --- a/.claude/rules/generator-design.md +++ b/.claude/rules/generator-design.md @@ -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. diff --git a/Documentation/Manual.md b/Documentation/Manual.md index de9b90fad4..be3ff7aea8 100644 --- a/Documentation/Manual.md +++ b/Documentation/Manual.md @@ -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 diff --git a/Sources/SafeDICore/Generators/DependencyTreeGenerator+MockOrchestration.swift b/Sources/SafeDICore/Generators/DependencyTreeGenerator+MockOrchestration.swift index 002f5a0e65..ea603162f7 100644 --- a/Sources/SafeDICore/Generators/DependencyTreeGenerator+MockOrchestration.swift +++ b/Sources/SafeDICore/Generators/DependencyTreeGenerator+MockOrchestration.swift @@ -29,6 +29,50 @@ extension DependencyTreeGenerator { additionalMocksToGenerate: Set, 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(_ 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?, + additionalMocksToGenerate: Set, + 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 diff --git a/Sources/SafeDICore/Generators/MockLowering+Walk.swift b/Sources/SafeDICore/Generators/MockLowering+Walk.swift index 1449236a0b..76efd9ffd4 100644 --- a/Sources/SafeDICore/Generators/MockLowering+Walk.swift +++ b/Sources/SafeDICore/Generators/MockLowering+Walk.swift @@ -18,6 +18,9 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. +import SwiftParser +import SwiftSyntax + /// Stage D1's core walk: the mock of a root whose tree it lowers, from the root's finished generator and its children in /// generation order. The walk writes each node's statements as it reaches the node and keeps no tree of nodes, and it /// recurses through `async` functions, whose frames the task allocates, so a tree as deep as the module has types neither @@ -1655,7 +1658,7 @@ extension MockLowering { /// The type of the closure that overrides how the node is built, handed the values its initializer takes. var builderClosureType: String { - "(\(builderParameterTypes)) -> \(property.typeDescription.asInstantiatedTypeSpelledAsDeclared.asSource)" + "\(BuilderParameters.attributesPrefix(MockBuilderIsolation.attributes(of: instantiable)))(\(builderParameterTypes)) -> \(property.typeDescription.asInstantiatedTypeSpelledAsDeclared.asSource)" } /// The types of the values the node's override is handed, joined: one per argument its construction is passed, which @@ -2158,6 +2161,19 @@ extension MockLowering { arguments = (usesMockInitializer ? instantiable.mockInitializer : instantiable.initializer)?.arguments ?? [] dependencies = instantiable.dependencies sendsArguments = instantiable.declarationType == .actorType && !usesMockInitializer + isolation = MockBuilderIsolation.attributes(of: instantiable) + } + + /// The closure type of a builder handed these parameters and returning `returnType`: spelled with the type's + /// `mockAttributes`, as its `mock()` is, so that a closure a caller writes for it is isolated as the type's own + /// construction is, `@Sendable` or not. + func closureType(returning returnType: String) -> String { + "\(Self.attributesPrefix(isolation))(\(spelled)) -> \(returnType)" + } + + /// `attributes`, a type's `mockAttributes`, followed by a space, or nothing where it spells none. + static func attributesPrefix(_ attributes: String) -> String { + attributes.isEmpty ? "" : "\(attributes) " } /// The parameters' types, spelled as the closure's parameter list. @@ -2177,6 +2193,8 @@ extension MockLowering { /// lets a closure send only a parameter declared `sending`, so an override written as `{ worker in Store(worker: worker) }` /// compiles only so. Each value the mock hands it is a local nothing else holds. private let sendsArguments: Bool + /// The type's `mockAttributes`, which the builder's closure type spells. + private let isolation: String } } @@ -2193,3 +2211,150 @@ extension MockLowering { return bindingNamesPassedByName } } + +/// The attributes a builder closure type of a mock spells, so that a closure a caller writes for the builder, such as a +/// preview's, runs in the isolation the user spelled: the built type's `mockAttributes`, where either +/// - every generated function in the module that calls the builder spells those attributes too, or +/// - the construction the builder replaces, the initializer, `instantiate(…)` or hand-written mock a mock calls where no +/// builder is given, spells them too: every place that calls the builder calls that construction synchronously where +/// it is `nil`, so a builder isolated as the construction is callable wherever the construction is. Of the attributes +/// only those are spelled that both the initializer and the hand-written mock spell, where the type has both, since +/// the type's one configuration serves every place that builds it. +/// None otherwise, as before. A closure a caller passes in has no generated caller, so it never counts against this. +/// SafeDI reads isolation from `mockAttributes` and the attributes a construction spells only, never from a type's +/// declaration, a superclass or a protocol: a caller isolated only by inheritance counts as spelling nothing. +/// +/// The functions that call a type's builder are the `mock()` of each mock root whose tree builds the type, which spells +/// the root's `mockAttributes`, and the local functions inside it, which take its isolation, except a `@Sendable` +/// function, which is `nonisolated`, and a public mock's or a seam's construction functions, which spell their +/// construction's attributes. So every generated caller spells the type's `mockAttributes` where every mock root of the +/// module that reaches it through `@Instantiated` dependencies spells them, and no `Sendable` wrapper, public mock or seam +/// reaches it. Reaching is read from the module's declarations, which reach at least what any tree builds: a type some +/// declaration reaches but no tree builds can lose its attributes, never gain wrong ones. +/// +/// Only an attribute a closure type takes is spelled: none with arguments, such as `@available(…)`, and none of the +/// declaration attributes `declarationOnlyAttributes` lists. +enum MockBuilderIsolation { + /// The attributes each builder closure type of a concrete type spells, for the module whose mocks are being generated + /// (`builderAttributes(among:additionalMocksToGenerate:)`), holding only types whose + /// builders spell some; empty outside mock generation. + @TaskLocal static var builderAttributesByType = [TypeDescription: String]() + + /// The attributes a builder closure type of `instantiable`'s type spells. Most types spell no `mockAttributes`, so + /// those read nothing more. + static func attributes(of instantiable: Instantiable) -> String { + guard !instantiable.mockAttributes.isEmpty else { return "" } + return builderAttributesByType[instantiable.concreteInstantiable] ?? "" + } + + /// The attributes of `attributes`, a `mockAttributes` as the user spelled it, that a closure type can spell, each as + /// written and in their order: read from its syntax, those without an argument clause whose name + /// `declarationOnlyAttributes` does not list. + static func closureAttributes(of attributes: String) -> [String] { + guard !attributes.isEmpty else { return [] } + return attributeSyntaxes(of: attributes) + .filter { $0.arguments == nil && !declarationOnlyAttributes.contains($0.attributeName.trimmedDescription) } + .map(\.trimmedDescription) + } + + /// The attributes `attributes` spells, read as the attributes of a declaration, which a declaration's spelled + /// attributes and modifiers (`Initializer.spelledAttributes`) and a `mockAttributes` both are. + static func attributeSyntaxes(of attributes: String) -> [AttributeSyntax] { + Parser.parse(source: "\(attributes) func declaration() {}").statements + .compactMap { $0.item.as(FunctionDeclSyntax.self) } + .flatMap(\.attributes) + .compactMap { $0.as(AttributeSyntax.self) } + } + + /// The compiler's attributes without arguments that a declaration takes and a closure type does not. + static let declarationOnlyAttributes: Set = ["discardableResult", "inlinable", "usableFromInline", "objc", "nonobjc", "preconcurrency", "_disfavoredOverload", "warn_unqualified_access", "_spi", "backDeployed", "available"] + + /// The attributes the builders of the module's types spell, by concrete type, for the types whose builders spell some: + /// all of a type's closure attributes where every generated caller spells them, else those that each of its + /// constructions spells too, its initializer or `instantiate(…)` and its hand-written mock, since the type's one + /// configuration serves every place that builds it, whichever construction that place calls. `instantiables` is the + /// module's by the types they fulfill; each declaration is read from its entry for its own concrete type, which only it + /// fulfills, since a second declaration fulfilling a type is rejected before mocks are generated, so no other entry's + /// declaration stands for it. The mock roots are the types that generate a mock, other modules' too, which can only + /// leave a builder plain, and those `additionalMocksToGenerate` names. + /// + /// Linear in what the mock roots reach, times the few distinct attribute spellings of the mock roots, and it walks + /// nothing where no declaration spells a closure attribute in its `mockAttributes`, or every one that does has + /// constructions that spell them all. `stepCount` counts each type the walks take up and each edge they follow, so a + /// test can check that the pass grows no faster than the graph. + static func builderAttributes(among instantiables: [TypeDescription: Instantiable], additionalMocksToGenerate: Set) -> (builderAttributesByType: [TypeDescription: String], stepCount: Int) { + var closureAttributesByType = [TypeDescription: [String]]() + for (type, instantiable) in instantiables where !instantiable.mockAttributes.isEmpty && type == instantiable.concreteInstantiable { + let attributes = closureAttributes(of: instantiable.mockAttributes) + if !attributes.isEmpty { + closureAttributesByType[type] = attributes + } + } + var builderAttributesByType = [TypeDescription: String]() + // The types whose constructions do not spell every attribute, which only their generated callers can isolate. + var typesAwaitingCallers = [TypeDescription: String]() + for (type, attributes) in closureAttributesByType { + let instantiable = instantiables[type] + let spelledByEach = [instantiable?.initializer, instantiable?.mockInitializer] + .compactMap { $0.map { Set(attributeSyntaxes(of: $0.spelledAttributes ?? "").map(\.trimmedDescription)) } } + let spelledByConstructions = spelledByEach.isEmpty ? [] : attributes.filter { attribute in spelledByEach.allSatisfy { $0.contains(attribute) } } + if !spelledByConstructions.isEmpty { + builderAttributesByType[type] = spelledByConstructions.joined(separator: " ") + } + if spelledByConstructions != attributes { + typesAwaitingCallers[type] = attributes.joined(separator: " ") + } + } + guard !typesAwaitingCallers.isEmpty else { return (builderAttributesByType, 0) } + var stepCount = 0 + + // Each reached type's `@Instantiated` children, with whether a `Sendable` wrapper builds the child, read once. + var childrenByType = [TypeDescription: [(type: TypeDescription, isSendable: Bool)]]() + func children(of type: TypeDescription) -> [(type: TypeDescription, isSendable: Bool)] { + if let children = childrenByType[type] { + return children + } else { + let children = (instantiables[type]?.dependencies ?? []).compactMap { dependency -> (type: TypeDescription, isSendable: Bool)? in + guard case .instantiated = dependency.source, let child = instantiables[dependency.asInstantiatedType] else { return nil } + return (type: child.concreteInstantiable, isSendable: dependency.property.propertyType.isSendable) + } + childrenByType[type] = children + return children + } + } + // The attributes of the mock roots that reach each type, each spelling carried down once per type. + var callerAttributesByType = [TypeDescription: Set]() + var reached = [(type: TypeDescription, attributes: String)]() + for (type, instantiable) in instantiables where type == instantiable.concreteInstantiable { + if instantiable.generatesMock || additionalMocksToGenerate.contains(type.asSource) { + reached.append((type: type, attributes: closureAttributes(of: instantiable.mockAttributes).joined(separator: " "))) + } + } + while let (type, attributes) = reached.popLast() { + stepCount += 1 + guard callerAttributesByType[type, default: []].insert(attributes).inserted else { continue } + reached += children(of: type).map { (type: $0.type, attributes: attributes) } + } + // What a `Sendable` wrapper, a public mock or a seam reaches among the reached types, whose generated callers do + // not take the mock roots' isolation. + var excluded = Set() + var pending = [TypeDescription]() + for type in callerAttributesByType.keys { + if let instantiable = instantiables[type], instantiable.generateMock == .public || instantiable.generatesDependencyTree { + pending.append(type) + } + for child in children(of: type) where child.isSendable { + pending.append(child.type) + } + } + while let type = pending.popLast() { + stepCount += 1 + guard excluded.insert(type).inserted else { continue } + pending += children(of: type).map(\.type) + } + for (type, attributes) in typesAwaitingCallers where !excluded.contains(type) && callerAttributesByType[type] == [attributes] { + builderAttributesByType[type] = attributes + } + return (builderAttributesByType, stepCount) + } +} diff --git a/Sources/SafeDICore/Generators/MockLowering.swift b/Sources/SafeDICore/Generators/MockLowering.swift index b33b54187f..b285dbb302 100644 --- a/Sources/SafeDICore/Generators/MockLowering.swift +++ b/Sources/SafeDICore/Generators/MockLowering.swift @@ -104,7 +104,7 @@ public enum MockLowering { /// The type of the closure that overrides how the node is built, returning its concrete type. var concreteBuilderClosureType: String { - "(\(builderParameters.spelled)) -> \(concreteType.asSource)" + builderParameters.closureType(returning: concreteType.asSource) } /// What spells a child's field: a node the tree builds, spelled when the field is read, or a field already spelled. @@ -123,7 +123,7 @@ public enum MockLowering { let typeSource = "\(configuredTypeName).\(ScopeGenerator.mockConfigurationStructName)" return ChildField(name: bindingName, typeSource: typeSource, defaultValue: ".init()", sendableForm: .init(typeSource: typeSource, defaultValue: ".init()", configuredTypeName: configuredTypeName)) } else { - let builderClosureType = "(\(builderParameters.spelled)) -> \(propertyType.asInstantiatedTypeSpelledAsDeclared.asSource)" + let builderClosureType = builderParameters.closureType(returning: propertyType.asInstantiatedTypeSpelledAsDeclared.asSource) return ChildField(name: bindingName, typeSource: "(\(requiresSendable ? "@Sendable " : "")\(builderClosureType))?", defaultValue: "nil", sendableForm: .init(typeSource: "(@Sendable \(builderClosureType))?", defaultValue: "nil", configuredTypeName: nil)) } case let .spelled(childField): diff --git a/Sources/SafeDICore/Generators/NodeRecords/NodeRecords+Loops.swift b/Sources/SafeDICore/Generators/NodeRecords/NodeRecords+Loops.swift index 18e74cc61e..6b7860c089 100644 --- a/Sources/SafeDICore/Generators/NodeRecords/NodeRecords+Loops.swift +++ b/Sources/SafeDICore/Generators/NodeRecords/NodeRecords+Loops.swift @@ -407,7 +407,7 @@ extension NodeRecords { let usesHandWrittenMock = world.construction(of: member) == .handWrittenMock && instantiable.mockInitializer != nil return isConfigured(member, in: world) ? mockConfigurationType(of: instantiable, in: world) - : .unknown(text: "(\(property.propertyType.isSendable ? "@Sendable " : "")(\(MockLowering.BuilderParameters(of: instantiable, usesMockInitializer: usesHandWrittenMock).spelled)) -> \(property.typeDescription.asInstantiatedTypeSpelledAsDeclared.asSource))?") + : .unknown(text: "(\(property.propertyType.isSendable ? "@Sendable " : "")\(MockLowering.BuilderParameters(of: instantiable, usesMockInitializer: usesHandWrittenMock).closureType(returning: property.typeDescription.asInstantiatedTypeSpelledAsDeclared.asSource)))?") } /// Whether `declaration` is a member of a loop of builders in a mock root's world: its function makes another member diff --git a/Sources/SafeDICore/Generators/NodeRecords/NodeRecords+MockConstruction.swift b/Sources/SafeDICore/Generators/NodeRecords/NodeRecords+MockConstruction.swift index ec9615a6f4..82db82f4a4 100644 --- a/Sources/SafeDICore/Generators/NodeRecords/NodeRecords+MockConstruction.swift +++ b/Sources/SafeDICore/Generators/NodeRecords/NodeRecords+MockConstruction.swift @@ -298,7 +298,7 @@ extension NodeRecords { if isConfigured { mockConfigurationType(of: instantiable) } else { - .unknown(text: "(\(isSendable ? "@Sendable " : "")(\(MockLowering.BuilderParameters(of: instantiable, usesMockInitializer: usesHandWrittenMock).spelled)) -> \(record.property.typeDescription.asInstantiatedTypeSpelledAsDeclared.asSource))?") + .unknown(text: "(\(isSendable ? "@Sendable " : "")\(MockLowering.BuilderParameters(of: instantiable, usesMockInitializer: usesHandWrittenMock).closureType(returning: record.property.typeDescription.asInstantiatedTypeSpelledAsDeclared.asSource)))?") } } diff --git a/Sources/SafeDICore/Generators/NodeRecords/NodeRecords+PublicMockActor.swift b/Sources/SafeDICore/Generators/NodeRecords/NodeRecords+PublicMockActor.swift index 3039c77be0..3d6faceef1 100644 --- a/Sources/SafeDICore/Generators/NodeRecords/NodeRecords+PublicMockActor.swift +++ b/Sources/SafeDICore/Generators/NodeRecords/NodeRecords+PublicMockActor.swift @@ -118,7 +118,7 @@ extension NodeRecords { let returnType = isConfigured ? instantiable.concreteInstantiable.asSource : property.typeDescription.asInstantiatedTypeSpelledAsDeclared.asSource let builder = local( named: declaration == start ? builderName : "\(path)_\(builderName)", - type: .unknown(text: "(@Sendable (\(builderParameters.spelled)) -> \(returnType))?"), + type: .unknown(text: "(@Sendable \(builderParameters.closureType(returning: returnType)))?"), value: isConfigured ? .member(builderName, of: configurationValue) : configurationValue, ) let fields = mockConfigurationFieldArguments(of: declaration, in: world).map { _, argument in diff --git a/Sources/SafeDICore/Generators/NodeRecords/NodeRecords+PublicMockRoot.swift b/Sources/SafeDICore/Generators/NodeRecords/NodeRecords+PublicMockRoot.swift index 46fb2491f2..8dec2369fb 100644 --- a/Sources/SafeDICore/Generators/NodeRecords/NodeRecords+PublicMockRoot.swift +++ b/Sources/SafeDICore/Generators/NodeRecords/NodeRecords+PublicMockRoot.swift @@ -265,7 +265,7 @@ extension NodeRecords { concreteType: childInstantiable.concreteInstantiable, source: .built( isConfigured: isOverriddenByConfiguration, - builderClosureType: "(\(builderParameters.spelled)) -> \(propertyType.asInstantiatedTypeSpelledAsDeclared.asSource)", + builderClosureType: builderParameters.closureType(returning: propertyType.asInstantiatedTypeSpelledAsDeclared.asSource), requiresSendable: requiresSendable || record.isSendable || childrenAreBuiltForActorArgument, accessTypes: (childInstantiable.initializer?.arguments ?? []).map(\.typeDescription) + [propertyType.asInstantiatedType], ), diff --git a/Tests/SafeDICoreTests/MockBuilderIsolationStepCountTests.swift b/Tests/SafeDICoreTests/MockBuilderIsolationStepCountTests.swift new file mode 100644 index 0000000000..3561cf4ff1 --- /dev/null +++ b/Tests/SafeDICoreTests/MockBuilderIsolationStepCountTests.swift @@ -0,0 +1,81 @@ +// Distributed under the MIT License +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +import SwiftParser +import SwiftSyntax +import Testing +@testable import SafeDICore + +/// The module-wide pass that decides which builders spell their type's `mockAttributes` walks what the mock roots reach +/// once per distinct spelling, so its steps grow no faster than the module. +struct MockBuilderIsolationStepCountTests { + @Test + func builderAttributes_takesAtMostTwiceTheSteps_whenMockRootsDouble() { + let steps = [20, 40].map { rootCount in + MockBuilderIsolation.builderAttributes(among: Self.instantiables(rootCount: rootCount), additionalMocksToGenerate: []).stepCount + } + #expect(steps[0] > 0) + #expect(steps[1] <= 2 * steps[0], "\(steps[0]) steps for 20 mock roots, \(steps[1]) for 40") + } + + /// `rootCount` main-actor mock roots, every other one spelling no `mockAttributes`, each building a screen of its own + /// and the shared `Loader`, whose initializer spells nothing, so the pass walks to learn the loader's callers. + private static func instantiables(rootCount: Int) -> [TypeDescription: Instantiable] { + var source = """ + @Instantiable(mockAttributes: "@MainActor") + public final class Loader: Instantiable { + public init() {} + } + + """ + for index in 0.. PhotoLoader { + PhotoLoader(thumbnails: thumbnails) + } + + @Instantiated let thumbnails: Thumbnails + } + """, + """ + @Instantiable(mockAttributes: "@MainActor", generateMock: true) + public actor ProfileStore: Instantiable { + @MainActor public init(photoLoader: PhotoLoader) { + self.photoLoader = photoLoader + } + + @Instantiated let photoLoader: PhotoLoader + } + """, + """ + @MainActor + @Instantiable(mockAttributes: "@MainActor", generateMock: true) + public final class GalleryScreen: Instantiable { + public init(photoLoader: PhotoLoader) { + self.photoLoader = photoLoader + } + + @Instantiated let photoLoader: PhotoLoader + } + """, + """ + #if DEBUG + @MainActor + func galleryPreview() -> GalleryScreen { + GalleryScreen.mock(safeDIOverrides: .init(photoLoader: .init({ thumbnails in .mock(thumbnails: thumbnails) }))) + } + #endif + """, + ], + buildSwiftOutputDirectory: true, + filesToDelete: &filesToDelete, + ) + + #expect(output.generatedFiles == [ + "GalleryScreen+SafeDIMock.swift": generatedFileHeader + """ + #if DEBUG + extension GalleryScreen { + /// Overrides for the mock dependency tree. + struct SafeDIOverrides { + init( + photoLoader: PhotoLoader.SafeDIMockConfiguration = .init() + ) { + __safeDI_storage = __safeDI_Storage( + photoLoader: photoLoader + ) + } + + var photoLoader: PhotoLoader.SafeDIMockConfiguration { __safeDI_storage.photoLoader } + + private let __safeDI_storage: __safeDI_Storage + + private final class __safeDI_Storage: Sendable { + init( + photoLoader: PhotoLoader.SafeDIMockConfiguration + ) { + self.photoLoader = photoLoader + } + + let photoLoader: PhotoLoader.SafeDIMockConfiguration + } + } + + @MainActor static func mock( + safeDIOverrides: SafeDIOverrides = .init() + ) -> GalleryScreen { + func __safeDI_photoLoader(safeDIOverrides: PhotoLoader.SafeDIMockConfiguration) -> PhotoLoader { + let thumbnails = if let safeDIBuilder = safeDIOverrides.thumbnails { safeDIBuilder() } else { Thumbnails() } + return if let safeDIBuilder = safeDIOverrides.safeDIBuilder { safeDIBuilder(thumbnails) } else { PhotoLoader.mock(thumbnails: thumbnails) } + } + let photoLoader: PhotoLoader = __safeDI_photoLoader(safeDIOverrides: safeDIOverrides.photoLoader) + return GalleryScreen(photoLoader: photoLoader) + } + } + #endif + """, + "ProfileStore+SafeDIMock.swift": generatedFileHeader + """ + #if DEBUG + extension ProfileStore { + /// Overrides for the mock dependency tree. + struct SafeDIOverrides { + init( + photoLoader: PhotoLoader.SafeDIMockConfiguration = .init() + ) { + __safeDI_storage = __safeDI_Storage( + photoLoader: photoLoader + ) + } + + var photoLoader: PhotoLoader.SafeDIMockConfiguration { __safeDI_storage.photoLoader } + + private let __safeDI_storage: __safeDI_Storage + + private final class __safeDI_Storage: Sendable { + init( + photoLoader: PhotoLoader.SafeDIMockConfiguration + ) { + self.photoLoader = photoLoader + } + + let photoLoader: PhotoLoader.SafeDIMockConfiguration + } + } + + @MainActor static func mock( + safeDIOverrides: SafeDIOverrides = .init() + ) -> ProfileStore { + func __safeDI_photoLoader(safeDIOverrides: PhotoLoader.SafeDIMockConfiguration) -> PhotoLoader { + let thumbnails = if let safeDIBuilder = safeDIOverrides.thumbnails { safeDIBuilder() } else { Thumbnails() } + return if let safeDIBuilder = safeDIOverrides.safeDIBuilder { safeDIBuilder(thumbnails) } else { PhotoLoader.mock(thumbnails: thumbnails) } + } + let photoLoader: PhotoLoader = __safeDI_photoLoader(safeDIOverrides: safeDIOverrides.photoLoader) + return ProfileStore(photoLoader: photoLoader) + } + } + #endif + """, + "SafeDIMockConfiguration.swift": generatedFileHeader + """ + #if DEBUG + extension PhotoLoader { + /// Configuration for how this type is constructed within a mock tree. + nonisolated struct SafeDIMockConfiguration: Sendable { + init( + thumbnails: (@Sendable () -> Thumbnails)? = nil, + _ safeDIBuilder: (@Sendable @MainActor (Thumbnails) -> PhotoLoader)? = nil + ) { + __safeDI_storage = __safeDI_Storage( + thumbnails: thumbnails, + safeDIBuilder: safeDIBuilder + ) + } + + var thumbnails: (@Sendable () -> Thumbnails)? { __safeDI_storage.thumbnails } + /// Overrides how this type is constructed. Parameters match the type’s initializer or custom mock method. When `nil`, the default generated construction function is used. + var safeDIBuilder: (@Sendable @MainActor (Thumbnails) -> PhotoLoader)? { __safeDI_storage.safeDIBuilder } + + private let __safeDI_storage: __safeDI_Storage + + private final class __safeDI_Storage: Sendable { + init( + thumbnails: (@Sendable () -> Thumbnails)?, + safeDIBuilder: (@Sendable @MainActor (Thumbnails) -> PhotoLoader)? + ) { + self.thumbnails = thumbnails + self.safeDIBuilder = safeDIBuilder + } + + let thumbnails: (@Sendable () -> Thumbnails)? + let safeDIBuilder: (@Sendable @MainActor (Thumbnails) -> PhotoLoader)? + } + } + } + #endif + + """, + ]) + } + + @Test + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + mutating func mock_typesBuilderWithClosureAttributesOfMockAttributes_whenMainActorTypeIsBuiltForActorMock() async throws { + // A real adopter's shape: `Loader` is a main-actor class whose `mockAttributes` spell the main actor, and an actor's + // main-actor mock builds it, which makes the override of `Loader` `@Sendable`. The preview's closure touches + // main-actor state and calls `Loader`'s main-actor initializer, which compiles only where the builder is isolated + // to the main actor. `@available(…)`, which a closure type cannot take, stays on the declarations. + let output = try await executeSafeDIToolTest( + swiftFileContent: [ + """ + public final class Shelf: Sendable { + public init() {} + } + + @MainActor + public final class Painter { + public init() {} + public func paint() -> Int { 1 } + } + """, + """ + @MainActor + @Instantiable(mockAttributes: "@MainActor @available(macOS 10.15, *)") + public final class Loader: Instantiable { + public init(shelf: Shelf) { + self.shelf = shelf + } + + @Received let shelf: Shelf + } + """, + """ + @Instantiable(mockAttributes: "@MainActor", generateMock: true) + public actor Library: Instantiable { + @MainActor public init(loader: Loader, shelf: Shelf) { + self.loader = loader + self.shelf = shelf + } + + @Instantiated let loader: Loader + @Received let shelf: Shelf + } + """, + """ + #if DEBUG + @MainActor + func libraryPreview() -> Library { + let painter = Painter() + return Library.mock(shelf: Shelf(), safeDIOverrides: .init(loader: { shelf in + _ = painter.paint() + return Loader(shelf: shelf) + })) + } + #endif + """, + ], + buildSwiftOutputDirectory: true, + filesToDelete: &filesToDelete, + ) + + #expect(output.generatedFiles == [ + "Library+SafeDIMock.swift": generatedFileHeader + """ + #if DEBUG + extension Library { + /// Overrides for the mock dependency tree. + struct SafeDIOverrides { + init( + loader: (@Sendable @MainActor (Shelf) -> Loader)? = nil + ) { + __safeDI_storage = __safeDI_Storage( + loader: loader + ) + } + + var loader: (@Sendable @MainActor (Shelf) -> Loader)? { __safeDI_storage.loader } + + private let __safeDI_storage: __safeDI_Storage + + private final class __safeDI_Storage: Sendable { + init( + loader: (@Sendable @MainActor (Shelf) -> Loader)? + ) { + self.loader = loader + } + + let loader: (@Sendable @MainActor (Shelf) -> Loader)? + } + } + + @MainActor static func mock( + shelf: Shelf, + safeDIOverrides: SafeDIOverrides = .init() + ) -> Library { + let loader = if let safeDIBuilder = safeDIOverrides.loader { safeDIBuilder(shelf) } else { Loader(shelf: shelf) } + return Library(loader: loader, shelf: shelf) + } + } + #endif + """, + "SafeDIMockConfiguration.swift": generatedFileHeader, + ]) + } + + @Test + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + mutating func mock_typesBuilderWithMockAttributesTheConstructionSpells_whenCallerIsIsolatedOnlyBySuperclass() async throws { + // A real adopter's shape: `ProfileScreen`'s mock is main-actor only through its superclass and spells no + // `mockAttributes`, so not every mock that builds `Loader` spells `@MainActor`, while an actor's main-actor mock + // makes the override of `Loader` `@Sendable`. `Loader`'s initializer and hand-written mock both spell the main + // actor, so every place that calls the builder already calls a main-actor construction, and the builder takes the + // main actor too: the preview's closure, which touches main-actor state, compiles. + let output = try await executeSafeDIToolTest( + swiftFileContent: [ + """ + public final class Shelf: Sendable { + public init() {} + } + + @MainActor + public final class Painter { + public init() {} + public func paint() -> Int { 1 } + } + + @MainActor + open class ScreenBase { + public init() {} + } + """, + """ + @MainActor + @Instantiable(mockAttributes: "@MainActor") + public final class Loader: Instantiable { + @MainActor public init(shelf: Shelf) { + self.shelf = shelf + } + + @MainActor public static func mock(shelf: Shelf) -> Loader { + Loader(shelf: shelf) + } + + @Received let shelf: Shelf + } + """, + """ + @Instantiable(mockAttributes: "@MainActor", generateMock: true) + public actor Library: Instantiable { + @MainActor public init(loader: Loader, shelf: Shelf) { + self.loader = loader + self.shelf = shelf + } + + @Instantiated let loader: Loader + @Received let shelf: Shelf + } + """, + """ + @Instantiable(generateMock: true) + public final class ProfileScreen: ScreenBase, Instantiable { + public init(loader: Loader, shelf: Shelf) { + self.loader = loader + self.shelf = shelf + super.init() + } + + @Instantiated let loader: Loader + @Received let shelf: Shelf + } + """, + """ + #if DEBUG + @MainActor + func profilePreview() -> (Library, ProfileScreen) { + let painter = Painter() + let library = Library.mock(shelf: Shelf(), safeDIOverrides: .init(loader: { shelf in + _ = painter.paint() + return .mock(shelf: shelf) + })) + let profileScreen = ProfileScreen.mock(shelf: Shelf(), safeDIOverrides: .init(loader: { shelf in + _ = painter.paint() + return .mock(shelf: shelf) + })) + return (library, profileScreen) + } + #endif + """, + ], + buildSwiftOutputDirectory: true, + filesToDelete: &filesToDelete, + ) + + #expect(output.generatedFiles == [ + "Library+SafeDIMock.swift": generatedFileHeader + """ + #if DEBUG + extension Library { + /// Overrides for the mock dependency tree. + struct SafeDIOverrides { + init( + loader: (@Sendable @MainActor (Shelf) -> Loader)? = nil + ) { + __safeDI_storage = __safeDI_Storage( + loader: loader + ) + } + + var loader: (@Sendable @MainActor (Shelf) -> Loader)? { __safeDI_storage.loader } + + private let __safeDI_storage: __safeDI_Storage + + private final class __safeDI_Storage: Sendable { + init( + loader: (@Sendable @MainActor (Shelf) -> Loader)? + ) { + self.loader = loader + } + + let loader: (@Sendable @MainActor (Shelf) -> Loader)? + } + } + + @MainActor static func mock( + shelf: Shelf, + safeDIOverrides: SafeDIOverrides = .init() + ) -> Library { + let loader = if let safeDIBuilder = safeDIOverrides.loader { safeDIBuilder(shelf) } else { Loader.mock(shelf: shelf) } + return Library(loader: loader, shelf: shelf) + } + } + #endif + """, + "ProfileScreen+SafeDIMock.swift": generatedFileHeader + """ + #if DEBUG + extension ProfileScreen { + /// Overrides for the mock dependency tree. + struct SafeDIOverrides { + init( + loader: (@MainActor (Shelf) -> Loader)? = nil + ) { + __safeDI_storage = __safeDI_Storage( + loader: loader + ) + } + + var loader: (@MainActor (Shelf) -> Loader)? { __safeDI_storage.loader } + + private let __safeDI_storage: __safeDI_Storage + + private final class __safeDI_Storage { + init( + loader: (@MainActor (Shelf) -> Loader)? + ) { + self.loader = loader + } + + let loader: (@MainActor (Shelf) -> Loader)? + } + } + + static func mock( + shelf: Shelf, + safeDIOverrides: SafeDIOverrides = .init() + ) -> ProfileScreen { + let loader = if let safeDIBuilder = safeDIOverrides.loader { safeDIBuilder(shelf) } else { Loader.mock(shelf: shelf) } + return ProfileScreen(loader: loader, shelf: shelf) + } + } + #endif + """, + "SafeDIMockConfiguration.swift": generatedFileHeader, + ]) + } + + @Test + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + mutating func mock_keepsBuilderWithoutMockAttributes_whenSendableInstantiatorBuildsTypeWithNonisolatedInitializer() async throws { + // `PhotoLoader` spells `mockAttributes: "@MainActor"`, but its initializer spells no isolation, so `Gallery`'s + // `SendableInstantiator` may build it in a `@Sendable` function, which calls its builder there: a builder isolated + // to the main actor could not be called, so it takes none of the attributes. + let output = try await executeSafeDIToolTest( + swiftFileContent: [ + """ + @Instantiable + public final class Thumbnails: Instantiable, Sendable { + public init() {} + } + """, + """ + @Instantiable(mockAttributes: "@MainActor", generateMock: true) + public final class PhotoLoader: Instantiable, Sendable { + public init(thumbnails: Thumbnails) { + self.thumbnails = thumbnails + } + + @Instantiated let thumbnails: Thumbnails + } + """, + """ + @Instantiable(generateMock: true) + public final class Gallery: Instantiable, Sendable { + public init(photoLoaderBuilder: SendableInstantiator) { + self.photoLoaderBuilder = photoLoaderBuilder + } + + @Instantiated let photoLoaderBuilder: SendableInstantiator + } + """, + ], + buildSwiftOutputDirectory: true, + filesToDelete: &filesToDelete, + ) + + #expect(output.generatedFiles == [ + "Gallery+SafeDIMock.swift": generatedFileHeader + """ + #if DEBUG + extension Gallery { + /// Overrides for the mock dependency tree. + struct SafeDIOverrides { + init( + photoLoaderBuilder: PhotoLoader.SafeDIMockConfiguration = .init() + ) { + __safeDI_storage = __safeDI_Storage( + photoLoaderBuilder: photoLoaderBuilder + ) + } + + var photoLoaderBuilder: PhotoLoader.SafeDIMockConfiguration { __safeDI_storage.photoLoaderBuilder } + + private let __safeDI_storage: __safeDI_Storage + + private final class __safeDI_Storage: Sendable { + init( + photoLoaderBuilder: PhotoLoader.SafeDIMockConfiguration + ) { + self.photoLoaderBuilder = photoLoaderBuilder + } + + let photoLoaderBuilder: PhotoLoader.SafeDIMockConfiguration + } + } + + static func mock( + safeDIOverrides: SafeDIOverrides = .init() + ) -> Gallery { + let __safeDI_photoLoaderBuilder__overrides = safeDIOverrides.photoLoaderBuilder + @Sendable nonisolated func __safeDI_photoLoaderBuilder() -> PhotoLoader { + let thumbnails = if let safeDIBuilder = __safeDI_photoLoaderBuilder__overrides.thumbnails { safeDIBuilder() } else { Thumbnails() } + return if let safeDIBuilder = __safeDI_photoLoaderBuilder__overrides.safeDIBuilder { safeDIBuilder(thumbnails) } else { PhotoLoader(thumbnails: thumbnails) } + } + let photoLoaderBuilder = SendableInstantiator(__safeDI_photoLoaderBuilder) + return Gallery(photoLoaderBuilder: photoLoaderBuilder) + } + } + #endif + """, + "PhotoLoader+SafeDIMock.swift": generatedFileHeader + """ + #if DEBUG + extension PhotoLoader { + /// Overrides for the mock dependency tree. + struct SafeDIOverrides { + init( + thumbnails: (() -> Thumbnails)? = nil + ) { + __safeDI_storage = __safeDI_Storage( + thumbnails: thumbnails + ) + } + + var thumbnails: (() -> Thumbnails)? { __safeDI_storage.thumbnails } + + private let __safeDI_storage: __safeDI_Storage + + private final class __safeDI_Storage { + init( + thumbnails: (() -> Thumbnails)? + ) { + self.thumbnails = thumbnails + } + + let thumbnails: (() -> Thumbnails)? + } + } + + @MainActor static func mock( + safeDIOverrides: SafeDIOverrides = .init() + ) -> PhotoLoader { + let thumbnails = if let safeDIBuilder = safeDIOverrides.thumbnails { safeDIBuilder() } else { Thumbnails() } + return PhotoLoader(thumbnails: thumbnails) + } + } + #endif + + #if DEBUG + extension PhotoLoader { + /// Configuration for how this type is constructed within a mock tree. + nonisolated struct SafeDIMockConfiguration: Sendable { + init( + thumbnails: (@Sendable () -> Thumbnails)? = nil, + _ safeDIBuilder: (@Sendable (Thumbnails) -> PhotoLoader)? = nil + ) { + __safeDI_storage = __safeDI_Storage( + thumbnails: thumbnails, + safeDIBuilder: safeDIBuilder + ) + } + + var thumbnails: (@Sendable () -> Thumbnails)? { __safeDI_storage.thumbnails } + /// Overrides how this type is constructed. Parameters match the type’s initializer or custom mock method. When `nil`, the default generated construction function is used. + var safeDIBuilder: (@Sendable (Thumbnails) -> PhotoLoader)? { __safeDI_storage.safeDIBuilder } + + private let __safeDI_storage: __safeDI_Storage + + private final class __safeDI_Storage: Sendable { + init( + thumbnails: (@Sendable () -> Thumbnails)?, + safeDIBuilder: (@Sendable (Thumbnails) -> PhotoLoader)? + ) { + self.thumbnails = thumbnails + self.safeDIBuilder = safeDIBuilder + } + + let thumbnails: (@Sendable () -> Thumbnails)? + let safeDIBuilder: (@Sendable (Thumbnails) -> PhotoLoader)? + } + } + } + #endif + """, + "SafeDIMockConfiguration.swift": generatedFileHeader, + ]) + } + + @Test + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + mutating func mock_typesBuilderWithMockAttributes_whenSendableInstantiatorBuildsTypeWithMainActorHandWrittenMock() async throws { + // `SendableInstantiator` requires every construction in its subtree, a hand-written mock's included, to be callable + // outside any actor, which `PhotoLoader`'s main-actor hand-written mock is not: the generated `@Sendable` function + // that calls it does not compile, in every release, so this test checks the generated code without compiling it. + // The builder is typed with the main actor, as the hand-written mock it replaces is, so the configuration is + // isolated as the construction is; the shape is one `SendableInstantiator` does not support. + let output = try await executeSafeDIToolTest( + swiftFileContent: [ + """ + @Instantiable + public final class Thumbnails: Instantiable, Sendable { + public init() {} + } + """, + """ + @Instantiable(mockAttributes: "@MainActor") + public final class PhotoLoader: Instantiable, Sendable { + public init(thumbnails: Thumbnails) { + self.thumbnails = thumbnails + } + + @MainActor public static func mock(thumbnails: Thumbnails) -> PhotoLoader { + PhotoLoader(thumbnails: thumbnails) + } + + @Instantiated let thumbnails: Thumbnails + } + """, + """ + @Instantiable(mockAttributes: "@MainActor", generateMock: true) + public final class Gallery: Instantiable, Sendable { + public init(photoLoaderBuilder: SendableInstantiator) { + self.photoLoaderBuilder = photoLoaderBuilder + } + + @Instantiated let photoLoaderBuilder: SendableInstantiator + } + """, + ], + buildSwiftOutputDirectory: true, + filesToDelete: &filesToDelete, + skipCompileVerification: true, + ) + + #expect(output.generatedFiles == [ + "Gallery+SafeDIMock.swift": generatedFileHeader + """ + #if DEBUG + extension Gallery { + /// Overrides for the mock dependency tree. + struct SafeDIOverrides { + init( + photoLoaderBuilder: PhotoLoader.SafeDIMockConfiguration = .init() + ) { + __safeDI_storage = __safeDI_Storage( + photoLoaderBuilder: photoLoaderBuilder + ) + } + + var photoLoaderBuilder: PhotoLoader.SafeDIMockConfiguration { __safeDI_storage.photoLoaderBuilder } + + private let __safeDI_storage: __safeDI_Storage + + private final class __safeDI_Storage: Sendable { + init( + photoLoaderBuilder: PhotoLoader.SafeDIMockConfiguration + ) { + self.photoLoaderBuilder = photoLoaderBuilder + } + + let photoLoaderBuilder: PhotoLoader.SafeDIMockConfiguration + } + } + + @MainActor static func mock( + safeDIOverrides: SafeDIOverrides = .init() + ) -> Gallery { + let __safeDI_photoLoaderBuilder__overrides = safeDIOverrides.photoLoaderBuilder + @Sendable nonisolated func __safeDI_photoLoaderBuilder() -> PhotoLoader { + let thumbnails = if let safeDIBuilder = __safeDI_photoLoaderBuilder__overrides.thumbnails { safeDIBuilder() } else { Thumbnails() } + return if let safeDIBuilder = __safeDI_photoLoaderBuilder__overrides.safeDIBuilder { safeDIBuilder(thumbnails) } else { PhotoLoader.mock(thumbnails: thumbnails) } + } + let photoLoaderBuilder = SendableInstantiator(__safeDI_photoLoaderBuilder) + return Gallery(photoLoaderBuilder: photoLoaderBuilder) + } + } + #endif + """, + "SafeDIMockConfiguration.swift": generatedFileHeader + """ + #if DEBUG + extension PhotoLoader { + /// Configuration for how this type is constructed within a mock tree. + nonisolated struct SafeDIMockConfiguration: Sendable { + init( + thumbnails: (@Sendable () -> Thumbnails)? = nil, + _ safeDIBuilder: (@Sendable (Thumbnails) -> PhotoLoader)? = nil + ) { + __safeDI_storage = __safeDI_Storage( + thumbnails: thumbnails, + safeDIBuilder: safeDIBuilder + ) + } + + var thumbnails: (@Sendable () -> Thumbnails)? { __safeDI_storage.thumbnails } + /// Overrides how this type is constructed. Parameters match the type’s initializer or custom mock method. When `nil`, the default generated construction function is used. + var safeDIBuilder: (@Sendable (Thumbnails) -> PhotoLoader)? { __safeDI_storage.safeDIBuilder } + + private let __safeDI_storage: __safeDI_Storage + + private final class __safeDI_Storage: Sendable { + init( + thumbnails: (@Sendable () -> Thumbnails)?, + safeDIBuilder: (@Sendable (Thumbnails) -> PhotoLoader)? + ) { + self.thumbnails = thumbnails + self.safeDIBuilder = safeDIBuilder + } + + let thumbnails: (@Sendable () -> Thumbnails)? + let safeDIBuilder: (@Sendable (Thumbnails) -> PhotoLoader)? + } + } + } + #endif + + """, + ]) + } + + // MARK: Private + + private var filesToDelete: [URL] +} diff --git a/Tests/SafeDIToolTestSupport/GraphFuzzer.swift b/Tests/SafeDIToolTestSupport/GraphFuzzer.swift index fb74be7eed..d5a66d657d 100644 --- a/Tests/SafeDIToolTestSupport/GraphFuzzer.swift +++ b/Tests/SafeDIToolTestSupport/GraphFuzzer.swift @@ -2773,6 +2773,12 @@ enum GraphFuzzerGenerator { var isStruct = false /// Whether the type is an `actor` rather than a `final class`. var isActor = false + /// The global actor the type is isolated to, such as `@MainActor`, written before the type, or `nil`. + var globalActor: String? + /// Whether the initializer and the hand-written mock spell `globalActor` themselves, beside the type's. + var membersSpellGlobalActor = false + /// The class the type inherits from, listed before its conformances, whose `init()` its initializer calls, or `nil`. + var superclass: String? /// Declarations written before the type's own, in its file. var precedingDeclarations = [String]() /// Modules the type's file imports beyond those of its module's header. @@ -3082,6 +3088,7 @@ enum GraphFuzzerGenerator { renamedLazyReaderRandom = GraphFuzzerRandomNumberGenerator(seed: seed ^ Self.renamedLazyReaderRandomSeedMask) renameSplitRandom = GraphFuzzerRandomNumberGenerator(seed: seed ^ Self.renameSplitRandomSeedMask) lazyInstanceNamedApartRandom = GraphFuzzerRandomNumberGenerator(seed: seed ^ Self.lazyInstanceNamedApartRandomSeedMask) + mainActorBuilderRandom = GraphFuzzerRandomNumberGenerator(seed: seed ^ Self.mainActorBuilderRandomSeedMask) seamDependencyRandom = GraphFuzzerRandomNumberGenerator(seed: seed ^ GraphFuzzerSeamDependencyDraw.seamRandomSeedMask) prefix = GraphFuzzerFixture.typeNamePrefix(forSeed: seed) // One draw decides, so graphs that are not mixed draw exactly what they drew before mixed graphs existed. @@ -3183,6 +3190,8 @@ enum GraphFuzzerGenerator { finalDeclarations = addingErasedBuilderFirstReachingMockedType(to: finalDeclarations) // Drawn after it, from a stream of its own, so that every other draw of a graph it draws in is drawn as before. finalDeclarations = addingLazyInstanceReadBesideLabelNamedApart(to: finalDeclarations) + // Drawn after it, from a stream of its own, so that every other draw of a graph it draws in is drawn as before. + finalDeclarations = addingMainActorBuilderPassedFromPreview(to: finalDeclarations) // In a graph split across modules, every file names its module and imports the seam's, so that a type of the // caller can name what the seam's module declares, such as the creation stamps' counter. let isSplit = finalDeclarations.contains { $0.module == .seamModule } @@ -3723,6 +3732,9 @@ enum GraphFuzzerGenerator { /// Draws only `addingLazyInstanceReadBesideLabelNamedApart`'s choices: whether a graph gains `ApartScreen`'s tree, /// and every shape of that tree. private var lazyInstanceNamedApartRandom: GraphFuzzerRandomNumberGenerator + /// Draws only `addingMainActorBuilderPassedFromPreview`'s choices: whether a graph gains `MainLoader`'s mocks, and + /// every shape of them. + private var mainActorBuilderRandom: GraphFuzzerRandomNumberGenerator /// The files `markerFreeFileRandom` moved a declaration into: each named, holding the declaration alone, and in the /// module of the type, `ownerName`, whose file it was drawn in. private var markerFreeFiles = [(ownerName: String, fileName: String, declaration: String)]() @@ -9332,6 +9344,54 @@ enum GraphFuzzerGenerator { private static let lazyInstanceNamedApartRandomSeedMask: UInt64 = 0x4170617274 + // MARK: A main-actor builder a preview passes + + /// The base corpus's draw, in one graph of sixteen, of a closure a `@MainActor` preview passes for the builder of a + /// main-actor type that an actor's mock builds, which makes the type's override `@Sendable`. `MainLoader` is a + /// `@MainActor` class whose `mockAttributes` spell the main actor, now and then with a hand-written mock. + /// `MainLibrary`, an actor whose mock spells the main actor too, instantiates it, and so does a second mocked type: + /// - in one arm `MainShelf`, a `@MainActor` class whose mock spells the main actor, so every mock that builds the + /// loader spells it, while the loader's initializer and mock spell nothing of their own; + /// - in the other `MainScreen`, main-actor only through its superclass `MainScreenBase` and spelling no + /// `mockAttributes`, while the loader's initializer and hand-written mock spell `@MainActor` themselves. + /// The preview, which the compile adds beside the generated code (`GraphFuzzerMainActorPreview`), passes closures + /// that touch main-actor state, `MainPainter`'s, so they compile only where the builder is isolated to the main + /// actor, as 2.2.0 typed it and 2.4.5 did not. `mainActorBuilderRandom` draws only for this pass, after every + /// other, and only in the base corpus. A fixture drawn for comparison with an older release omits it, since 2.3.0 + /// rejects its actor. + private mutating func addingMainActorBuilderPassedFromPreview(to declarations: [TypeDeclaration]) -> [TypeDeclaration] { + guard !omitsDrawsOlderReleasesReject, features.isEmpty, mainActorBuilderRandom.percentChance(6) else { return declarations } + var declarations = declarations + let constructionsSpellIsolation = mainActorBuilderRandom.percentChance(50) + let hasHandWrittenMock = mainActorBuilderRandom.percentChance(50) + let loaderName = "\(prefix)MainLoader" + let painterName = "\(prefix)MainPainter" + let libraryName = "\(prefix)MainLibrary" + let secondName = constructionsSpellIsolation ? "\(prefix)MainScreen" : "\(prefix)MainShelf" + let loaderProperty = PropertyDeclaration(attribute: "@Instantiated", label: "mainLoader", type: loaderName) + var loader = TypeDeclaration(name: loaderName, instantiableArguments: ["mockAttributes: \"@MainActor\""], properties: [], declaresHelperTypes: false) + loader.globalActor = "@MainActor" + loader.membersSpellGlobalActor = constructionsSpellIsolation + loader.handWrittenMockName = hasHandWrittenMock ? "mock" : nil + loader.additionalDeclarations = ["@MainActor\npublic final class \(painterName) {\n\tpublic init() {}\n\tpublic func paint() -> Int { 1 }\n}"] + declarations.append(loader) + var library = TypeDeclaration(name: libraryName, instantiableArguments: ["mockAttributes: \"@MainActor\"", "generateMock: true"], properties: [loaderProperty], declaresHelperTypes: false) + library.isActor = true + declarations.append(library) + var second = TypeDeclaration(name: secondName, instantiableArguments: ["generateMock: true"], properties: [loaderProperty], declaresHelperTypes: false) + if constructionsSpellIsolation { + second.superclass = "\(prefix)MainScreenBase" + second.precedingDeclarations = ["@MainActor\nopen class \(prefix)MainScreenBase {\n\tpublic init() {}\n}"] + } else { + second.instantiableArguments.insert("mockAttributes: \"@MainActor\"", at: 0) + second.globalActor = "@MainActor" + } + declarations.append(second) + return declarations + } + + private static let mainActorBuilderRandomSeedMask: UInt64 = 0x4D61696E4163 + // MARK: A rename fulfilled by a value and by a wrapper /// The base corpus's draw, in one graph of sixteen, of one type whose rename is fulfilled by a label one parent @@ -12013,8 +12073,10 @@ enum GraphFuzzerGenerator { case (.nonSendable, false), (.mixed, false): "Instantiable" } - let conformances = ([baseConformances] + declaration.additionalConformances).joined(separator: ", ") - var lines = [instantiableAttribute, "\(declaration.access.modifier)\(declaration.isStruct ? "struct" : declaration.isActor ? "actor" : "final class") \(declaration.name): \(conformances) {"] + let conformances = ((declaration.superclass.map { [$0] } ?? []) + [baseConformances] + declaration.additionalConformances).joined(separator: ", ") + let memberGlobalActor = declaration.membersSpellGlobalActor ? declaration.globalActor.map { "\($0) " } ?? "" : "" + let superInitialization = declaration.superclass == nil ? [String]() : ["\t\tsuper.init()"] + var lines = (declaration.globalActor.map { [$0] } ?? []) + [instantiableAttribute, "\(declaration.access.modifier)\(declaration.isStruct ? "struct" : declaration.isActor ? "actor" : "final class") \(declaration.name): \(conformances) {"] // A function-typed parameter is stored, so it escapes. let parameters = (declaration.properties.map { "\($0.label): \(GraphFuzzerSpelling.escapingType(of: $0.type))" } + declaration.defaultValuedParameters.map(\.declaration)).joined(separator: ", ") // The initializer is no wider, once its type caps it, than the narrowest type it names, so that the fixture @@ -12025,12 +12087,13 @@ enum GraphFuzzerGenerator { let storedParameters = storesEveryParameter ? declaration.defaultValuedParameters.filter(\.isStored) : [] if let guardedMockParameter = declaration.guardedMockParameter { lines += guardedMockParameter.bodyLines(ofTypeNamed: declaration.name) - } else if declaration.properties.isEmpty, storedParameters.isEmpty { - lines.append("\t\(initializerAccess.modifier)init(\(parameters)) {}") + } else if declaration.properties.isEmpty, storedParameters.isEmpty, superInitialization.isEmpty { + lines.append("\t\(memberGlobalActor)\(initializerAccess.modifier)init(\(parameters)) {}") } else { - lines.append("\t\(initializerAccess.modifier)init(\(parameters)) {") + lines.append("\t\(memberGlobalActor)\(initializerAccess.modifier)init(\(parameters)) {") lines += declaration.properties.map { "\t\tself.\($0.label) = \($0.label)" } lines += storedParameters.map { "\t\tself.\($0.name) = \($0.name)" } + lines += superInitialization lines.append("\t}") lines.append("") lines += declaration.properties.map { "\t\($0.attribute) let \($0.label): \($0.type)" } @@ -12043,7 +12106,7 @@ enum GraphFuzzerGenerator { lines += [ "", "\t#if DEBUG", - "\t\(initializerAccess.modifier)static func \(handWrittenMockName)(\(parameters)) -> \(declaration.name) {", + "\t\(memberGlobalActor)\(initializerAccess.modifier)static func \(handWrittenMockName)(\(parameters)) -> \(declaration.name) {", "\t\t\(declaration.name)(\(arguments.joined(separator: ", ")))", "\t}", "\t#endif", @@ -19631,7 +19694,11 @@ enum GraphFuzzerOracle { let fileModules = runs.fixture.modules ?? Array(repeating: .seamModule, count: runs.fixture.swiftFileContent.count) // The hand-written calls `C` of each seam's readable initializer compile with the generated code; the outcomes the // other oracles compare hold none. - let generatedFilesWithCalls = GraphFuzzerBuilderSurface.addingBuilderCalls(to: runs.generatedFiles, seamTypeAccess: runs.fixture.seamTypeAccess, modules: Set(runs.fixture.modules ?? [])) + // The preview of `addingMainActorBuilderPassedFromPreview`'s draw calls the generated mocks, so it compiles with them. + let generatedFilesWithCalls = GraphFuzzerMainActorPreview.addingPreview( + to: GraphFuzzerBuilderSurface.addingBuilderCalls(to: runs.generatedFiles, seamTypeAccess: runs.fixture.seamTypeAccess, modules: Set(runs.fixture.modules ?? [])), + of: runs.fixture, + ) // A type a module's generated code declares once for the module at file scope, such as the plain form of the // places a mock's cycles enter (`__safeDI_Place`), carries no graph's prefix, so two such graphs in one // invocation would declare it twice: the graph compiles in an invocation of its own. @@ -20032,3 +20099,37 @@ enum GraphFuzzerHostedHomes { return (separated, homesByModule.mapValues { $0.sorted() }) } } + +/// The preview a person writes for the mocks of the base corpus's draw of a main-actor builder +/// (`addingMainActorBuilderPassedFromPreview`): a `@MainActor` function that passes each mock a closure for +/// `MainLoader`'s builder that touches `MainPainter`'s main-actor state and builds the loader with its hand-written mock or +/// its initializer. It calls the generated mocks, so it compiles beside the generated code, never with the fixture alone. +enum GraphFuzzerMainActorPreview { + /// `generatedFiles` with the preview, in a file named after the graph's prefix, where `fixture` holds the draw in one + /// module and the tool generated code for it; `generatedFiles` unchanged otherwise. + static func addingPreview(to generatedFiles: [String: String], of fixture: GraphFuzzerFixture) -> [String: String] { + let prefix = fixture.typeNamePrefix + guard fixture.modules == nil, + generatedFiles.keys.contains(where: { $0.hasPrefix("\(prefix)MainLibrary+") }), + let loaderFile = fixture.swiftFileContent.first(where: { $0.contains("final class \(prefix)MainLoader:") }) + else { return generatedFiles } + let secondName = fixture.swiftFileContent.contains { $0.contains("final class \(prefix)MainScreen:") } ? "\(prefix)MainScreen" : "\(prefix)MainShelf" + let build = loaderFile.contains("static func mock(") ? "\(prefix)MainLoader.mock()" : "\(prefix)MainLoader()" + let closure = "{\n\t\t\t_ = painter.paint()\n\t\t\treturn \(build)\n\t\t}" + var withPreview = generatedFiles + withPreview["\(prefix)MainPreview.swift"] = [ + "#if DEBUG", + "@MainActor", + "func \(prefix)mainPreview() -> (\(prefix)MainLibrary, \(secondName)) {", + "\tlet painter = \(prefix)MainPainter()", + "\treturn (", + "\t\t\(prefix)MainLibrary.mock(safeDIOverrides: .init(mainLoader: \(closure))),", + "\t\t\(secondName).mock(safeDIOverrides: .init(mainLoader: \(closure))),", + "\t)", + "}", + "#endif", + "", + ].joined(separator: "\n") + return withPreview + } +} diff --git a/Tests/SafeDIToolTestSupport/GraphFuzzerMockMirrors.swift b/Tests/SafeDIToolTestSupport/GraphFuzzerMockMirrors.swift index 2cb9b56256..f7e39b6102 100644 --- a/Tests/SafeDIToolTestSupport/GraphFuzzerMockMirrors.swift +++ b/Tests/SafeDIToolTestSupport/GraphFuzzerMockMirrors.swift @@ -901,6 +901,10 @@ enum GraphFuzzerMirrorSkip: String, CaseIterable, Comparable { /// its chain, nothing builds: a mock binds every property its tree receives only if available, to an override, so /// it creates the alias, which production does not create, and rejects the receive. case requiredReceiveOfUncreatedAlias + /// The mocked type is one of the base corpus's draw of a main-actor builder (`addingMainActorBuilderPassedFromPreview`), + /// whose tree builds `MainLoader`, whose initializer only a main-actor caller may call: a mirror, a nonisolated root, + /// cannot build it. The preview the compile adds judges that draw. + case mainActorBuilderDraw static func < (lhs: GraphFuzzerMirrorSkip, rhs: GraphFuzzerMirrorSkip) -> Bool { lhs.rawValue < rhs.rawValue @@ -1763,6 +1767,10 @@ struct GraphFuzzerValueOraclePlan { modelFailures.append(disagreement) continue } + guard !["MainLibrary", "MainShelf", "MainScreen"].contains(where: { typeName == fixture.typeNamePrefix + $0 }) else { + skips.append((typeName, .mainActorBuilderDraw)) + continue + } // The mock's required parameters are handed sample values, which the mirror forwards. let requiredParameters = GraphFuzzerMockOverrides.requiredParameters(mockFile) let mockArguments = requiredParameters.map { parameter in samples.expression(ofType: parameter.type).map { "\(parameter.label): \($0)" } }