From bcda4769a79bc5d2ad43862b6e815ce6a2111712 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 08:22:17 +0000 Subject: [PATCH 1/8] Type a mock builder with the mockAttributes its construction spells A builder in a mock's overrides replaces how a type is built. It is now typed with those of the type's mockAttributes that its initializer or hand-written mock spells too, so a closure a preview passes runs in that construction's isolation. Before, an actor mock root made the type's configuration @Sendable module-wide, and a closure that called a @MainActor hand-written mock stopped compiling, though it compiled on 2.2.0. A public configuration, whose one builder serves both of the type's constructions, spells only what both spell. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HLuVQL2AyjmTVDPHyoJd4Z --- Documentation/Manual.md | 2 + .../MockLowering+PublicConfigurations.swift | 27 +- .../Generators/MockLowering+Walk.swift | 41 +- .../SafeDICore/Generators/MockLowering.swift | 6 +- .../NodeRecords/NodeRecords+Loops.swift | 2 +- .../NodeRecords+MockConstruction.swift | 2 +- .../NodeRecords+PublicMockActor.swift | 2 +- .../NodeRecords+PublicMockRoot.swift | 2 +- .../SafeDIToolMockBuilderIsolationTests.swift | 524 ++++++++++++++++++ 9 files changed, 597 insertions(+), 11 deletions(-) create mode 100644 Tests/SafeDIToolMockTests/SafeDIToolMockBuilderIsolationTests.swift diff --git a/Documentation/Manual.md b/Documentation/Manual.md index de9b90fad4..2648aab0b2 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 those of the type’s `mockAttributes` that its initializer or hand-written mock spells too, so a closure you pass for it, such as `.init({ .mock() })` in a preview, runs in that construction’s isolation. SafeDI cannot apply an attribute the construction does not spell, such as `@MainActor` on a type whose `nonisolated` initializer a `SendableInstantiator` calls: the mock calls the builder wherever it would call the construction, which can be outside that actor. + `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/MockLowering+PublicConfigurations.swift b/Sources/SafeDICore/Generators/MockLowering+PublicConfigurations.swift index 02aab9cf27..e6f02353ac 100644 --- a/Sources/SafeDICore/Generators/MockLowering+PublicConfigurations.swift +++ b/Sources/SafeDICore/Generators/MockLowering+PublicConfigurations.swift @@ -104,11 +104,14 @@ extension MockLowering { let structRecord = typeRecords.first(where: \.describesConfiguration) ?? typeRecords.first(where: { !$0.usesMockInitializer }) ?? typeRecords.first, let configurationTypeName = context.configurationTypeNameByType[type] else { continue } + // The configuration's one builder is handed to every construction function, so it spells only the attributes + // each of those constructions spells. + let sharedBuilderAttributes = structRecord.builderAttributes(sharedWith: typeRecords) let constructionRecords = [false, true].compactMap { usesMockInitializer in - typeRecords.first { $0.usesMockInitializer == usesMockInitializer } + typeRecords.first { $0.usesMockInitializer == usesMockInitializer }.map { $0.withBuilderAttributes(sharedBuilderAttributes) } } declarations.append(publicConfigurationDeclaration( - of: structRecord, + of: structRecord.withBuilderAttributes(sharedBuilderAttributes), constructionRecords: constructionRecords, configurationTypeName: configurationTypeName, context: context, @@ -294,6 +297,7 @@ extension MockLowering.PublicConstructionRecord { childMembers: childMembers, defaultFields: defaultFields, ) + builderAttributes = MockBuilderIsolation.attributes(of: instantiable, usesMockInitializer: usesMockInitializer) } /// The name of the construction function: `__safeDI_mock` for the hand-written mock, else `__safeDI_init`. @@ -304,10 +308,25 @@ extension MockLowering.PublicConstructionRecord { /// The name of the construction function that builds the type with its initializer. static let initializerFunctionName = "\(ReservedName.builderFunctionNamePrefix)init" + /// The attributes of `builderAttributes` that each of `records` spells too, in this record’s order. + func builderAttributes(sharedWith records: [Self]) -> String { + let spelledByEach = records.map { Set($0.builderAttributes.split(separator: " ")) } + return builderAttributes.split(separator: " ") + .filter { attribute in spelledByEach.allSatisfy { $0.contains(attribute) } } + .joined(separator: " ") + } + + /// This record with its builder spelling `attributes`. + func withBuilderAttributes(_ attributes: String) -> Self { + var record = self + record.builderAttributes = attributes + return record + } + /// The type of the builder that overrides the construction: optional, handed each argument, returning the concrete type, - /// `@Sendable` where the configuration is `@Sendable`-typed. + /// `@Sendable` where the configuration is `@Sendable`-typed, and spelling `builderAttributes`. func builderType(requiresSendable: Bool) -> String { - "(\(requiresSendable ? "@Sendable " : "")(\(builderParameterTypes.map { sending($0.asSource) }.joined(separator: ", "))) -> \(concreteType.asSource))?" + "(\(requiresSendable ? "@Sendable " : "")\(MockLowering.BuilderParameters.attributesPrefix(builderAttributes))(\(builderParameterTypes.map { sending($0.asSource) }.joined(separator: ", "))) -> \(concreteType.asSource))?" } /// `parameter` spelled `sending` where the construction is an actor's initializer. diff --git a/Sources/SafeDICore/Generators/MockLowering+Walk.swift b/Sources/SafeDICore/Generators/MockLowering+Walk.swift index 1449236a0b..2b715e05aa 100644 --- a/Sources/SafeDICore/Generators/MockLowering+Walk.swift +++ b/Sources/SafeDICore/Generators/MockLowering+Walk.swift @@ -1655,7 +1655,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, usesMockInitializer: usesMockInitializer)))(\(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 +2158,19 @@ extension MockLowering { arguments = (usesMockInitializer ? instantiable.mockInitializer : instantiable.initializer)?.arguments ?? [] dependencies = instantiable.dependencies sendsArguments = instantiable.declarationType == .actorType && !usesMockInitializer + isolation = MockBuilderIsolation.attributes(of: instantiable, usesMockInitializer: usesMockInitializer) + } + + /// 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 +2190,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 +2208,27 @@ extension MockLowering { return bindingNamesPassedByName } } + +/// The attributes a builder closure type of a mock spells: those of the built type's `mockAttributes` that the construction +/// the builder replaces spells too, the initializer, `instantiate(…)` or hand-written mock a mock calls where no builder is +/// given, so that a closure a caller writes for the builder, such as a preview's, is isolated as that construction is. Every +/// place that calls the builder calls that construction where it is `nil`, so a builder isolated so is callable wherever the +/// construction is, and a type whose construction spells no isolation, such as a `nonisolated` initializer of a type built +/// inside a `@Sendable` function, keeps a builder without attributes. Only an attribute without arguments is spelled, as a +/// global actor is: a closure type takes no declaration attribute, such as `@available(…)`. +enum MockBuilderIsolation { + /// The attributes a builder closure type of `instantiable`'s type spells, built with its hand-written mock where + /// `usesMockInitializer` and the type has one, else with its initializer, as `ScopeGenerator.MockConstruction` builds it. + static func attributes(of instantiable: Instantiable, usesMockInitializer: Bool) -> String { + let construction = if usesMockInitializer, let mockInitializer = instantiable.mockInitializer { + mockInitializer + } else { + instantiable.initializer + } + guard let constructionAttributes = construction?.spelledAttributes.map({ Set($0.split(separator: " ")) }) else { return "" } + return instantiable.mockAttributes + .split(separator: " ") + .filter { $0.hasPrefix("@") && !$0.contains("(") && constructionAttributes.contains($0) } + .joined(separator: " ") + } +} diff --git a/Sources/SafeDICore/Generators/MockLowering.swift b/Sources/SafeDICore/Generators/MockLowering.swift index b33b54187f..b3a60c9268 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): @@ -171,6 +171,8 @@ public enum MockLowering { let constructionAttributes: String? /// What the construction returns: the concrete type, or what a hand-written mock returns. let constructionReturnType: TypeDescription + /// The attributes the builder that overrides the construction spells (`MockBuilderIsolation.attributes(of:)`). + var builderAttributes = "" /// Whether the construction is an actor's initializer, which takes each argument into the actor's isolation: the /// construction function takes each `sending`, and so does the builder that overrides it /// (`MockLowering.BuilderParameters`). 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/SafeDIToolMockTests/SafeDIToolMockBuilderIsolationTests.swift b/Tests/SafeDIToolMockTests/SafeDIToolMockBuilderIsolationTests.swift new file mode 100644 index 0000000000..0eddc0280f --- /dev/null +++ b/Tests/SafeDIToolMockTests/SafeDIToolMockBuilderIsolationTests.swift @@ -0,0 +1,524 @@ +// 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 Foundation +import SafeDICore +import Testing +@testable import SafeDIToolLibrary +@testable import SafeDIToolTestSupport + +/// A builder in a mock's overrides that replaces how a type is built is typed with those of the type's `mockAttributes` that +/// its construction spells too, so a closure a caller writes for it, such as a preview's `.init({ .mock() })`, is isolated +/// as that construction is, also where the configuration takes the `Sendable` form because an actor's mock builds the type +/// for its initializer. A construction that spells no isolation, such as a `nonisolated` initializer a `SendableInstantiator` +/// calls inside a `@Sendable` function, keeps a builder without attributes, which that function can call. +struct SafeDIToolMockBuilderIsolationTests: ~Copyable { + // MARK: Initialization + + init() throws { + filesToDelete = [URL]() + } + + deinit { + for fileToDelete in filesToDelete { + try! FileManager.default.removeItem(at: fileToDelete) + } + } + + // MARK: Tests + + @Test + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + mutating func mock_typesBuilderWithMockAttributes_whenActorMockMakesConfigurationSendable() async throws { + // `ProfileStore`'s mock builds `PhotoLoader` for the actor's initializer, which makes `PhotoLoader`'s configuration + // take the `Sendable` form in every mock of the module. `GalleryScreen`'s preview overrides its `PhotoLoader` with + // the main-actor hand-written mock, which compiles only where the builder is isolated to the main actor. + 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 actor ProfileStore: Instantiable { + @MainActor public init(photoLoader: PhotoLoader) { + self.photoLoader = photoLoader + } + + @Instantiated let photoLoader: PhotoLoader + } + """, + """ + @MainActor + @Instantiable(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 + } + } + + 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_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 @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 + + """, + ]) + } + + // MARK: Private + + private var filesToDelete: [URL] +} From 1343cf84cd27e6023a764d3e7ad38380081641b8 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 09:29:07 +0000 Subject: [PATCH 2/8] Format the builder isolation tests Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HLuVQL2AyjmTVDPHyoJd4Z --- .../SafeDIToolMockBuilderIsolationTests.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Tests/SafeDIToolMockTests/SafeDIToolMockBuilderIsolationTests.swift b/Tests/SafeDIToolMockTests/SafeDIToolMockBuilderIsolationTests.swift index 0eddc0280f..13756df91a 100644 --- a/Tests/SafeDIToolMockTests/SafeDIToolMockBuilderIsolationTests.swift +++ b/Tests/SafeDIToolMockTests/SafeDIToolMockBuilderIsolationTests.swift @@ -224,7 +224,7 @@ struct SafeDIToolMockBuilderIsolationTests: ~Copyable { } } #endif - + """, ]) } @@ -513,7 +513,7 @@ struct SafeDIToolMockBuilderIsolationTests: ~Copyable { } } #endif - + """, ]) } From 12731a7d2548e56cce62e62f538b76b9f9a9481f Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 10:03:37 +0000 Subject: [PATCH 3/8] Type a mock builder with mockAttributes only where every caller spells them The rule now compares only what the user spelled in mockAttributes: a builder takes its type's mockAttributes when every mock root in the module that reaches the type spells the same ones, and no Sendable wrapper, public mock or seam reaches it. A closure passed in from a preview has no generated caller, so it does not count. Every other builder stays as before. Only attributes a closure type takes are carried; @available stays on the declarations. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HLuVQL2AyjmTVDPHyoJd4Z --- Documentation/Manual.md | 2 +- ...dencyTreeGenerator+MockOrchestration.swift | 21 ++++ .../MockLowering+PublicConfigurations.swift | 27 +--- .../Generators/MockLowering+Walk.swift | 108 +++++++++++++--- .../SafeDICore/Generators/MockLowering.swift | 2 - .../SafeDIToolMockBuilderIsolationTests.swift | 118 ++++++++++++++++-- 6 files changed, 225 insertions(+), 53 deletions(-) diff --git a/Documentation/Manual.md b/Documentation/Manual.md index 2648aab0b2..61b3e5ce02 100644 --- a/Documentation/Manual.md +++ b/Documentation/Manual.md @@ -324,7 +324,7 @@ 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 those of the type’s `mockAttributes` that its initializer or hand-written mock spells too, so a closure you pass for it, such as `.init({ .mock() })` in a preview, runs in that construction’s isolation. SafeDI cannot apply an attribute the construction does not spell, such as `@MainActor` on a type whose `nonisolated` initializer a `SendableInstantiator` calls: the mock calls the builder wherever it would call the construction, which can be outside that actor. +A builder in a mock’s overrides that replaces how a type is built is typed with the type’s `mockAttributes`, such as `@MainActor`, when every mock in the module that builds the type spells the same `mockAttributes`, so a closure you pass for it, such as `.init({ .mock() })` in a preview, runs in that isolation. SafeDI reads isolation only from `mockAttributes`, never from a type’s or an initializer’s declaration, so spell `mockAttributes` on the type and on the mocks that build it. A builder keeps no attributes where a mock that builds the type spells others, or where a `Sendable` wrapper such as `SendableInstantiator`, a public mock or a seam builds it, 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. diff --git a/Sources/SafeDICore/Generators/DependencyTreeGenerator+MockOrchestration.swift b/Sources/SafeDICore/Generators/DependencyTreeGenerator+MockOrchestration.swift index 002f5a0e65..85c0acacd8 100644 --- a/Sources/SafeDICore/Generators/DependencyTreeGenerator+MockOrchestration.swift +++ b/Sources/SafeDICore/Generators/DependencyTreeGenerator+MockOrchestration.swift @@ -29,6 +29,27 @@ 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. + try await MockBuilderIsolation.$isolatedTypes.withValue(MockBuilderIsolation.isolatedTypes(among: typeDescriptionToFulfillingInstantiableMap, additionalMocksToGenerate: additionalMocksToGenerate)) { + try await generateMockCodeChoosingRecords( + mockConditionalCompilation: mockConditionalCompilation, + currentModuleSourceFilePaths: currentModuleSourceFilePaths, + additionalMocksToGenerate: additionalMocksToGenerate, + storesPublicMockPlans: storesPublicMockPlans, + publicMockContext: publicMockContext, + ) + } + } + + /// `generateMockCode(mockConditionalCompilation:currentModuleSourceFilePaths:additionalMocksToGenerate:storesPublicMockPlans:publicMockContext:)` + /// with the module's isolated builders set. + 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+PublicConfigurations.swift b/Sources/SafeDICore/Generators/MockLowering+PublicConfigurations.swift index e6f02353ac..02aab9cf27 100644 --- a/Sources/SafeDICore/Generators/MockLowering+PublicConfigurations.swift +++ b/Sources/SafeDICore/Generators/MockLowering+PublicConfigurations.swift @@ -104,14 +104,11 @@ extension MockLowering { let structRecord = typeRecords.first(where: \.describesConfiguration) ?? typeRecords.first(where: { !$0.usesMockInitializer }) ?? typeRecords.first, let configurationTypeName = context.configurationTypeNameByType[type] else { continue } - // The configuration's one builder is handed to every construction function, so it spells only the attributes - // each of those constructions spells. - let sharedBuilderAttributes = structRecord.builderAttributes(sharedWith: typeRecords) let constructionRecords = [false, true].compactMap { usesMockInitializer in - typeRecords.first { $0.usesMockInitializer == usesMockInitializer }.map { $0.withBuilderAttributes(sharedBuilderAttributes) } + typeRecords.first { $0.usesMockInitializer == usesMockInitializer } } declarations.append(publicConfigurationDeclaration( - of: structRecord.withBuilderAttributes(sharedBuilderAttributes), + of: structRecord, constructionRecords: constructionRecords, configurationTypeName: configurationTypeName, context: context, @@ -297,7 +294,6 @@ extension MockLowering.PublicConstructionRecord { childMembers: childMembers, defaultFields: defaultFields, ) - builderAttributes = MockBuilderIsolation.attributes(of: instantiable, usesMockInitializer: usesMockInitializer) } /// The name of the construction function: `__safeDI_mock` for the hand-written mock, else `__safeDI_init`. @@ -308,25 +304,10 @@ extension MockLowering.PublicConstructionRecord { /// The name of the construction function that builds the type with its initializer. static let initializerFunctionName = "\(ReservedName.builderFunctionNamePrefix)init" - /// The attributes of `builderAttributes` that each of `records` spells too, in this record’s order. - func builderAttributes(sharedWith records: [Self]) -> String { - let spelledByEach = records.map { Set($0.builderAttributes.split(separator: " ")) } - return builderAttributes.split(separator: " ") - .filter { attribute in spelledByEach.allSatisfy { $0.contains(attribute) } } - .joined(separator: " ") - } - - /// This record with its builder spelling `attributes`. - func withBuilderAttributes(_ attributes: String) -> Self { - var record = self - record.builderAttributes = attributes - return record - } - /// The type of the builder that overrides the construction: optional, handed each argument, returning the concrete type, - /// `@Sendable` where the configuration is `@Sendable`-typed, and spelling `builderAttributes`. + /// `@Sendable` where the configuration is `@Sendable`-typed. func builderType(requiresSendable: Bool) -> String { - "(\(requiresSendable ? "@Sendable " : "")\(MockLowering.BuilderParameters.attributesPrefix(builderAttributes))(\(builderParameterTypes.map { sending($0.asSource) }.joined(separator: ", "))) -> \(concreteType.asSource))?" + "(\(requiresSendable ? "@Sendable " : "")(\(builderParameterTypes.map { sending($0.asSource) }.joined(separator: ", "))) -> \(concreteType.asSource))?" } /// `parameter` spelled `sending` where the construction is an actor's initializer. diff --git a/Sources/SafeDICore/Generators/MockLowering+Walk.swift b/Sources/SafeDICore/Generators/MockLowering+Walk.swift index 2b715e05aa..e7c6102536 100644 --- a/Sources/SafeDICore/Generators/MockLowering+Walk.swift +++ b/Sources/SafeDICore/Generators/MockLowering+Walk.swift @@ -1655,7 +1655,7 @@ extension MockLowering { /// The type of the closure that overrides how the node is built, handed the values its initializer takes. var builderClosureType: String { - "\(BuilderParameters.attributesPrefix(MockBuilderIsolation.attributes(of: instantiable, usesMockInitializer: usesMockInitializer)))(\(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,7 +2158,7 @@ extension MockLowering { arguments = (usesMockInitializer ? instantiable.mockInitializer : instantiable.initializer)?.arguments ?? [] dependencies = instantiable.dependencies sendsArguments = instantiable.declarationType == .actorType && !usesMockInitializer - isolation = MockBuilderIsolation.attributes(of: instantiable, usesMockInitializer: usesMockInitializer) + isolation = MockBuilderIsolation.attributes(of: instantiable) } /// The closure type of a builder handed these parameters and returning `returnType`: spelled with the type's @@ -2209,26 +2209,94 @@ extension MockLowering { } } -/// The attributes a builder closure type of a mock spells: those of the built type's `mockAttributes` that the construction -/// the builder replaces spells too, the initializer, `instantiate(…)` or hand-written mock a mock calls where no builder is -/// given, so that a closure a caller writes for the builder, such as a preview's, is isolated as that construction is. Every -/// place that calls the builder calls that construction where it is `nil`, so a builder isolated so is callable wherever the -/// construction is, and a type whose construction spells no isolation, such as a `nonisolated` initializer of a type built -/// inside a `@Sendable` function, keeps a builder without attributes. Only an attribute without arguments is spelled, as a -/// global actor is: a closure type takes no declaration attribute, such as `@available(…)`. +/// The attributes a builder closure type of a mock spells: the built type's `mockAttributes`, where every generated +/// function in the module that calls the builder spells those attributes too, so that a closure a caller writes for the +/// builder, such as a preview's, runs in the isolation the user spelled; 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` only, +/// never from a type's or an initializer's declaration. +/// +/// 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 a type has an isolated builder where every mock root of the module that reaches it +/// through `@Instantiated` dependencies spells the type's `mockAttributes`, 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 a builder closure type of `instantiable`'s type spells, built with its hand-written mock where - /// `usesMockInitializer` and the type has one, else with its initializer, as `ScopeGenerator.MockConstruction` builds it. - static func attributes(of instantiable: Instantiable, usesMockInitializer: Bool) -> String { - let construction = if usesMockInitializer, let mockInitializer = instantiable.mockInitializer { - mockInitializer - } else { - instantiable.initializer - } - guard let constructionAttributes = construction?.spelledAttributes.map({ Set($0.split(separator: " ")) }) else { return "" } - return instantiable.mockAttributes + /// The concrete types whose builders spell their `mockAttributes`, for the module whose mocks are being generated + /// (`isolatedTypes(among:)`); empty outside mock generation. + @TaskLocal static var isolatedTypes = Set() + + /// The attributes a builder closure type of `instantiable`'s type spells. + static func attributes(of instantiable: Instantiable) -> String { + guard isolatedTypes.contains(instantiable.concreteInstantiable) else { return "" } + return closureAttributes(of: instantiable.mockAttributes) + } + + /// The attributes of `attributes` a closure type can spell, in their order. + static func closureAttributes(of attributes: String) -> String { + attributes .split(separator: " ") - .filter { $0.hasPrefix("@") && !$0.contains("(") && constructionAttributes.contains($0) } + .filter { $0.hasPrefix("@") && !$0.contains("(") && !declarationOnlyAttributes.contains(String($0.dropFirst())) } .joined(separator: " ") } + + /// 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 concrete types of `instantiables`, the module's by the types they fulfill, whose builders spell their + /// `mockAttributes`, where the mock roots are the types that generate a mock and those `additionalMocksToGenerate` + /// names. Linear in the module's declarations and dependencies, times the few distinct attribute spellings of its mock + /// roots. + static func isolatedTypes(among instantiables: [TypeDescription: Instantiable], additionalMocksToGenerate: Set) -> Set { + var instantiableByConcreteType = [TypeDescription: Instantiable]() + for instantiable in instantiables.values { + instantiableByConcreteType[instantiable.concreteInstantiable] = instantiable + } + // Each type's `@Instantiated` children, with whether a `Sendable` wrapper builds the child. + var childrenByType = [TypeDescription: [(type: TypeDescription, isSendable: Bool)]]() + for (type, instantiable) in instantiableByConcreteType { + childrenByType[type] = instantiable.dependencies.compactMap { dependency in + guard case .instantiated = dependency.source, let child = instantiables[dependency.asInstantiatedType] else { return nil } + return (type: child.concreteInstantiable, isSendable: dependency.property.propertyType.isSendable) + } + } + // What a `Sendable` wrapper, a public mock or a seam reaches, whose builders keep no attributes. + var excluded = Set() + var pending = [TypeDescription]() + for (type, instantiable) in instantiableByConcreteType { + if instantiable.generateMock == .public || instantiable.generatesDependencyTree { + pending.append(type) + } + for child in childrenByType[type] ?? [] where child.isSendable { + pending.append(child.type) + } + } + while let type = pending.popLast() { + guard excluded.insert(type).inserted else { continue } + pending += (childrenByType[type] ?? []).map(\.type) + } + // 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 instantiableByConcreteType where instantiable.generatesMock || additionalMocksToGenerate.contains(type.asSource) { + reached.append((type: type, attributes: closureAttributes(of: instantiable.mockAttributes))) + } + while let (type, attributes) = reached.popLast() { + guard callerAttributesByType[type, default: []].insert(attributes).inserted else { continue } + reached += (childrenByType[type] ?? []).map { (type: $0.type, attributes: attributes) } + } + var isolatedTypes = Set() + for (type, instantiable) in instantiableByConcreteType where !excluded.contains(type) { + guard let callerAttributes = callerAttributesByType[type] else { continue } + let attributes = closureAttributes(of: instantiable.mockAttributes) + if !attributes.isEmpty, callerAttributes == [attributes] { + isolatedTypes.insert(type) + } + } + return isolatedTypes + } } diff --git a/Sources/SafeDICore/Generators/MockLowering.swift b/Sources/SafeDICore/Generators/MockLowering.swift index b3a60c9268..b285dbb302 100644 --- a/Sources/SafeDICore/Generators/MockLowering.swift +++ b/Sources/SafeDICore/Generators/MockLowering.swift @@ -171,8 +171,6 @@ public enum MockLowering { let constructionAttributes: String? /// What the construction returns: the concrete type, or what a hand-written mock returns. let constructionReturnType: TypeDescription - /// The attributes the builder that overrides the construction spells (`MockBuilderIsolation.attributes(of:)`). - var builderAttributes = "" /// Whether the construction is an actor's initializer, which takes each argument into the actor's isolation: the /// construction function takes each `sending`, and so does the builder that overrides it /// (`MockLowering.BuilderParameters`). diff --git a/Tests/SafeDIToolMockTests/SafeDIToolMockBuilderIsolationTests.swift b/Tests/SafeDIToolMockTests/SafeDIToolMockBuilderIsolationTests.swift index 13756df91a..7738c9af5f 100644 --- a/Tests/SafeDIToolMockTests/SafeDIToolMockBuilderIsolationTests.swift +++ b/Tests/SafeDIToolMockTests/SafeDIToolMockBuilderIsolationTests.swift @@ -48,7 +48,8 @@ struct SafeDIToolMockBuilderIsolationTests: ~Copyable { mutating func mock_typesBuilderWithMockAttributes_whenActorMockMakesConfigurationSendable() async throws { // `ProfileStore`'s mock builds `PhotoLoader` for the actor's initializer, which makes `PhotoLoader`'s configuration // take the `Sendable` form in every mock of the module. `GalleryScreen`'s preview overrides its `PhotoLoader` with - // the main-actor hand-written mock, which compiles only where the builder is isolated to the main actor. + // the main-actor hand-written mock, which compiles only where the builder is isolated to the main actor: both mocks + // that build `PhotoLoader` spell `PhotoLoader`'s `mockAttributes`, so its builder does too. let output = try await executeSafeDIToolTest( swiftFileContent: [ """ @@ -83,7 +84,7 @@ struct SafeDIToolMockBuilderIsolationTests: ~Copyable { """, """ @MainActor - @Instantiable(generateMock: true) + @Instantiable(mockAttributes: "@MainActor", generateMock: true) public final class GalleryScreen: Instantiable { public init(photoLoader: PhotoLoader) { self.photoLoader = photoLoader @@ -134,7 +135,7 @@ struct SafeDIToolMockBuilderIsolationTests: ~Copyable { } } - static func mock( + @MainActor static func mock( safeDIOverrides: SafeDIOverrides = .init() ) -> GalleryScreen { func __safeDI_photoLoader(safeDIOverrides: PhotoLoader.SafeDIMockConfiguration) -> PhotoLoader { @@ -229,6 +230,109 @@ struct SafeDIToolMockBuilderIsolationTests: ~Copyable { ]) } + @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_keepsBuilderWithoutMockAttributes_whenSendableInstantiatorBuildsTypeWithNonisolatedInitializer() async throws { @@ -484,7 +588,7 @@ struct SafeDIToolMockBuilderIsolationTests: ~Copyable { nonisolated struct SafeDIMockConfiguration: Sendable { init( thumbnails: (@Sendable () -> Thumbnails)? = nil, - _ safeDIBuilder: (@Sendable @MainActor (Thumbnails) -> PhotoLoader)? = nil + _ safeDIBuilder: (@Sendable (Thumbnails) -> PhotoLoader)? = nil ) { __safeDI_storage = __safeDI_Storage( thumbnails: thumbnails, @@ -494,21 +598,21 @@ struct SafeDIToolMockBuilderIsolationTests: ~Copyable { 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 } + 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 @MainActor (Thumbnails) -> PhotoLoader)? + safeDIBuilder: (@Sendable (Thumbnails) -> PhotoLoader)? ) { self.thumbnails = thumbnails self.safeDIBuilder = safeDIBuilder } let thumbnails: (@Sendable () -> Thumbnails)? - let safeDIBuilder: (@Sendable @MainActor (Thumbnails) -> PhotoLoader)? + let safeDIBuilder: (@Sendable (Thumbnails) -> PhotoLoader)? } } } From fd9a9a8e609be6a75a1c9ebc70a70d130fd6a19c Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 13:14:32 +0000 Subject: [PATCH 4/8] Type a builder with the mockAttributes its constructions spell too A builder now also takes its type's mockAttributes when 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. Every place that calls the builder already calls one of those constructions synchronously, so a builder isolated as they are is callable there. This covers callers that are main-actor only through a superclass, such as a UIKit view controller, which spell no mockAttributes and so kept the builder plain under the rule that every generated caller spells the same attributes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HLuVQL2AyjmTVDPHyoJd4Z --- Documentation/Manual.md | 2 +- .../Generators/MockLowering+Walk.swift | 36 ++-- .../SafeDIToolMockBuilderIsolationTests.swift | 169 ++++++++++++++++++ 3 files changed, 196 insertions(+), 11 deletions(-) diff --git a/Documentation/Manual.md b/Documentation/Manual.md index 61b3e5ce02..be3ff7aea8 100644 --- a/Documentation/Manual.md +++ b/Documentation/Manual.md @@ -324,7 +324,7 @@ 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`, when every mock in the module that builds the type spells the same `mockAttributes`, so a closure you pass for it, such as `.init({ .mock() })` in a preview, runs in that isolation. SafeDI reads isolation only from `mockAttributes`, never from a type’s or an initializer’s declaration, so spell `mockAttributes` on the type and on the mocks that build it. A builder keeps no attributes where a mock that builds the type spells others, or where a `Sendable` wrapper such as `SendableInstantiator`, a public mock or a seam builds it, 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. +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. diff --git a/Sources/SafeDICore/Generators/MockLowering+Walk.swift b/Sources/SafeDICore/Generators/MockLowering+Walk.swift index e7c6102536..c13a4119ba 100644 --- a/Sources/SafeDICore/Generators/MockLowering+Walk.swift +++ b/Sources/SafeDICore/Generators/MockLowering+Walk.swift @@ -2209,17 +2209,23 @@ extension MockLowering { } } -/// The attributes a builder closure type of a mock spells: the built type's `mockAttributes`, where every generated -/// function in the module that calls the builder spells those attributes too, so that a closure a caller writes for the -/// builder, such as a preview's, runs in the isolation the user spelled; 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` only, -/// never from a type's or an initializer's declaration. +/// 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 (`isolatedTypes`), 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 a type has an isolated builder where every mock root of the module that reaches it -/// through `@Instantiated` dependencies spells the type's `mockAttributes`, and no `Sendable` wrapper, public mock or seam +/// 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. /// @@ -2230,10 +2236,20 @@ enum MockBuilderIsolation { /// (`isolatedTypes(among:)`); empty outside mock generation. @TaskLocal static var isolatedTypes = Set() - /// The attributes a builder closure type of `instantiable`'s type spells. + /// The attributes a builder closure type of `instantiable`'s type spells: all of its closure attributes where the type + /// is among `isolatedTypes`, 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. static func attributes(of instantiable: Instantiable) -> String { - guard isolatedTypes.contains(instantiable.concreteInstantiable) else { return "" } - return closureAttributes(of: instantiable.mockAttributes) + let attributes = closureAttributes(of: instantiable.mockAttributes) + guard !isolatedTypes.contains(instantiable.concreteInstantiable) else { return attributes } + let spelledByEach = [instantiable.initializer, instantiable.mockInitializer] + .compactMap { $0.map { Set(($0.spelledAttributes ?? "").split(separator: " ")) } } + guard !spelledByEach.isEmpty else { return "" } + return attributes + .split(separator: " ") + .filter { attribute in spelledByEach.allSatisfy { $0.contains(attribute) } } + .joined(separator: " ") } /// The attributes of `attributes` a closure type can spell, in their order. diff --git a/Tests/SafeDIToolMockTests/SafeDIToolMockBuilderIsolationTests.swift b/Tests/SafeDIToolMockTests/SafeDIToolMockBuilderIsolationTests.swift index 7738c9af5f..9f2c176573 100644 --- a/Tests/SafeDIToolMockTests/SafeDIToolMockBuilderIsolationTests.swift +++ b/Tests/SafeDIToolMockTests/SafeDIToolMockBuilderIsolationTests.swift @@ -333,6 +333,175 @@ struct SafeDIToolMockBuilderIsolationTests: ~Copyable { ]) } + @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 { From f2e673b78b2e2de3cb85e3bb6d8f9c768d51ecdf Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 16:07:28 +0000 Subject: [PATCH 5/8] Draw a main-actor builder a preview passes in the base corpus One base graph in sixteen, on a stream of its own, gains MainLoader, a @MainActor class whose mockAttributes spell the main actor, built by an actor's main-actor mock and by a second mocked type: a @MainActor class whose mock spells the main actor too, or a class main-actor only through its superclass whose loader's initializer and hand-written mock spell @MainActor. A preview the compile adds beside the generated code passes each mock a closure for the loader's builder that touches main-actor state. With the builder fix reverted, seeds 38 and 59 fail to compile. The mock mirror oracle skips the draw's mocked types, which a nonisolated root cannot build. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HLuVQL2AyjmTVDPHyoJd4Z --- .../SafeDIToolGraphFuzzerTests.swift | 11 +- Tests/SafeDIToolTestSupport/GraphFuzzer.swift | 114 ++++++++++++++++-- .../GraphFuzzerMockMirrors.swift | 8 ++ 3 files changed, 121 insertions(+), 12 deletions(-) diff --git a/Tests/SafeDIToolFuzzerTests/SafeDIToolGraphFuzzerTests.swift b/Tests/SafeDIToolFuzzerTests/SafeDIToolGraphFuzzerTests.swift index 028548f790..c99996fb2d 100644 --- a/Tests/SafeDIToolFuzzerTests/SafeDIToolGraphFuzzerTests.swift +++ b/Tests/SafeDIToolFuzzerTests/SafeDIToolGraphFuzzerTests.swift @@ -7649,9 +7649,9 @@ struct SafeDIToolGraphFuzzerTests { /// `SAFEDI_GRAPH_FUZZER_ITERATIONS=corpus` selects. `knownIssues` lists every one that fails. static let corpusSeedCount = 5_000 - static let corpusFixtureHash: UInt64 = 0x5F6096F77B47A820 + static let corpusFixtureHash: UInt64 = 0x3CA8733F95F0E9B6 - static let corpusPartitionHash: UInt64 = 0xB2FB2367E1CDF49A + static let corpusPartitionHash: UInt64 = 0x4A75D13EABA46C47 /// How many of the corpus's graphs the tool accepts, and which ones, as a `GraphFuzzerSeedSetSum`, which /// shards of the corpus can add up. @@ -7663,7 +7663,7 @@ struct SafeDIToolGraphFuzzerTests { /// corpus, so a generator change that stops drawing a feature, or a tool change that stops accepting the graphs that /// draw it, changes these and must update them deliberately, with the hashes and the accepted-seed pins. static let corpusAcceptedFeatureCounts: [GraphFuzzerFeature: Int] = [ - .constantProperty: 2_634, + .constantProperty: 2_637, .erasedConstantProperty: 560, .instantiatorProperty: 2_214, .sendableInstantiatorProperty: 931, @@ -7709,7 +7709,7 @@ struct SafeDIToolGraphFuzzerTests { .forwardedPropertiesTypealiasArgument: 156, .forwardedTupleBuilderReceivedByMockedType: 137, .multipleRoots: 2_134, - .generateMock: 2_532, + .generateMock: 2_539, .lazyCycle: 1_524, .constantCycleCloser: 301, .builderReceivedInsideItsTree: 179, @@ -7734,7 +7734,7 @@ struct SafeDIToolGraphFuzzerTests { .forwardedErasedInstantiator: 171, .defaultValuedInstantiateParameter: 643, .nonSendableValuesInsideSendableBuilder: 152, - .handWrittenMockUnderMockCondition: 723, + .handWrittenMockUnderMockCondition: 749, .customMockNameBesideGeneratedMock: 894, .mockOnlyExtensionOfReceivedType: 1_095, .instantiableStruct: 544, @@ -7904,6 +7904,7 @@ struct SafeDIToolGraphFuzzerTests { .twoFormsOfOneLabel: 360, .requiredOptionalReceiveOfNonOptionalDeclaration: 49, .requiredReceiveOfUncreatedAlias: 40, + .mainActorBuilderDraw: 322, ], shapeCounts: [ .rootTreePropertyReceivedByTwoOrMoreTypes: 1_915, diff --git a/Tests/SafeDIToolTestSupport/GraphFuzzer.swift b/Tests/SafeDIToolTestSupport/GraphFuzzer.swift index fb74be7eed..e2a40e2f7c 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,53 @@ 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. + private mutating func addingMainActorBuilderPassedFromPreview(to declarations: [TypeDeclaration]) -> [TypeDeclaration] { + guard 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 +12072,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 +12086,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 +12105,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 +19693,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 +20098,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)" } } From ebc8dcb5ae82082fb6d1c35fdbd42ffd08f4d70a Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 16:40:33 +0000 Subject: [PATCH 6/8] Read builder attributes from their syntax, once per module, and count the pass The pass that decides which builders spell their type's mockAttributes now reads the attributes from their parsed syntax instead of scanning the string, computes each type's builder attributes once and hands every spelling site the result, returns at once where no type spells a closure attribute or every one that does has constructions spelling them all, walks only what the mock roots reach otherwise, and reads each declaration from its own concrete type's entry. Its walks count their steps, and a test checks that doubling the mock roots at most doubles them. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HLuVQL2AyjmTVDPHyoJd4Z --- .claude/rules/generator-design.md | 2 +- ...dencyTreeGenerator+MockOrchestration.swift | 2 +- .../Generators/MockLowering+Walk.swift | 162 +++++++++++------- .../MockBuilderIsolationStepCountTests.swift | 81 +++++++++ 4 files changed, 185 insertions(+), 62 deletions(-) create mode 100644 Tests/SafeDICoreTests/MockBuilderIsolationStepCountTests.swift diff --git a/.claude/rules/generator-design.md b/.claude/rules/generator-design.md index 1f0955c368..47104dc35f 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 tried and dropped. A builder’s closure type takes the attributes of `mockAttributes` that its type’s initializer and hand-written mock spell too (`MockBuilderIsolation`): reading the attributes an initializer spells is still reading what the user spelled, as the syntax holds them, never inferring isolation from a declaration’s kind, a superclass or an attribute’s name. - **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/Sources/SafeDICore/Generators/DependencyTreeGenerator+MockOrchestration.swift b/Sources/SafeDICore/Generators/DependencyTreeGenerator+MockOrchestration.swift index 85c0acacd8..e2d51204cb 100644 --- a/Sources/SafeDICore/Generators/DependencyTreeGenerator+MockOrchestration.swift +++ b/Sources/SafeDICore/Generators/DependencyTreeGenerator+MockOrchestration.swift @@ -31,7 +31,7 @@ extension DependencyTreeGenerator { 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. - try await MockBuilderIsolation.$isolatedTypes.withValue(MockBuilderIsolation.isolatedTypes(among: typeDescriptionToFulfillingInstantiableMap, additionalMocksToGenerate: additionalMocksToGenerate)) { + try await MockBuilderIsolation.$builderAttributesByType.withValue(MockBuilderIsolation.builderAttributes(among: typeDescriptionToFulfillingInstantiableMap, additionalMocksToGenerate: additionalMocksToGenerate).builderAttributesByType) { try await generateMockCodeChoosingRecords( mockConditionalCompilation: mockConditionalCompilation, currentModuleSourceFilePaths: currentModuleSourceFilePaths, diff --git a/Sources/SafeDICore/Generators/MockLowering+Walk.swift b/Sources/SafeDICore/Generators/MockLowering+Walk.swift index c13a4119ba..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 @@ -2211,7 +2214,7 @@ extension MockLowering { /// 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 (`isolatedTypes`), or +/// - 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 @@ -2232,87 +2235,126 @@ extension MockLowering { /// 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 concrete types whose builders spell their `mockAttributes`, for the module whose mocks are being generated - /// (`isolatedTypes(among:)`); empty outside mock generation. - @TaskLocal static var isolatedTypes = Set() - - /// The attributes a builder closure type of `instantiable`'s type spells: all of its closure attributes where the type - /// is among `isolatedTypes`, 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. + /// 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 { - let attributes = closureAttributes(of: instantiable.mockAttributes) - guard !isolatedTypes.contains(instantiable.concreteInstantiable) else { return attributes } - let spelledByEach = [instantiable.initializer, instantiable.mockInitializer] - .compactMap { $0.map { Set(($0.spelledAttributes ?? "").split(separator: " ")) } } - guard !spelledByEach.isEmpty else { return "" } - return attributes - .split(separator: " ") - .filter { attribute in spelledByEach.allSatisfy { $0.contains(attribute) } } - .joined(separator: " ") + 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 of `attributes` a closure type can spell, in their order. - static func closureAttributes(of attributes: String) -> String { - attributes - .split(separator: " ") - .filter { $0.hasPrefix("@") && !$0.contains("(") && !declarationOnlyAttributes.contains(String($0.dropFirst())) } - .joined(separator: " ") + /// 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 concrete types of `instantiables`, the module's by the types they fulfill, whose builders spell their - /// `mockAttributes`, where the mock roots are the types that generate a mock and those `additionalMocksToGenerate` - /// names. Linear in the module's declarations and dependencies, times the few distinct attribute spellings of its mock - /// roots. - static func isolatedTypes(among instantiables: [TypeDescription: Instantiable], additionalMocksToGenerate: Set) -> Set { - var instantiableByConcreteType = [TypeDescription: Instantiable]() - for instantiable in instantiables.values { - instantiableByConcreteType[instantiable.concreteInstantiable] = instantiable - } - // Each type's `@Instantiated` children, with whether a `Sendable` wrapper builds the child. - var childrenByType = [TypeDescription: [(type: TypeDescription, isSendable: Bool)]]() - for (type, instantiable) in instantiableByConcreteType { - childrenByType[type] = instantiable.dependencies.compactMap { dependency in - guard case .instantiated = dependency.source, let child = instantiables[dependency.asInstantiatedType] else { return nil } - return (type: child.concreteInstantiable, isSendable: dependency.property.propertyType.isSendable) + /// 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 } } - // What a `Sendable` wrapper, a public mock or a seam reaches, whose builders keep no attributes. - var excluded = Set() - var pending = [TypeDescription]() - for (type, instantiable) in instantiableByConcreteType { - if instantiable.generateMock == .public || instantiable.generatesDependencyTree { - pending.append(type) + 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: " ") } - for child in childrenByType[type] ?? [] where child.isSendable { - pending.append(child.type) + if spelledByConstructions != attributes { + typesAwaitingCallers[type] = attributes.joined(separator: " ") } } - while let type = pending.popLast() { - guard excluded.insert(type).inserted else { continue } - pending += (childrenByType[type] ?? []).map(\.type) + 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 instantiableByConcreteType where instantiable.generatesMock || additionalMocksToGenerate.contains(type.asSource) { - reached.append((type: type, attributes: closureAttributes(of: instantiable.mockAttributes))) + 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 += (childrenByType[type] ?? []).map { (type: $0.type, attributes: attributes) } + reached += children(of: type).map { (type: $0.type, attributes: attributes) } } - var isolatedTypes = Set() - for (type, instantiable) in instantiableByConcreteType where !excluded.contains(type) { - guard let callerAttributes = callerAttributesByType[type] else { continue } - let attributes = closureAttributes(of: instantiable.mockAttributes) - if !attributes.isEmpty, callerAttributes == [attributes] { - isolatedTypes.insert(type) + // 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) } } - return isolatedTypes + 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/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.. Date: Thu, 3 Dec 2026 17:08:11 +0000 Subject: [PATCH 7/8] Bind the builder attributes out of line, only where a module has some Swift 6.2.4's release builds abort in swift_task_dealloc ("freed pointer was not the last allocation") where nested async withValue calls are inlined into one frame, as the builder attributes' binding was beside generateMockCode's own. The binding now runs in an unoptimized function kept out of line, the function it wraps is kept out of line too, and a module whose builders spell no attributes binds nothing. The rules sentence is shortened to keep the rules a generator file loads within their budget. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HLuVQL2AyjmTVDPHyoJd4Z --- .claude/rules/generator-design.md | 2 +- ...dencyTreeGenerator+MockOrchestration.swift | 27 +++++++++++++++++-- 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/.claude/rules/generator-design.md b/.claude/rules/generator-design.md index 47104dc35f..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. A builder’s closure type takes the attributes of `mockAttributes` that its type’s initializer and hand-written mock spell too (`MockBuilderIsolation`): reading the attributes an initializer spells is still reading what the user spelled, as the syntax holds them, never inferring isolation from a declaration’s kind, a superclass or an attribute’s name. +- **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/Sources/SafeDICore/Generators/DependencyTreeGenerator+MockOrchestration.swift b/Sources/SafeDICore/Generators/DependencyTreeGenerator+MockOrchestration.swift index e2d51204cb..ea603162f7 100644 --- a/Sources/SafeDICore/Generators/DependencyTreeGenerator+MockOrchestration.swift +++ b/Sources/SafeDICore/Generators/DependencyTreeGenerator+MockOrchestration.swift @@ -31,7 +31,17 @@ extension DependencyTreeGenerator { 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. - try await MockBuilderIsolation.$builderAttributesByType.withValue(MockBuilderIsolation.builderAttributes(among: typeDescriptionToFulfillingInstantiableMap, additionalMocksToGenerate: additionalMocksToGenerate).builderAttributesByType) { + 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, @@ -42,8 +52,21 @@ extension DependencyTreeGenerator { } } + /// 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. + /// 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?, From 8603613f6ce38fb93ba0a95d9ce38fac2795ac32 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 18:02:24 +0000 Subject: [PATCH 8/8] Omit the main-actor builder draw from fixtures compared with older releases The draw's actor is a shape 2.3.0 rejects, so the release acceptance fixture, drawn for comparison, leaves it out the way the other actor draws do. The draw also moved the smoke and known-issue fixture and partition hashes, which this re-pins. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HLuVQL2AyjmTVDPHyoJd4Z --- Tests/SafeDIToolFuzzerTests/SafeDIToolGraphFuzzerTests.swift | 4 ++-- Tests/SafeDIToolTestSupport/GraphFuzzer.swift | 5 +++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/Tests/SafeDIToolFuzzerTests/SafeDIToolGraphFuzzerTests.swift b/Tests/SafeDIToolFuzzerTests/SafeDIToolGraphFuzzerTests.swift index 1149194cc4..29a146e079 100644 --- a/Tests/SafeDIToolFuzzerTests/SafeDIToolGraphFuzzerTests.swift +++ b/Tests/SafeDIToolFuzzerTests/SafeDIToolGraphFuzzerTests.swift @@ -7633,7 +7633,7 @@ struct SafeDIToolGraphFuzzerTests { /// one compile and one link. static let smokeSeeds: [UInt64] = [4, 5, 12, 18, 25, 30, 40, 53, 59, 62, 70, 86, 94, 97, 98, 99, 133, 161, 212, 267, 304, 327, 378, 466, 520, 582, 691, 705, 731, 930, 2_186, 2_314, 2_420, 2_449, 2_611, 3_360, 4_002, 4_224, 4_516, 5_889, 6_388] - static let smokeAndKnownIssueFixtureHash: UInt64 = 0x1FEA9E97EB1A6EF2 + static let smokeAndKnownIssueFixtureHash: UInt64 = 0xE4FC41132EDD47BA /// The remedies the remedy oracle applies in the smoke batch's rejected graphs. `SafeDIToolGraphFuzzerRemedyTests` /// holds a representative of every kind. @@ -7643,7 +7643,7 @@ struct SafeDIToolGraphFuzzerTests { /// them; `corpusPartitionHash` pins the whole corpus's. The partition draws nothing from the seed, so changing it /// changes neither the graphs nor the pins on them: these pins make a change to the partition deliberate. They /// move with the generator and, this one, with the smoke and known-issue seeds too, as the fixture hashes do. - static let smokeAndKnownIssuePartitionHash: UInt64 = 0xC1D9B3C5E55B6FA9 + static let smokeAndKnownIssuePartitionHash: UInt64 = 0xD54E7F7024A522AA /// The corpus, seeds `0.. [TypeDeclaration] { - guard features.isEmpty, mainActorBuilderRandom.percentChance(6) else { return declarations } + guard !omitsDrawsOlderReleasesReject, features.isEmpty, mainActorBuilderRandom.percentChance(6) else { return declarations } var declarations = declarations let constructionsSpellIsolation = mainActorBuilderRandom.percentChance(50) let hasHandWrittenMock = mainActorBuilderRandom.percentChance(50)