diff --git a/.github/workflows/macOS.yml b/.github/workflows/macOS.yml index b4157c4b8..95c09b29b 100644 --- a/.github/workflows/macOS.yml +++ b/.github/workflows/macOS.yml @@ -26,6 +26,9 @@ jobs: configuration: [debug, release] env: MACHO_SWIFT_SECTION_SILENT_TEST: 1 + # Quiets `.print()` of MachOKitExtensions' MachOFixtureSupport, which + # reads it at run time. + MACHO_TESTING_SILENT: 1 GH_TOKEN: ${{ github.token }} steps: - uses: actions/checkout@v4 diff --git a/.gitignore b/.gitignore index 3e28e3bb8..e1a6e04c0 100644 --- a/.gitignore +++ b/.gitignore @@ -23,3 +23,18 @@ Tests/Projects/SymbolTests/DerivedData .omc .swiftpm/xcode/xcshareddata/xcschemes __pycache__/ + +# The Tuist development workspace (Documentations/Internal/TuistDevelopment.md): everything +# ./TuistScript.sh and Tuist generate inside the checkout. +/MachOSwiftSection-Tuist.xcworkspace/ +/MachOSwiftSection.xcodeproj/ +/Derived/ +/PrecompiledLibraries/swift-syntax/swift-syntax.xcodeproj/ +/PrecompiledLibraries/swift-syntax/Derived/ +/PrecompiledLibraries/swift-syntax/.build/ +/Tuist/.build/ +/Tuist/.build-LocalDependencies/ +/Tuist/CommandLine/*.xcodeproj/ +/Tuist/CommandLine/Derived/ +/Tuist/.local-dependencies +/Tuist/.claimed-checkouts diff --git a/.swiftpm/xcode/package.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/.swiftpm/xcode/package.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 000000000..54782e32f --- /dev/null +++ b/.swiftpm/xcode/package.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + IDEWorkspaceSharedSettings_AutocreateContextsIfNeeded + + + diff --git a/AGENTS.md b/AGENTS.md index 628f9821e..5332e89a0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -37,7 +37,7 @@ SwiftInspection and everything above it also import `SwiftLayout` is a peer of that spine: it depends on `SwiftObjCInterop` + `SwiftInspection` + `MachOSwiftSection` (+ `MachOObjCSection` for ObjC-ancestor instance sizes) and is consumed by `SwiftDeclarationRendering`; `SwiftThunkAnalysis` depends on `SwiftObjCInterop` too. `TypeIndexing`, `SwiftDiffing`, `SwiftPrivateDiscriminators` and `OutputTransformer` hang off the same level as the modules that use them. The cross-reference analysis is three modules in three packages: MachOKitExtensions' `MachOCodeReferences` reads machine code on MachOKit, `MachOAddressResolution` and `ARM64InstructionDecoding` (both MachOKitExtensions too; `SwiftThunkAnalysis` and `SwiftDeclarationRendering` share the address resolution) and knows no language; MachOObjCSection's `ObjCCodeReferences` adds sends, class lists and method lists; this package's `CrossReferenceAnalysis` reaches up to `SwiftInspection` and `MachOSwiftSection` (Swift metadata, `SymbolicDemangler`, mangled names) and is the public facade. -**`Sources/` is grouped by layer, not flat**: `Support/`, `Symbols/`, `ABI/`, `Analysis/`, `Declaration/`, `Output/`, `Commands/`, `Executables/`, `TestSupport/`, each holding the targets of that layer (the former `MachO/` group is gone: its modules moved to MachOKitExtensions, and the Swift half of the symbol index lives in `Symbols/SwiftSymbols`). SwiftPM's default `Sources/` therefore never applies — a new target goes into a group directory and declares `path: "Sources//"` in `Package.swift`. Code that locates a source file from `#filePath` assumes this depth: the fixture paths in `MachOFileName` / `MachOImageName` climb three levels to the package root, and the source scans in the tests take the module name from two levels below `Sources`. [0055-group-sources-by-layer](Documentations/Evolutions/0055-group-sources-by-layer.md). +**`Sources/` is grouped by layer, not flat**: `Support/`, `Symbols/`, `ABI/`, `Analysis/`, `Declaration/`, `Output/`, `Commands/`, `Executables/`, `TestSupport/`, each holding the targets of that layer (the former `MachO/` group is gone: its modules moved to MachOKitExtensions, and the Swift half of the symbol index lives in `Symbols/SwiftSymbols`). SwiftPM's default `Sources/` therefore never applies — a new target goes into a group directory and declares `path: "Sources//"` in `Package.swift`. Code that locates a source file from `#filePath` assumes this depth: the SymbolTests entries this package adds to MachOKitExtensions' `MachOFileName` (`Sources/TestSupport/SwiftSectionFixtureSupport/MachOFileName+SymbolTests.swift`) climb three levels from that file to the package root, and the source scans in the tests take the module name from two levels below `Sources`. [0055-group-sources-by-layer](Documentations/Evolutions/0055-group-sources-by-layer.md). ## What each module does @@ -51,7 +51,7 @@ One or two lines each; the linked document is the authority. - **SwiftObjCInterop** — the Objective-C side of Swift types, and where `MachOObjCSection` enters the Swift-facing stack: per-image indexes of `@objc @implementation` classes, of the Swift classes a source renamed for the ObjC runtime (`SwiftClassObjectIndex` — every name-keyed ObjC-side lookup of a Swift class falls back to it on a miss), of the Swift classes with no class object in `__objc_classlist`, and of the `@objc` protocols declared in Swift; the seam through which a host hands over the ObjC class hierarchies it already indexed (`ObjCClassHierarchyProviding`), the library's own reader behind it and the ancestor chain followed into a standalone file's dependency closure; the per-class ObjC member table (`ObjCMemberTable`); the ClangImporter's naming rules, and the records an ObjC class, category or protocol is imported into Swift from (`ObjCImportedContainerIndex`). A Swift class's ObjC-side name is not always `_TtC…`: in a file, a category on another image's Swift class names it by the class metadata symbol it is bound to (`_$s…CN`). Read every such name through `NodeTypeNaming.swiftClassNode(fromRuntimeName:)`, never a `hasPrefix("_Tt")` check — one printed `extension __C._$s…` and found none of its `@objc` witnesses. The linker merges a binary's categories on its own classes into those classes, so `__objc_catlist` lists only categories on other images' classes. An `@objc` protocol declared in Swift has NO protocol descriptor and a class's conformance to an ObjC protocol has NO conformance record — the facts live in `__swift5_fieldmd`, `protocol_t` and `class_ro_t`. [Modules/SwiftObjCInterop.md](Documentations/Internal/Modules/SwiftObjCInterop.md). - **SwiftDump** — high-level wrappers (`Struct`, `Enum`, `Class`, `Protocol`, `ProtocolConformance`, `AssociatedType`, `ObjCImplementationClass`) and the `dump` output path. - **SwiftDeclaration** — the shared declaration model every higher module reads and writes, plus the `SwiftIndexEvents` namespace. Its files split by visibility: a `public` type that stays in the model after indexing goes under `Model/`; code that only runs while the model is built (`package` / `internal`) goes under `Indexing/` — a new `TypeDefinition+…` step goes in `Indexing/TypeDefinition/`, never beside `TypeDefinition.swift`. [Modules/SwiftDeclaration.md](Documentations/Internal/Modules/SwiftDeclaration.md). -- **SwiftDeclarationRendering** — the comment engine shared by dump and interface (`FieldLayoutRenderer`, opaque-type rewriting, specialized-metadata substitution), reader-specialized: live metadata in-process, SwiftLayout offline ([FieldLayoutRendererReaderSpecialization.md](Documentations/Internal/FieldLayoutRendererReaderSpecialization.md)). +- **SwiftDeclarationRendering** — the comment engine shared by dump and interface (`FieldLayoutRenderer`, opaque-type rewriting, specialized-metadata substitution), reader-specialized: live metadata in-process, SwiftLayout offline ([FieldLayoutRendererReaderSpecialization.md](Documentations/Internal/FieldLayoutRendererReaderSpecialization.md)). Also `MultilineTypeFormatting`, which breaks a finished print's long types at their brackets — applied once at the output (the `dump` / `interface` requests, a host's assembled print), never inside a printer ([0102-multiline-type-formatting](Documentations/Evolutions/0102-multiline-type-formatting.md)). - **SwiftIndexing** — builds the declaration model from an image (`SwiftDeclarationIndexer.prepare()`), unifies extension containers, owns the per-image cache eviction. - **SwiftPrivateDiscriminators** — recovers the source file a private discriminator was derived from (`MD5(module name + file name)`): candidate file names hashed until one matches — a generated list of known ones, then names the image itself declares. `PrivateDiscriminatorSourceFileIndex` holds one image's candidates and remembers every answer. `dump` / `interface --emit-private-source-files` reach it through `SwiftDeclarationRendering`'s `PrivateDeclarationSourceFileProviding`, after one search over the whole image (`recoverSourceFiles(ofEveryDeclarationIn:)`) — asked one declaration at a time, every discriminator nothing recovers runs through all the candidates again. [Modules/SwiftPrivateDiscriminators.md](Documentations/Internal/Modules/SwiftPrivateDiscriminators.md). - **SwiftAttributeInference** — infers source-level attributes (`@propertyWrapper`, `@resultBuilder`, `@dynamicMemberLookup`, `@objc`, …). @@ -66,7 +66,7 @@ One or two lines each; the linked document is the authority. - **ARM64InstructionDecoding** (MachOKitExtensions) — hand readers for the few A64 encodings the analyses decode, and `ARM64Trampoline`, which recognizes a GOT stub, a stub island and a cache-shared selector stub by shape. MachOKitExtensions' `MachOCodeReferences` and `MachOAddressResolution` and this package's `CrossReferenceAnalysis` share it. A GOT stub's load counts only when the next instruction jumps through the loaded register: a function that starts by loading a Swift field offset (`adrp; ldr`) looks the same for two instructions (`ARM64TrampolineTests.aFunctionLoadingAGlobalIsNoSlotStub`, which with the other Capstone-checked decoder tests stays here). - **MachOAddressResolution** (MachOKitExtensions; was `CodeAddressResolution`) — what a call from a Mach-O *file* reaches, read offline: one image's address space (`ImageAddressSpace` — the offset convention below, segment-range containment, symbol-value and export-trie conversions), the trampolines a call passes through (`StubChainResolver`, hop by hop), what any pointer slot holds (`SlotResolver` — a bind's name before a rebase's unslid target), and the cache image an address lies in (`CacheImageLocator`). Knows no Swift or ObjC metadata; the accessor-thunk reader and the cross-reference analysis's file mode read through it. It keeps no per-image cache itself — a consumer holds one locator per image in its own `SharedCache`. MachOKitExtensions' `Documentations/Internal/MachOAddressResolution.md`. - **The modules that moved out speak `@_spi(Internals)`.** Every interface of `MachOCodeReferences`, `MachOAddressResolution`, `ARM64InstructionDecoding` (MachOKitExtensions) and `ObjCCodeReferences` (MachOObjCSection) that this package uses is `@_spi(Internals) public` — `package` does not cross packages. Import it per file with `@_spi(Internals) import `: `CrossReferenceAnalysis`'s `@_exported import` re-exports only the public value types (`CodeLocation`, `CodeReferenceKind`, `CodeReferenceRoute`, `IndirectCallEvidence`, `ReceiverClassHint`). A test file that must compile on both sides of an A/B (`ReferenceTableDigestTests`) or proves the public face (`PublicNameTests`) imports no SPI. Their tests that need no analyzer live in their own packages; everything that drives a scan stays in `CrossReferenceAnalysisTests` ([0098 move-cross-reference-layers](Documentations/Evolutions/0098-move-cross-reference-layers.md)). -- **TypeIndexing** — `__C` module attribution (`__C.NSString` → `Foundation.NSString`), macOS-only, via SourceKit module interfaces + APINotes + a lazy ObjC-metadata index. [TypeIndexingPipeline.md](Documentations/Internal/TypeIndexingPipeline.md). +- **SwiftTypeNameResolution** — `__C` type names (`__C.NSString` → `Foundation.NSString`, `__C.UICellConfigurationState` → `UIKit.__UICellConfigurationState`), macOS-only: the printer's adapter onto [swift-type-indexing](https://github.com/MxIris-Reverse-Engineering/swift-type-indexing), the separate package the SDK index (module interfaces + API notes + MachOObjCSection's `ObjCDeclaredTypeNames`) moved to. A private CF type (no SDK header) is attributed to the image exporting its `…GetTypeID` through `CFDeclaredTypeNames` — registered alone for the root, and for each direct dependency inside an `ImageDeclaredTypeNames` with its ObjC names, because `TypeDatabase` keeps only the first source per image path and silently drops a second. The export only locates a type: it claims a name only when the root's foreign class descriptors confirm a CF class (`cfTypedefNames(referencedBy:)`) ([private-cf-type-modules](Documentations/Evolutions/0108-private-cf-type-modules.md)). Also the module a Swift type the SDK moved between modules is declared in now (`CoreGraphics.CGFloat` → `CoreFoundation.CGFloat`; `@_originallyDefinedIn` keeps the mangling on the old module), through the printer's `MovedTypeModuleResolving` role and `interface --resolve-moved-type-modules` — gated on the SDK version the binary was built with, and display only: never let it reach a lookup key or the diff/snapshot/evolution path, which compare manglings ([0107-moved-swift-type-modules](Documentations/Evolutions/0107-moved-swift-type-modules.md)). Its implementation note is that package's `Documentations/Internal/TypeIndexingPipeline.md`. - **OutputTransformer** — token-template rendering for the Swift comment kinds, dependency-free, shared with RuntimeViewer's settings UI. [OutputTransformerMigration.md](Documentations/Internal/OutputTransformerMigration.md), [CLITransformerTemplateInterface.md](Documentations/Internal/CLITransformerTemplateInterface.md). - **Semantic** (upstream package) — `SemanticString`, for colored/annotated output. @@ -78,7 +78,7 @@ Everything in this section except `SwiftSymbols` is external: since 0.25.0 these - **MachOFoundation** (external, MachOKitExtensions) — `MachOBase` + `MachOSymbols` + `MachODependencies`: the umbrella for everything above the ABI model, which imports `SwiftSymbols` beside it. - **MachOReading / MachOResolving** (external, MachOKitExtensions) — reading abstractions; address/offset resolution. `MachOResolving` also holds the symbol *value* types (`Symbol`, `Symbols`, `SymbolOrElement`), which carry no lookup behavior — "the symbols at this offset" is a query, not a read. Implementation note: MachOKitExtensions' `Documentations/Internal/ReadingContextAbstraction.md`. - **MachOPointers** (external, MachOKitExtensions) — relative and indirect pointer types, plus `SymbolOrElementPointer`. -- **MachOSymbols** (external, MachOKitExtensions) — the language-neutral half of the symbol index: the 16-byte-row `SymbolTable`, `SymbolRowBucket`, `SymbolValueOffsetConverter`, the `NlistProtocol` checks, `SymbolLanguage` with its `SymbolLanguageRegistry` (C++ is recognized there; Swift is registered by this repo's `SwiftSymbols`, which defines `.swift`, from the C target `SwiftSymbolsRegistration`'s load-time constructor), the one-pass sweep over symbol table and export trie (`SymbolSweep`, steered by a `SymbolTableRouting`), and a `SymbolIndexStore` that holds C and C++ names only, keeping registered languages' symbols as offsets alone (eviction group `.symbolStore`). The building blocks this repo uses are `@_spi(Internals)`. [SymbolIndex.md](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Internal/SymbolIndex.md). +- **MachOSymbols** (external, MachOKitExtensions) — the language-neutral half of the symbol index: the 16-byte-row `SymbolTable`, `SymbolRowBucket`, `SymbolValueOffsetConverter`, the `NlistProtocol` checks, `SymbolLanguage` with its `SymbolLanguageRegistry` (C++ is recognized there; Swift is registered by this repo's `SwiftSymbols`, which defines `.swift`, from the C target `SwiftSymbolsRegistration`'s load-time constructor — which a static-archive link (a Tuist static framework) loads only because `SymbolLanguage+Swift.swift` calls the no-op `swift_symbols_registration_anchor()`; never remove that call), the one-pass sweep over symbol table and export trie (`SymbolSweep`, steered by a `SymbolTableRouting`), and a `SymbolIndexStore` that holds C and C++ names only, keeping registered languages' symbols as offsets alone (eviction group `.symbolStore`). The building blocks this repo uses are `@_spi(Internals)`. [SymbolIndex.md](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Internal/SymbolIndex.md). - **SwiftSymbols** (this repo, `Sources/Symbols/SwiftSymbols`) — the Swift symbol index: `SwiftSymbolIndexStore` routes the sweep through `SwiftSymbolTableRouting`, then demangles, classifies and holds the per-image node stores; also `LargeStackTaskExecution`, and the image's `_symbolic` symbols in a table of their own that no offset or name query sees (`symbolicManglingSymbols(in:)`). Eviction group `.swiftSymbolStore`, dependency key `swiftSymbolIndexStore`. [Modules/SwiftSymbols.md](Documentations/Internal/Modules/SwiftSymbols.md). - **MachOCaches** (external, MachOKitExtensions) — the per-image cache primitive, NOT dyld shared cache support (that is `MachOKitExtensions` and `MachODependencies`): `SharedCache` (get-or-build per image, one build shared by concurrent callers, the build closure supplied at the call site), `SharedCacheKey` (hashes a file on its UUID alone, an image read from a dyld cache on its own and its cache's) and `SharedCacheRegistry` + `SharedCacheEvictionGroup` (which caches an indexer claims for an image and what its last live instance evicts). [SharedCache.md](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Internal/SharedCache.md). - **MachODependencies** (external, MachOKitExtensions) — the one dependency-resolution implementation every feature shares (`DependencyClosure`, the in-process and file locators, `DependencySearchPath`, `SharedDependencyClosure` for consumers of one root that resolve lazily). The file locator filters dyld-cache candidates by platform (`DependencyPlatforms`, from `LC_BUILD_VERSION`): the host's macOS cache is every root's default search path and carries Mac Catalyst UIKit / SwiftUI under `/System/iOSSupport`, which an iOS root used to resolve to by bare name. Reach the host's cache through `FullDyldCache.cachedHost` (MachOKitExtensions), never `FullDyldCache.host`: `host` opens and maps all 82 files of a macOS 27 cache on every read, and a locator is built per root — an evolution over 51 archived caches held 51 copies open (`FileDependencyLocatorTests` in MachOKitExtensions pins the sharing). [DependencyResolution.md](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Internal/DependencyResolution.md). @@ -147,6 +147,7 @@ python3 Scripts/test-run-rendering-ab-verification.py - **The rendering A/B verification is mandatory after any large refactor** touching demangling, printing, indexing, or the reader stack: byte-identical `dump` + `interface` output over real system frameworks through all three reader paths (archived dyld caches, simulator-runtime files, in-process `MachOImage`). Procedure, fallback rules, pitfalls: [SystemFrameworkRenderingVerification.md](Documentations/Internal/SystemFrameworkRenderingVerification.md). - **Re-run the harness's own unit tests after touching `compare_all_pairs` or the skip-marker writing.** Every hole found there so far was the same shape — the harness reporting a pass over a comparison it never made (zero pairs compared; both sides failing with *different* exit codes, leaving no `.txt` for either glob to see). Its green light is what this file makes acceptance evidence, so a harness that cannot fail is worse than no harness. - CI runs only a subset of suites. A green CI is not a green full suite; run the full suite locally before claiming one. +- **`./TuistScript.sh` generates `MachOSwiftSection-Tuist.xcworkspace`, a development-only second path**: third-party dependencies from Tuist's binary cache, `--local-dependencies` for the native workspace's upstream packages. Never run a bare `tuist` command — it gets none of the variables the manifests read and skips the claim RuntimeViewer's Tuist workspace shares on the same checkouts. As an agent set `TUIST_SCRIPT_ROOT=/Volumes/DerivedData/Agents.noindex//Tuist-MachOSwiftSection` and run `warm` / `build` / `test` through `queued-build`. The `TUIST_MAPS_LOCAL_PACKAGE_TESTS` block at the end of `Package.swift` exists for it; a test-only dependency added to `Package.swift` also goes into `Tuist/Package.swift`, a new dependency of `swift-section` into `Tuist/CommandLine/Project.swift`. [TuistDevelopment.md](Documentations/Internal/TuistDevelopment.md). @@ -154,11 +155,13 @@ python3 Scripts/test-run-rendering-ab-verification.py - Swift Testing runs test bodies on **512 KB cooperative threads**. A test calling a library entry point gets the large-stack executor from that entry's own `LargeStackTaskExecution.run`; a test driving the demangler or printer *directly* in deep recursion does not — wrap such a body in `LargeStackTaskExecution.run` when the hop cost or the 8 MB pool depth is what is being measured. "The suite passed" is not evidence the executor was used. - **Never block a cooperative thread with an untimed wait on work that itself needs a pool thread** — a `DispatchQueue.global()` block, a `Task`. The CI runner has 3 cores, so the pool is 3 threads wide: on 2026-09-29 three such tests froze the whole test process there, while a 10-core machine never lines three up. Give the counterpart a `Thread { … }.start()` of its own, or run the blocking side on one. CI re-runs `ConcurrentDefinitionPrintingTests` on a one-thread pool (`LIBDISPATCH_COOPERATIVE_POOL_STRICT=1`) to catch this — the `SharedCache` suites that step was written for moved to MachOKitExtensions with the cache; a new suite that blocks on purpose belongs in that step. [FixtureTestingAndContinuousIntegration.md](Documentations/Internal/FixtureTestingAndContinuousIntegration.md). +- **A test that scans many images in parallel goes through `ImageScanConcurrency.concurrentPerform(iterations:execute:)` (CrossReferenceAnalysisTests), never a bare `DispatchQueue.concurrentPerform`.** A Debug whole-cache scan keeps every core it gets busy for minutes, and Swift Testing runs suites in parallel, so the budget — half the cores, at least two — is one for the whole process. Its body must not call it again (a nested call waits for a permit its caller holds). `ParallelScanSourceTests` enforces the rule; only the opt-in `ScanThroughputBenchmarkTests` is exempt. [FixtureTestingAndContinuousIntegration.md](Documentations/Internal/FixtureTestingAndContinuousIntegration.md). - **Look a definition up by its full `name` or by `declaredNameForTesting` (SwiftSectionTestingSupport), never by `currentName`.** `currentName` is the display name dump and interface print in a declaration header — the printed name's last dot-separated component — and a function-local type's is the tail of its enclosing function's signature. A test indexing the test binary sees the library's local types: a `Hashable` enum declared in a function returning `Int` read as a second `Int` candidate, and a specialization test passed or failed on `Set` order ([ReviewAdjudications A52](Documentations/Internal/ReviewAdjudications.md)). -- **A suite asserting on whole-process state derived from an image must declare `ExclusiveImageAccess(.TheFixture)` — and so must every other suite touching that image.** A one-sided declaration excludes nothing. `.serialized` does not work (it orders within one container only, and `swift test` links everything into one process) and neither does a global actor (these tests are `async`, and `await` yields the actor). Do not assert exclusivity in a doc comment: `grep ExclusiveImageAccess` finds every declared user, grepping a fixture name does not. +- **A suite asserting on whole-process state derived from an image must declare `ExclusiveImageAccess(.TheFixture)` — and so must every other suite touching that image.** (The trait is MachOKitExtensions'; the initializers taking this package's `MachOFileName` / `MachOImageName` key it by the bare image name, so a suite naming a fixture by file and one naming it by image exclude each other.) A one-sided declaration excludes nothing. `.serialized` does not work (it orders within one container only, and `swift test` links everything into one process) and neither does a global actor (these tests are `async`, and `await` yields the actor). Do not assert exclusivity in a doc comment: `grep ExclusiveImageAccess` finds every declared user, grepping a fixture name does not. - **A `swift test` process never enforces pointer authentication, even built and reported as arm64e** — auth fixups are strip-applied there, so signed slots read back bare. Any "verified because the suite passed as arm64e" claim is a placebo; verify by spawning a real arm64e child process, as `Arm64eSignedVWTPointerTests` does. - **`SymbolTestsCore` must not enable the CoroutineAccessors feature** — it would move every implementation offset the ABI baselines pin. A suite needing a `…Twc` compiles its own fixture and asserts structurally. -- Tests use `MACHO_SWIFT_SECTION_SILENT_TEST=1` to suppress verbose output, and read Mach-O files from Xcode frameworks and the dyld shared cache for real-world validation. +- Tests use `MACHO_SWIFT_SECTION_SILENT_TEST=1` (turned into the `SILENT_TEST` compilation condition for this package's test targets) and `MACHO_TESTING_SILENT=1` (read at run time by `.print()`, which lives in MachOKitExtensions now) to suppress verbose output, and read Mach-O files from Xcode frameworks and the dyld shared cache for real-world validation. +- **The Swift-free test support lives in MachOKitExtensions** (`MachOFixtureSupport`, `MachOTestingSupport`, re-exported by `SwiftSectionFixtureSupport` / `SwiftSectionTestingSupport`): fixture and cache names, `HostSlice` for picking a file's slice, `FixtureCompiler` for compiling a library or executable at test time, `ExclusiveImageAccess`, and the base classes down to `MachOFixtureTests` with `acrossAllReaders` / `acrossAllContexts`. Use them instead of hand-writing a `Process` running `xcrun` or a slice switch; what they cannot express yet (a module name differing from the product name, extra outputs at a chosen path, stripping after linking) is listed in the shared-macho-testing-support proposal. A change to them goes to MachOKitExtensions and ships in a release before this package can use it. A read of this Mac's dyld shared cache goes through `FullDyldCache.cachedHost` (its `mainCache` for a `DyldCache`); open a fresh `DyldCache(path: .current)` only when the test needs its own instance, and say why. - Test design in general: the `write-tests` skill. @@ -182,11 +185,13 @@ That directory is exhaustively covered by `Tests/MachOSwiftSectionTests/Fixtures 1. Add the method. 2. `swift test --filter MachOSwiftSectionCoverageInvariantTests` to see which Suite needs updating. -3. Add a `@Test` to that Suite — `acrossAllReaders` for fixture-bound types, `usingInProcessOnly` for runtime-only metadata. +3. Add a `@Test` to that Suite — `acrossAllReaders` for fixture-bound types (the paired form `acrossAllReaders(fileSubject, imageSubject) { $0.member }`, or `acrossAllContexts(fileSubject, imageSubject) { subject, context in … }` for a read through a context; three closures only when the sides differ, e.g. an `inProcess:` read), `usingInProcessOnly` for runtime-only metadata. 4. Append the member name to `registeredTestMethodNames`. 5. `swift package --allow-writing-to-package-directory regen-baselines --suite `. 6. Re-run the affected Suite. +A new Suite is a class marked `@FixtureSuite` (SwiftSectionTestingSupport): the macro adds `testedTypeName` — the class name without `Tests` — and `registeredTestMethodNames` read from `Baseline`, plus the `FixtureSuite` conformance. Name either with a literal only when it differs (`@FixtureSuite(testedTypeName: "EnumTagCounts")`); `SuiteBehaviorScanner` reads the tested type from the attribute the same way. [0100-fixture-suite-macro](Documentations/Evolutions/0100-fixture-suite-macro.md). + A type with genuinely nothing to test goes on the sentinel allowlist with a typed `SentinelReason` (`pureDataUtility` / `runtimeOnly` / `needsFixtureExtension`) in `CoverageAllowlistEntries.swift`. Rationale and history: [FixtureTestingAndContinuousIntegration.md](Documentations/Internal/FixtureTestingAndContinuousIntegration.md). diff --git a/AgentPlugins/swift-section/.claude-plugin/plugin.json b/AgentPlugins/swift-section/.claude-plugin/plugin.json index 7beeb1974..a20ee6d3a 100644 --- a/AgentPlugins/swift-section/.claude-plugin/plugin.json +++ b/AgentPlugins/swift-section/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "swift-section", - "version": "0.26.0", + "version": "0.28.0", "description": "Teaches coding agents to drive the swift-section CLI: Swift and Objective-C declarations, memory layout and ABI diffs recovered from a Mach-O binary or a dyld shared cache.", "author": { "name": "MxIris-Reverse-Engineering", diff --git a/AgentPlugins/swift-section/.codex-plugin/plugin.json b/AgentPlugins/swift-section/.codex-plugin/plugin.json index a7f58228c..ae02ee00b 100644 --- a/AgentPlugins/swift-section/.codex-plugin/plugin.json +++ b/AgentPlugins/swift-section/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "swift-section", - "version": "0.26.0", + "version": "0.28.0", "description": "Teaches coding agents to drive the swift-section CLI: Swift and Objective-C declarations, memory layout and ABI diffs recovered from a Mach-O binary or a dyld shared cache.", "author": { "name": "MxIris-Reverse-Engineering", diff --git a/AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md b/AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md index f0b61a565..670210747 100644 --- a/AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md +++ b/AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md @@ -50,7 +50,10 @@ Flags added comparatively late, and therefore worth checking: `--emit-header`, `interface --requirements-on-associated-types` and `--emit-private-source-files`, and from 0.25.0 `objc evolution --interface` / `--emit-available` / `--platform`, `objc interface --swift`, `interface --no-existential-any` / `dump --disable-existential-any`, -`interface --expand-macros` and the `refs` and `symbolicate` subcommands. +`interface --expand-macros` and the `refs` and `symbolicate` subcommands, and after 0.26.0 +`--multiline-types` / `--maximum-line-width` on `dump` and `interface`, +`objc interface --mark-sdk-swift-names`, and `refs --type` / `--type-image` (with `refs` +listing selector references and function address references). When one is missing, say so rather than silently producing a weaker answer — the alternative is usually "upgrade (`brew upgrade swift-section`), or do without that annotation". @@ -66,7 +69,7 @@ missing, say so rather than silently producing a weaker answer — the alternati | How did this API evolve across N OS versions? | `evolution` | | Reformat the memory-layout comments the two above emit | `transformer` | | Objective-C headers, IMP addresses, or an Objective-C API diff (0.20.0+, formerly the separate `objc-section` executable) | `objc` — read `references/objc.md` first | -| Who calls this selector / symbol / function, who references this class, ivar or string — across a whole dyld shared cache or an app's files | `refs` — read `references/cross-references.md` first | +| Who calls this selector / symbol / function, who references this class, ivar, string or Swift type — across a whole dyld shared cache or an app's files | `refs` — read `references/cross-references.md` first | | What is this address: which function and how far into it, a stub and where it leads, a slot and what it holds | `symbolicate` — same reference | `dump` is the default subcommand: `swift-section ` is `swift-section dump `. @@ -152,7 +155,20 @@ The single most common mistake. Same underlying comment, different name: Spelled the same on both: `--emit-type-layout`, `--emit-enum-layout`, `--emit-member-addresses`, `--emit-vtable-offsets`, `--emit-expanded-field-offsets` (implies the field-offset flag), `--emit-header`, `--emit-export-status`, `--emit-private-source-files`, `--color-scheme`, -`--output-path`, `--dependency-search-path` (§2). +`--output-path`, `--dependency-search-path` (§2), `--multiline-types`, `--maximum-line-width`. + +`--multiline-types` breaks a long type over several lines at its brackets — a SwiftUI view's +`typealias Body = SwiftUI.ModifiedContent<…>` otherwise prints as one line thousands of +characters long. A type whose closing `>` lies past `--maximum-line-width` (default 100; a +line's indentation does not count) puts each argument of every generic with two or more +arguments on a line of its own; a single-argument generic, a tuple, a parameter list or +`[…]` sugar breaks only when something inside it breaks, so a signature's parameter list opens +up around a broken parameter type. A type that fits stays on one line, and so does a line that +is long for any other reason (many parameters, a trailing comment). Off by default. With it on, +a declaration no longer sits on one line: grep for a short name, not a whole one-line type +spelling, and do not feed the output to anything that expects one declaration per line. +`--maximum-line-width` without `--multiline-types` is a usage error. `diff`, `evolution` and +`snapshot` do not take these flags. `--emit-private-source-files` puts a comment above each declaration whose name carries a private discriminator, naming the source file the discriminator was derived from: @@ -200,8 +216,9 @@ switches). Only `interface` has: `--exported-only`, `--sort-members-by-offset`, `--parse-opaque-return-type`, `--show-c-imported-types`, `--resolve-c-module-names`, -`--supplementary-apinotes`, `--infer-objc-overrides`, `--requirements-on-associated-types`, -`--expand-macros`. +`--resolve-moved-type-modules`, `--supplementary-apinotes`, `--c-imported-type-name-spelling`, +`--infer-objc-overrides`, +`--requirements-on-associated-types`, `--expand-macros`. `--requirements-on-associated-types` changes where a protocol's requirements print, never which: `associatedtype Body: SwiftUI.View` instead of `protocol View where Self.Body: SwiftUI.View`, @@ -335,15 +352,53 @@ swift-section evolution 17.0.json 18.0.json /path/Foo --labels 17.0,18.0,26.0 one as changed. Formats 8 through 12 only ever existed on the development branch, between those changes. -## 8. `--resolve-c-module-names` (interface, macOS only) - -Turns `__C.NSString` into `Foundation.NSString`. Needs macOS 13+ and an Xcode installation, and -the first run per SDK generates module interfaces through sourcekitd — slow once, cached after. -Attribution against a non-macOS binary is limited (it warns and degrades rather than failing). -`--supplementary-apinotes` only does anything alongside it. +## 8. `--resolve-c-module-names` and `--resolve-moved-type-modules` (interface, macOS only) + +Turns `__C.NSString` into `Foundation.NSString`, and applies the SDK's Swift renames: a +`SwiftPrivate` type prints with `__` (`UIKit.__UICellConfigurationState`), a `SwiftName` one under +that name (`PencilKit.PKDrawingReference`). Needs macOS 13+ and the binary's SDK in the active +developer directory — Xcode, or the Command Line Tools for macOS and Mac Catalyst binaries. The +first run per SDK generates module interfaces through sourcekitd — slow once (UIKit takes about two +minutes), cached after in `~/Library/Application Support/swift-type-indexing`. Without sourcekitd only +API notes, Objective-C metadata and exported `GetTypeID` functions attribute names. A binary whose SDK +is not installed warns and prints `__C.` unresolved. `--supplementary-apinotes` only does anything +alongside it. + +**A private CF type is attributed to the image exporting its `GetTypeID`.** No SDK header declares +`CGSVGDocumentRef`, but CoreSVG exports `CGSVGDocumentGetTypeID`, so SwiftUICore's reference prints +as `CoreSVG.CGSVGDocument`. Only the binary itself and its direct dependencies are read: a type whose +function lives in a re-exported sub-framework (LaunchServices under CoreServices) or a transitive +dependency keeps the bare Swift name. The export only says where a type lives: a name is attributed +this way only when the binary's own metadata shows it is a CF class (a C-imported class descriptor +promoted from a typedef), so a reference with no such descriptor stays `__C.CGSVGDocumentRef`, and a +bridged type nobody exports a `GetTypeID` for keeps its bare name. + +**Swift names come first, with or without the SDK.** A C type has two names: its descriptor carries the one Swift code uses, every mangled reference the C one. `interface` prints the Swift one everywhere — declaration, member types, extension headers — when the binary's own descriptor gives it (`AnyWeakAttribute` for `AGWeakAttribute`, `CGColor` for `CGColorRef`), with no module when nothing resolves it and under its module when this flag does. A descriptor with no separate C name says the two names are one, so such a type prints bare too (`AGDescriptionOption`, not `__C.AGDescriptionOption`). `__C.` stays in two cases. The binary has no descriptor for the type, because it passes the type around but never needs its metadata (`__C.AGValueOptions`): nothing in the binary says what Swift calls it, and the image that does carry its descriptor may be one that links this binary, not one it links. Or the descriptor's name may be only the leaf of a member import (`__C.AGTreeValue`, whose descriptor says `TreeValue`; see section 9). `--c-imported-type-name-spelling c-name` prints every C-imported type as the binary mangles it (`struct AGWeakAttribute`, `__C.AGWeakAttribute`) and makes this flag do nothing. + +**`interface`'s expanded field-offset comments spell their types the way the declarations do**: the rows under `var base: AnyWeakAttribute` read `identifier (AnyAttribute)`, follow `--c-imported-type-name-spelling`, `--module-selectors` (`Swift::UInt32`) and `--existential-any`, use `?` / `[…]` sugar, and print a private type without its discriminator, as its declaration does. `dump`'s rows keep the plain demangled spelling (`__C.AGAttribute`, `Swift.UInt32`, `(Foo in _ABC…)`), so the two commands' comments differ for the same field. A row whose type comes from a dependency image is spelled with the root binary's descriptors only, so it can keep `__C.` where that dependency's own interface prints a bare name. + +**`--resolve-moved-type-modules` is the Swift-type counterpart, and independent of it.** When the +SDK moves a Swift type to another module it marks the declaration `@_originallyDefinedIn`, and the +compiler keeps mangling the type — and every type nested in it — under the old module, so the binary +only ever says `CoreGraphics.CGFloat` and `SwiftUI.View`. This flag prints them as the SDK declares +them, `CoreFoundation.CGFloat` and `SwiftUICore.View`, references, module selectors and extension +headers alike. It reads the SDK's textual `.swiftinterface` files (about two seconds, no sourcekitd), +and only rewrites a type the binary's own SDK (`LC_BUILD_VERSION`'s `sdk`) already had moved: the +macOS 14 SwiftUI keeps `SwiftUI.View`, since `View` moved in macOS 15. Off by default, because the +result depends on the SDK installed on the machine. Both spellings compile — the old module +re-exports the new one — so the `import` lines are left as they are. + +`objc interface --mark-sdk-swift-names` reads the same SDK's API notes for an Objective-C header: +the class's or protocol's `NS_SWIFT_NAME(...)` / `NS_REFINED_FOR_SWIFT` on a line above +`@interface`, a member's before its `;`. API notes only, about two seconds, no sourcekitd. ## 9. Reading the output: things that look like bugs and are not +- **A C type imported as a member keeps its C name** (`struct NSAttributedStringKey`, + `__C.NSAttributedStringKey`) unless `--resolve-c-module-names` spells it + (`Foundation.NSAttributedString.Key`): its descriptor stores only the leaf (`Key`), and nothing + in the binary names the type it belongs to. A top-level rename shaped the same way + (`NSDecimal` → `Decimal`) keeps its C name too. - **`// not exported`** is an export-trie fact, not an access-level claim. A missing entry means "not statically callable from outside this image", which is not the same as `internal`. - **`… is declared in Enabled.swift of module SwiftUICore`** above a SwiftUI declaration is not a @@ -414,7 +469,12 @@ Attribution against a non-macOS binary is limited (it warns and degrades rather protocol has no Swift conformance record. An extension in the class's own module is folded into the class there, so its conformances show in the header too, while `extension __C.NSView: M.P {}` is an extension of another module's class (its category). - Neither shows in `diff`, `evolution` or a snapshot. + Neither shows in `diff`, `evolution` or a snapshot. An image no Swift code went into (its + `objc_image_info` carries no Swift version, as in every framework from before Swift) prints + no such extension. In an image with Swift, the categories its Objective-C code declares + print the same way: the linker merges the categories of one class, so + `extension __C.NSString: __C.NSPasteboardWriting, …` from AppKit can list protocols the + Objective-C headers adopt. Check a header before reading one as Swift's. - **`@objc(Name)` above a class** is the name the Objective-C runtime knows it by, and matters even when it equals the Swift name (`@objc(NSScrollPocket) class NSScrollPocket`): without it the runtime name would be the `_TtC…` mangling. That is also the class name `objc` headers diff --git a/AgentPlugins/swift-section/skills/swift-section-cli/references/cross-references.md b/AgentPlugins/swift-section/skills/swift-section-cli/references/cross-references.md index 9f84b70bc..5b2038a1a 100644 --- a/AgentPlugins/swift-section/skills/swift-section-cli/references/cross-references.md +++ b/AgentPlugins/swift-section/skills/swift-section-cli/references/cross-references.md @@ -1,7 +1,8 @@ # `refs` and `symbolicate` Two subcommands that read arm64 machine code rather than metadata: who references a selector, -a symbol, a class, a function, an instance variable or a string — and what an address is. They +a symbol, a class, a function, an instance variable, a string or a Swift type — and what an +address is. They work on a whole dyld shared cache (an archived one, another device's, or the running system's, read from its files) or on a set of standalone Mach-O files read together, without IDA and without loading anything into a process. @@ -17,12 +18,22 @@ swift-section refs --class NSWindow --uses-system-dyld-shared-cache --in-image A # What one function calls, in instruction order swift-section refs --function 0x1880a1000 --callees --uses-system-dyld-shared-cache +# Every reference to a Swift type, by its mangling or a $s…Mn / $s…Ma / $s…N symbol of it +swift-section refs --type 7SwiftUI4TextV --uses-system-dyld-shared-cache --in-image SwiftUICore + +# Every load of an Objective-C instance variable's offset, named . +swift-section refs --ivar NSWindow._frame --uses-system-dyld-shared-cache --in-image AppKit + # An app's executable and its frameworks, read together; a fat file needs -a swift-section refs --symbol _objc_msgSend Foo.app/Contents/MacOS/Foo \ Foo.app/Contents/Frameworks/Bar.framework/Bar -a arm64e # What these addresses are swift-section symbolicate 0x19012345 0x1e1226590 --uses-system-dyld-shared-cache + +# The same in standalone files: symbolicate's arguments are the addresses, so files go in --file +swift-section symbolicate 0x100004a10 --file Foo.app/Contents/MacOS/Foo \ + --file Foo.app/Contents/Frameworks/Bar.framework/Bar -a arm64e ``` ## What a `refs` line says @@ -35,13 +46,17 @@ swift-section symbolicate 0x19012345 0x1e1226590 --uses-system-dyld-shared-cache by its symbol, or, where the symbol table names none, by the export trie, the Objective-C method lists or the Swift metadata (`-[NSWindow …]`, `…Ma`); its address when nothing names it. - **kind** — `call`, `tailCall` (a branch out that does not return), or `reference` (an - address taken: a class object, a type's metadata, a string, an ivar offset). + address taken: a class object, a type's metadata, a string, an ivar offset, a function's + start, a selector handed on). - **route** — how the code got there: `direct`, `imageStub`, `stubIsland`, `cacheSharedStub` (macOS / iOS 27's selector and GOT stubs outside every image), `pointerSlot`, `addressMaterialization`, `literalLoad`, `indirect`. A reference that went through a stub is as real as a direct one; the route is what to check before trusting it. -- **target** — `send sel:` (`to self`, `to NSWindow` when the receiver is known), a function - and its image, a class, `ivar Class._name`, a string, `type …`, `indirect` (`at offset …` when the callee was loaded from memory). +- **target** — `send sel:` (`to self`, `to NSWindow` when the receiver is known), `selector + sel:` (loaded but sent nothing with: an argument of `respondsToSelector:` or + `performSelector:`, a returned selector, an action), a function and its image, a class, + `ivar Class._name`, a string, `type …`, `indirect` (`at offset …` when the callee was loaded + from memory). A one-line summary goes to stderr: how many references, in how many images, and how many images were scanned. @@ -52,6 +67,11 @@ were scanned. images share one address space; **standalone files each have their own**, and two dylibs linked at 0 overlap. `--function` names the file with `--function-image` when the address is ambiguous (the command says so), and `symbolicate` takes `--in-image` for the same reason. +- **`refs` takes its files as arguments, `symbolicate` takes them with `--file`**: `symbolicate`'s + arguments are the addresses. `--file` repeats, once per file, and the files are read together + as dyld would load them; a path given as an argument is parsed as an address and rejected. +- **`--ivar` takes `.`** (`NSWindow._frame`) and lists every load of the ivar's + offset variable. `--symbol _OBJC_IVAR_$_NSWindow._frame` names the same variable by its symbol. - **A fat file needs `-a`**, as everywhere in this tool. Only arm64 / arm64e slices can be analyzed; anything else fails with "holds no arm64 code". - **`--in-image` narrows where to look, not where the subject is.** `refs --symbol _foo @@ -64,12 +84,30 @@ were scanned. whole cache, name the images. - **`--class` on a class no symbol exports** (most private classes in a cache) reads every image's class list first; the first such query takes a few seconds longer. +- **`--selector` lists more than sends**: a `selector` row is the selector loaded from the + image's `__objc_selrefs` and handed on. A dyld cache's builder rewrites those loads into the + selector string's address, so inside a cache only the sends show; in an app's files both do. +- **`--function` lists the code that takes the function's address too** (`kind reference`, + route `addressMaterialization`): a block's invoke function shows the function that builds the + block, a callback the function that hands it to `dispatch_async_f`. A call-hierarchy walk can + go through blocks and closures this way; data that points at a function (a method list, a + vtable) still does not show. +- **`--type` takes a mangling, not a Swift name**: `7SwiftUI4TextV`, or a symbol of the type + (`$s7SwiftUI4TextVMn`, `_$s…Ma`, `$s…N`). In a dyld cache, a type no image exports a + descriptor of (an internal one) needs `--type-image `, the image that defines it; a set + of files is searched whole. A Swift class is also listed as the Objective-C class it is. +- **A class reference can sit at an `add`**: optimized Swift code builds the address of a + class's GOT slot and hands it to the helper that makes the class's metadata, so the reference + is where the slot's address is built, not where it is loaded. - **`--json`** prints one document whose every address is a hexadecimal string, never a number. Its field names are a contract. `--limit` keeps the first references in image and address order and sets `isTruncated`. - **Not reported, by design or not yet**: a call through a vtable, a witness table or any register says `indirect` with what the call site shows (the offset of the load, the pointer- - authentication discriminator) but no callee — never which table it was; a Swift class's stored-property offset variables are not + authentication discriminator) but no callee — never which table it was; a load from + `__objc_superrefs` is the start of a super send, reported as `send super …`, never as a + reference to the class; data references (a method list's IMP, a pointer in `__const`); a + Swift class's stored-property offset variables are not reported as ivar references; an app read together with the running system's cache is not supported — read the app's files alone, and a call into a system library stays the imported symbol it is. diff --git a/Changelogs/0.28.0.md b/Changelogs/0.28.0.md new file mode 100644 index 000000000..59230c908 --- /dev/null +++ b/Changelogs/0.28.0.md @@ -0,0 +1,29 @@ +# 0.28.0 + +## Breaking + +- Requires MachOKitExtensions 3.4.0, MachOObjCSection 0.10.102 and swift-type-indexing 0.2.0. +- The `TypeIndexing` product moved to the swift-type-indexing package. +- C and Objective-C types now print under their Swift names; `--c-imported-type-name-spelling c-name` restores the C names. + +## New + +- `--multiline-types` and `--maximum-line-width` break long types over several lines in `dump` and `interface`. +- `interface --resolve-moved-type-modules` prints a type the SDK moved under the module that declares it now. +- `refs --type` lists the references to a Swift type. +- `objc interface --mark-sdk-swift-names` marks the `NS_SWIFT_NAME` and `NS_REFINED_FOR_SWIFT` the SDK gives a declaration. +- Stored properties of `@objc @implementation` classes known only by their ivar get their Swift type back. + +## Improved + +- `refs` finds more references, including selectors loaded but never sent and functions whose address is taken. +- `--resolve-c-module-names` also finds the module of private CF types. + +## Fixed + +- Objective-C categories in an image without Swift code no longer show up as Swift conformances. +- Static layouts no longer mix up two private types with the same name. +- `symbolicate` no longer says a slot holding a descriptor points at a function, and `--in-image` reads every image of that name. +- `refs --type` no longer misses types instantiated from their mangled name in stripped standalone files. +- Swift symbols are recognized when the library is linked statically. +- Fixed hangs and crashes on malformed binaries. diff --git a/Documentations/Evolutions/0097-offline-cross-references-and-symbolication.md b/Documentations/Evolutions/0097-offline-cross-references-and-symbolication.md index dd50b40f4..35f2ce6bd 100644 --- a/Documentations/Evolutions/0097-offline-cross-references-and-symbolication.md +++ b/Documentations/Evolutions/0097-offline-cross-references-and-symbolication.md @@ -902,3 +902,4 @@ README 的 CLI 一节、`swift-section-cli` skill、四个模块参考文档(` | 2026-11-19 | RuntimeViewer 交叉引用模块的并发超时是基线就有的 | 在沙盒里对本分支跑 RuntimeViewer 整个交叉引用测试模块(82 条并发),「分析器换新后要重新读名字」的两条等了 60 秒没等到;基线(RuntimeViewer 远端 `next` 加本库 `next`)整模块跑同样有其中一条在同一行失败,两边单跑这一组(18 条)都在 41 秒内全过。是会话队列在整模块并发时被前面的准备工作占满,与本次改动无关,没有修 | | 2026-11-19 | 实现完成,待用户看过后收尾 | 九个落地步骤都已完成。本库全量测试(跳过 IntegrationTests)2,993 个零失败;渲染 A/B 84 对一致;RuntimeViewer 一侧在沙盒里对本分支编过 Core、CLI 与 MCP 三个包,新测试全过,App 工程本身没有构建。文档判断:配套使用指南不另写——CLI 的用法与契约写在 README、`swift-section` 插件的 `references/cross-references.md` 与 RuntimeViewer 的 `Guides/CommandLineInterface.md`,实现细节在三份模块文档;新术语「地址符号化」「识别器」「引用路线」「stub island」已登记进术语表。两个仓库的功能分支已在本地合进各自常驻的 `next` 检出,没有推送 | | 2026-11-19 | Implemented,取号 0097,两个仓库合进各自的 `next` 并推送 | 用户验收后批准收尾。验收在 JHs-Mac-Studio-Ultra 上用功能分支的 release 版 CLI 做(Xcode 27.2,本地兄弟依赖):运行中系统 cache 里 `makeKeyAndOrderFront:` 的 439 处发送,0.7 秒;归档 27.0 与 27.2 cache 里 `UINSPasteboardWritingItemProvider` 的两个调用者;cache 共用 `objc_msgSend` 桩解成 selector(`ipsw dyld a2s` 对同一地址只回 `?`),GOT 槽、类对象与未映射地址的符号化;TextEdit 胖文件带 `-a arm64e` 找到 4 处发送,不带时按约定报错。落地前验证沿用「实现完成」一行的结果,之后只改了文档。文档判断不变:不另写使用指南,配套文档登记在头部,新术语已登记。正文去掉了段内硬换行,内容不变。没做完的列在「后续项」 | +| 2026-11-26 | 补做全面核对 | 按 2026-11-18 的方法复测 0.25.0:标准答案与选目标的代码从当次对话记录原样取回,复现出同一批 120 个目标。代码引用召回 90.3%,IDA 一次查询 97.0%、两跳 99.4%。数字与漏报原因写进愿景「我们选的方向」第 1 条的复测段,修复另起提案 [0113-cross-reference-recall-gaps](0113-cross-reference-recall-gaps.md)。上文「全面核对没有重做」一段留下的缺口至此补上 | diff --git a/Documentations/Evolutions/0099-tuist-workspace.html b/Documentations/Evolutions/0099-tuist-workspace.html new file mode 100644 index 000000000..c4b9912ea --- /dev/null +++ b/Documentations/Evolutions/0099-tuist-workspace.html @@ -0,0 +1,1028 @@ + + + + + + +Draft - Tuist 开发 workspace:第三方依赖走二进制缓存,上游库可切换为本地检出 + + + + +
+ +
+

MachOSwiftSectionEvolutions0099

+

0099 Tuist 开发 workspace:第三方依赖走二进制缓存,上游库可切换为本地检出

+
+
状态
Implemented
+
最后更新
2026-11-20
+
项目类型
库
+
原文
0099-tuist-workspace.md
+
+
+ + + +
+ +
+

摘要

+

在原生的 MachOSwiftSection.xcworkspace 之外,加一条只供日常开发用的 Tuist 路:./TuistScript.sh 生成 MachOSwiftSection-Tuist.xcworkspace。本库照常从源码编,可以跳转、可以编辑;27 个真正的第三方依赖(swift-dependencies 一族、swift-collections、Capstone、swift-crypto、Yams……)预编进本机的 Tuist 二进制缓存,只编一次。原生 workspace 里放的五个上游库——MachOKit、MachOKitExtensions、MachOObjCSection、swift-demangling、swift-semantic-string——默认按锁文件版本从源码编;加上 --local-dependencies 就改用检出旁边(worktree 里就是 .worktrees/ 下那组链接)的本地检出,没提交的改动也算,--remote-dependencies 切回,选过的模式会记住。

+

Tuist workspace 能跑测试:本库 21 个测试 target 由 Tuist 从 Package.swift 转换过来,依赖可执行 target 的 SwiftSectionCommandTests 在一个小的 Tuist 工程里手写;本地模式下五个上游库的测试也一起进来。做到这一点要在本库和三个上游库的 Package.swift 末尾加同一段适配,它只在 Tuist 解析时设下的环境变量下生效,平时的 SwiftPM、Xcode 与 CI 一律不受影响。RuntimeViewer 的本地依赖模式也会往这几个检出里写同名工程,两边的脚本改成共用一份占用记录,一边占着时另一边直接报错。发版、CI、swift build / swift test 和原生 workspace 都不变。

+
+ +
+

要你定

+
+

已定:本地模式下的测试

+
    +
  1. 给 MachOKitExtensions、MachOObjCSection、swift-demangling 三个上游库的 Package.swift 末尾加同一段适配(默认不生效),换来本地模式下六个包的测试都能在 Tuist workspace 里跑;还是不改上游库,本地模式下不映射任何测试(RuntimeViewer 的做法,连本库自己的测试也没有)?用户选了前者:加适配块,本地模式带测试。
  2. +
+
+
+ +
+

动机

+
    +
  • 第三方依赖在每个干净的 DerivedData 里都要重编一遍。本库的依赖闭包里有 27 个与本仓库开发无关的包。原生 workspace 走 Xcode 自带的 SwiftPM 集成,每换一个 DerivedData(新 worktree、清缓存、换 Xcode)就全部从源码编一次。Tuist 的二进制缓存按内容寻址,同一台机器、同一个 Xcode 下只编一次。RuntimeViewer 用同样的做法量过:完整 App 从空 DerivedData 构建,不用缓存 504 秒,走缓存 155 秒。本库在 Ultra 上量的:清空 DerivedData 编 swift-section,不走缓存 63 秒,走缓存 46 秒(决策日志「缓存计时」)。
  • +
  • 原生 workspace 切换本地上游库的方式太粗。今天的切换靠 USING_LOCAL_DEPENDENCIES=1 加兄弟目录是否存在(Package.swift:42 起的 package(local:remote:)):这个变量要进到 Xcode 的启动环境里才生效;对所有声明了本地路径的依赖一刀切,连 workspace 里没有列出的 swift-capstone(Package.swift:275)也会被换成本地;切换后要等 Xcode 重新解析。Tuist 这边由 Tuist/Package.swift 按路径逐个声明要本地化的库,名单就是 workspace 的成员,切换只发生在命令行上。
  • +
  • RuntimeViewer 的本地依赖模式已经在往本仓库的检出里写工程,而没有任何东西拦着另一方。它在每个按路径声明的包目录里生成 <包名>.xcodeproj 与 Derived/。2026-11-20 实测:RuntimeViewer 的集成 worktree 正占着本库的集成 worktree,本 worktree 根目录那份被忽略的 MachOSwiftSection.xcodeproj 就是它生成的。本库自己的 Tuist 也会在同一位置生成同名工程,两边的 PackageSettings 不同,谁后生成谁就让另一边的 workspace 坏掉。
  • +
+
+ +
+

提议方案

+
    +
  1. 新增 Tuist 描述,全部是开发用的:mise.toml 钉 Tuist 4.210.0(与 RuntimeViewer 相同);Tuist/Package.swift 按路径声明本库、预编译 swift-syntax、只被测试用到的 swift-snapshot-testing,本地模式下再按路径声明五个上游库,PackageSettings 恢复警告、补 Capstone 的 trait 宏、按需调测试设置;Tuist/CommandLine/Project.swift 放 swift-section CLI、给测试用的 swift_section 模块与 SwiftSectionCommandTests;Workspace.swift 命名 MachOSwiftSection-Tuist,每个映射了测试的包一个测试 scheme(不含 IntegrationTests);Tuist.swift 只缓存外部依赖,本库与五个上游库的全部 target 留作源码,名单由脚本经环境变量传入。
  2. +
  3. Package.swift 末尾加一段适配,只在 TUIST_MAPS_LOCAL_PACKAGE_TESTS=1 时生效:摘掉依赖本包可执行 target 的测试,给测试依赖却不属于任何 product 的普通 target 补 library product。同一段代码原样加进 MachOKitExtensions、MachOObjCSection、swift-demangling。
  4. +
  5. TuistScript.sh:install、generate、warm、build、test、release 六个命令,--local-dependencies / --remote-dependencies 切换并记住模式,--configuration Debug|Release,--dry-run。依赖 checkout、缓存与产物放 /Volumes/DerivedData/MachOSwiftSection/Tuist/。本地模式开始前先读各上游库的清单,有包会被 Tuist 拒掉测试时整体关掉测试映射并点名,而不是让生成失败。
  6. +
  7. 占用记录两边共用:被占检出的 git 目录里写 tuist-generated-project-owner(占用者路径、释放它的命令),占用者在自己的 Tuist/.claimed-checkouts 列出手里的检出,列着才算有效。本库的脚本在任何模式下都占着自己的检出,本地模式下再占五个上游库;RuntimeViewer 的脚本改用同一份记录,旧记录仍然认。
  8. +
  9. 文档:使用指南 Documentations/Internal/TuistDevelopment.md,AGENTS.md 构建一节加一条,Documentations/README.md 登记。
  10. +
+

非目标

+
    +
  • 不替代原生 workspace、swift build / swift test 与 CI;Package.swift 仍是 target 与依赖的唯一定义。
  • +
  • 不做「与原生工程对照」的 check,不重排导航栏:本库没有原生 App 工程可对照,唯一手抄的是 CLI 的依赖清单。
  • +
  • 只做 macOS,只有 Debug 与 Release 两套配置。
  • +
  • 不映射 reader-benchmark、baseline-generator,没有 regen-baselines 插件,照旧 swift run / swift package。
  • +
  • 不跑 IntegrationTests:target 会被转换进来,但不进任何 scheme。
  • +
  • 不上传缓存:不设 fullHandle。
  • +
  • MachOKit 与 swift-semantic-string 不改:实测它们现在不需要适配。
  • +
  • 不改 USING_LOCAL_DEPENDENCIES 机制:脚本运行时忽略这个变量并提示。
  • +
+
+ +
+

架构图

+

改了什么

+
    +
  • 新增
  • +
  • 修改
  • +
  • 不变 / 生成物
  • +
+
+ + + MachOSwiftSection/ (a checkout) + TuistScript.shinstall generate warm build test release + Tuist/CommandLine/Project.swiftswift-section, swift_section, command tests + Workspace.swiftMachOSwiftSection-Tuist, test schemes + Tuist.swiftcache profile "development" + mise.tomltuist 4.210.0 + Tuist/Package.swiftthe graph Tuist converts + Package.swift+ TUIST_MAPS_LOCAL_PACKAGE_TESTS block + MachOSwiftSection.xcworkspace+ 3 upstream members + .gitignore+ generated outputs + generated, ignoredMachOSwiftSection-Tuist.xcworkspaceMachOSwiftSection.xcodeproj, Derived/Tuist/CommandLine/*.xcodeproj + + by path + + + upstream checkouts (../) + MachOKitExtensions/Package.swift+ the same block + MachOObjCSection/Package.swift+ the same block + swift-demangling/Package.swift+ the same block + MachOKit, swift-semantic-stringunchanged + + local + + + RuntimeViewer/ + TuistScript.shclaims through the shared record + Documentations/Guides/TuistDevelopment.md follows + +
+

本库新增六个 Tuist 文件、改三个文件;三个上游库各改 Package.swift,RuntimeViewer 改脚本与指南。虚线箭头:只在本地模式下按路径声明。

+ +

生成出的 workspace 里有什么

+
    +
  • 手写的 Tuist target
  • +
  • Tuist 从 Package.swift 转换来的
  • +
+
+ + + Tuist/CommandLine (hand-written) + swift-sectioncommandLineTool + swift_sectionstaticFramework, same sources + SwiftSectionCommandTestsunitTests, @testable import + + + + converted from the Package.swift files + MachOSwiftSection.xcodeprojsource, 27 targets + 21 tests + five upstream packagessource; their tests in the local mode + third-party packagesbinary cache after warm + swift-syntax (precompiled)xcframeworks + + + + .external + + + remote mode: upstream from checkouts/, at the pinned versions + local mode: upstream from ../<name>, uncommitted edits included + +
+

CLI 源码编两遍:一遍成 tool,一遍成给测试用的 framework。

+ +

一条命令怎么走

+
+ + check the pinned Tuist, unset USING_LOCAL_DEPENDENCIESmise.toml + read the local package namesMachOSwiftSection.xcworkspace: container:../<name> + record the modeTuist/.local-dependencies ← the upstream directory + read the manifests (dump-package, TUIST_MAPS_LOCAL_PACKAGE_TESTS=1)→ TUIST_SOURCE_TARGET_NAMES, TUIST_PACKAGE_TEST_TARGETSa test Tuist would reject? → mapping off + a warning naming the package + ensure_dependenciesSWIFTPM_BUILD_DIR per mode; seed Tuist/Package.resolved; tuist install + claim the checkoutsthis checkout + the five upstream onesanother live owner? → fail with the owner's release command + tuist generate --no-openMachOSwiftSection-Tuist.xcworkspace + + + + + + + +
+

绿色两步是 RuntimeViewer 脚本里没有的:清单预检与占用本库自己的检出。

+ +

占用记录(两个仓库的脚本共用)

+
+ + + claimed checkout + <git dir>/tuist-generated-project-ownerline 1: /path/to/owner/checkoutline 2: ./TuistScript.sh release (MachOSwiftSection) ./TuistScript.sh generate --remote-dependencies (RuntimeViewer) + <git dir>/runtimeviewer-tuist-local-dependencieslegacy; live ⇔ owner's Tuist/.local-dependencies/<name> is this checkout + + owner checkout + Tuist/.claimed-checkoutsone real path per line + + a claim is live ⇔ the owner's list holds the claimed real path; + a stale claim is taken over silently + +
+
+ +
+

改动地图

+
+ + + + + + + + + + + + + + + + + + + + + + + +
文件 / 类型动作改什么为什么步骤
mise.toml新增[tools] tuist = "4.210.0"两台机器、两个仓库用同一个 Tuist;RuntimeViewer 记下的坑都是这个版本1
Tuist/Package.swift新增按路径声明本库、预编译 swift-syntax,按 URL 声明 swift-snapshot-testing;本地模式加五个上游库;PackageSettingsTuist 的依赖图从这里来;路径依赖顶替图里同名的 URL 声明1、2、3
Tuist/CommandLine/Project.swift新增swift-section、swift_section、SwiftSectionCommandTests 三个 targetTuist 不转换可执行 target,也不接受依赖它的测试(实测第 1、5 条)1、2
Workspace.swift新增workspace 名 MachOSwiftSection-Tuist,成员 Tuist/CommandLine,按包生成测试 scheme不与原生 workspace 同名;测试 target 在转换出的工程里,只能由 workspace 的 scheme 引用1、2
Tuist.swift新增缓存 profile development:.onlyExternal,例外取 TUIST_SOURCE_TARGET_NAMES本库与上游库留作源码,其余进缓存;名单由脚本从清单算(实测第 9 条)4
TuistScript.sh新增六个命令、两种依赖模式、存放位置、日志、锁文件种子与比对、占用记录、测试映射的预检直接跑 tuist 拿不到正确的环境变量与占用保护1–5
Package.swift修改文件末尾加 TUIST_MAPS_LOCAL_PACKAGE_TESTS 适配块让 Tuist 能映射本库测试(实测第 1–4 条);变量不设时什么都不变2
MachOSwiftSection.xcworkspace/contents.xcworkspacedata修改加入 MachOKitExtensions、swift-demangling、swift-semantic-string,与集成 worktree 里未提交的改动内容相同脚本从这里读本地依赖名单,五个都要在1
.gitignore修改忽略 Tuist workspace、根目录的 MachOSwiftSection.xcodeproj/ 与 Derived/、Tuist/.build*/、Tuist/CommandLine/ 下的生成物、Tuist/.local-dependencies、Tuist/.claimed-checkouts生成物不提交;根目录那两项今天只靠 RuntimeViewer 写进 info/exclude 才被忽略1
MachOKitExtensions Package.swift修改末尾加同一段适配块本地模式下 CPlusPlusSymbolsFixture 找不到(实测第 7 条)3
MachOObjCSection Package.swift修改同上本地模式下 ObjCSectionCommandTests 被拒(实测第 6 条)3
swift-demangling Package.swift修改同上本地模式下 DemanglingTestingSupport 找不到(实测第 7 条)3
RuntimeViewer TuistScript.sh · claim_local_checkouts / release_local_checkouts修改改用共用的 tuist-generated-project-owner 与 Tuist/.claimed-checkouts;旧记录照旧认、自己占着的顺手删掉双向互斥:今天它看不见本库的占用5
RuntimeViewer Documentations/Guides/TuistDevelopment.md修改「写进库目录的文件」「同一时刻只让一个检出用这组库」两段改写成共用的占用记录文档与代码同批5
Documentations/Internal/TuistDevelopment.md新增使用指南:第一次使用、日常用法、两种模式、占用记录、存放位置、已知的坑维护者要知道怎么用、什么时候要重新 install / generate6
AGENTS.md修改构建一节加一条:只经脚本运行,agent 设 TUIST_SCRIPT_ROOT 并经 queued-buildagent 默认会直接跑 tuist generate,那样既没有环境变量也没有占用保护6
Documentations/README.md修改Internal 一节登记新指南文档索引6
Documentations/Evolutions/README.md修改状态表加本提案提案索引创建、落地
Documentations/Internal/ProjectEvolutionLog.md修改落地时加一节演进账本落地
+
+
+ +
+

详细设计

+
+ Package.swift 的适配块 +
+

本库与三个上游库的 Package.swift 末尾原样加这一段(探针里五个上游库副本都用它通过了 swift package dump-package 与 tuist generate)。它读的是 Context.environment,平时这个变量不存在,块里什么都不做;作为别人的远程依赖时也一样。

+
// MachOSwiftSection's Tuist development workspace (its Documentations/Internal/TuistDevelopment.md)
+// maps this package's tests with Tuist, which rejects two shapes SwiftPM accepts: a test that depends
+// on an executable target, and a test that depends on a target no product contains. Only while Tuist
+// resolves the packages, with TUIST_MAPS_LOCAL_PACKAGE_TESTS=1, the first kind is left out and the
+// second kind gets a library product of its own. Nothing changes without the variable.
+if Context.environment["TUIST_MAPS_LOCAL_PACKAGE_TESTS"] == "1" {
+    let executableTargetNames = Set(package.targets.filter { $0.type == .executable }.map(\.name))
+    func dependencyName(_ dependency: Target.Dependency) -> String? {
+        switch dependency {
+        case .targetItem(let name, _), .byNameItem(let name, _):
+            return name
+        default:
+            return nil
+        }
+    }
+    package.targets.removeAll { target in
+        target.type == .test && target.dependencies.contains { dependency in
+            dependencyName(dependency).map(executableTargetNames.contains) ?? false
+        }
+    }
+    let productTargetNames = Set(package.products.flatMap { product in (product as? Product.Library)?.targets ?? [] })
+    let testDependencyNames = Set(package.targets.filter { $0.type == .test }.flatMap { $0.dependencies.compactMap(dependencyName) })
+    package.products += package.targets
+        .filter { target in target.type == .regular && testDependencyNames.contains(target.name) && !productTargetNames.contains(target.name) }
+        .map { target in Product.library(name: target.name, targets: [target.name]) }
+}
+
    +
  • 在本库里它摘掉 SwiftSectionCommandTests,给 SwiftSectionFixtureSupport、SwiftSectionTestingSupport(以及测试直接依赖的其余普通 target)补 product。在 MachOObjCSection 里摘掉 ObjCSectionCommandTests;在 MachOKitExtensions 与 swift-demangling 里补 CPlusPlusSymbolsFixture、DemanglingTestingSupport 的 product。
  • +
  • 被摘掉的测试 Tuist workspace 里就没有了,照旧用 swift test --filter 跑;本库的 SwiftSectionCommandTests 例外,它在 Tuist/CommandLine/Project.swift 里手写(下文)。MachOObjCSection 的 ObjCSectionCommandTests 不手写:那要在本库描述另一个仓库的 target,非目标。
  • +
  • 只看 target 依赖(targetItem / byNameItem),不看 productItem:依赖别的包的可执行 product 的测试,Tuist 怎么处理没有实测,目前四个包里也没有。
  • +
+
+
+
+ Tuist/Package.swift +
+
// swift-tools-version: 6.2
+import Foundation
+import PackageDescription
+
+// The dependencies of MachOSwiftSection-Tuist.xcworkspace, the development-only Tuist workspace
+// (Documentations/Internal/TuistDevelopment.md). Generate it with ./TuistScript.sh, never with a bare
+// `tuist generate`: the script sets the variables everything below reads.
+//
+// MachOSwiftSection itself is declared by path, so its Package.swift stays the only definition of its
+// targets and dependencies. In the local dependency mode (`./TuistScript.sh <command>
+// --local-dependencies`) the script names the upstream packages the native workspace lists beside
+// the checkout in TUIST_LOCAL_PACKAGE_NAMES and the directory holding them in
+// TUIST_LOCAL_PACKAGE_CHECKOUTS. A root's path dependency stands in for every other declaration of the
+// same package in the graph — MachOSwiftSection's URLs and the upstream packages' own — so they build
+// from those checkouts, uncommitted edits included. A path package's identity is its directory's name.
+let processEnvironment = ProcessInfo.processInfo.environment
+let localPackageCheckoutsDirectory = processEnvironment["TUIST_LOCAL_PACKAGE_CHECKOUTS"] ?? ""
+let localPackageNames = (processEnvironment["TUIST_LOCAL_PACKAGE_NAMES"] ?? "")
+    .split(separator: ",")
+    .map(String.init)
+// Qualified: Tuist evaluates this file with ProjectDescription imported too, which has a Package of
+// its own.
+let localPackageDependencies: [PackageDescription.Package.Dependency] = localPackageCheckoutsDirectory.isEmpty
+    ? []
+    : localPackageNames.map { packageName in .package(path: "\(localPackageCheckoutsDirectory)/\(packageName)") }
+
+#if TUIST
+    import ProjectDescription
+
+    func targetNames(in variable: String) -> [String] {
+        (processEnvironment[variable] ?? "").split(separator: ",").map(String.init)
+    }
+
+    // Tuist suppresses warnings in every package; Xcode does so for remote packages only. The targets
+    // of the packages declared by path get theirs back: MachOSwiftSection always, the upstream
+    // packages in the local dependency mode.
+    let warningSettings: [String: Settings] = Dictionary(
+        targetNames(in: "TUIST_WARNING_TARGET_NAMES").map { targetName in
+            (targetName, Settings.settings(base: ["SWIFT_SUPPRESS_WARNINGS": "NO", "GCC_WARN_INHIBIT_ALL_WARNINGS": "NO"]))
+        },
+        uniquingKeysWith: { first, _ in first }
+    )
+
+    // Tuist drops a package setting whose only condition is a trait. MachOSwiftSection enables
+    // swift-capstone's AARCH64 trait, which defines CAPSTONE_HAS_AARCH64 for both the Swift wrapper and
+    // the C library that way. Without it the wrapper does not compile, and the C library would compile
+    // but support no architecture at all.
+    let restatedTraitDefinitions: [String: Settings] = [
+        "Capstone": .settings(base: [
+            "SWIFT_ACTIVE_COMPILATION_CONDITIONS": ["$(inherited)", "CAPSTONE_HAS_AARCH64"],
+            "GCC_PREPROCESSOR_DEFINITIONS": ["$(inherited)", "CAPSTONE_HAS_AARCH64=1"],
+        ]),
+        "Ccapstone": .settings(base: [
+            "GCC_PREPROCESSOR_DEFINITIONS": ["$(inherited)", "CAPSTONE_HAS_AARCH64=1"],
+        ]),
+    ]
+
+    // A library target that imports Testing, such as a package's testing support, uses Swift Testing's
+    // macros (#expect, #require). Xcode points only test targets at the toolchain's TestingMacros
+    // plugin; SwiftPM gives it to every target. TUIST_TESTING_SUPPORT_TARGET_NAMES lists the library
+    // targets whose sources import Testing.
+    let testingSupportSettings: [String: Settings] = Dictionary(
+        targetNames(in: "TUIST_TESTING_SUPPORT_TARGET_NAMES").map { targetName in
+            (targetName, Settings.settings(base: [
+                "ENABLE_TESTING_SEARCH_PATHS": "YES",
+                "OTHER_SWIFT_FLAGS": ["$(inherited)", "-plugin-path", "$(TOOLCHAIN_DIR)/usr/lib/swift/host/plugins/testing"],
+            ]))
+        },
+        uniquingKeysWith: { first, _ in first }
+    )
+
+    // The test targets, which SwiftPM builds and links differently in three ways:
+    // - It builds a test target for at least the macOS version XCTest and Swift Testing require (14.0
+    //   with Xcode 26 and 27), whatever its package declares; Tuist takes the package's own minimum, and
+    //   MachOSwiftSection's 10.15 leaves TypeIndexingTests without the macOS 13 APIs it tests.
+    //   TUIST_RAISED_TEST_TARGET_NAMES lists the test targets of the packages that declare less.
+    // - It links each package target's object files whole, where Tuist links static frameworks and the
+    //   linker loads only the archive members something refers to by symbol. A protocol conformance
+    //   nothing names goes missing, and `as?` fails without a word: the readers that wrap a MachOImage
+    //   or MachOFile (MachOReaderWrapper) read as neither. -ObjC also loads every member that defines an
+    //   Objective-C class or category or a Swift type or extension (Xcode 27's linker), as it does for
+    //   RuntimeViewer's Tuist workspace.
+    // - A load-time constructor nothing refers to never runs that way at all: MachOSwiftSection's
+    //   SwiftSymbolsRegistration registers Swift as a symbol language from one. TUIST_FORCE_LOADS pairs
+    //   each final link with the constructor targets its in-package dependencies reach, as
+    //   "<linking target>:<constructor target>,…"; those archives are loaded whole.
+    // TUIST_TEST_TARGET_NAMES lists every mapped test target, IntegrationTests included, so that a build
+    // of the whole workspace compiles and links too. Tuist/CommandLine/Project.swift gives the
+    // swift-section executable and SwiftSectionCommandTests the same link flags.
+    let forceLoadedTargetsByLinkingTarget: [String: [String]] = Dictionary(
+        targetNames(in: "TUIST_FORCE_LOADS").compactMap { pair -> (String, [String])? in
+            let parts = pair.split(separator: ":").map(String.init)
+            return parts.count == 2 ? (parts[0], [parts[1]]) : nil
+        },
+        uniquingKeysWith: +
+    )
+    let raisedTestTargetNames = Set(targetNames(in: "TUIST_RAISED_TEST_TARGET_NAMES"))
+    let testTargetSettings: [String: Settings] = Dictionary(
+        targetNames(in: "TUIST_TEST_TARGET_NAMES").map { targetName in
+            let forceLoadFlags = (forceLoadedTargetsByLinkingTarget[targetName] ?? []).map { loadedTarget in
+                "-Wl,-force_load,$(BUILT_PRODUCTS_DIR)/\(loadedTarget).framework/\(loadedTarget)"
+            }
+            var settings: SettingsDictionary = ["OTHER_LDFLAGS": .array(["$(inherited)", "-ObjC"] + forceLoadFlags)]
+            if raisedTestTargetNames.contains(targetName) {
+                settings["MACOSX_DEPLOYMENT_TARGET"] = "14.0"
+            }
+            return (targetName, Settings.settings(base: settings))
+        },
+        uniquingKeysWith: { first, _ in first }
+    )
+
+    // One target may need several of the settings above; their keys never overlap.
+    func mergingSettings(_ settingsByTarget: [String: Settings]...) -> [String: Settings] {
+        settingsByTarget.reduce(into: [:]) { merged, settings in
+            merged.merge(settings) { first, second in .settings(base: first.base.merging(second.base) { $1 }) }
+        }
+    }
+
+    let packageSettings = PackageSettings(
+        targetSettings: mergingSettings(warningSettings, restatedTraitDefinitions, testTargetSettings, testingSupportSettings),
+        // TuistScript.sh sets the variable to 1 unless a package declared by path still has a test of
+        // a shape Tuist rejects (the manifests' TUIST_MAPS_LOCAL_PACKAGE_TESTS block removes them).
+        includeLocalPackageTestTargets: processEnvironment["TUIST_MAPS_LOCAL_PACKAGE_TESTS"] == "1"
+    )
+#endif
+
+let package = Package(
+    name: "MachOSwiftSectionTuistDependencies",
+    dependencies: [
+        .package(path: ".."),
+        // Stands in for swift-syntax in every macro package, as it does as a member of the native
+        // workspace: SwiftPM matches it by package identity.
+        .package(path: "../PrecompiledLibraries/swift-syntax"),
+        // Used only by MachOSwiftSection's tests. Tuist maps a test target only when every package
+        // its dependencies come from is declared here, with the requirement Package.swift gives it.
+        .package(url: "https://github.com/pointfreeco/swift-snapshot-testing", from: "1.18.9"),
+    ] + localPackageDependencies
+)
+
    +
  • 包名 MachOSwiftSectionTuistDependencies。根包的路径依赖 .. 的身份是目录名:worktree 叫 MachOSwiftSection-<用途> 时身份就变了,而上游库的清单不按 URL 引用本库,所以不受影响;生成的工程名取自 Package(name:),仍是 MachOSwiftSection.xcodeproj。
  • +
  • TUIST_WARNING_TARGET_NAMES 是本库全部 target,本地模式下再加五个上游库的全部 target(与原生 workspace 一致:Xcode 只给远程包关警告)。
  • +
+
+
+
+ Tuist/CommandLine/Project.swift +
+
import ProjectDescription
+
+// What Tuist cannot convert from ../../Package.swift (Documentations/Internal/TuistDevelopment.md):
+// the swift-section executable, and SwiftSectionCommandTests, which imports the executable's module
+// (`@testable import swift_section`). Tuist converts no executable target and rejects a test that
+// depends on one, so Package.swift leaves that test out while Tuist resolves it and it is described
+// here instead. swift_section compiles the command's sources as a static framework for the test; the
+// tool compiles them again, so its link needs no trick around the @main entry point.
+//
+// The dependency list mirrors the swift-section target in Package.swift and is the one hand-written
+// copy in the Tuist description: a dependency added there that is missing here fails to compile.
+let commandLineDependencies: [TargetDependency] = [
+    .external(name: "SwiftSectionKit"),
+    .external(name: "MachOFoundation"),
+    .external(name: "SwiftSymbols"),
+    .external(name: "SwiftDump"),
+    .external(name: "SwiftOutputTransformer"),
+    .external(name: "SwiftDeclaration"),
+    .external(name: "SwiftIndexing"),
+    .external(name: "Semantic"),
+    .external(name: "OutputTransformer"),
+    .external(name: "ObjCDeclarationRendering"),
+    .external(name: "ObjCOutputTransformer"),
+    .external(name: "Rainbow"),
+    .external(name: "ArgumentParser"),
+]
+
+// Tuist builds swift-argument-parser for macOS 12, the minimum that package declares; the package's
+// own 10.15 does not reach the executable here the way SwiftPM's build of it does.
+let commandLineDeploymentTargets: DeploymentTargets = .macOS("12.0")
+
+let commandLineSources: SourceFilesList = ["../../Sources/Executables/swift-section/**"]
+
+// The link flags Tuist/Package.swift gives the package's test targets, for the same reasons: -ObjC, so
+// that the archive members defining Swift types and extensions (protocol conformances among them) are
+// loaded, and -force_load of the constructor targets the swift-section executable reaches in
+// Package.swift, which TuistScript.sh lists in TUIST_FORCE_LOADS.
+let forceLoadedTargetNames: [String] = Environment.forceLoads.getString(default: "")
+    .split(separator: ",")
+    .compactMap { pair in
+        let parts = pair.split(separator: ":").map(String.init)
+        return parts.count == 2 && parts[0] == "swift-section" ? parts[1] : nil
+    }
+let linkFlags: SettingsDictionary = [
+    "OTHER_LDFLAGS": .array(["$(inherited)", "-ObjC"] + forceLoadedTargetNames.map { targetName in
+        "-Wl,-force_load,$(BUILT_PRODUCTS_DIR)/\(targetName).framework/\(targetName)"
+    }),
+]
+
+// MACHO_SWIFT_SECTION_SILENT_TEST=1, which Package.swift turns into SILENT_TEST for its test targets;
+// TuistScript.sh passes it on as TUIST_SILENT_TEST, the only form a Tuist manifest can read.
+let commandTestSettings: Settings = .settings(base: linkFlags.merging(
+    Environment.silentTest.getBoolean(default: false) ? ["SWIFT_ACTIVE_COMPILATION_CONDITIONS": ["$(inherited)", "SILENT_TEST"]] : [:]
+) { $1 })
+
+let project = Project(
+    name: "MachOSwiftSectionCommandLine",
+    // In SwiftPM these targets belong to the MachOSwiftSection package, whose `package` declarations
+    // they use (SwiftSectionCommandTests calls SwiftSectionKit's applyTransformersEnablingCommentKinds).
+    // Tuist gives the targets it converts SWIFT_PACKAGE_NAME = MachOSwiftSection; these need the same.
+    settings: .settings(base: ["SWIFT_PACKAGE_NAME": "MachOSwiftSection"]),
+    targets: [
+        .target(
+            name: "swift-section",
+            destinations: .macOS,
+            product: .commandLineTool,
+            // Tuist would name the executable swift_section, as it turns every dash of a target's name
+            // into an underscore.
+            productName: "swift-section",
+            bundleId: "com.machoswiftsection.swift-section",
+            deploymentTargets: commandLineDeploymentTargets,
+            sources: commandLineSources,
+            dependencies: commandLineDependencies,
+            settings: .settings(base: linkFlags)
+        ),
+        .target(
+            name: "swift_section",
+            destinations: .macOS,
+            product: .staticFramework,
+            bundleId: "com.machoswiftsection.swift-section.module",
+            deploymentTargets: commandLineDeploymentTargets,
+            sources: commandLineSources,
+            dependencies: commandLineDependencies
+        ),
+        .target(
+            name: "SwiftSectionCommandTests",
+            destinations: .macOS,
+            product: .unitTests,
+            bundleId: "com.machoswiftsection.SwiftSectionCommandTests",
+            deploymentTargets: .macOS("14.0"),
+            sources: ["../../Tests/SwiftSectionCommandTests/**"],
+            dependencies: [
+                .target(name: "swift_section"),
+                .external(name: "SwiftDeclarationRendering"),
+                .external(name: "SwiftPrinting"),
+            ] + commandLineDependencies,
+            settings: commandTestSettings
+        ),
+    ]
+)
+
    +
  • CLI 的源码编两遍(tool 一遍、framework 一遍)。另一种写法是 tool 不带源码、只链 framework,靠链接器从静态库里取 _main;省一遍编译,但能否链接成功依赖链接器怎么处理入口符号,没实测,放进「替代方案」。
  • +
  • MACHO_SWIFT_SECTION_SILENT_TEST=1 在 Package.swift 里变成测试 target 的 SILENT_TEST 定义:tuist install 时设了它,转换出的测试就带上。手写的 SwiftSectionCommandTests 也要带:Tuist 的 manifest 只读得到 TUIST_ 开头的变量,所以脚本把它转成 TUIST_SILENT_TEST=1,Project.swift 据此给这个 target 加 SILENT_TEST。
  • +
+
+
+
+ Workspace.swift +
+
import ProjectDescription
+
+// MachOSwiftSection-Tuist.xcworkspace, the development-only workspace Tuist generates beside the
+// native MachOSwiftSection.xcworkspace (Documentations/Internal/TuistDevelopment.md).
+//
+// The packages' test targets live in the projects Tuist converts from their Package.swift files, which
+// only a workspace scheme can reference. TuistScript.sh lists them in TUIST_PACKAGE_TEST_TARGETS as
+// "<package directory>=<test target>,<test target>;…", one entry per package whose tests are mapped:
+// MachOSwiftSection always (directory "."), the upstream packages in the local dependency mode
+// (absolute directories). IntegrationTests, the maintainer's manual-inspection target, is never listed.
+let packageTestTargets: [(directory: String, targets: [String])] = Environment.packageTestTargets
+    .getString(default: "")
+    .split(separator: ";")
+    .compactMap { entry in
+        let parts = entry.split(separator: "=", maxSplits: 1).map(String.init)
+        guard parts.count == 2 else { return nil }
+        return (parts[0], parts[1].split(separator: ",").map(String.init))
+    }
+
+func packageName(ofDirectory directory: String) -> String {
+    directory == "." ? "MachOSwiftSection" : String(directory.split(separator: "/").last ?? Substring(directory))
+}
+
+func projectPath(ofDirectory directory: String) -> Path {
+    directory.hasPrefix("/") ? .path(directory) : .relativeToRoot(directory)
+}
+
+let workspace = Workspace(
+    name: "MachOSwiftSection-Tuist",
+    projects: ["Tuist/CommandLine"],
+    schemes: packageTestTargets.map { entry in
+        var testableTargets = entry.targets.map { targetName in
+            TestableTarget.testableTarget(
+                target: .project(path: projectPath(ofDirectory: entry.directory), target: targetName),
+                parallelization: .swiftTestingOnly
+            )
+        }
+        if entry.directory == "." {
+            testableTargets.append(.testableTarget(
+                target: .project(path: "Tuist/CommandLine", target: "SwiftSectionCommandTests"),
+                parallelization: .swiftTestingOnly
+            ))
+        }
+        return .scheme(
+            name: "\(packageName(ofDirectory: entry.directory)) Tests",
+            testAction: .targets(
+                testableTargets,
+                // The test process as `swift test` runs it. The Thread Performance Checker inserts
+                // libRPAC.dylib, which rebinds calls in the loaded images: the cross-reference tests that
+                // compare a cache image read in process with the same image read from its file then
+                // see calls into libRPAC. The Main Thread Checker swizzles Objective-C methods the same
+                // way. Tuist 4.210 writes only the Main Thread Checker's attribute; TuistScript.sh adds
+                // disablePerformanceAntipatternChecker to the generated schemes.
+                diagnosticsOptions: .options(mainThreadCheckerEnabled: false, performanceAntipatternCheckerEnabled: false)
+            )
+        )
+    }
+)
+
    +
  • 上游库的目录是绝对路径;Path 接受绝对路径字符串(第 3 步验证过:本地模式下六个包的 scheme 都生成了)。包名取目录的最后一段,自己切,不 import Foundation。
  • +
  • 测试映射被预检关掉时 TUIST_PACKAGE_TEST_TARGETS 为空,只剩各 target 自己的 scheme;SwiftSectionCommandTests 仍在 MachOSwiftSectionCommandLine 工程里,Tuist 自动生成的 scheme 能跑它。
  • +
+
+
+
+ Tuist.swift +
+
import ProjectDescription
+
+// Every target of MachOSwiftSection and of the five upstream packages its native workspace lists
+// (MachOKit, MachOKitExtensions, MachOObjCSection, swift-demangling, swift-semantic-string) stays
+// source, in both dependency modes; every other dependency comes out of the binary cache once
+// `./TuistScript.sh warm` has filled it. The script reads the names from the packages' manifests and
+// passes them in TUIST_SOURCE_TARGET_NAMES. No fullHandle: the cache stays on this machine and
+// nothing is uploaded. Documentations/Internal/TuistDevelopment.md.
+let sourceTargetNames = Environment.sourceTargetNames
+    .getString(default: "")
+    .split(separator: ",")
+    .map(String.init)
+
+let tuist = Tuist(
+    project: .tuist(
+        cacheOptions: .options(
+            profiles: .profiles(
+                ["development": .profile(.onlyExternal, except: sourceTargetNames.map { .named($0) })],
+                default: "development"
+            )
+        )
+    )
+)
+
    +
  • 上游库在远程模式下也留作源码,理由与 RuntimeViewer 相同:本库经常跟着它们改、频繁挪 pin,放进缓存就要一次次重新预热;它们留作源码也能直接跳进去看。代价是远程模式从空 DerivedData 构建要多编这五个库;第 4 步量出 CLI 冷编 63 秒、走缓存 46 秒,暂不改。
  • +
  • 例外按名字匹配所有包的 target。脚本在算名单时检查有没有第三方包的 target 与名单同名,有就警告(同名的会被一起留成源码)。
  • +
+
+
+
+ TuistScript.sh +
+

照 RuntimeViewer 的脚本写,只保留与本库有关的部分。

+

命令:

+
+ + + + + + + + + +
命令做什么
install从种子锁文件开始解析当前模式的依赖(tuist install),结束时与种子比对 pin
generate [--configuration <c>]需要时先 install,占用检出,生成 workspace(默认 Debug)
warm [--configuration <c>]带 --cache-profile development 把第三方依赖编进缓存,再生成
build [--configuration <c>] [--scheme <s>] [-- <xcodebuild 参数>]生成后用 xcodebuild 编 swift-section scheme,或另一个
test [--configuration <c>] [--scheme <s>] [-- <xcodebuild 参数>]生成后用 xcodebuild test 跑 MachOSwiftSection Tests scheme(本地模式下上游库各有 <包名> Tests),结果存进 Work/<checkout>/TestResults/*.xcresult 并打印通过 / 失败 / 跳过的个数,退出码就是 xcodebuild 的
release放弃所有占用:删掉生成进各检出的工程(git 跟踪的不删)、占用记录与 MachOSwiftSection-Tuist.xcworkspace;Derived/ 留着
+

--local-dependencies / --remote-dependencies 可以跟在任何命令后面,从这条命令起切换模式;--dry-run 打印要做的事;--help 打印脚本头部的说明。

+

环境变量(脚本设,manifest 读):

+
+ + + + + + + + + + + + + + + +
变量谁读内容
TUIST_MAPS_LOCAL_PACKAGE_TESTS四个包的 Package.swift,Tuist/Package.swift1:映射测试;预检不通过时 0
TUIST_LOCAL_PACKAGE_CHECKOUTS、TUIST_LOCAL_PACKAGE_NAMESTuist/Package.swift本地模式下上游库所在目录与名字;远程模式不设
TUIST_SOURCE_TARGET_NAMESTuist.swift本库与五个上游库的全部 target
TUIST_WARNING_TARGET_NAMESTuist/Package.swift恢复警告的 target:本库全部,本地模式再加上游库全部
TUIST_PACKAGE_TEST_TARGETSWorkspace.swift每个映射了测试的包的测试 target,不含 IntegrationTests
TUIST_TEST_TARGET_NAMESTuist/Package.swift所有转换进来的测试 target(含 IntegrationTests),给它们 -ObjC 与 -force_load
TUIST_RAISED_TEST_TARGET_NAMESTuist/Package.swift声明的 macOS 最低版本低于 14 的包的测试 target,部署版本抬到 14.0
TUIST_TESTING_SUPPORT_TARGET_NAMESTuist/Package.swift源码里 import Testing 的库 target,加 TestingMacros 插件路径
TUIST_FORCE_LOADSTuist/Package.swift、Tuist/CommandLine/Project.swift<链接的 target>:<有加载期 constructor 的 target>,…,后者整个 -force_load
TUIST_SILENT_TESTTuist/CommandLine/Project.swift用户设了 MACHO_SWIFT_SECTION_SILENT_TEST=1 时为 1
SWIFTPM_BUILD_DIRTuist当前模式的依赖 checkout 目录
TUIST_XDG_CACHE_HOME、TUIST_CACHE_WARM_SCRATCH_DIRECTORYTuist二进制缓存与预热的临时目录
+

USING_LOCAL_DEPENDENCIES 被设了就提示一句并 unset:它会让本库清单自己换上本地兄弟,连 swift-capstone 一起,与 Tuist/Package.swift 的名单对不上。

+

名单从哪来:本地依赖的名字读 MachOSwiftSection.xcworkspace/contents.xcworkspacedata 里的 container:../<名字>(不含 / 的那些),workspace 加了库这里自动跟上。每次 install 之后,脚本用 swift package dump-package(带 TUIST_MAPS_LOCAL_PACKAGE_TESTS=1,8 个并行,--scratch-path 放在 Work/<checkout>/Manifests/Scratch/)读一遍所有包的清单,存进 Work/<checkout>/Manifests/:本库与本地模式下的上游库读检出里的,远程模式下的上游库和全部第三方包读 SWIFTPM_BUILD_DIR/checkouts/ 里的。generate、warm 前由 Python 从这些清单算出上表的各个名单,并扫描路径包里 target 的源码找 import Testing 与 __attribute__((constructor));Python 出错脚本就失败,不带着空名单生成。

+

测试映射的预检:对每个按路径声明的包,在它的清单 JSON 里找 Tuist 会拒绝的两种形态——测试依赖本包的可执行 target、测试依赖不属于任何 product 的普通 target(实测第 1、3、6 条)。适配块生效时这两种都不该剩下;还剩,说明那个包没有适配块(比如本地检出停在加块之前的提交),这次就整体设 TUIST_MAPS_LOCAL_PACKAGE_TESTS=0,警告点名那个包,生成照常进行。只被测试用到的外部依赖(实测第 2 条)预检查不出来,生成时 Tuist 自己会报,指南里写怎么补。

+

锁文件:Tuist/Package.resolved 不提交(*.resolved 已忽略)。每次 install 前用本检出根目录的 Package.resolved 当种子(没有就不种,由 Tuist 解析最新版本),结束时逐条比对,不同就警告;swift-syntax(这边是预编译包,没有 pin)与本地模式下的五个库不参与比对。

+

依赖模式:模式记在 Tuist/.local-dependencies(内容是上游库所在目录;远程模式下这个文件不存在)。默认目录是检出的上一级,worktree 里就是 .worktrees/;打开本地模式时设了 TUIST_LOCAL_PACKAGE_CHECKOUTS 就用它。两种模式各用一份依赖 checkout(Dependencies/<checkout> 与 Dependencies/<checkout>-LocalDependencies),共用 Tuist/Package.resolved,所以切换后、或上次解析用的是另一种模式时先重新 install(Work/<checkout>/InstalledDependencies 记着上次)。这个记号还带着 Tuist/Package.swift、Package.swift、种子锁文件与本地模式下各上游库清单的 hash:改了其中任何一个,下一次 generate 自己重新解析。切到远程时释放五个上游库的占用。

+

存放位置:/Volumes/DerivedData 挂着时全放在 /Volumes/DerivedData/MachOSwiftSection/Tuist/ 下(Cache/、Dependencies/<checkout>[-LocalDependencies]/、WarmScratch/<checkout>/、Work/<checkout>/),<checkout> 是目录名加路径的短 hash;没挂载时放在仓库里的 Tuist/.build/、Tuist/.build-LocalDependencies/ 与 DerivedData/Tuist/(都已忽略)。TUIST_SCRIPT_ROOT 指定别处。build / test 的 DerivedData 在 Work/<checkout>/DerivedData。日志在 Products/Logs/Tuist/;Tuist 的输出原样显示并记进日志,xcodebuild 的输出只进日志,失败时显示错误摘要。

+

占用记录(与 RuntimeViewer 共用):

+
    +
  • 被占的检出:它的 git 目录(git rev-parse --absolute-git-dir,worktree 各有一份)里的 tuist-generated-project-owner,第一行是占用者检出的路径,第二行是在占用者检出里释放它的命令,第三行是生成进这个检出的工程名(释放时删它)。
  • +
  • 占用者:自己的 Tuist/.claimed-checkouts,每行一个被占检出的真实路径(pwd -P)。
  • +
  • 有效:占用者的 .claimed-checkouts 列着这个路径。占用者不在了、或已经不列了,记录就是陈旧的,可以直接覆盖。
  • +
  • 旧记录 runtimeviewer-tuist-local-dependencies:占用者的 Tuist/.local-dependencies 加上包名指向这个检出时算有效(RuntimeViewer 今天的规则)。
  • +
  • 本库的脚本在 generate 前占用自己的检出与(本地模式下)五个上游库;遇到别人的有效占用就失败,报出占用者路径与它的释放命令。检出里 git 跟踪着 <包名>.xcodeproj 时也失败(Tuist 会覆盖它)。上游库的 <包名>.xcodeproj/ 与 Derived/ 写进那个仓库的 info/exclude,本库自己的生成物走 .gitignore。
  • +
  • 释放:删掉生成进那个检出的工程、占用记录,并从 .claimed-checkouts 里去掉。
  • +
+

Tuist 版本:读 mise.toml 的版本;有 mise 就 mise exec -- tuist,否则用 PATH 里的 tuist;版本不对就失败并提示 mise install。

+

生成之后:给每个 * Tests.xcscheme 的 TestAction 补 disablePerformanceAntipatternChecker = "YES"(Tuist 4.210 只写主线程检查那一项,见决策日志)。

+

agent 运行:TUIST_SCRIPT_ROOT=/Volumes/DerivedData/Agents.noindex/<agent>/Tuist-MachOSwiftSection;warm、build、test 要编译,写成 queued-build ./TuistScript.sh <命令>,install、generate、release 不编译。

+
+
+
+ RuntimeViewer 那一侧 +
+
    +
  • claim_local_checkouts:先读共用记录与旧记录,任何一个有效且占用者不是自己就失败,报出占用者与释放命令;然后写共用记录(第二行是 ./TuistScript.sh generate --remote-dependencies),把路径写进自己的 Tuist/.claimed-checkouts,自己的旧记录删掉。
  • +
  • release_local_checkouts:删掉自己的共用记录(以及残留的旧记录),从 .claimed-checkouts 里去掉。
  • +
  • 今天它占着本库的集成 worktree 与五个上游检出(旧记录)。改完后它下一次 generate 就把记录换成新的;在那之前,本库的脚本按旧规则认出它的占用。
  • +
+
+
+
+ 实现中确认的点(Ultra,Xcode 27.2) +
+
    +
  1. swift_section 与 SwiftSectionCommandTests 能编、能链、@testable import 成立:124 个测试全部通过。另需 SWIFT_PACKAGE_NAME = MachOSwiftSection(它调用 SwiftSectionKit 的 package 方法),工具 target 写明 productName。
  2. +
  3. 部署版本与链接参数:测试 target 要抬到 macOS 14.0(TypeIndexingTests),CLI 要 macOS 12.0(swift-argument-parser);测试与 CLI 都要 -ObjC(包装读取器的 conformance)和对 SwiftSymbolsRegistration 的 -force_load(Swift 符号语言的注册);导入 Testing 的库 target 要 TestingMacros 插件路径;测试 scheme 要关掉两个运行时检查。逐条见决策日志。
  4. +
  5. Capstone 的 trait 宏补上后 SwiftThunkAnalysis 编过,它的测试通过(86 个通过、2 个跳过)。
  6. +
  7. 远程模式:Tuist workspace 的测试 scheme 与原生 swift test --skip IntegrationTests 在同一台机器、同一个 Xcode 下逐 bundle 对照,全部通过;Tuist 编的 swift-section 与原生编的对 SymbolTestsCore 输出的 dump、interface 逐字节相同。
  8. +
  9. 本地模式与按绝对路径引用上游库工程:见决策日志「本地模式实测」。
  10. +
+
+
+
+ +
+

调研

+
+ 现状 +
+
    +
  • 原生 workspace 的成员(MachOSwiftSection.xcworkspace/contents.xcworkspacedata):container:../MachOKit、container:../MachOObjCSection、group:(本库)、group:PrecompiledLibraries/swift-syntax。集成 worktree 里还有一处没提交的改动,又加了 container:../MachOKitExtensions、container:../swift-demangling、container:../swift-semantic-string。「本地依赖」指的就是这五个 container:../<名字> 成员。
  • +
  • PrecompiledLibraries/swift-syntax 是一个按包身份顶替 swift-syntax 的包,每个 product 是一个 binaryTarget(PrecompiledLibraries/swift-syntax/Package.swift:46 起,xcframework 从 MxIris-DeveloperTool/swift-syntax-builder 的 release 下载)。原生 workspace 靠把它列为成员来顶替;Tuist 这边要在 Tuist/Package.swift 里按路径声明它,两种模式都声明。
  • +
  • 本库 Package.swift 的本地依赖开关:usingLocalDependencies = envEnable("USING_LOCAL_DEPENDENCIES")(Package.swift:42);package(local:remote:) 在 #filePath 含 /checkouts/、/SourcePackages/ 或 /.build/ 时一律走远程(Package.swift:49-74),所以作为别人的远程依赖时不受这个变量影响。
  • +
  • 可执行 target 与测试:swift-section、reader-benchmark、baseline-generator 三个可执行 target(Package.swift:929、956、972),一个命令插件 RegenerateBaselinesPlugin(Package.swift:987),22 个测试 target。SwiftSectionCommandTests(Package.swift:1305)依赖 swift-section,测试文件里是 @testable import swift_section(13 个文件),不启动子进程。SwiftSectionFixtureSupport、SwiftSectionTestingSupport、SwiftSectionTestingSupportC 是普通 target,不属于任何 product(Package.swift 的 products: 只有 20 个库与 swift-section)。
  • +
  • 没有提交的锁文件:.gitignore 有 *.resolved,根目录的 Package.resolved 是每台机器、每个检出自己解析出来的。
  • +
  • RuntimeViewer 的做法(RuntimeViewer/TuistScript.sh,1774 行;Documentations/Guides/TuistDevelopment.md):Tuist/Package.swift 按路径声明四个本地包;Tuist.swift 的缓存 profile development 用 .onlyExternal,按名字把本地包与 MachO 那几个库的 target 留作源码;本地依赖模式在 Tuist/.local-dependencies 记住目录,两种模式各用一份 SWIFTPM_BUILD_DIR;占用记录写在被占检出的 git 目录里(runtimeviewer-tuist-local-dependencies,内容是占用者的路径),判断占用是否仍然有效的办法是看占用者的 Tuist/.local-dependencies 是否指向这个目录;切回远程时删掉生成进库目录的工程;Tuist 生成的文件经被占仓库的 info/exclude 忽略。它的本地模式不映射测试,原因正是下面的第 1 条与第 6 条。RuntimeViewer 钉的 Tuist 是 4.210.0(mise.toml),它记下的 Tuist 4.210 的坑(${inherited}、-ObjC、测试 target 部署版本、trait 宏、--cache-profile)大部分只与 App 工程有关,与本提案相关的三条在「详细设计」里逐条说明。
  • +
+
+
+
+ 实测(2026-11-20,JH's Mac Studio,Xcode 27.2,Tuist 4.210.0) +
+

探针放在 /Volumes/DerivedData/Agents.noindex/claude/Probes/MachOSwiftSection-Tuist/:本库 next 与五个上游库集成分支的 HEAD 用 git archive 导出成副本,Tuist/Package.swift 按路径声明本库副本与预编译 swift-syntax,Tuist/CommandLine/Project.swift 放 CLI。只跑了 tuist install 与 tuist generate,没有编译。没碰任何真实检出。

+
    +
  1. 远程模式、打开 includeLocalPackageTestTargets:生成失败。The test target 'SwiftSectionCommandTests' in the local package 'MachOSwiftSection' depends on the executable target 'swift-section', which Tuist omits when mapping local package dependencies. 这个选项对所有按路径声明的包一视同仁,没有按 target 排除的参数(PackageSettings.init 只有 includeLocalPackageTestTargets: Bool,见 Tuist 4.218.1 的 ProjectDescription.swiftinterface)。
  2. +
  3. 用环境变量在 Package.swift 里摘掉 SwiftSectionCommandTests:开关生效(tuist install 的环境能传进依赖清单的 Context.environment,而 Tuist 在 install 时就把清单解析结果缓存下来)。下一个错误:The local package test target 'SwiftDumpTests' depends on 'SnapshotTesting', which is not a configured external dependency. 只被测试用到的依赖必须在 Tuist/Package.swift 里声明。
  4. +
  5. 补上 swift-snapshot-testing:Couldn't find target 'SwiftSectionFixtureSupport'。测试依赖的普通 target 不属于任何 product 时,Tuist 找不到它。
  6. +
  7. 同一开关下给测试依赖的普通 target 补 library product:生成成功。MachOSwiftSection.xcodeproj 有 48 个 target,其中 21 个测试 target(除 SwiftSectionCommandTests 外全部,含 IntegrationTests)。原生 MachOSwiftSection.xcworkspace 没被碰,新生成的是 MachOSwiftSection-Tuist.xcworkspace。
  8. +
  9. 在 Tuist 工程里手写 CLI:swift-section(command line tool)、swift_section(static framework,同一批源码,模块名就是测试要的 swift_section)、SwiftSectionCommandTests(unit tests,依赖 swift_section)三个 target,都按 .external(name:) 依赖包的 product,生成成功。工程放在 Tuist/CommandLine/ 下也能生成。没编译,链接与 @testable import 是否成立待第 2 步在 Ultra 上验证。
  10. +
  11. 本地模式(五个上游库副本按路径声明):生成失败。The test target 'ObjCSectionCommandTests' in the local package 'MachOObjCSection' depends on the executable target 'objc-section'。换 Tuist 4.218.1 同样失败。
  12. +
  13. 五个上游库副本的 Package.swift 末尾都加上同一段通用适配(见「详细设计」,第 1、3 条的两种形态都按规则处理):生成成功,六个包的测试全部映射进来:本库 21、MachOKit 1、MachOKitExtensions 9、MachOObjCSection 8、swift-demangling 1、swift-semantic-string 2。再逐个去掉适配:MachOKit 与 swift-semantic-string 不加也能过;swift-demangling 不加时报 Couldn't find target 'DemanglingTestingSupport'。最少要改三个上游库:MachOKitExtensions(CPlusPlusSymbolsFixture)、MachOObjCSection(ObjCSectionCommandTests)、swift-demangling(DemanglingTestingSupport)。
  14. +
  15. 生成的工程确实写进各包自己的目录:Siblings/<名字>/<名字>.xcodeproj 与 Derived/,本库副本根目录也是。这就是与 RuntimeViewer 冲突的地方。
  16. +
  17. Tuist.swift 能读环境变量:把 TUIST_SOURCE_TARGET_NAMES=Utilities,SwiftSymbols,MachOSwiftSection 经 Environment.sourceTargetNames 读进缓存 profile,tuist dump config 显示 exceptTargetQueries 正是这三个名字。缓存例外名单因此可以由脚本从各包清单算出来,不用像 RuntimeViewer 那样手抄、再用 check 守着。
  18. +
  19. tuist install 解析出的远程依赖(远程模式,种子锁文件取自集成 worktree 的 Package.resolved):AssociatedObject、capstone、combine-schedulers、FrameworkToolbox、MetaCodable、Rainbow、SourceKitD、swift-apinotes、swift-argument-parser、swift-asn1、swift-async-algorithms、swift-binary-parse-support、swift-capstone、swift-clocks、swift-collections、swift-concurrency-extras、swift-crypto、swift-dependencies、swift-fileio、swift-fileio-extra、swift-issue-reporting、swift-literal-type-inference、swift-memberwise-init-macro、swift-object-association、swift-objc-dump、swift-snapshot-testing、Yams,加上五个上游库。
  20. +
+
+
+
+ 推测(写提案时未验证;实现中全部证实,见决策日志) +
+
    +
  • 测试 target 的部署版本:SwiftPM 给测试 target 的部署版本不低于 XCTest 与 Swift Testing 的要求(macOS 14.0),Tuist 照搬包声明的 10.15,RuntimeViewer 因此在 Duration、timeLimit 上编不过。本库测试大概率踩同一个坑。
  • +
  • -ObjC:Tuist 把包编成静态库,链接器只拉被符号引用到的成员。本库测试是否依赖按名字在运行时查找的类,没查过。
  • +
  • CAPSTONE_HAS_AARCH64:本库开了 swift-capstone 的 AARCH64 trait(Package.swift:291 的 capstoneTraits),Tuist 会丢掉只以 trait 为条件的设置,RuntimeViewer 因此手动补上了这个宏。
  • +
  • swift_section 这个 static framework 里有 @main,链进测试 bundle 后会多出一个 _main 符号。bundle 不是可执行文件,这应该无害。
  • +
+
+
+
+ +
+

替代方案

+
+ 九条,都否了(或暂否) +
+
    +
  • Tuist 的「把 Package.swift 当工程」(beta):切换仍要一个根清单按路径声明上游库;不打算支持 SwiftPM 全部特性;很可能按包名生成与原生同名的 workspace(推测)。否。
  • +
  • 在 Project.swift 里手写全部 target:冲突自然消失,但五十来个 target 的依赖要再抄一份,必然漂移。否。
  • +
  • Tuist 的 Xcode 原生包集成:不往包目录写工程,但没有二进制缓存,与原生 workspace 相比什么也没得到。否。
  • +
  • 本地模式不映射测试(RuntimeViewer 的做法):不用改上游库;但跨仓库改动时用的正是本地模式,那时连本库自己的测试也跑不了。用户选了加适配块。
  • +
  • 只针对点名的 target 打补丁:三个上游库各写一份不同的补丁,以后每加一个这种形态的测试都要回来改。否。
  • +
  • CLI 只链 framework、不带源码:省一遍编译,但能否链接成功没实测。否,第 2 步可以顺手试。
  • +
  • 远程模式下把五个上游库也放进缓存:更快,但 pin 动得勤、要反复预热,也跳不进源码。暂否,第 4 步量出差距后可重议。
  • +
  • 只在本库这边检查 RuntimeViewer 的占用:RuntimeViewer 照样会盖掉本库生成的工程。用户选了双向互斥。
  • +
  • 用 USING_LOCAL_DEPENDENCIES=1 实现本地模式:对所有带本地路径的依赖一刀切(含 swift-capstone),三个上游库的清单也各有自己的开关。否。
  • +
+
+
+
+ +
+

影响

+
    +
  • 源码兼容性:纯新增,没有任何公开 API 变化。适配块只在 TUIST_MAPS_LOCAL_PACKAGE_TESTS=1 时生效,swift build、swift test、原生 workspace、CI 与下游的 SwiftPM 解析都不会设这个变量。
  • +
  • ABI 兼容性:不适用——本库以 SPM 源码分发,使用方每次重新编译。
  • +
  • 本仓库内:没有 target 受影响;.gitignore 多几项,workspace 多三个成员。
  • +
  • RuntimeViewer:脚本换用共用的占用记录。它的 Tuist 不设那个变量,适配块不生效,它生成的工程不变。
  • +
  • 三个上游库:清单末尾多一段默认不生效的代码,不需要发版。其他下游(MachOKitUI、SymbolViewer……)不受影响。
  • +
  • 文档:新增使用指南并登记;AGENTS.md 加一条;README.md 不改;RuntimeViewer 的指南改两段。
  • +
  • API 演进与废弃:无。
  • +
+
+ +
+

落地步骤

+

在 Ultra 上构建与跑测试(本机是 10 核那台),用默认的 Xcode 27.2;第 2、3 步的测试结果另用 Xcode 26.6 的 swift test 结果对照。

+
    +
  1. 骨架:远程模式能生成、能编 CLI(已完成) —— 改动地图里 mise.toml、Tuist/Package.swift(不含测试相关)、Tuist/CommandLine/Project.swift(只有 swift-section)、Workspace.swift(无测试 scheme)、TuistScript.sh(install、generate、build、release,存放位置,锁文件,自己检出的占用)、.gitignore、workspace 成员 +
      +
    • 行为:generateCreatesTheTuistWorkspaceAndLeavesTheNativeWorkspaceUntouched
    • +
    • 行为:buildCompilesSwiftSectionFromTheTuistWorkspace
    • +
    • 行为:generateFailsNamingTheOwnerWhenAnotherCheckoutHoldsThisOne
    • +
    • 行为:releaseRemovesTheGeneratedProjectsAndTheClaim
    • +
    • 行为:installWarnsWhenTheResolvedPinsDifferFromTheSeedLockFile
    • +
    • 行为:usingLocalDependenciesIsIgnoredWithAWarning
    • +
    +
  2. +
  3. 本库的测试(已完成) —— Package.swift 适配块,Tuist/Package.swift 的 swift-snapshot-testing 与测试设置,Project.swift 的 swift_section 与 SwiftSectionCommandTests,Workspace.swift 的测试 scheme,脚本的 test 命令与清单读取 +
      +
    • 行为:theTestSchemeHoldsEveryTestTargetExceptIntegrationTests
    • +
    • 行为:swiftSectionCommandTestsImportTheCommandModuleAndPass
    • +
    • 行为:theTuistTestRunMatchesSwiftTestTargetByTarget
    • +
    • 行为:packageManifestIsUnchangedWithoutTheTuistVariable(swift package dump-package 不带变量时与改动前逐字节相同)
    • +
    +
  4. +
  5. 本地模式(已完成) —— 三个上游库的适配块(各自的功能分支),Tuist/Package.swift 的本地依赖,脚本的模式切换、上游库占用、预检 +
      +
    • 行为:localDependenciesBuildTheUpstreamPackagesFromTheirCheckoutsWithUncommittedEdits
    • +
    • 行为:theModeIsRememberedAndSwitchingResolvesAgain
    • +
    • 行为:localModeMapsTheTestsOfAllSixPackages
    • +
    • 行为:anUpstreamCheckoutWithoutTheBlockTurnsTestMappingOffWithAWarning
    • +
    • 行为:switchingToRemoteReleasesTheUpstreamCheckouts
    • +
    +
  6. +
  7. 二进制缓存(已完成) —— Tuist.swift,脚本的 warm 与 TUIST_SOURCE_TARGET_NAMES +
      +
    • 行为:warmCachesEveryThirdPartyPackageAndNoneOfTheSixOwnPackages
    • +
    • 行为:generateAfterWarmLinksTheCachedBinaries
    • +
    • 行为:aThirdPartyTargetNamedLikeAnOwnTargetIsReported
    • +
    • 记录:空 DerivedData 下不用缓存与走缓存各编一次 swift-section 与测试 scheme 的时间,写进决策日志与指南。
    • +
    +
  8. +
  9. 与 RuntimeViewer 互斥(已完成) —— RuntimeViewer 的 TuistScript.sh 与指南 +
      +
    • 行为:runtimeViewerLocalModeFailsWhileMachOSwiftSectionHoldsTheCheckout
    • +
    • 行为:machOSwiftSectionFailsWhileRuntimeViewerHoldsAnUpstreamCheckout(新旧两种记录各一次)
    • +
    • 行为:aStaleClaimIsTakenOverSilently
    • +
    +
  10. +
  11. 文档(已完成) —— 使用指南、AGENTS.md、Documentations/README.md
  12. +
+

收尾时必须判断两件事(判断结果写进决策日志,不允许沉默跳过):

+
    +
  • 要不要配套专题文章 —— 本提案已定要写使用指南 Documentations/Internal/TuistDevelopment.md;实现说明是否另写,收尾时判断。
  • +
  • 有没有引入新术语 —— 「Tuist 开发 workspace」「本地依赖模式」「占用记录」是否进 Documentations/Glossary.md,收尾时判断。
  • +
+
+ +
+

决策日志

+
+ 22 条,最近一条:Implemented,编号 0099 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
日期变更说明
2026-11-20Created as Draft用户要一个照 RuntimeViewer 做法建的 Tuist 开发 workspace,依赖可在本地检出与远程版本之间切换,本地依赖就是原生 workspace 里放的那几个上游库。按轻量档处理:新增的开发路径,不改原有的构建、发版与 CI。
2026-11-20定下三个方向用户选定:提供二进制缓存与 warm;Tuist workspace 要能跑测试,先实测再定写法;与 RuntimeViewer 的本地依赖模式双向互斥,为此顺带改 RuntimeViewer 的脚本。
2026-11-20实测定下测试的写法十项实测见「前期调研」:Tuist 的测试映射对路径包一刀切,会拒绝两种形态的测试;用一段只在 Tuist 解析时生效的清单适配块处理,本库加,三个上游库也要加才能在本地模式下带测试;SwiftSectionCommandTests 在 Tuist/CommandLine/Project.swift 里手写。三个上游库要不要加,留给用户定。
2026-11-20用户批准,开始实现用户选定给 MachOKitExtensions、MachOObjCSection、swift-demangling 加适配块,本地模式带测试;状态改 Accepted。实现在本库的 feature/tuist-workspace,三个上游库与 RuntimeViewer 各用同名分支。
2026-11-20清单改由脚本自己读本想直接读 Tuist 缓存的清单索引(swifterpm/package-info/index.json),实测设了 SWIFTPM_BUILD_DIR 时 Tuist 不产出这份索引,靠它不可靠。改回提案原写法:每次 install 之后脚本用 swift package dump-package(带 TUIST_MAPS_LOCAL_PACKAGE_TESTS=1,8 个并行)读一遍所有包的清单存进 Work/<checkout>/Manifests/,名单、预检和同名检查都读它(35 个包)。Python 出错时脚本直接失败,而不是带着空名单生成。
2026-11-20解析依赖的记号带上清单的 hashWork/<checkout>/InstalledDependencies 除了模式,还记 Tuist/Package.swift、Package.swift、种子锁文件与(本地模式下)上游库清单的 hash:改了 Package.swift 或换了根目录的 Package.resolved,下一次 generate 自己重新解析,不必记得先跑 install。
2026-11-20CLI 的部署版本改为 macOS 12.0Ultra 首次构建:Tuist 把 swift-argument-parser 编成它声明的 macOS 12,10.15 的 swift-section import 不了它(11 处同一错误,其余全部编过)。
2026-11-20测试 target 抬到 macOS 14.0(原定「按需」,确认需要)TypeIndexingTests 用的 macOS 13 API 在 10.15 下编不过。脚本把所有转换进来的测试 target(含 IntegrationTests)传进新变量 TUIST_TEST_TARGET_NAMES。
2026-11-20手写的 target 设 SWIFT_PACKAGE_NAME = MachOSwiftSectionSwiftSectionCommandTests 调用 SwiftSectionKit 的 package 方法;Tuist 转换的 target 都带这个设置,手写的没有。
2026-11-20导入 Testing 的库 target 加 TestingMacros 插件路径SwiftSectionTestingSupport 用了 #require,Xcode 只给测试 target 带 TestingMacros 插件。脚本扫描路径包里普通 target 的源码找 import Testing,传进新变量 TUIST_TESTING_SUPPORT_TARGET_NAMES;本地模式下 swift-demangling 的 DemanglingTestingSupport 也会被找到。
2026-11-20build / test 加 --scheme本地模式下要跑上游库各自的测试 scheme(<包名> Tests)。
2026-11-20MachOKitExtensions 的 next 已不需要适配块,仍按决定加上探针用的是它的 main(有 CPlusPlusSymbolsFixture),next 上这个测试支撑 target 已经没有了,块目前不起作用。另:本库 .worktrees/MachOKitExtensions 链接指向它的主检出(main),不是它的 next worktree,所以公司那台上的本地模式编的是 main,预检会因为那个 target 关掉测试并点名。
2026-11-20Tuist 往 PrecompiledLibraries/swift-syntax/ 里写 .build/它是按路径声明的包,Tuist 在那里下载二进制产物;与它生成的工程一起写进 .gitignore。
2026-11-20SwiftSymbolsRegistration 整个 -force_loadUltra 上第一次跑通测试 scheme:2,935 通过、8 失败,原生 swift test 同一台、同一个 Xcode 27.2 全部通过(21 个 bundle、2,905 个测试)。SwiftSymbolsTests 里 registeredLanguages → []:这个 C target 只有一个 static 的加载期 constructor、没有全局符号,SwiftPM 整块链接 target 所以它总会跑,Tuist 的静态 framework 里这个成员没人引用、链接器不拉。脚本找出源码里有 __attribute__((constructor)) 的 target,沿包内依赖算出会链到它的测试与可执行 target,传进 TUIST_FORCE_LOADS。同一机制意味着 RuntimeViewer 的 Tuist workspace(静态 framework,只加了 -ObjC)里 Swift 也没注册成符号语言——按链接方式推断,没有实测,不在本提案范围内修。
2026-11-20测试与 swift-section 链接时加 -ObjC修好注册后还剩 4 条,都在包装读取器(MachOReaderWrapper)上:没人点名的 protocol conformance 所在的归档成员没被链进来,as? 静默失败。与 RuntimeViewer 的 Tuist workspace 一样加 -ObjC;测试 target 的部署版本、-ObjC 与 -force_load 合进同一份设置,免得两处 OTHER_LDFLAGS 互相覆盖。SwiftSymbolsTests 与 SwiftInspectionTests 重跑 227 个全部通过。
2026-11-20只给声明低于 macOS 14 的包的测试抬部署版本六个包今天都声明 10.15,但以后有包声明 15 时,统一设 14.0 会把它的测试调低。脚本另传 TUIST_RAISED_TEST_TARGET_NAMES;-ObjC 与 -force_load 照旧给全部测试。
2026-11-20测试 scheme 关掉 Xcode 的两个运行时检查全量重跑后只剩 FileModeTests.fileModeMatchesInProcessReferencesOnTheRunningSystemCache 一条:进程内的调用目标落在 /usr/lib/libRPAC.dylib。那是 Thread Performance Checker 插入的库,它改写了已加载镜像里的调用;swift test 的进程里没有它。Workspace.swift 的测试 scheme 关掉它与 Main Thread Checker;Tuist 4.210 只写后者的属性,脚本生成后给 * Tests.xcscheme 的 TestAction 补 disablePerformanceAntipatternChecker = "YES"。
2026-11-20工具 target 写明 productNameTuist 把 target 名里的 - 换成 _,可执行文件成了 swift_section。
2026-11-20本地模式实测Ultra 上用五个上游库的沙盒副本(TUIST_LOCAL_PACKAGE_CHECKOUTS 指过去,各在本提案的功能分支上)打开本地模式:解析、读清单、生成都成功,六个包各有一个 <包名> Tests scheme,副本的 git status 保持干净。MachOSwiftSection Tests 全量 2,943 个通过、0 失败、7 个跳过(修完前面几处之后的第一次全量);MachOKitExtensions 171 个、swift-demangling 641 个、swift-semantic-string 464 个全部通过。MachOKit 10 个失败、MachOObjCSection 26 个失败,全是测试自己读写死的路径或系统文件:AotCachePrintTests 读不存在的 aot_shared_cache.0,ArchiveFileTests 读 clang 17 目录(Xcode 27.2 是 21),MachOObjCSectionTests 的 setUp 读 /Users/JH/Downloads/iOS18.5-SwiftUI,两条 testDylibsPreBuildLoaderSet 在 macOS 27 的系统 cache 上读不出 loader set 版本。这些按源码判断与 Tuist 无关,没有再用原生 swift test 对照。切回远程模式后副本的占用全部释放。
2026-11-20缓存计时Ultra(28 核,Xcode 27.2),清空 DerivedData 后编 swift-section(Debug):不走缓存 63 秒,走缓存 46 秒;warm 把 70 个第三方 target 编成 xcframework 用了 60 秒,再生成时这 70 个都换成了缓存。测试 scheme 走缓存的全量重跑用户嫌慢叫停了,没有结果;远程模式下修完的那几处都按 bundle 重跑过,本地模式的全量也已通过。写进使用指南。
2026-11-20实现完成,待用户看过后收尾配套文档:使用指南已写;实现说明不另写,清单里每处特殊写法的原因都在指南「已知的坑」与本决策日志里。术语表(「Tuist 开发 workspace」「本地依赖模式」「占用记录」)留到正式收尾时判断。
2026-11-20Implemented,编号 0099用户看过后收尾。术语表登记「Tuist 开发 workspace」与「占用记录」(后者另注明与 SharedCacheRegistry 的 claim 无关);「本地依赖模式」就是本地依赖的字面意思,不登记。落地前用 Xcode 27.2 与 26.6 各解析一遍四个包的清单:都能解析,不带变量时与改动前一致,带变量时补的 product 与拿掉的测试和设计相符(MachOKitExtensions 的 main 上补 CPlusPlusDemangling、CPlusPlusSymbolsFixture)。MachOKitExtensions 的功能分支切自它本地一条没推送过的 next(只有一个空合并,比 main 落后 10 个提交),落地时把那一个提交接到 main 上推送;那条本地 next 原样留着。账本第 143 节。
+
+
+
+
+ +
+
+ + diff --git a/Documentations/Evolutions/0099-tuist-workspace.md b/Documentations/Evolutions/0099-tuist-workspace.md new file mode 100644 index 000000000..5901caaca --- /dev/null +++ b/Documentations/Evolutions/0099-tuist-workspace.md @@ -0,0 +1,745 @@ +# 0099 - Tuist 开发 workspace:第三方依赖走二进制缓存,上游库可切换为本地检出 + +- **状态**: Implemented +- **作者**: JH +- **创建日期**: 2026-11-20 +- **最后更新**: 2026-11-20 +- **所属愿景**: 无 +- **关联提案**: RuntimeViewer 仓库的 `Documentations/Evolutions/0053-tuist-coexistence.md`(Tuist workspace 与原生工程并存)与 `0082-tuist-local-dependencies.md`(本地依赖模式)。本提案的脚本照它们的做法写,并顺带改 RuntimeViewer 脚本里的占用检查,让两边的本地依赖模式互斥(落地步骤第 5 步)。 +- **跨仓库**: 本提案是唯一的一份。另外四个仓库只有配套小改动:MachOKitExtensions、MachOObjCSection、swift-demangling 的 `Package.swift` 末尾各加同一段适配(第 3 步),RuntimeViewer 改 `TuistScript.sh` 与它的使用指南(第 5 步)。它们的提交信息按 slug 指回本提案,各自的文档按各仓库自己的规定同步。 +- **实现分支 / PR**: 本库 `feature/tuist-workspace`,从 `next` 切出;另外四个仓库用同名分支,从各自的 `next` 切出。落地:本库、MachOObjCSection、swift-demangling、RuntimeViewer 合进 `next`,MachOKitExtensions 接到 `main` 上(它只有 `main` 一条远端分支,见决策日志最后一行)。 +- **配套文档**: 使用指南 [`Documentations/Internal/TuistDevelopment.md`](../Internal/TuistDevelopment.md)(第 6 步新增) +- **网页版**: 同目录同名的 `.html` + +## 摘要 + +在原生的 `MachOSwiftSection.xcworkspace` 之外,加一条只供日常开发用的 Tuist 路:`./TuistScript.sh` 生成 `MachOSwiftSection-Tuist.xcworkspace`。本库照常从源码编,可以跳转、可以编辑;27 个真正的第三方依赖(swift-dependencies 一族、swift-collections、Capstone、swift-crypto、Yams……)预编进本机的 Tuist 二进制缓存,只编一次。原生 workspace 里放的五个上游库——MachOKit、MachOKitExtensions、MachOObjCSection、swift-demangling、swift-semantic-string——默认按锁文件版本从源码编;加上 `--local-dependencies` 就改用检出旁边(worktree 里就是 `.worktrees/` 下那组链接)的本地检出,没提交的改动也算,`--remote-dependencies` 切回,选过的模式会记住。Tuist workspace 能跑测试:本库 21 个测试 target 由 Tuist 从 `Package.swift` 转换过来,依赖可执行 target 的 `SwiftSectionCommandTests` 在一个小的 Tuist 工程里手写;本地模式下五个上游库的测试也一起进来。做到这一点要在本库和三个上游库的 `Package.swift` 末尾加同一段适配,它只在 Tuist 解析时设下的环境变量下生效,平时的 SwiftPM、Xcode 与 CI 一律不受影响。RuntimeViewer 的本地依赖模式也会往这几个检出里写同名工程,两边的脚本改成共用一份占用记录,一边占着时另一边直接报错。发版、CI、`swift build` / `swift test` 和原生 workspace 都不变。 + +## 动机 + +- **第三方依赖在每个干净的 DerivedData 里都要重编一遍。** 本库的依赖闭包里有 27 个与本仓库开发无关的包(`tuist install` 实测解析出的清单见「前期调研」):Capstone 的 C 库、swift-crypto、swift-collections、pointfree 的 swift-dependencies 一族、MetaCodable 与 MemberwiseInit 两个宏包、Yams、SourceKitD、swift-apinotes……原生 workspace 走 Xcode 自带的 SwiftPM 集成,每换一个 DerivedData(新 worktree、清缓存、换 Xcode)就全部从源码编一次。Tuist 的二进制缓存按内容寻址,同一台机器、同一个 Xcode 下只编一次。RuntimeViewer 用同样的做法量过:完整 App 从空 DerivedData 构建,不用缓存 504 秒,走缓存 155 秒。本库在 Ultra 上量的:清空 DerivedData 编 `swift-section`,不走缓存 63 秒,走缓存 46 秒(决策日志「缓存计时」)。 +- **原生 workspace 切换本地上游库的方式太粗。** 今天的切换靠 `USING_LOCAL_DEPENDENCIES=1` 加兄弟目录是否存在(`Package.swift:42` 起的 `package(local:remote:)`):这个变量要进到 Xcode 的启动环境里才生效;对所有声明了本地路径的依赖一刀切,连 workspace 里没有列出的 swift-capstone(`Package.swift:275`,`../swift-capstone` 在 `.worktrees/` 下有链接)也会被换成本地;切换后要等 Xcode 重新解析。Tuist 这边由 `Tuist/Package.swift` 按路径逐个声明要本地化的库,SwiftPM 让根包的路径依赖顶替图里所有同名声明,名单就是 workspace 的成员,切换只发生在命令行上。 +- **RuntimeViewer 的本地依赖模式已经在往本仓库的检出里写工程,而没有任何东西拦着另一方。** 它在每个按路径声明的包目录里生成 `<包名>.xcodeproj` 与 `Derived/`。2026-11-20 实测:RuntimeViewer 的集成 worktree 正占着本库的集成 worktree(本 worktree 的 git 目录里 `runtimeviewer-tuist-local-dependencies` 记着 `/Volumes/Repositories/Private/Org/MxIris-Reverse-Engineering/RuntimeViewer/.worktrees/RuntimeViewer`),本 worktree 根目录那份被忽略的 `MachOSwiftSection.xcodeproj` 就是它生成的。本库自己的 Tuist 也会在同一位置生成同名工程,两边的 `PackageSettings` 不同(配置名、警告、测试映射),谁后生成谁就让另一边的 workspace 坏掉。 + +## 前期调研 + +### 现状 + +- **原生 workspace 的成员**(`MachOSwiftSection.xcworkspace/contents.xcworkspacedata`):`container:../MachOKit`、`container:../MachOObjCSection`、`group:`(本库)、`group:PrecompiledLibraries/swift-syntax`。集成 worktree 里还有一处没提交的改动,又加了 `container:../MachOKitExtensions`、`container:../swift-demangling`、`container:../swift-semantic-string`。「本地依赖」指的就是这五个 `container:../<名字>` 成员。 +- **`PrecompiledLibraries/swift-syntax`** 是一个按包身份顶替 swift-syntax 的包,每个 product 是一个 `binaryTarget`(`PrecompiledLibraries/swift-syntax/Package.swift:46` 起,xcframework 从 `MxIris-DeveloperTool/swift-syntax-builder` 的 release 下载)。原生 workspace 靠把它列为成员来顶替;Tuist 这边要在 `Tuist/Package.swift` 里按路径声明它,两种模式都声明。 +- **本库 `Package.swift` 的本地依赖开关**:`usingLocalDependencies = envEnable("USING_LOCAL_DEPENDENCIES")`(`Package.swift:42`);`package(local:remote:)` 在 `#filePath` 含 `/checkouts/`、`/SourcePackages/` 或 `/.build/` 时一律走远程(`Package.swift:49-74`),所以作为别人的远程依赖时不受这个变量影响。 +- **可执行 target 与测试**:`swift-section`、`reader-benchmark`、`baseline-generator` 三个可执行 target(`Package.swift:929`、`956`、`972`),一个命令插件 `RegenerateBaselinesPlugin`(`Package.swift:987`),22 个测试 target。`SwiftSectionCommandTests`(`Package.swift:1305`)依赖 `swift-section`,测试文件里是 `@testable import swift_section`(13 个文件),不启动子进程。`SwiftSectionFixtureSupport`、`SwiftSectionTestingSupport`、`SwiftSectionTestingSupportC` 是普通 target,不属于任何 product(`Package.swift` 的 `products:` 只有 20 个库与 `swift-section`)。 +- **没有提交的锁文件**:`.gitignore` 有 `*.resolved`,根目录的 `Package.resolved` 是每台机器、每个检出自己解析出来的。 +- **RuntimeViewer 的做法**(`RuntimeViewer/TuistScript.sh`,1774 行;`Documentations/Guides/TuistDevelopment.md`):`Tuist/Package.swift` 按路径声明四个本地包;`Tuist.swift` 的缓存 profile `development` 用 `.onlyExternal`,按名字把本地包与 MachO 那几个库的 target 留作源码;本地依赖模式在 `Tuist/.local-dependencies` 记住目录,两种模式各用一份 `SWIFTPM_BUILD_DIR`;占用记录写在被占检出的 git 目录里(`runtimeviewer-tuist-local-dependencies`,内容是占用者的路径),判断占用是否仍然有效的办法是看占用者的 `Tuist/.local-dependencies` 是否指向这个目录;切回远程时删掉生成进库目录的工程;Tuist 生成的文件经被占仓库的 `info/exclude` 忽略。它的本地模式不映射测试,原因正是下面的第 1 条与第 6 条。RuntimeViewer 钉的 Tuist 是 4.210.0(`mise.toml`),它记下的 Tuist 4.210 的坑(`${inherited}`、`-ObjC`、测试 target 部署版本、trait 宏、`--cache-profile`)大部分只与 App 工程有关,与本提案相关的三条在「详细设计」里逐条说明。 + +### 实测(2026-11-20,JH's Mac Studio,Xcode 27.2,Tuist 4.210.0) + +探针放在 `/Volumes/DerivedData/Agents.noindex/claude/Probes/MachOSwiftSection-Tuist/`:本库 `next` 与五个上游库集成分支的 HEAD 用 `git archive` 导出成副本,`Tuist/Package.swift` 按路径声明本库副本与预编译 swift-syntax,`Tuist/CommandLine/Project.swift` 放 CLI。只跑了 `tuist install` 与 `tuist generate`,没有编译。没碰任何真实检出。 + +1. **远程模式、打开 `includeLocalPackageTestTargets`**:生成失败。`The test target 'SwiftSectionCommandTests' in the local package 'MachOSwiftSection' depends on the executable target 'swift-section', which Tuist omits when mapping local package dependencies.` 这个选项对所有按路径声明的包一视同仁,没有按 target 排除的参数(`PackageSettings.init` 只有 `includeLocalPackageTestTargets: Bool`,见 Tuist 4.218.1 的 `ProjectDescription.swiftinterface`)。 +2. **用环境变量在 `Package.swift` 里摘掉 `SwiftSectionCommandTests`**:开关生效(`tuist install` 的环境能传进依赖清单的 `Context.environment`,而 Tuist 在 install 时就把清单解析结果缓存下来)。下一个错误:`The local package test target 'SwiftDumpTests' depends on 'SnapshotTesting', which is not a configured external dependency.` 只被测试用到的依赖必须在 `Tuist/Package.swift` 里声明。 +3. **补上 swift-snapshot-testing**:`Couldn't find target 'SwiftSectionFixtureSupport'`。测试依赖的普通 target 不属于任何 product 时,Tuist 找不到它。 +4. **同一开关下给测试依赖的普通 target 补 library product**:生成成功。`MachOSwiftSection.xcodeproj` 有 48 个 target,其中 21 个测试 target(除 `SwiftSectionCommandTests` 外全部,含 `IntegrationTests`)。原生 `MachOSwiftSection.xcworkspace` 没被碰,新生成的是 `MachOSwiftSection-Tuist.xcworkspace`。 +5. **在 Tuist 工程里手写 CLI**:`swift-section`(command line tool)、`swift_section`(static framework,同一批源码,模块名就是测试要的 `swift_section`)、`SwiftSectionCommandTests`(unit tests,依赖 `swift_section`)三个 target,都按 `.external(name:)` 依赖包的 product,生成成功。工程放在 `Tuist/CommandLine/` 下也能生成。没编译,链接与 `@testable import` 是否成立待第 2 步在 Ultra 上验证。 +6. **本地模式(五个上游库副本按路径声明)**:生成失败。`The test target 'ObjCSectionCommandTests' in the local package 'MachOObjCSection' depends on the executable target 'objc-section'`。换 Tuist 4.218.1 同样失败。 +7. **五个上游库副本的 `Package.swift` 末尾都加上同一段通用适配**(见「详细设计」,第 1、3 条的两种形态都按规则处理):生成成功,六个包的测试全部映射进来:本库 21、MachOKit 1、MachOKitExtensions 9、MachOObjCSection 8、swift-demangling 1、swift-semantic-string 2。再逐个去掉适配:MachOKit 与 swift-semantic-string 不加也能过;swift-demangling 不加时报 `Couldn't find target 'DemanglingTestingSupport'`。**最少要改三个上游库:MachOKitExtensions(`CPlusPlusSymbolsFixture`)、MachOObjCSection(`ObjCSectionCommandTests`)、swift-demangling(`DemanglingTestingSupport`)。** +8. **生成的工程确实写进各包自己的目录**:`Siblings/<名字>/<名字>.xcodeproj` 与 `Derived/`,本库副本根目录也是。这就是与 RuntimeViewer 冲突的地方。 +9. **`Tuist.swift` 能读环境变量**:把 `TUIST_SOURCE_TARGET_NAMES=Utilities,SwiftSymbols,MachOSwiftSection` 经 `Environment.sourceTargetNames` 读进缓存 profile,`tuist dump config` 显示 `exceptTargetQueries` 正是这三个名字。缓存例外名单因此可以由脚本从各包清单算出来,不用像 RuntimeViewer 那样手抄、再用 `check` 守着。 +10. **`tuist install` 解析出的远程依赖**(远程模式,种子锁文件取自集成 worktree 的 `Package.resolved`):AssociatedObject、capstone、combine-schedulers、FrameworkToolbox、MetaCodable、Rainbow、SourceKitD、swift-apinotes、swift-argument-parser、swift-asn1、swift-async-algorithms、swift-binary-parse-support、swift-capstone、swift-clocks、swift-collections、swift-concurrency-extras、swift-crypto、swift-dependencies、swift-fileio、swift-fileio-extra、swift-issue-reporting、swift-literal-type-inference、swift-memberwise-init-macro、swift-object-association、swift-objc-dump、swift-snapshot-testing、Yams,加上五个上游库。 + +### 推测(写提案时未验证;实现中全部证实,见决策日志) + +- 测试 target 的部署版本:SwiftPM 给测试 target 的部署版本不低于 XCTest 与 Swift Testing 的要求(macOS 14.0),Tuist 照搬包声明的 10.15,RuntimeViewer 因此在 `Duration`、`timeLimit` 上编不过。本库测试大概率踩同一个坑。 +- `-ObjC`:Tuist 把包编成静态库,链接器只拉被符号引用到的成员。本库测试是否依赖按名字在运行时查找的类,没查过。 +- `CAPSTONE_HAS_AARCH64`:本库开了 swift-capstone 的 `AARCH64` trait(`Package.swift:291` 的 `capstoneTraits`),Tuist 会丢掉只以 trait 为条件的设置,RuntimeViewer 因此手动补上了这个宏。 +- `swift_section` 这个 static framework 里有 `@main`,链进测试 bundle 后会多出一个 `_main` 符号。bundle 不是可执行文件,这应该无害。 + +## 提议方案 + +1. **新增 Tuist 描述**,全部是开发用的,不进发版与 CI: + - `mise.toml` 钉 Tuist 4.210.0,与 RuntimeViewer 相同(探针里用这个版本全部生成成功;4.218.1 的 `tuist install` 在本地模式下失败过一次,没查原因)。 + - `Tuist/Package.swift` 按路径声明本库(`..`)、预编译 swift-syntax、只被测试用到的 swift-snapshot-testing;本地模式下再按路径声明五个上游库。`PackageSettings` 恢复本库(以及本地模式下上游库)target 的警告,补上 Capstone 的 trait 宏,按需给测试 target 抬部署版本、加 `-ObjC`。 + - `Tuist/CommandLine/Project.swift` 是 Tuist 转换不了的那部分:`swift-section` CLI、给测试用的 `swift_section` 模块、`SwiftSectionCommandTests`。 + - `Workspace.swift` 命名 `MachOSwiftSection-Tuist`,每个映射了测试的包一个测试 scheme(不含 `IntegrationTests`)。 + - `Tuist.swift` 的缓存 profile:只缓存外部依赖,例外名单是本库与五个上游库的全部 target,名单由脚本经环境变量传入。两种模式下上游库都从源码编。 +2. **`Package.swift` 末尾加一段适配**,只在 `TUIST_MAPS_LOCAL_PACKAGE_TESTS=1` 时生效:摘掉依赖本包可执行 target 的测试,给测试依赖却不属于任何 product 的普通 target 补 library product。同一段代码原样加进 MachOKitExtensions、MachOObjCSection、swift-demangling。规则是通用的,以后谁新加了这两种形态的测试都不用再改清单。 +3. **`TuistScript.sh`**:`install`、`generate`、`warm`、`build`、`test`、`release` 六个命令,`--local-dependencies` / `--remote-dependencies` 切换并记住模式,`--configuration Debug|Release`,`--dry-run`。依赖 checkout、二进制缓存、构建产物放 `/Volumes/DerivedData/MachOSwiftSection/Tuist/`,`TUIST_SCRIPT_ROOT` 可改。本地模式开始前先读各上游库的清单,有包会被 Tuist 拒掉测试时整体关掉测试映射并说明是哪个包,而不是让生成失败。 +4. **占用记录两边共用**:被占检出的 git 目录里写 `tuist-generated-project-owner`(占用者路径、释放它的命令),占用者在自己的 `Tuist/.claimed-checkouts` 列出手里的检出,列着才算有效。本库的脚本在任何模式下都占着自己的检出(根目录那份工程总要生成),本地模式下再占五个上游库;RuntimeViewer 的脚本改用同一份记录,旧记录仍然认。 +5. **文档**:使用指南 `Documentations/Internal/TuistDevelopment.md`,`AGENTS.md` 构建一节加一条,`Documentations/README.md` 登记。 + +### 非目标 + +- 不替代原生 workspace、`swift build` / `swift test` 与 CI;发版与 CI 只走原生路径。`Package.swift` 仍是 target 与依赖的唯一定义,Tuist 描述不另抄一份。 +- 不做 RuntimeViewer 那种「与原生工程对照」的 `check`,也不重排导航栏:本库没有原生 App 工程可对照,Tuist 直接读 `Package.swift`;唯一手抄的是 CLI 的依赖清单,编不过就会暴露。 +- 只做 macOS,只有 Debug 与 Release 两套配置。 +- 不映射 `reader-benchmark`、`baseline-generator` 两个维护者工具,也没有 `regen-baselines` 插件,照旧 `swift run` / `swift package`。 +- 不跑 `IntegrationTests`:target 会被转换进来,但不进任何 scheme(`AGENTS.md`:它是维护者手工查看用的)。 +- 不上传缓存:`Tuist.swift` 不设 `fullHandle`,二进制缓存只在本机。 +- MachOKit 与 swift-semantic-string 不改:实测它们现在不需要适配。以后它们新增了那两种形态的测试,脚本会关掉本地模式的测试映射并点名,到时再加同一段适配。 +- 不改 `USING_LOCAL_DEPENDENCIES` 机制:原生 workspace 的用法不变;脚本运行时忽略这个变量并提示。 + +## 改动地图 + +| 文件 / 类型 | 动作 | 改什么 | 为什么 | 步骤 | +|---|---|---|---|---| +| `mise.toml` | 新增 | `[tools] tuist = "4.210.0"` | 两台机器、两个仓库用同一个 Tuist;RuntimeViewer 记下的坑都是这个版本 | 1 | +| `Tuist/Package.swift` | 新增 | 按路径声明本库、预编译 swift-syntax,按 URL 声明 swift-snapshot-testing;本地模式加五个上游库;`PackageSettings` | Tuist 的依赖图从这里来;路径依赖顶替图里同名的 URL 声明 | 1、2、3 | +| `Tuist/CommandLine/Project.swift` | 新增 | `swift-section`、`swift_section`、`SwiftSectionCommandTests` 三个 target | Tuist 不转换可执行 target,也不接受依赖它的测试(实测第 1、5 条) | 1、2 | +| `Workspace.swift` | 新增 | workspace 名 `MachOSwiftSection-Tuist`,成员 `Tuist/CommandLine`,按包生成测试 scheme | 不与原生 `MachOSwiftSection.xcworkspace` 同名;测试 target 在转换出的工程里,只能由 workspace 的 scheme 引用 | 1、2 | +| `Tuist.swift` | 新增 | 缓存 profile `development`:`.onlyExternal`,例外取 `TUIST_SOURCE_TARGET_NAMES` | 本库与上游库留作源码,其余进缓存;名单由脚本从清单算(实测第 9 条) | 4 | +| `TuistScript.sh` | 新增 | 六个命令、两种依赖模式、存放位置、日志、锁文件种子与比对、占用记录、测试映射的预检 | 直接跑 `tuist` 拿不到正确的环境变量与占用保护 | 1–5 | +| `Package.swift` | 修改 | 文件末尾加 `TUIST_MAPS_LOCAL_PACKAGE_TESTS` 适配块 | 让 Tuist 能映射本库测试(实测第 1–4 条);变量不设时什么都不变 | 2 | +| `MachOSwiftSection.xcworkspace/contents.xcworkspacedata` | 修改 | 加入 MachOKitExtensions、swift-demangling、swift-semantic-string 三个成员,与集成 worktree 里那处未提交的改动内容相同 | 脚本从这里读本地依赖名单,五个都要在 | 1 | +| `.gitignore` | 修改 | 忽略 `MachOSwiftSection-Tuist.xcworkspace/`、根目录的 `MachOSwiftSection.xcodeproj/` 与 `Derived/`、`Tuist/.build*/`、`Tuist/CommandLine/` 下生成的工程与 `Derived/`、`Tuist/.local-dependencies`、`Tuist/.claimed-checkouts` | 生成物不提交;根目录那两项今天只靠 RuntimeViewer 写进 `info/exclude` 才被忽略 | 1 | +| MachOKitExtensions `Package.swift` | 修改 | 末尾加同一段适配块 | 本地模式下 `CPlusPlusSymbolsFixture` 找不到(实测第 7 条) | 3 | +| MachOObjCSection `Package.swift` | 修改 | 同上 | 本地模式下 `ObjCSectionCommandTests` 被拒(实测第 6 条) | 3 | +| swift-demangling `Package.swift` | 修改 | 同上 | 本地模式下 `DemanglingTestingSupport` 找不到(实测第 7 条) | 3 | +| RuntimeViewer `TuistScript.sh` · `claim_local_checkouts` / `release_local_checkouts` | 修改 | 改用共用的 `tuist-generated-project-owner` 与 `Tuist/.claimed-checkouts`;旧的 `runtimeviewer-tuist-local-dependencies` 照旧认、自己占着的顺手删掉 | 双向互斥:今天它看不见本库的占用 | 5 | +| RuntimeViewer `Documentations/Guides/TuistDevelopment.md` | 修改 | 「写进库目录的文件」「同一时刻只让一个检出用这组库」两段改写成共用的占用记录 | 文档与代码同批 | 5 | +| `Documentations/Internal/TuistDevelopment.md` | 新增 | 使用指南:第一次使用、日常用法、两种模式、占用记录、存放位置、已知的坑 | 维护者要知道怎么用、什么时候要重新 `install` / `generate` | 6 | +| `AGENTS.md` | 修改 | 构建一节加一条:Tuist workspace 是开发用的第二条路,只经脚本运行,agent 设 `TUIST_SCRIPT_ROOT` 并经 `queued-build` | agent 默认会直接跑 `tuist generate`,那样既没有环境变量也没有占用保护 | 6 | +| `Documentations/README.md` | 修改 | Internal 一节登记新指南 | 文档索引 | 6 | +| `Documentations/Evolutions/README.md` | 修改 | 状态表加本提案 | 提案索引 | 创建时、落地时 | +| `Documentations/Internal/ProjectEvolutionLog.md` | 修改 | 落地时加一节 | 演进账本 | 落地时 | + +## 架构图 + +改了什么(文件与生成物): + +```text +MachOSwiftSection/ (a checkout) +├── MachOSwiftSection.xcworkspace ~ members: + MachOKitExtensions, swift-demangling, swift-semantic-string +├── Package.swift ~ + TUIST_MAPS_LOCAL_PACKAGE_TESTS block at the end +├── + mise.toml tuist 4.210.0 +├── + Tuist.swift cache profile "development" +├── + Workspace.swift MachOSwiftSection-Tuist +├── + TuistScript.sh +├── + Tuist/ +│ ├── + Package.swift the dependency graph Tuist converts +│ └── + CommandLine/Project.swift swift-section, swift_section, SwiftSectionCommandTests +└── generated, ignored: + ├── MachOSwiftSection-Tuist.xcworkspace + ├── MachOSwiftSection.xcodeproj, Derived/ (converted from ./Package.swift) + └── Tuist/CommandLine/MachOSwiftSectionCommandLine.xcodeproj + +../MachOKitExtensions/Package.swift ~ + the same block +../MachOObjCSection/Package.swift ~ + the same block +../swift-demangling/Package.swift ~ + the same block +RuntimeViewer/TuistScript.sh ~ shared claim record +``` + +生成出的 workspace 里有什么: + +```text +MachOSwiftSection-Tuist.xcworkspace +├── Tuist/CommandLine/MachOSwiftSectionCommandLine.xcodeproj (+ hand-written Tuist targets) +│ ├── swift-section commandLineTool sources: Sources/Executables/swift-section/** +│ ├── swift_section staticFramework same sources, for @testable import +│ └── SwiftSectionCommandTests unitTests ──► swift_section +│ (all three ──► .external(SwiftSectionKit, MachOFoundation, ArgumentParser, …)) +├── MachOSwiftSection.xcodeproj source, 27 library/macro/C targets + 21 test targets +├── remote mode: checkouts//… source (cache exception), no tests +├── local mode: ..//.xcodeproj source from the local checkout, + its tests +└── third-party packages binary cache after `warm`, source before +``` + +一条命令怎么走(`./TuistScript.sh generate --local-dependencies`): + +```text +TuistScript.sh generate --local-dependencies +├── check the pinned Tuist (mise.toml), unset USING_LOCAL_DEPENDENCIES +├── read the local package names MachOSwiftSection.xcworkspace: container:../ +├── record the mode Tuist/.local-dependencies ← +├── read the manifests swift package dump-package, TUIST_MAPS_LOCAL_PACKAGE_TESTS=1 +│ ├── TUIST_SOURCE_TARGET_NAMES every target of this package and the five upstream ones +│ ├── TUIST_PACKAGE_TEST_TARGETS =,…;… +│ └── tests rejected by Tuist anywhere? → TUIST_MAPS_LOCAL_PACKAGE_TESTS=0 + a warning naming the package +├── ensure_dependencies SWIFTPM_BUILD_DIR per mode; seed Tuist/Package.resolved; tuist install +├── claim_checkouts this checkout + the five upstream checkouts +│ └── another live owner? → fail with the owner's release command +└── tuist generate --no-open +``` + +占用记录(两个仓库的脚本共用): + +```text +/tuist-generated-project-owner + line 1: /path/to/owner/checkout + line 2: ./TuistScript.sh release (MachOSwiftSection) + ./TuistScript.sh generate --remote-dependencies (RuntimeViewer) + +/Tuist/.claimed-checkouts one real path per line + +a claim is live ⇔ the owner's .claimed-checkouts lists the claimed checkout's real path +legacy: /runtimeviewer-tuist-local-dependencies is live + ⇔ /Tuist/.local-dependencies/ is the claimed checkout +``` + +## 详细设计 + +### `Package.swift` 的适配块 + +本库与三个上游库的 `Package.swift` 末尾原样加这一段(探针里五个上游库副本都用它通过了 `swift package dump-package` 与 `tuist generate`)。它读的是 `Context.environment`,平时这个变量不存在,块里什么都不做;作为别人的远程依赖时也一样。 + +```swift +// MachOSwiftSection's Tuist development workspace (its Documentations/Internal/TuistDevelopment.md) +// maps this package's tests with Tuist, which rejects two shapes SwiftPM accepts: a test that depends +// on an executable target, and a test that depends on a target no product contains. Only while Tuist +// resolves the packages, with TUIST_MAPS_LOCAL_PACKAGE_TESTS=1, the first kind is left out and the +// second kind gets a library product of its own. Nothing changes without the variable. +if Context.environment["TUIST_MAPS_LOCAL_PACKAGE_TESTS"] == "1" { + let executableTargetNames = Set(package.targets.filter { $0.type == .executable }.map(\.name)) + func dependencyName(_ dependency: Target.Dependency) -> String? { + switch dependency { + case .targetItem(let name, _), .byNameItem(let name, _): + return name + default: + return nil + } + } + package.targets.removeAll { target in + target.type == .test && target.dependencies.contains { dependency in + dependencyName(dependency).map(executableTargetNames.contains) ?? false + } + } + let productTargetNames = Set(package.products.flatMap { product in (product as? Product.Library)?.targets ?? [] }) + let testDependencyNames = Set(package.targets.filter { $0.type == .test }.flatMap { $0.dependencies.compactMap(dependencyName) }) + package.products += package.targets + .filter { target in target.type == .regular && testDependencyNames.contains(target.name) && !productTargetNames.contains(target.name) } + .map { target in Product.library(name: target.name, targets: [target.name]) } +} +``` + +- 在本库里它摘掉 `SwiftSectionCommandTests`,给 `SwiftSectionFixtureSupport`、`SwiftSectionTestingSupport`(以及测试直接依赖的其余普通 target)补 product。在 MachOObjCSection 里摘掉 `ObjCSectionCommandTests`;在 MachOKitExtensions 与 swift-demangling 里补 `CPlusPlusSymbolsFixture`、`DemanglingTestingSupport` 的 product。 +- 被摘掉的测试 Tuist workspace 里就没有了,照旧用 `swift test --filter` 跑;本库的 `SwiftSectionCommandTests` 例外,它在 `Tuist/CommandLine/Project.swift` 里手写(下文)。MachOObjCSection 的 `ObjCSectionCommandTests` 不手写:那要在本库描述另一个仓库的 target,非目标。 +- 只看 target 依赖(`targetItem` / `byNameItem`),不看 `productItem`:依赖别的包的可执行 product 的测试,Tuist 怎么处理没有实测,目前四个包里也没有。 + +### `Tuist/Package.swift` + +```swift +// swift-tools-version: 6.2 +import Foundation +import PackageDescription + +// The dependencies of MachOSwiftSection-Tuist.xcworkspace, the development-only Tuist workspace +// (Documentations/Internal/TuistDevelopment.md). Generate it with ./TuistScript.sh, never with a bare +// `tuist generate`: the script sets the variables everything below reads. +// +// MachOSwiftSection itself is declared by path, so its Package.swift stays the only definition of its +// targets and dependencies. In the local dependency mode (`./TuistScript.sh +// --local-dependencies`) the script names the upstream packages the native workspace lists beside +// the checkout in TUIST_LOCAL_PACKAGE_NAMES and the directory holding them in +// TUIST_LOCAL_PACKAGE_CHECKOUTS. A root's path dependency stands in for every other declaration of the +// same package in the graph — MachOSwiftSection's URLs and the upstream packages' own — so they build +// from those checkouts, uncommitted edits included. A path package's identity is its directory's name. +let processEnvironment = ProcessInfo.processInfo.environment +let localPackageCheckoutsDirectory = processEnvironment["TUIST_LOCAL_PACKAGE_CHECKOUTS"] ?? "" +let localPackageNames = (processEnvironment["TUIST_LOCAL_PACKAGE_NAMES"] ?? "") + .split(separator: ",") + .map(String.init) +// Qualified: Tuist evaluates this file with ProjectDescription imported too, which has a Package of +// its own. +let localPackageDependencies: [PackageDescription.Package.Dependency] = localPackageCheckoutsDirectory.isEmpty + ? [] + : localPackageNames.map { packageName in .package(path: "\(localPackageCheckoutsDirectory)/\(packageName)") } + +#if TUIST + import ProjectDescription + + func targetNames(in variable: String) -> [String] { + (processEnvironment[variable] ?? "").split(separator: ",").map(String.init) + } + + // Tuist suppresses warnings in every package; Xcode does so for remote packages only. The targets + // of the packages declared by path get theirs back: MachOSwiftSection always, the upstream + // packages in the local dependency mode. + let warningSettings: [String: Settings] = Dictionary( + targetNames(in: "TUIST_WARNING_TARGET_NAMES").map { targetName in + (targetName, Settings.settings(base: ["SWIFT_SUPPRESS_WARNINGS": "NO", "GCC_WARN_INHIBIT_ALL_WARNINGS": "NO"])) + }, + uniquingKeysWith: { first, _ in first } + ) + + // Tuist drops a package setting whose only condition is a trait. MachOSwiftSection enables + // swift-capstone's AARCH64 trait, which defines CAPSTONE_HAS_AARCH64 for both the Swift wrapper and + // the C library that way. Without it the wrapper does not compile, and the C library would compile + // but support no architecture at all. + let restatedTraitDefinitions: [String: Settings] = [ + "Capstone": .settings(base: [ + "SWIFT_ACTIVE_COMPILATION_CONDITIONS": ["$(inherited)", "CAPSTONE_HAS_AARCH64"], + "GCC_PREPROCESSOR_DEFINITIONS": ["$(inherited)", "CAPSTONE_HAS_AARCH64=1"], + ]), + "Ccapstone": .settings(base: [ + "GCC_PREPROCESSOR_DEFINITIONS": ["$(inherited)", "CAPSTONE_HAS_AARCH64=1"], + ]), + ] + + // A library target that imports Testing, such as a package's testing support, uses Swift Testing's + // macros (#expect, #require). Xcode points only test targets at the toolchain's TestingMacros + // plugin; SwiftPM gives it to every target. TUIST_TESTING_SUPPORT_TARGET_NAMES lists the library + // targets whose sources import Testing. + let testingSupportSettings: [String: Settings] = Dictionary( + targetNames(in: "TUIST_TESTING_SUPPORT_TARGET_NAMES").map { targetName in + (targetName, Settings.settings(base: [ + "ENABLE_TESTING_SEARCH_PATHS": "YES", + "OTHER_SWIFT_FLAGS": ["$(inherited)", "-plugin-path", "$(TOOLCHAIN_DIR)/usr/lib/swift/host/plugins/testing"], + ])) + }, + uniquingKeysWith: { first, _ in first } + ) + + // The test targets, which SwiftPM builds and links differently in three ways: + // - It builds a test target for at least the macOS version XCTest and Swift Testing require (14.0 + // with Xcode 26 and 27), whatever its package declares; Tuist takes the package's own minimum, and + // MachOSwiftSection's 10.15 leaves TypeIndexingTests without the macOS 13 APIs it tests. + // TUIST_RAISED_TEST_TARGET_NAMES lists the test targets of the packages that declare less. + // - It links each package target's object files whole, where Tuist links static frameworks and the + // linker loads only the archive members something refers to by symbol. A protocol conformance + // nothing names goes missing, and `as?` fails without a word: the readers that wrap a MachOImage + // or MachOFile (MachOReaderWrapper) read as neither. -ObjC also loads every member that defines an + // Objective-C class or category or a Swift type or extension (Xcode 27's linker), as it does for + // RuntimeViewer's Tuist workspace. + // - A load-time constructor nothing refers to never runs that way at all: MachOSwiftSection's + // SwiftSymbolsRegistration registers Swift as a symbol language from one. TUIST_FORCE_LOADS pairs + // each final link with the constructor targets its in-package dependencies reach, as + // ":,…"; those archives are loaded whole. + // TUIST_TEST_TARGET_NAMES lists every mapped test target, IntegrationTests included, so that a build + // of the whole workspace compiles and links too. Tuist/CommandLine/Project.swift gives the + // swift-section executable and SwiftSectionCommandTests the same link flags. + let forceLoadedTargetsByLinkingTarget: [String: [String]] = Dictionary( + targetNames(in: "TUIST_FORCE_LOADS").compactMap { pair -> (String, [String])? in + let parts = pair.split(separator: ":").map(String.init) + return parts.count == 2 ? (parts[0], [parts[1]]) : nil + }, + uniquingKeysWith: + + ) + let raisedTestTargetNames = Set(targetNames(in: "TUIST_RAISED_TEST_TARGET_NAMES")) + let testTargetSettings: [String: Settings] = Dictionary( + targetNames(in: "TUIST_TEST_TARGET_NAMES").map { targetName in + let forceLoadFlags = (forceLoadedTargetsByLinkingTarget[targetName] ?? []).map { loadedTarget in + "-Wl,-force_load,$(BUILT_PRODUCTS_DIR)/\(loadedTarget).framework/\(loadedTarget)" + } + var settings: SettingsDictionary = ["OTHER_LDFLAGS": .array(["$(inherited)", "-ObjC"] + forceLoadFlags)] + if raisedTestTargetNames.contains(targetName) { + settings["MACOSX_DEPLOYMENT_TARGET"] = "14.0" + } + return (targetName, Settings.settings(base: settings)) + }, + uniquingKeysWith: { first, _ in first } + ) + + // One target may need several of the settings above; their keys never overlap. + func mergingSettings(_ settingsByTarget: [String: Settings]...) -> [String: Settings] { + settingsByTarget.reduce(into: [:]) { merged, settings in + merged.merge(settings) { first, second in .settings(base: first.base.merging(second.base) { $1 }) } + } + } + + let packageSettings = PackageSettings( + targetSettings: mergingSettings(warningSettings, restatedTraitDefinitions, testTargetSettings, testingSupportSettings), + // TuistScript.sh sets the variable to 1 unless a package declared by path still has a test of + // a shape Tuist rejects (the manifests' TUIST_MAPS_LOCAL_PACKAGE_TESTS block removes them). + includeLocalPackageTestTargets: processEnvironment["TUIST_MAPS_LOCAL_PACKAGE_TESTS"] == "1" + ) +#endif + +let package = Package( + name: "MachOSwiftSectionTuistDependencies", + dependencies: [ + .package(path: ".."), + // Stands in for swift-syntax in every macro package, as it does as a member of the native + // workspace: SwiftPM matches it by package identity. + .package(path: "../PrecompiledLibraries/swift-syntax"), + // Used only by MachOSwiftSection's tests. Tuist maps a test target only when every package + // its dependencies come from is declared here, with the requirement Package.swift gives it. + .package(url: "https://github.com/pointfreeco/swift-snapshot-testing", from: "1.18.9"), + ] + localPackageDependencies +) +``` + +- 包名 `MachOSwiftSectionTuistDependencies`。根包的路径依赖 `..` 的身份是目录名:worktree 叫 `MachOSwiftSection-<用途>` 时身份就变了,而上游库的清单不按 URL 引用本库,所以不受影响;生成的工程名取自 `Package(name:)`,仍是 `MachOSwiftSection.xcodeproj`。 +- `TUIST_WARNING_TARGET_NAMES` 是本库全部 target,本地模式下再加五个上游库的全部 target(与原生 workspace 一致:Xcode 只给远程包关警告)。 + +### `Tuist/CommandLine/Project.swift` + +```swift +import ProjectDescription + +// What Tuist cannot convert from ../../Package.swift (Documentations/Internal/TuistDevelopment.md): +// the swift-section executable, and SwiftSectionCommandTests, which imports the executable's module +// (`@testable import swift_section`). Tuist converts no executable target and rejects a test that +// depends on one, so Package.swift leaves that test out while Tuist resolves it and it is described +// here instead. swift_section compiles the command's sources as a static framework for the test; the +// tool compiles them again, so its link needs no trick around the @main entry point. +// +// The dependency list mirrors the swift-section target in Package.swift and is the one hand-written +// copy in the Tuist description: a dependency added there that is missing here fails to compile. +let commandLineDependencies: [TargetDependency] = [ + .external(name: "SwiftSectionKit"), + .external(name: "MachOFoundation"), + .external(name: "SwiftSymbols"), + .external(name: "SwiftDump"), + .external(name: "SwiftOutputTransformer"), + .external(name: "SwiftDeclaration"), + .external(name: "SwiftIndexing"), + .external(name: "Semantic"), + .external(name: "OutputTransformer"), + .external(name: "ObjCDeclarationRendering"), + .external(name: "ObjCOutputTransformer"), + .external(name: "Rainbow"), + .external(name: "ArgumentParser"), +] + +// Tuist builds swift-argument-parser for macOS 12, the minimum that package declares; the package's +// own 10.15 does not reach the executable here the way SwiftPM's build of it does. +let commandLineDeploymentTargets: DeploymentTargets = .macOS("12.0") + +let commandLineSources: SourceFilesList = ["../../Sources/Executables/swift-section/**"] + +// The link flags Tuist/Package.swift gives the package's test targets, for the same reasons: -ObjC, so +// that the archive members defining Swift types and extensions (protocol conformances among them) are +// loaded, and -force_load of the constructor targets the swift-section executable reaches in +// Package.swift, which TuistScript.sh lists in TUIST_FORCE_LOADS. +let forceLoadedTargetNames: [String] = Environment.forceLoads.getString(default: "") + .split(separator: ",") + .compactMap { pair in + let parts = pair.split(separator: ":").map(String.init) + return parts.count == 2 && parts[0] == "swift-section" ? parts[1] : nil + } +let linkFlags: SettingsDictionary = [ + "OTHER_LDFLAGS": .array(["$(inherited)", "-ObjC"] + forceLoadedTargetNames.map { targetName in + "-Wl,-force_load,$(BUILT_PRODUCTS_DIR)/\(targetName).framework/\(targetName)" + }), +] + +// MACHO_SWIFT_SECTION_SILENT_TEST=1, which Package.swift turns into SILENT_TEST for its test targets; +// TuistScript.sh passes it on as TUIST_SILENT_TEST, the only form a Tuist manifest can read. +let commandTestSettings: Settings = .settings(base: linkFlags.merging( + Environment.silentTest.getBoolean(default: false) ? ["SWIFT_ACTIVE_COMPILATION_CONDITIONS": ["$(inherited)", "SILENT_TEST"]] : [:] +) { $1 }) + +let project = Project( + name: "MachOSwiftSectionCommandLine", + // In SwiftPM these targets belong to the MachOSwiftSection package, whose `package` declarations + // they use (SwiftSectionCommandTests calls SwiftSectionKit's applyTransformersEnablingCommentKinds). + // Tuist gives the targets it converts SWIFT_PACKAGE_NAME = MachOSwiftSection; these need the same. + settings: .settings(base: ["SWIFT_PACKAGE_NAME": "MachOSwiftSection"]), + targets: [ + .target( + name: "swift-section", + destinations: .macOS, + product: .commandLineTool, + // Tuist would name the executable swift_section, as it turns every dash of a target's name + // into an underscore. + productName: "swift-section", + bundleId: "com.machoswiftsection.swift-section", + deploymentTargets: commandLineDeploymentTargets, + sources: commandLineSources, + dependencies: commandLineDependencies, + settings: .settings(base: linkFlags) + ), + .target( + name: "swift_section", + destinations: .macOS, + product: .staticFramework, + bundleId: "com.machoswiftsection.swift-section.module", + deploymentTargets: commandLineDeploymentTargets, + sources: commandLineSources, + dependencies: commandLineDependencies + ), + .target( + name: "SwiftSectionCommandTests", + destinations: .macOS, + product: .unitTests, + bundleId: "com.machoswiftsection.SwiftSectionCommandTests", + deploymentTargets: .macOS("14.0"), + sources: ["../../Tests/SwiftSectionCommandTests/**"], + dependencies: [ + .target(name: "swift_section"), + .external(name: "SwiftDeclarationRendering"), + .external(name: "SwiftPrinting"), + ] + commandLineDependencies, + settings: commandTestSettings + ), + ] +) +``` + +- CLI 的源码编两遍(tool 一遍、framework 一遍)。另一种写法是 tool 不带源码、只链 framework,靠链接器从静态库里取 `_main`;省一遍编译,但能否链接成功依赖链接器怎么处理入口符号,没实测,放进「替代方案」。 +- `MACHO_SWIFT_SECTION_SILENT_TEST=1` 在 `Package.swift` 里变成测试 target 的 `SILENT_TEST` 定义:`tuist install` 时设了它,转换出的测试就带上。手写的 `SwiftSectionCommandTests` 也要带:Tuist 的 manifest 只读得到 `TUIST_` 开头的变量,所以脚本把它转成 `TUIST_SILENT_TEST=1`,`Project.swift` 据此给这个 target 加 `SILENT_TEST`。 + +### `Workspace.swift` + +```swift +import ProjectDescription + +// MachOSwiftSection-Tuist.xcworkspace, the development-only workspace Tuist generates beside the +// native MachOSwiftSection.xcworkspace (Documentations/Internal/TuistDevelopment.md). +// +// The packages' test targets live in the projects Tuist converts from their Package.swift files, which +// only a workspace scheme can reference. TuistScript.sh lists them in TUIST_PACKAGE_TEST_TARGETS as +// "=,;…", one entry per package whose tests are mapped: +// MachOSwiftSection always (directory "."), the upstream packages in the local dependency mode +// (absolute directories). IntegrationTests, the maintainer's manual-inspection target, is never listed. +let packageTestTargets: [(directory: String, targets: [String])] = Environment.packageTestTargets + .getString(default: "") + .split(separator: ";") + .compactMap { entry in + let parts = entry.split(separator: "=", maxSplits: 1).map(String.init) + guard parts.count == 2 else { return nil } + return (parts[0], parts[1].split(separator: ",").map(String.init)) + } + +func packageName(ofDirectory directory: String) -> String { + directory == "." ? "MachOSwiftSection" : String(directory.split(separator: "/").last ?? Substring(directory)) +} + +func projectPath(ofDirectory directory: String) -> Path { + directory.hasPrefix("/") ? .path(directory) : .relativeToRoot(directory) +} + +let workspace = Workspace( + name: "MachOSwiftSection-Tuist", + projects: ["Tuist/CommandLine"], + schemes: packageTestTargets.map { entry in + var testableTargets = entry.targets.map { targetName in + TestableTarget.testableTarget( + target: .project(path: projectPath(ofDirectory: entry.directory), target: targetName), + parallelization: .swiftTestingOnly + ) + } + if entry.directory == "." { + testableTargets.append(.testableTarget( + target: .project(path: "Tuist/CommandLine", target: "SwiftSectionCommandTests"), + parallelization: .swiftTestingOnly + )) + } + return .scheme( + name: "\(packageName(ofDirectory: entry.directory)) Tests", + testAction: .targets( + testableTargets, + // The test process as `swift test` runs it. The Thread Performance Checker inserts + // libRPAC.dylib, which rebinds calls in the loaded images: the cross-reference tests that + // compare a cache image read in process with the same image read from its file then + // see calls into libRPAC. The Main Thread Checker swizzles Objective-C methods the same + // way. Tuist 4.210 writes only the Main Thread Checker's attribute; TuistScript.sh adds + // disablePerformanceAntipatternChecker to the generated schemes. + diagnosticsOptions: .options(mainThreadCheckerEnabled: false, performanceAntipatternCheckerEnabled: false) + ) + ) + } +) +``` + +- 上游库的目录是绝对路径;`Path` 接受绝对路径字符串(第 3 步验证过:本地模式下六个包的 scheme 都生成了)。包名取目录的最后一段,自己切,不 `import Foundation`。 +- 测试映射被预检关掉时 `TUIST_PACKAGE_TEST_TARGETS` 为空,只剩各 target 自己的 scheme;`SwiftSectionCommandTests` 仍在 `MachOSwiftSectionCommandLine` 工程里,Tuist 自动生成的 scheme 能跑它。 + +### `Tuist.swift` + +```swift +import ProjectDescription + +// Every target of MachOSwiftSection and of the five upstream packages its native workspace lists +// (MachOKit, MachOKitExtensions, MachOObjCSection, swift-demangling, swift-semantic-string) stays +// source, in both dependency modes; every other dependency comes out of the binary cache once +// `./TuistScript.sh warm` has filled it. The script reads the names from the packages' manifests and +// passes them in TUIST_SOURCE_TARGET_NAMES. No fullHandle: the cache stays on this machine and +// nothing is uploaded. Documentations/Internal/TuistDevelopment.md. +let sourceTargetNames = Environment.sourceTargetNames + .getString(default: "") + .split(separator: ",") + .map(String.init) + +let tuist = Tuist( + project: .tuist( + cacheOptions: .options( + profiles: .profiles( + ["development": .profile(.onlyExternal, except: sourceTargetNames.map { .named($0) })], + default: "development" + ) + ) + ) +) +``` + +- 上游库在远程模式下也留作源码,理由与 RuntimeViewer 相同:本库经常跟着它们改、频繁挪 pin,放进缓存就要一次次重新预热;它们留作源码也能直接跳进去看。代价是远程模式从空 DerivedData 构建要多编这五个库;第 4 步量出 CLI 冷编 63 秒、走缓存 46 秒,暂不改。 +- 例外按名字匹配所有包的 target。脚本在算名单时检查有没有第三方包的 target 与名单同名,有就警告(同名的会被一起留成源码)。 + +### `TuistScript.sh` + +照 RuntimeViewer 的脚本写,只保留与本库有关的部分。 + +**命令**: + +| 命令 | 做什么 | +|---|---| +| `install` | 从种子锁文件开始解析当前模式的依赖(`tuist install`),结束时与种子比对 pin | +| `generate [--configuration ]` | 需要时先 `install`,占用检出,生成 workspace(默认 Debug) | +| `warm [--configuration ]` | 带 `--cache-profile development` 把第三方依赖编进缓存,再生成 | +| `build [--configuration ] [--scheme ] [-- ]` | 生成后用 `xcodebuild` 编 `swift-section` scheme,或另一个 | +| `test [--configuration ] [--scheme ] [-- ]` | 生成后用 `xcodebuild test` 跑 `MachOSwiftSection Tests` scheme(本地模式下上游库各有 `<包名> Tests`),结果存进 `Work//TestResults/*.xcresult` 并打印通过 / 失败 / 跳过的个数,退出码就是 `xcodebuild` 的 | +| `release` | 放弃所有占用:删掉生成进各检出的工程(git 跟踪的不删)、占用记录与 `MachOSwiftSection-Tuist.xcworkspace`;`Derived/` 留着 | + +`--local-dependencies` / `--remote-dependencies` 可以跟在任何命令后面,从这条命令起切换模式;`--dry-run` 打印要做的事;`--help` 打印脚本头部的说明。 + +**环境变量**(脚本设,manifest 读): + +| 变量 | 谁读 | 内容 | +|---|---|---| +| `TUIST_MAPS_LOCAL_PACKAGE_TESTS` | 四个包的 `Package.swift`,`Tuist/Package.swift` | `1`:映射测试;预检不通过时 `0` | +| `TUIST_LOCAL_PACKAGE_CHECKOUTS`、`TUIST_LOCAL_PACKAGE_NAMES` | `Tuist/Package.swift` | 本地模式下上游库所在目录与名字;远程模式不设 | +| `TUIST_SOURCE_TARGET_NAMES` | `Tuist.swift` | 本库与五个上游库的全部 target | +| `TUIST_WARNING_TARGET_NAMES` | `Tuist/Package.swift` | 恢复警告的 target:本库全部,本地模式再加上游库全部 | +| `TUIST_PACKAGE_TEST_TARGETS` | `Workspace.swift` | 每个映射了测试的包的测试 target,不含 `IntegrationTests` | +| `TUIST_TEST_TARGET_NAMES` | `Tuist/Package.swift` | 所有转换进来的测试 target(含 `IntegrationTests`),给它们 `-ObjC` 与 `-force_load` | +| `TUIST_RAISED_TEST_TARGET_NAMES` | `Tuist/Package.swift` | 声明的 macOS 最低版本低于 14 的包的测试 target,部署版本抬到 14.0 | +| `TUIST_TESTING_SUPPORT_TARGET_NAMES` | `Tuist/Package.swift` | 源码里 `import Testing` 的库 target,加 TestingMacros 插件路径 | +| `TUIST_FORCE_LOADS` | `Tuist/Package.swift`、`Tuist/CommandLine/Project.swift` | `<链接的 target>:<有加载期 constructor 的 target>,…`,后者整个 `-force_load` | +| `TUIST_SILENT_TEST` | `Tuist/CommandLine/Project.swift` | 用户设了 `MACHO_SWIFT_SECTION_SILENT_TEST=1` 时为 `1` | +| `SWIFTPM_BUILD_DIR` | Tuist | 当前模式的依赖 checkout 目录 | +| `TUIST_XDG_CACHE_HOME`、`TUIST_CACHE_WARM_SCRATCH_DIRECTORY` | Tuist | 二进制缓存与预热的临时目录 | + +`USING_LOCAL_DEPENDENCIES` 被设了就提示一句并 `unset`:它会让本库清单自己换上本地兄弟,连 swift-capstone 一起,与 `Tuist/Package.swift` 的名单对不上。 + +**名单从哪来**:本地依赖的名字读 `MachOSwiftSection.xcworkspace/contents.xcworkspacedata` 里的 `container:../<名字>`(不含 `/` 的那些),workspace 加了库这里自动跟上。每次 `install` 之后,脚本用 `swift package dump-package`(带 `TUIST_MAPS_LOCAL_PACKAGE_TESTS=1`,8 个并行,`--scratch-path` 放在 `Work//Manifests/Scratch/`)读一遍所有包的清单,存进 `Work//Manifests/`:本库与本地模式下的上游库读检出里的,远程模式下的上游库和全部第三方包读 `SWIFTPM_BUILD_DIR/checkouts/` 里的。`generate`、`warm` 前由 Python 从这些清单算出上表的各个名单,并扫描路径包里 target 的源码找 `import Testing` 与 `__attribute__((constructor))`;Python 出错脚本就失败,不带着空名单生成。 + +**测试映射的预检**:对每个按路径声明的包,在它的清单 JSON 里找 Tuist 会拒绝的两种形态——测试依赖本包的可执行 target、测试依赖不属于任何 product 的普通 target(实测第 1、3、6 条)。适配块生效时这两种都不该剩下;还剩,说明那个包没有适配块(比如本地检出停在加块之前的提交),这次就整体设 `TUIST_MAPS_LOCAL_PACKAGE_TESTS=0`,警告点名那个包,生成照常进行。只被测试用到的外部依赖(实测第 2 条)预检查不出来,生成时 Tuist 自己会报,指南里写怎么补。 + +**锁文件**:`Tuist/Package.resolved` 不提交(`*.resolved` 已忽略)。每次 `install` 前用本检出根目录的 `Package.resolved` 当种子(没有就不种,由 Tuist 解析最新版本),结束时逐条比对,不同就警告;swift-syntax(这边是预编译包,没有 pin)与本地模式下的五个库不参与比对。 + +**依赖模式**:模式记在 `Tuist/.local-dependencies`(内容是上游库所在目录;远程模式下这个文件不存在)。默认目录是检出的上一级,worktree 里就是 `.worktrees/`;打开本地模式时设了 `TUIST_LOCAL_PACKAGE_CHECKOUTS` 就用它。两种模式各用一份依赖 checkout(`Dependencies/` 与 `Dependencies/-LocalDependencies`),共用 `Tuist/Package.resolved`,所以切换后、或上次解析用的是另一种模式时先重新 `install`(`Work//InstalledDependencies` 记着上次)。这个记号还带着 `Tuist/Package.swift`、`Package.swift`、种子锁文件与本地模式下各上游库清单的 hash:改了其中任何一个,下一次 `generate` 自己重新解析。切到远程时释放五个上游库的占用。 + +**存放位置**:`/Volumes/DerivedData` 挂着时全放在 `/Volumes/DerivedData/MachOSwiftSection/Tuist/` 下(`Cache/`、`Dependencies/[-LocalDependencies]/`、`WarmScratch//`、`Work//`),`` 是目录名加路径的短 hash;没挂载时放在仓库里的 `Tuist/.build/`、`Tuist/.build-LocalDependencies/` 与 `DerivedData/Tuist/`(都已忽略)。`TUIST_SCRIPT_ROOT` 指定别处。`build` / `test` 的 DerivedData 在 `Work//DerivedData`。日志在 `Products/Logs/Tuist/`;Tuist 的输出原样显示并记进日志,`xcodebuild` 的输出只进日志,失败时显示错误摘要。 + +**占用记录**(与 RuntimeViewer 共用): + +- 被占的检出:它的 git 目录(`git rev-parse --absolute-git-dir`,worktree 各有一份)里的 `tuist-generated-project-owner`,第一行是占用者检出的路径,第二行是在占用者检出里释放它的命令,第三行是生成进这个检出的工程名(释放时删它)。 +- 占用者:自己的 `Tuist/.claimed-checkouts`,每行一个被占检出的真实路径(`pwd -P`)。 +- 有效:占用者的 `.claimed-checkouts` 列着这个路径。占用者不在了、或已经不列了,记录就是陈旧的,可以直接覆盖。 +- 旧记录 `runtimeviewer-tuist-local-dependencies`:占用者的 `Tuist/.local-dependencies` 加上包名指向这个检出时算有效(RuntimeViewer 今天的规则)。 +- 本库的脚本在 `generate` 前占用自己的检出与(本地模式下)五个上游库;遇到别人的有效占用就失败,报出占用者路径与它的释放命令。检出里 git 跟踪着 `<包名>.xcodeproj` 时也失败(Tuist 会覆盖它)。上游库的 `<包名>.xcodeproj/` 与 `Derived/` 写进那个仓库的 `info/exclude`,本库自己的生成物走 `.gitignore`。 +- 释放:删掉生成进那个检出的工程、占用记录,并从 `.claimed-checkouts` 里去掉。 + +**Tuist 版本**:读 `mise.toml` 的版本;有 mise 就 `mise exec -- tuist`,否则用 PATH 里的 `tuist`;版本不对就失败并提示 `mise install`。 + +**生成之后**:给每个 `* Tests.xcscheme` 的 TestAction 补 `disablePerformanceAntipatternChecker = "YES"`(Tuist 4.210 只写主线程检查那一项,见决策日志)。 + +**agent 运行**:`TUIST_SCRIPT_ROOT=/Volumes/DerivedData/Agents.noindex//Tuist-MachOSwiftSection`;`warm`、`build`、`test` 要编译,写成 `queued-build ./TuistScript.sh <命令>`,`install`、`generate`、`release` 不编译。 + +### RuntimeViewer 那一侧 + +- `claim_local_checkouts`:先读共用记录与旧记录,任何一个有效且占用者不是自己就失败,报出占用者与释放命令;然后写共用记录(第二行是 `./TuistScript.sh generate --remote-dependencies`),把路径写进自己的 `Tuist/.claimed-checkouts`,自己的旧记录删掉。 +- `release_local_checkouts`:删掉自己的共用记录(以及残留的旧记录),从 `.claimed-checkouts` 里去掉。 +- 今天它占着本库的集成 worktree 与五个上游检出(旧记录)。改完后它下一次 `generate` 就把记录换成新的;在那之前,本库的脚本按旧规则认出它的占用。 + +### 实现中确认的点(Ultra,Xcode 27.2) + +1. `swift_section` 与 `SwiftSectionCommandTests` 能编、能链、`@testable import` 成立:124 个测试全部通过。另需 `SWIFT_PACKAGE_NAME = MachOSwiftSection`(它调用 SwiftSectionKit 的 `package` 方法),工具 target 写明 `productName`。 +2. 部署版本与链接参数:测试 target 要抬到 macOS 14.0(`TypeIndexingTests`),CLI 要 macOS 12.0(swift-argument-parser);测试与 CLI 都要 `-ObjC`(包装读取器的 conformance)和对 `SwiftSymbolsRegistration` 的 `-force_load`(Swift 符号语言的注册);导入 Testing 的库 target 要 TestingMacros 插件路径;测试 scheme 要关掉两个运行时检查。逐条见决策日志。 +3. `Capstone` 的 trait 宏补上后 `SwiftThunkAnalysis` 编过,它的测试通过(86 个通过、2 个跳过)。 +4. 远程模式:Tuist workspace 的测试 scheme 与原生 `swift test --skip IntegrationTests` 在同一台机器、同一个 Xcode 下逐 bundle 对照,全部通过;Tuist 编的 `swift-section` 与原生编的对 SymbolTestsCore 输出的 `dump`、`interface` 逐字节相同。 +5. 本地模式与按绝对路径引用上游库工程:见决策日志「本地模式实测」。 + +## 替代方案考量 + +- **Tuist 的「把 `Package.swift` 当工程」**(beta,`tuist generate` 直接读根目录的 `Package.swift`):不用 `Tuist/Package.swift`,可本地 / 远程切换要靠顶替同名包,还是得有一个根清单按路径声明上游库;文档写明它不打算支持 SwiftPM 的全部特性;它很可能按包名生成 `MachOSwiftSection.xcworkspace`,与原生 workspace 同名(推测,没实测)。否。 +- **在 `Project.swift` 里手写全部 target**:生成的工程名可以避开 RuntimeViewer 用的 `MachOSwiftSection.xcodeproj`,冲突自然消失;但要把五十来个 target 的依赖关系从 `Package.swift` 再抄一份,必然漂移,还得写一个 `check` 守着。否。 +- **Tuist 的 Xcode 原生包集成**(生成的工程里仍用 Xcode 的 SwiftPM 集成):不往包目录写工程,冲突也消失;但它没有二进制缓存,与原生 workspace 相比什么也没得到。否。 +- **本地模式不映射测试**(RuntimeViewer 的做法):不用改任何上游库;但本库跨仓库改动时用的正是本地模式,那时 Tuist workspace 里跑不了任何测试,本库自己的也跑不了(这个选项对所有路径包一刀切)。用户选了加适配块(决策日志「用户批准,开始实现」)。 +- **只针对点名的 target 打补丁**(在本库清单里按名字摘掉 `SwiftSectionCommandTests`、按名字补 product):探针第一版就是这么做的;但三个上游库各要写一份不同的补丁,以后每加一个这种形态的测试都要回来改。通用规则一段代码四个仓库共用。否。 +- **CLI 只链 framework、不带源码**:省一遍 CLI 源码的编译;能否链接成功取决于链接器会不会为入口符号 `_main` 从静态库里取成员,没实测,失败了还得改成给 framework 加 `-entry-point-function-name`。编两遍的写法没有这个风险,CLI 模块也不大。否,可以在第 2 步顺手试一次,成了再换。 +- **远程模式下把五个上游库也放进缓存**:远程模式从空 DerivedData 构建会更快;但它们的 pin 动得勤,每次都要重新预热,缓存里旧版本越积越多,也跳不进源码。暂否,第 4 步量出差距后可以重议。 +- **只在本库这边检查 RuntimeViewer 的占用**:不用改 RuntimeViewer;但 RuntimeViewer 的本地模式照样会盖掉本库生成的工程。用户选了双向互斥。 +- **用 `USING_LOCAL_DEPENDENCIES=1` 实现本地模式**:本库清单自己就会换上本地兄弟;但它对所有带本地路径的依赖一刀切(含 swift-capstone),三个上游库的清单也各有自己的开关,结果取决于每个清单怎么写。按路径逐个声明更精确,与 RuntimeViewer 一致。否。 + +## 影响 + +### 源码兼容性(source compatibility) + +纯新增。没有任何公开 API 变化。`Package.swift` 的适配块只在 `TUIST_MAPS_LOCAL_PACKAGE_TESTS=1` 时生效,`swift build`、`swift test`、Xcode 的原生 workspace、CI 与下游的 SwiftPM 解析都不会设这个变量;三个上游库同样。 + +### ABI 兼容性(条件项) + +不适用 —— 本库以 SPM 源码分发,使用方每次重新编译。 + +### 下游影响 + +- **本仓库内**:没有 target 受影响。`.gitignore` 多了几项生成物,`MachOSwiftSection.xcworkspace` 多了三个成员(它们本来就在集成 worktree 的未提交改动里)。 +- **RuntimeViewer**:`TuistScript.sh` 换用共用的占用记录(第 5 步)。它的 Tuist 在本地模式下按路径读本库与三个上游库的清单,但不设 `TUIST_MAPS_LOCAL_PACKAGE_TESTS`,适配块不生效,它生成的工程不变。 +- **MachOKitExtensions、MachOObjCSection、swift-demangling**:清单末尾多一段默认不生效的代码,不需要发版——只有本地模式读它们的本地检出时才用到。它们的其他下游(MachOKitUI、SymbolViewer……)不受影响。 + +### 文档与示例 + +- 新增使用指南 `Documentations/Internal/TuistDevelopment.md`,登记进 `Documentations/README.md`。 +- `AGENTS.md` 构建一节加一条。 +- `README.md` 不改:Tuist workspace 只给维护者用。 +- RuntimeViewer 的 `Documentations/Guides/TuistDevelopment.md` 改两段(第 5 步)。 + +## API 演进与废弃策略 + +无:没有公开 API 变化,不涉及版本号。 + +## 落地步骤 + +在 Ultra 上构建与跑测试(本机是 10 核那台),用默认的 Xcode 27.2;第 2、3 步的测试结果另用 Xcode 26.6 的 `swift test` 结果对照。 + +1. **骨架:远程模式能生成、能编 CLI**(已完成) —— 改动地图里 `mise.toml`、`Tuist/Package.swift`(不含测试相关)、`Tuist/CommandLine/Project.swift`(只有 `swift-section`)、`Workspace.swift`(无测试 scheme)、`TuistScript.sh`(`install`、`generate`、`build`、`release`,存放位置,锁文件,自己检出的占用)、`.gitignore`、workspace 成员 + - 行为:`generateCreatesTheTuistWorkspaceAndLeavesTheNativeWorkspaceUntouched` + - 行为:`buildCompilesSwiftSectionFromTheTuistWorkspace` + - 行为:`generateFailsNamingTheOwnerWhenAnotherCheckoutHoldsThisOne` + - 行为:`releaseRemovesTheGeneratedProjectsAndTheClaim` + - 行为:`installWarnsWhenTheResolvedPinsDifferFromTheSeedLockFile` + - 行为:`usingLocalDependenciesIsIgnoredWithAWarning` +2. **本库的测试**(已完成) —— `Package.swift` 适配块,`Tuist/Package.swift` 的 swift-snapshot-testing 与测试设置,`Project.swift` 的 `swift_section` 与 `SwiftSectionCommandTests`,`Workspace.swift` 的测试 scheme,脚本的 `test` 命令与清单读取 + - 行为:`theTestSchemeHoldsEveryTestTargetExceptIntegrationTests` + - 行为:`swiftSectionCommandTestsImportTheCommandModuleAndPass` + - 行为:`theTuistTestRunMatchesSwiftTestTargetByTarget` + - 行为:`packageManifestIsUnchangedWithoutTheTuistVariable`(`swift package dump-package` 不带变量时与改动前逐字节相同) +3. **本地模式**(已完成) —— 三个上游库的适配块(各自的功能分支),`Tuist/Package.swift` 的本地依赖,脚本的模式切换、上游库占用、预检 + - 行为:`localDependenciesBuildTheUpstreamPackagesFromTheirCheckoutsWithUncommittedEdits` + - 行为:`theModeIsRememberedAndSwitchingResolvesAgain` + - 行为:`localModeMapsTheTestsOfAllSixPackages` + - 行为:`anUpstreamCheckoutWithoutTheBlockTurnsTestMappingOffWithAWarning` + - 行为:`switchingToRemoteReleasesTheUpstreamCheckouts` +4. **二进制缓存**(已完成) —— `Tuist.swift`,脚本的 `warm` 与 `TUIST_SOURCE_TARGET_NAMES` + - 行为:`warmCachesEveryThirdPartyPackageAndNoneOfTheSixOwnPackages` + - 行为:`generateAfterWarmLinksTheCachedBinaries` + - 行为:`aThirdPartyTargetNamedLikeAnOwnTargetIsReported` + - 记录:空 DerivedData 下不用缓存与走缓存各编一次 `swift-section` 与测试 scheme 的时间,写进决策日志与指南。 +5. **与 RuntimeViewer 互斥**(已完成) —— RuntimeViewer 的 `TuistScript.sh` 与指南 + - 行为:`runtimeViewerLocalModeFailsWhileMachOSwiftSectionHoldsTheCheckout` + - 行为:`machOSwiftSectionFailsWhileRuntimeViewerHoldsAnUpstreamCheckout`(新旧两种记录各一次) + - 行为:`aStaleClaimIsTakenOverSilently` +6. **文档**(已完成) —— 使用指南、`AGENTS.md`、`Documentations/README.md` + +**收尾时必须判断两件事**(判断结果写进决策日志,不允许沉默跳过): + +- **要不要配套专题文章** —— 本提案已定要写使用指南 `Documentations/Internal/TuistDevelopment.md`;实现说明是否另写,收尾时判断。 +- **有没有引入新术语** —— 「Tuist 开发 workspace」「本地依赖模式」「占用记录」是否进 `Documentations/Glossary.md`,收尾时判断。 + +## 决策日志 + +| 日期 | 变更 | 说明 | +|------|------|------| +| 2026-11-20 | Created as Draft | 用户要一个照 RuntimeViewer 做法建的 Tuist 开发 workspace,依赖可在本地检出与远程版本之间切换,本地依赖就是原生 workspace 里放的那几个上游库。按轻量档处理:新增的开发路径,不改原有的构建、发版与 CI。 | +| 2026-11-20 | 定下三个方向 | 用户选定:提供二进制缓存与 `warm`;Tuist workspace 要能跑测试,先实测再定写法;与 RuntimeViewer 的本地依赖模式双向互斥,为此顺带改 RuntimeViewer 的脚本。 | +| 2026-11-20 | 实测定下测试的写法 | 十项实测见「前期调研」:Tuist 的测试映射对路径包一刀切,会拒绝两种形态的测试;用一段只在 Tuist 解析时生效的清单适配块处理,本库加,三个上游库也要加才能在本地模式下带测试;`SwiftSectionCommandTests` 在 `Tuist/CommandLine/Project.swift` 里手写。三个上游库要不要加,留给用户定。 | +| 2026-11-20 | 用户批准,开始实现 | 用户选定给 MachOKitExtensions、MachOObjCSection、swift-demangling 加适配块,本地模式带测试;状态改 Accepted。实现在本库的 `feature/tuist-workspace`,三个上游库与 RuntimeViewer 各用同名分支。 | +| 2026-11-20 | 清单改由脚本自己读 | 本想直接读 Tuist 缓存的清单索引(`swifterpm/package-info/index.json`),实测设了 `SWIFTPM_BUILD_DIR` 时 Tuist 不产出这份索引,靠它不可靠。改回提案原写法:每次 `install` 之后脚本用 `swift package dump-package`(带 `TUIST_MAPS_LOCAL_PACKAGE_TESTS=1`,8 个并行)读一遍所有包的清单存进 `Work//Manifests/`,名单、预检和同名检查都读它(35 个包)。Python 出错时脚本直接失败,而不是带着空名单生成。 | +| 2026-11-20 | 解析依赖的记号带上清单的 hash | `Work//InstalledDependencies` 除了模式,还记 `Tuist/Package.swift`、`Package.swift`、种子锁文件与(本地模式下)上游库清单的 hash:改了 `Package.swift` 或换了根目录的 `Package.resolved`,下一次 `generate` 自己重新解析,不必记得先跑 `install`。 | +| 2026-11-20 | CLI 的部署版本改为 macOS 12.0 | Ultra 首次构建:Tuist 把 swift-argument-parser 编成它声明的 macOS 12,10.15 的 `swift-section` import 不了它(11 处同一错误,其余全部编过)。 | +| 2026-11-20 | 测试 target 抬到 macOS 14.0(原定「按需」,确认需要) | `TypeIndexingTests` 用的 macOS 13 API 在 10.15 下编不过。脚本把所有转换进来的测试 target(含 `IntegrationTests`)传进新变量 `TUIST_TEST_TARGET_NAMES`。 | +| 2026-11-20 | 手写的 target 设 `SWIFT_PACKAGE_NAME = MachOSwiftSection` | `SwiftSectionCommandTests` 调用 SwiftSectionKit 的 `package` 方法;Tuist 转换的 target 都带这个设置,手写的没有。 | +| 2026-11-20 | 导入 Testing 的库 target 加 TestingMacros 插件路径 | `SwiftSectionTestingSupport` 用了 `#require`,Xcode 只给测试 target 带 TestingMacros 插件。脚本扫描路径包里普通 target 的源码找 `import Testing`,传进新变量 `TUIST_TESTING_SUPPORT_TARGET_NAMES`;本地模式下 swift-demangling 的 `DemanglingTestingSupport` 也会被找到。 | +| 2026-11-20 | `build` / `test` 加 `--scheme` | 本地模式下要跑上游库各自的测试 scheme(`<包名> Tests`)。 | +| 2026-11-20 | MachOKitExtensions 的 `next` 已不需要适配块,仍按决定加上 | 探针用的是它的 `main`(有 `CPlusPlusSymbolsFixture`),`next` 上这个测试支撑 target 已经没有了,块目前不起作用。另:本库 `.worktrees/MachOKitExtensions` 链接指向它的主检出(`main`),不是它的 `next` worktree,所以公司那台上的本地模式编的是 `main`,预检会因为那个 target 关掉测试并点名。 | +| 2026-11-20 | Tuist 往 `PrecompiledLibraries/swift-syntax/` 里写 `.build/` | 它是按路径声明的包,Tuist 在那里下载二进制产物;与它生成的工程一起写进 `.gitignore`。 | +| 2026-11-20 | `SwiftSymbolsRegistration` 整个 `-force_load` | Ultra 上第一次跑通测试 scheme:2,935 通过、8 失败,原生 `swift test` 同一台、同一个 Xcode 27.2 全部通过(21 个 bundle、2,905 个测试)。`SwiftSymbolsTests` 里 `registeredLanguages → []`:这个 C target 只有一个 `static` 的加载期 constructor、没有全局符号,SwiftPM 整块链接 target 所以它总会跑,Tuist 的静态 framework 里这个成员没人引用、链接器不拉。脚本找出源码里有 `__attribute__((constructor))` 的 target,沿包内依赖算出会链到它的测试与可执行 target,传进 `TUIST_FORCE_LOADS`。同一机制意味着 RuntimeViewer 的 Tuist workspace(静态 framework,只加了 `-ObjC`)里 Swift 也没注册成符号语言——按链接方式推断,没有实测,不在本提案范围内修。 | +| 2026-11-20 | 测试与 `swift-section` 链接时加 `-ObjC` | 修好注册后还剩 4 条,都在包装读取器(`MachOReaderWrapper`)上:没人点名的 protocol conformance 所在的归档成员没被链进来,`as?` 静默失败。与 RuntimeViewer 的 Tuist workspace 一样加 `-ObjC`;测试 target 的部署版本、`-ObjC` 与 `-force_load` 合进同一份设置,免得两处 `OTHER_LDFLAGS` 互相覆盖。`SwiftSymbolsTests` 与 `SwiftInspectionTests` 重跑 227 个全部通过。 | +| 2026-11-20 | 只给声明低于 macOS 14 的包的测试抬部署版本 | 六个包今天都声明 10.15,但以后有包声明 15 时,统一设 14.0 会把它的测试调低。脚本另传 `TUIST_RAISED_TEST_TARGET_NAMES`;`-ObjC` 与 `-force_load` 照旧给全部测试。 | +| 2026-11-20 | 测试 scheme 关掉 Xcode 的两个运行时检查 | 全量重跑后只剩 `FileModeTests.fileModeMatchesInProcessReferencesOnTheRunningSystemCache` 一条:进程内的调用目标落在 `/usr/lib/libRPAC.dylib`。那是 Thread Performance Checker 插入的库,它改写了已加载镜像里的调用;`swift test` 的进程里没有它。`Workspace.swift` 的测试 scheme 关掉它与 Main Thread Checker;Tuist 4.210 只写后者的属性,脚本生成后给 `* Tests.xcscheme` 的 TestAction 补 `disablePerformanceAntipatternChecker = "YES"`。 | +| 2026-11-20 | 工具 target 写明 `productName` | Tuist 把 target 名里的 `-` 换成 `_`,可执行文件成了 `swift_section`。 | +| 2026-11-20 | 本地模式实测 | Ultra 上用五个上游库的沙盒副本(`TUIST_LOCAL_PACKAGE_CHECKOUTS` 指过去,各在本提案的功能分支上)打开本地模式:解析、读清单、生成都成功,六个包各有一个 `<包名> Tests` scheme,副本的 `git status` 保持干净。`MachOSwiftSection Tests` 全量 2,943 个通过、0 失败、7 个跳过(修完前面几处之后的第一次全量);MachOKitExtensions 171 个、swift-demangling 641 个、swift-semantic-string 464 个全部通过。MachOKit 10 个失败、MachOObjCSection 26 个失败,全是测试自己读写死的路径或系统文件:`AotCachePrintTests` 读不存在的 `aot_shared_cache.0`,`ArchiveFileTests` 读 clang 17 目录(Xcode 27.2 是 21),`MachOObjCSectionTests` 的 `setUp` 读 `/Users/JH/Downloads/iOS18.5-SwiftUI`,两条 `testDylibsPreBuildLoaderSet` 在 macOS 27 的系统 cache 上读不出 loader set 版本。这些按源码判断与 Tuist 无关,没有再用原生 `swift test` 对照。切回远程模式后副本的占用全部释放。 | +| 2026-11-20 | 缓存计时 | Ultra(28 核,Xcode 27.2),清空 DerivedData 后编 `swift-section`(Debug):不走缓存 63 秒,走缓存 46 秒;`warm` 把 70 个第三方 target 编成 xcframework 用了 60 秒,再生成时这 70 个都换成了缓存。测试 scheme 走缓存的全量重跑用户嫌慢叫停了,没有结果;远程模式下修完的那几处都按 bundle 重跑过,本地模式的全量也已通过。写进使用指南。 | +| 2026-11-20 | 实现完成,待用户看过后收尾 | 配套文档:使用指南已写;实现说明不另写,清单里每处特殊写法的原因都在指南「已知的坑」与本决策日志里。术语表(「Tuist 开发 workspace」「本地依赖模式」「占用记录」)留到正式收尾时判断。 | +| 2026-11-20 | Implemented,编号 0099 | 用户看过后收尾。术语表登记「Tuist 开发 workspace」与「占用记录」(后者另注明与 `SharedCacheRegistry` 的 claim 无关);「本地依赖模式」就是本地依赖的字面意思,不登记。落地前用 Xcode 27.2 与 26.6 各解析一遍四个包的清单:都能解析,不带变量时与改动前一致,带变量时补的 product 与拿掉的测试和设计相符(MachOKitExtensions 的 `main` 上补 `CPlusPlusDemangling`、`CPlusPlusSymbolsFixture`)。MachOKitExtensions 的功能分支切自它本地一条没推送过的 `next`(只有一个空合并,比 `main` 落后 10 个提交),落地时把那一个提交接到 `main` 上推送;那条本地 `next` 原样留着。账本第 143 节。 | diff --git a/Documentations/Evolutions/0100-fixture-suite-macro.html b/Documentations/Evolutions/0100-fixture-suite-macro.html new file mode 100644 index 000000000..15a55c81f --- /dev/null +++ b/Documentations/Evolutions/0100-fixture-suite-macro.html @@ -0,0 +1,313 @@ + + + + + + +0100 - @FixtureSuite 宏:夹具测试套件开头的固定写法由宏生成 + + + + +
+
+

MachOSwiftSectionEvolutions0100

+

0100 @FixtureSuite 宏:夹具测试套件开头的固定写法由宏生成

+
+
状态
Implemented
+
最后更新
2026-11-20
+
项目类型
库
+
原文
0100-fixture-suite-macro.md
+
+
+ +
+
+

摘要

+

新增 attached 宏 @FixtureSuite,挂在夹具测试套件类上,生成 static let testedTypeName、static var registeredTestMethodNames,并补上对 FixtureSuite 协议的遵循。被测类型名默认取类名去掉 Tests 后缀,baseline 默认取「类名去掉 Tests 加 Baseline」;少数例外用参数写明。SuiteBehaviorScanner 改为也认宏的写法。MachOSwiftSectionTests 里按固定写法写的 170 个夹具套件改用宏,每处省 3 行(CoroFunctionPointerTests 没有 baseline,保持手写)。宏的实现放在新的宏 target SwiftSectionTestingMacros,声明放在 SwiftSectionTestingSupport,只有测试链接它。

+ +
+ +
+

要你定

+

已实现,与 Swift 6 迁移同批合入 next,没有要定的事。

+
+ +
+

架构图

+
  • 新增
  • 修改
  • 不变
+
+ + + MachOSwiftSection (package) + SwiftSectionMacros (macro)@Layout ... production, unchanged + SwiftSectionTestingMacros (macro)FixtureSuiteMacro: member + extension + SwiftSectionTestingMacrosTestsexpansion tests + SwiftSectionTestingSupport+ macro FixtureSuite(testedTypeName:baseline:) + SwiftSectionFixtureSupport~ SuiteBehaviorScanner reads @FixtureSuite + MachOSwiftSectionTests170 suites: @FixtureSuite + + + + + +
+

新宏 target 只给测试支持依赖;扫描器同时认宏的写法与手写的静态成员。

+ +

展开前后

+
@Suite @FixtureSuite
+final class StructDescriptorTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { ... }
+
+ ↓ member
+    static let testedTypeName: Swift.String = "StructDescriptor"
+    static var registeredTestMethodNames: Swift.Set<Swift.String> { StructDescriptorBaseline.registeredTestMethodNames }
+ ↓ extension
+extension StructDescriptorTests: SwiftSectionFixtureSupport.FixtureSuite {}
+
+
+

改动地图

+
文件 / 类型动作改什么为什么步骤
Package.swift修改新增宏 target SwiftSectionTestingMacros(SwiftSyntax、SwiftSyntaxMacros、SwiftCompilerPlugin、SwiftSyntaxBuilder)与测试 target SwiftSectionTestingMacrosTests(加 SwiftSyntaxMacrosGenericTestSupport);SwiftSectionTestingSupport 依赖新宏 target;Tuist 适配块留在文件末尾宏的实现与测试1
Sources/TestSupport/SwiftSectionTestingMacros/FixtureSuiteMacro.swift、TestingMacroPlugin.swift新增FixtureSuiteMacro(MemberMacro、ExtensionMacro):推出类名词干、读两个字面量参数、生成成员与遵循、诊断与 Fix-It宏实现1
Sources/TestSupport/SwiftSectionTestingSupport/FixtureSuiteMacro.swift新增package macro FixtureSuite(testedTypeName:baseline:) 声明宏声明1
Tests/SwiftSectionTestingMacrosTests/FixtureSuiteMacroTests.swift新增展开测试:默认、只给 testedTypeName、两个都给、类名不以 Tests 结尾、参数不是字面量宏的行为1
Sources/TestSupport/SwiftSectionFixtureSupport/Coverage/SuiteBehaviorScanner.swift修改认 @FixtureSuite:取参数或类名词干扫描器按源码读被测类型名2
Tests/SwiftSectionTestingSupportTests/Coverage/SuiteBehaviorScannerTests.swift、Fixtures/SuiteSampleSource.swift.txt修改加宏写法的样例与测试扫描器的行为2
Tests/MachOSwiftSectionTests/Fixtures/**/*Tests.swift(170 个夹具套件)修改改用 @FixtureSuite去掉样板3
AGENTS.md、Documentations/Internal/FixtureTestingAndContinuousIntegration.md修改添加夹具测试的写法文档同步4
+ +
+ +
+

提议方案

+
  1. 宏声明放在 SwiftSectionTestingSupport(夹具套件都 import 它),package 可见:member 角色生成两个静态成员,extension 角色添加 FixtureSuite。
  2. 宏实现放在新的宏 target SwiftSectionTestingMacros(Sources/TestSupport/SwiftSectionTestingMacros),只给 SwiftSectionTestingSupport 依赖,生产的 SwiftSectionMacros 插件不带测试代码。
  3. 默认值:testedTypeName 取类名去掉 Tests 后缀;baseline 取同一个词干加 Baseline。类名不以 Tests 结尾时报错并给 Fix-It(写明 testedTypeName:)。
  4. 参数:@FixtureSuite(testedTypeName: "EnumTagCounts")、@FixtureSuite(testedTypeName: "OpaqueType", baseline: OpaqueTypeBaseline.self)。两个参数都只收字面量(字符串字面量、类型.self),给变量就报错,不静默退回默认值。
  5. 扫描器:SuiteBehaviorScanner 先看类上有没有 @FixtureSuite:有就取 testedTypeName: 参数的字面量,没有参数就取类名去掉 Tests;没有宏的类照旧读静态成员。
  6. 迁移:按完整写法写的 170 个夹具套件改用宏——类声明里去掉 FixtureSuite 遵循和两个静态成员,挂上 @FixtureSuite;5 个例外带参数。CoroFunctionPointerTests 没有 baseline、注册名单是字面量,保持手写。
  7. 本包 AGENTS.md「添加夹具测试」那几条(:186 一带)改成用宏的写法。
+

非目标

+
  • 给 MachOFileTests 等其他基类的子类(override class var fileName 之类)做宏:属于基类配置,宏省不了几行。
  • 把 acrossAllReaders 做成宏:归 0104-shared-macho-testing-support,用普通函数重载。
  • 自动维护 BaselineGenerator 里手写的套件清单(AllFixtureSuites 的来源)。
  • @Suite 与 ExclusiveImageAccess 等 trait 的组合:已经只有一行。
+ +
+ +
+

详细设计

+
+ 宏声明与展开规则 +
+
// SwiftSectionTestingSupport
+@attached(member, names: named(testedTypeName), named(registeredTestMethodNames))
+@attached(extension, conformances: FixtureSuite)
+package macro FixtureSuite(testedTypeName: String? = nil, baseline: Any.Type? = nil) =
+    #externalMacro(module: "SwiftSectionTestingMacros", type: "FixtureSuiteMacro")
+
  • 词干:类名去掉末尾的 Tests。类名不以 Tests 结尾且没给 testedTypeName: → 诊断「类名不以 Tests 结尾,写明 testedTypeName:」并给 Fix-It。
  • baseline:参数写 X.self 时取 X,否则取「词干 + Baseline」。
  • 只收字面量:testedTypeName: 不是字符串字面量(含插值)、baseline: 不是 类型.self → 诊断落在参数上。
  • 挂错地方:挂在非 class 声明上 → 诊断。
  • 全名:生成代码写 Swift.String、Swift.Set<Swift.String>、SwiftSectionFixtureSupport.FixtureSuite。
  • 隔离:套件类继承 @MainActor 的 MachOSwiftSectionFixtureTests,协议也是 @MainActor,生成成员不另加隔离标注。
  • 扫描器:SuiteBehaviorVisitor.visit(_ node: ClassDeclSyntax) 先查 node.attributes 里名字最后一段是 FixtureSuite 的属性;有 testedTypeName: 字符串字面量就用它,否则用类名词干;没有该属性才走现有的静态成员读取。
+
+
+
+ +
+

动机

+
  • 同样的 5 行写了 170 遍。 MachOSwiftSectionTests 里每个夹具套件的开头都是:
    @Suite
    +final class StructDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable {
    +    static let testedTypeName = "StructDescriptor"
    +    static var registeredTestMethodNames: Set<String> {
    +        StructDescriptorBaseline.registeredTestMethodNames
    +    }
    +

    (Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructDescriptorTests.swift:16-21)171 个夹具套件遵循 FixtureSuite;按完整写法匹配的 170 个里,165 个的被测类型名就是类名去掉 Tests,只有 5 个例外。

  • 手抄容易抄错。 testedTypeName 决定覆盖率不变式按哪个类型检查成员(FixtureSuite.swift 的文档注释),抄错一个字母,这个套件就静默地对不上源码里的类型。
  • 起因:用户问能否给测试加便捷的宏减少样板。调研后,跨读取器写法 acrossAllReaders 不适合做宏(改用普通函数重载,归 0104-shared-macho-testing-support),套件开头这一处适合,另写本提案。
+ +
+ +
+

调研

+
+ 协议、扫描器、例外与现有宏 +
+
  • 协议:package protocol FixtureSuite(Sources/TestSupport/SwiftSectionFixtureSupport/Coverage/FixtureSuite.swift),@MainActor,两个要求:static var testedTypeName: String、static var registeredTestMethodNames: Set<String>。
  • 谁读这两个值:
    • 覆盖率不变式测试 Tests/MachOSwiftSectionTests/Fixtures/MachOSwiftSectionCoverageInvariantTests.swift:53-55 在运行时读 suite.testedTypeName 与 registeredTestMethodNames——宏生成的成员照样读得到。
    • SuiteBehaviorScanner(Coverage/SuiteBehaviorScanner.swift:118-133)按源码语法读 testedTypeName:在类的成员里找 static 且初始值是字符串字面量的 testedTypeName。宏生成的成员不在源码里,所以扫描器要改,认 @FixtureSuite 的参数或类名。它的样例源码在 Tests/SwiftSectionTestingSupportTests/Coverage/Fixtures/SuiteSampleSource.swift.txt。
    • BaselineGenerator.writeAllFixtureSuitesIndex(Baseline/BaselineGenerator.swift:693-710)用手维护的类名清单生成 __Baseline__/AllFixtureSuites.swift,不读 testedTypeName,不受影响。
  • 5 个例外(类名 → testedTypeName、baseline):
    • OpaqueTypeFixtureTests → "OpaqueType"、OpaqueTypeBaseline(类名加了 Fixture 避开同 target 里的快照套件 OpaqueTypeTests,见 BaselineGenerator.swift:701-704)
    • EnumFunctionsTests → "EnumTagCounts"、EnumFunctionsBaseline
    • TupleTypeMetadataElementTests → "Element"、TupleTypeMetadataElementBaseline
    • GenericContextTests → "TargetGenericContext"、GenericContextBaseline
    • GenericRequirementContentTests → "InvertedProtocols"、GenericRequirementContentBaseline
    +

    baseline 名除 OpaqueTypeFixtureTests 外都是「类名去掉 Tests 加 Baseline」。

  • 现有的宏:宏 target SwiftSectionMacros(Package.swift:1007-1016,Sources/Support/SwiftSectionMacros,@Layout 等),供 Utilities、MachOSwiftSection 两个生产 target 用;本包没有宏的展开测试。swift-syntax 依赖是 602.0.0..<605.0.0(Package.swift:93)。
  • 同名先例:Observation 里协议 Observable 与宏 @Observable 同名,@Observable 解析到宏;本提案的宏与协议同名同理。
  • 宏的硬规则(swift-macro-patterns skill):conformances: 只列一定会添加的协议——本宏总是添加 FixtureSuite,满足;生成代码里的类型写全名(Swift.Set<Swift.String>)。
+
+
+
+ +
+

替代方案

+
+ 3 条被否的路 +
+
  • 把宏实现放进现有的 SwiftSectionMacros:少一个 target,但生产代码链接的插件会带上测试用的宏。否决。
  • 只用基类或协议扩展给默认值:协议扩展能给 testedTypeName 一个按类型名推的默认实现(运行时 String(describing: Self.self) 去掉 Tests),但 registeredTestMethodNames 要引用 baseline 类型,运行时拿不到,且扫描器按源码读不到运行时默认值。否决。
  • 做成宏后不改扫描器、保留手写的 testedTypeName:省一行都不到。否决。
+
+
+
+ +
+

影响

+

源码兼容性(source compatibility)

+

只改测试支持与测试,对外 product 不变。

+

ABI 兼容性(条件项)

+

不适用 —— 本库以 SPM 源码分发,使用方每次重新编译。

+

下游影响

+

无:新宏 target 与测试支持都不是 product。0104-shared-macho-testing-support 落地时,MachOSwiftSectionFixtureTests 变成共享基类的子类,@FixtureSuite 不受影响;两份提案改到同一批测试文件(这份改类声明,那份改 acrossAllReaders 调用),先落地的一份之后,另一份在合并时解冲突。

+

文档与示例

+

AGENTS.md 的「添加夹具测试」步骤与 FixtureTestingAndContinuousIntegration.md。

+

API 演进与废弃策略

+
  • package 级别的宏,只给本包测试用,没有对外承诺。
  • 不保留旧写法的兼容:迁移在同一批完成,扫描器两种写法都认,所以中途也不会坏。
+
+ +
+

落地步骤

+
  1. 宏与展开测试(完成)—— Package.swift、SwiftSectionTestingMacros、宏声明、FixtureSuiteMacroTests
    • 行为:defaultsTakeTheTestedTypeAndBaselineFromTheClassName
    • 行为:anExplicitTestedTypeNameKeepsTheBaselineFromTheClassName
    • 行为:anExplicitBaselineIsUsedAsWritten
    • 行为:aClassNameWithoutTestsAsksForTheTestedTypeName(诊断加 Fix-It)
    • 行为:aNonLiteralArgumentIsRejected
    • 行为:theMacroAddsTheFixtureSuiteConformance
  2. 扫描器认宏(完成)—— SuiteBehaviorScanner、样例源码与测试
    • 行为:scannerReadsTheTestedTypeNameFromTheMacroArgument
    • 行为:scannerTakesTheClassNameStemWhenTheMacroHasNoArgument
    • 行为:scannerStillReadsAStaticTestedTypeName
  3. 迁移 170 个套件(完成)—— Tests/MachOSwiftSectionTests/Fixtures/**
    • 行为:覆盖率不变式测试照常通过,迁移前后 allFixtureSuites 各套件的 testedTypeName 与 registeredTestMethodNames 逐个相等
    • 行为:SuiteBehaviorScanner 认出的「被测类型 → 测试方法 → 行为」与迁移前逐条相同
  4. 文档(完成)—— AGENTS.md、FixtureTestingAndContinuousIntegration.md
    • 收尾判断:实现说明不必单写,AGENTS.md 的步骤与宏的文档注释够用;没有新术语。
+ +
+ +
+

决策日志

+
+ 9 条,最近一条:状态 → Implemented,编号 0100 +
+
日期变更说明
2026-11-20Created as Draft用户问能否给测试代码加便捷的宏减少样板。只读调研统计了两个包测试里的重复写法:值得做成宏的是 176 个夹具套件开头的固定 5 行;acrossAllReaders 改用普通函数重载(归 0104-shared-macho-testing-support)。用户选择把这个宏另写一份本包提案。
2026-11-20宏实现放新 target SwiftSectionTestingMacros生产代码链接的 SwiftSectionMacros 插件不带测试用的宏。
2026-11-20宏与协议同名 FixtureSuite照 Observation 的 Observable 先例,@FixtureSuite 读起来就是「这是一个夹具套件」。
2026-11-20状态 → Accepted用户批准,开始实现。
2026-11-20第 1、2 步完成宏的 6 个展开测试与扫描器的 9 个测试在 MacBook 上通过(Ultra 负载过高,按规则分流)。
2026-11-20套件数更正:171 个,迁 170 个提案里的 176 是 grep 把扫描器样例文本里的几个类也数进去了。CoroFunctionPointerTests 自己编夹具、没有 baseline,注册名单是字面量,套不上宏,保持手写。
2026-11-20实现完成,待用户看过后收尾在 MacBook 上按 CI 的 ad-hoc 签名编出 SymbolTestsCore,跑 swift test --skip IntegrationTests:MachOSwiftSectionCoverageInvariantTests、宏与扫描器的测试全部通过。另有 150 组失败——夹具套件的 offset()、layout() 等与 baseline 写死的偏移不符,以及 SymbolicDemanglerTests 找不到 iOS 26.5 模拟器运行时——在同一台机器、同一份夹具上切到 next 跑同一批,失败逐条相同,是 MacBook 的环境(夹具与 baseline 的产物不一致、没装该运行时),不是本次引入的。Ultra 负载过高(1 分钟负载约 90–107),没在 Ultra 上跑。文档:AGENTS.md 与 FixtureTestingAndContinuousIntegration.md 已写明用法;不另写实现说明;没有新术语。
2026-11-20与 Swift 6 迁移一起落地用户看过分支后决定与 0101-swift6-mode-and-upcoming-features 同批落地:本分支先快进合入 next,Swift 6 那一支合在它之上;合并后的构建与全量测试在两者合并的结果上统一跑,过了再一起推送。
2026-11-20状态 → Implemented,编号 0100落地时取号:远端共享分支上最大编号是 0099。收尾判断:不另写实现说明或使用指南,AGENTS.md 的步骤、FixtureTestingAndContinuousIntegration.md 的一节与宏的文档注释已经够用;没有新术语,术语表不动。演进账本记第 145 节。没有后续项。
+
+
+ +
+ +
+
+ + diff --git a/Documentations/Evolutions/0100-fixture-suite-macro.md b/Documentations/Evolutions/0100-fixture-suite-macro.md new file mode 100644 index 000000000..76f36f163 --- /dev/null +++ b/Documentations/Evolutions/0100-fixture-suite-macro.md @@ -0,0 +1,189 @@ +# 0100 - `@FixtureSuite` 宏:夹具测试套件开头的固定写法由宏生成 + +- **状态**: Implemented +- **作者**: JH +- **创建日期**: 2026-11-20 +- **最后更新**: 2026-11-20 +- **所属愿景**: 无 +- **关联提案**: [0104-shared-macho-testing-support](0104-shared-macho-testing-support.md)(同一次「减少测试样板」的讨论里拆出来;那份统一跨包的测试支持,这份只管本包的 Swift 夹具覆盖率体系,两份互不依赖) +- **实现分支 / PR**: `feature/fixture-suite-macro`,从 `next` 切出,快进合入 `next` +- **配套文档**: 无单独文档;用法写在 `AGENTS.md`「添加夹具测试」与 [FixtureTestingAndContinuousIntegration.md](../Internal/FixtureTestingAndContinuousIntegration.md)「套件头由 `@FixtureSuite` 生成」一节;演进账本第 145 节 +- **网页版**: 同目录同名的 `.html` + +## 摘要 + +新增 attached 宏 `@FixtureSuite`,挂在夹具测试套件类上,生成 `static let testedTypeName`、`static var registeredTestMethodNames`,并补上对 `FixtureSuite` 协议的遵循。被测类型名默认取类名去掉 `Tests` 后缀,baseline 默认取「类名去掉 `Tests` 加 `Baseline`」;少数例外用参数写明。`SuiteBehaviorScanner` 改为也认宏的写法。`MachOSwiftSectionTests` 里按固定写法写的 170 个夹具套件改用宏,每处省 3 行(`CoroFunctionPointerTests` 没有 baseline,保持手写)。宏的实现放在新的宏 target `SwiftSectionTestingMacros`,声明放在 `SwiftSectionTestingSupport`,只有测试链接它。 + +## 动机 + +- **同样的 5 行写了 170 遍。** `MachOSwiftSectionTests` 里每个夹具套件的开头都是: + + ```swift + @Suite + final class StructDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { + static let testedTypeName = "StructDescriptor" + static var registeredTestMethodNames: Set { + StructDescriptorBaseline.registeredTestMethodNames + } + ``` + + (`Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructDescriptorTests.swift:16-21`)171 个夹具套件遵循 `FixtureSuite`;按完整写法匹配的 170 个里,165 个的被测类型名就是类名去掉 `Tests`,只有 5 个例外。 +- **手抄容易抄错。** `testedTypeName` 决定覆盖率不变式按哪个类型检查成员(`FixtureSuite.swift` 的文档注释),抄错一个字母,这个套件就静默地对不上源码里的类型。 +- **起因**:用户问能否给测试加便捷的宏减少样板。调研后,跨读取器写法 `acrossAllReaders` 不适合做宏(改用普通函数重载,归 `0104-shared-macho-testing-support`),套件开头这一处适合,另写本提案。 + +## 前期调研 + +- **协议**:`package protocol FixtureSuite`(`Sources/TestSupport/SwiftSectionFixtureSupport/Coverage/FixtureSuite.swift`),`@MainActor`,两个要求:`static var testedTypeName: String`、`static var registeredTestMethodNames: Set`。 +- **谁读这两个值**: + - 覆盖率不变式测试 `Tests/MachOSwiftSectionTests/Fixtures/MachOSwiftSectionCoverageInvariantTests.swift:53-55` 在运行时读 `suite.testedTypeName` 与 `registeredTestMethodNames`——宏生成的成员照样读得到。 + - `SuiteBehaviorScanner`(`Coverage/SuiteBehaviorScanner.swift:118-133`)**按源码语法**读 `testedTypeName`:在类的成员里找 `static` 且初始值是字符串字面量的 `testedTypeName`。宏生成的成员不在源码里,所以扫描器要改,认 `@FixtureSuite` 的参数或类名。它的样例源码在 `Tests/SwiftSectionTestingSupportTests/Coverage/Fixtures/SuiteSampleSource.swift.txt`。 + - `BaselineGenerator.writeAllFixtureSuitesIndex`(`Baseline/BaselineGenerator.swift:693-710`)用手维护的类名清单生成 `__Baseline__/AllFixtureSuites.swift`,不读 `testedTypeName`,不受影响。 +- **5 个例外**(类名 → `testedTypeName`、baseline): + - `OpaqueTypeFixtureTests` → `"OpaqueType"`、`OpaqueTypeBaseline`(类名加了 `Fixture` 避开同 target 里的快照套件 `OpaqueTypeTests`,见 `BaselineGenerator.swift:701-704`) + - `EnumFunctionsTests` → `"EnumTagCounts"`、`EnumFunctionsBaseline` + - `TupleTypeMetadataElementTests` → `"Element"`、`TupleTypeMetadataElementBaseline` + - `GenericContextTests` → `"TargetGenericContext"`、`GenericContextBaseline` + - `GenericRequirementContentTests` → `"InvertedProtocols"`、`GenericRequirementContentBaseline` + + baseline 名除 `OpaqueTypeFixtureTests` 外都是「类名去掉 `Tests` 加 `Baseline`」。 +- **现有的宏**:宏 target `SwiftSectionMacros`(`Package.swift:1007-1016`,`Sources/Support/SwiftSectionMacros`,`@Layout` 等),供 `Utilities`、`MachOSwiftSection` 两个生产 target 用;本包没有宏的展开测试。swift-syntax 依赖是 `602.0.0..<605.0.0`(`Package.swift:93`)。 +- **同名先例**:Observation 里协议 `Observable` 与宏 `@Observable` 同名,`@Observable` 解析到宏;本提案的宏与协议同名同理。 +- **宏的硬规则**(`swift-macro-patterns` skill):`conformances:` 只列一定会添加的协议——本宏总是添加 `FixtureSuite`,满足;生成代码里的类型写全名(`Swift.Set`)。 + +## 提议方案 + +1. **宏声明**放在 `SwiftSectionTestingSupport`(夹具套件都 import 它),`package` 可见:member 角色生成两个静态成员,extension 角色添加 `FixtureSuite`。 +2. **宏实现**放在新的宏 target `SwiftSectionTestingMacros`(`Sources/TestSupport/SwiftSectionTestingMacros`),只给 `SwiftSectionTestingSupport` 依赖,生产的 `SwiftSectionMacros` 插件不带测试代码。 +3. **默认值**:`testedTypeName` 取类名去掉 `Tests` 后缀;baseline 取同一个词干加 `Baseline`。类名不以 `Tests` 结尾时报错并给 Fix-It(写明 `testedTypeName:`)。 +4. **参数**:`@FixtureSuite(testedTypeName: "EnumTagCounts")`、`@FixtureSuite(testedTypeName: "OpaqueType", baseline: OpaqueTypeBaseline.self)`。两个参数都只收字面量(字符串字面量、`类型.self`),给变量就报错,不静默退回默认值。 +5. **扫描器**:`SuiteBehaviorScanner` 先看类上有没有 `@FixtureSuite`:有就取 `testedTypeName:` 参数的字面量,没有参数就取类名去掉 `Tests`;没有宏的类照旧读静态成员。 +6. **迁移**:按完整写法写的 170 个夹具套件改用宏——类声明里去掉 `FixtureSuite` 遵循和两个静态成员,挂上 `@FixtureSuite`;5 个例外带参数。`CoroFunctionPointerTests` 没有 baseline、注册名单是字面量,保持手写。 +7. 本包 `AGENTS.md`「添加夹具测试」那几条(`:186` 一带)改成用宏的写法。 + +### 非目标 + +- 给 `MachOFileTests` 等其他基类的子类(`override class var fileName` 之类)做宏:属于基类配置,宏省不了几行。 +- 把 `acrossAllReaders` 做成宏:归 `0104-shared-macho-testing-support`,用普通函数重载。 +- 自动维护 `BaselineGenerator` 里手写的套件清单(`AllFixtureSuites` 的来源)。 +- `@Suite` 与 `ExclusiveImageAccess` 等 trait 的组合:已经只有一行。 + +## 改动地图 + +| 文件 / 类型 | 动作 | 改什么 | 为什么 | 步骤 | +|---|---|---|---|---| +| `Package.swift` | 修改 | 新增宏 target `SwiftSectionTestingMacros`(SwiftSyntax、SwiftSyntaxMacros、SwiftCompilerPlugin、SwiftSyntaxBuilder)与测试 target `SwiftSectionTestingMacrosTests`(加 `SwiftSyntaxMacrosGenericTestSupport`);`SwiftSectionTestingSupport` 依赖新宏 target;Tuist 适配块留在文件末尾 | 宏的实现与测试 | 1 | +| `Sources/TestSupport/SwiftSectionTestingMacros/FixtureSuiteMacro.swift`、`TestingMacroPlugin.swift` | 新增 | `FixtureSuiteMacro`(`MemberMacro`、`ExtensionMacro`):推出类名词干、读两个字面量参数、生成成员与遵循、诊断与 Fix-It | 宏实现 | 1 | +| `Sources/TestSupport/SwiftSectionTestingSupport/FixtureSuiteMacro.swift` | 新增 | `package macro FixtureSuite(testedTypeName:baseline:)` 声明 | 宏声明 | 1 | +| `Tests/SwiftSectionTestingMacrosTests/FixtureSuiteMacroTests.swift` | 新增 | 展开测试:默认、只给 `testedTypeName`、两个都给、类名不以 `Tests` 结尾、参数不是字面量 | 宏的行为 | 1 | +| `Sources/TestSupport/SwiftSectionFixtureSupport/Coverage/SuiteBehaviorScanner.swift` | 修改 | 认 `@FixtureSuite`:取参数或类名词干 | 扫描器按源码读被测类型名 | 2 | +| `Tests/SwiftSectionTestingSupportTests/Coverage/SuiteBehaviorScannerTests.swift`、`Fixtures/SuiteSampleSource.swift.txt` | 修改 | 加宏写法的样例与测试 | 扫描器的行为 | 2 | +| `Tests/MachOSwiftSectionTests/Fixtures/**/*Tests.swift`(170 个夹具套件) | 修改 | 改用 `@FixtureSuite` | 去掉样板 | 3 | +| `AGENTS.md`、`Documentations/Internal/FixtureTestingAndContinuousIntegration.md` | 修改 | 添加夹具测试的写法 | 文档同步 | 4 | + +## 架构图 + +```text +Package (MachOSwiftSection) + SwiftSectionMacros (macro) @Layout, ... (unchanged, production) ++ SwiftSectionTestingMacros (macro) FixtureSuiteMacro: member + extension + SwiftSectionFixtureSupport + Coverage/FixtureSuite (protocol) (unchanged) +~ Coverage/SuiteBehaviorScanner reads @FixtureSuite too +~ SwiftSectionTestingSupport -> + SwiftSectionTestingMacros ++ macro FixtureSuite(testedTypeName:baseline:) +~ MachOSwiftSectionTests 170 suites: @FixtureSuite ++ SwiftSectionTestingMacrosTests expansion tests +``` + +展开前后: + +```text +@Suite @FixtureSuite +final class StructDescriptorTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { ... } + + ↓ member + static let testedTypeName: Swift.String = "StructDescriptor" + static var registeredTestMethodNames: Swift.Set { StructDescriptorBaseline.registeredTestMethodNames } + ↓ extension +extension StructDescriptorTests: SwiftSectionFixtureSupport.FixtureSuite {} +``` + +## 详细设计 + +```swift +// SwiftSectionTestingSupport +@attached(member, names: named(testedTypeName), named(registeredTestMethodNames)) +@attached(extension, conformances: FixtureSuite) +package macro FixtureSuite(testedTypeName: String? = nil, baseline: Any.Type? = nil) = + #externalMacro(module: "SwiftSectionTestingMacros", type: "FixtureSuiteMacro") +``` + +- **词干**:类名去掉末尾的 `Tests`。类名不以 `Tests` 结尾且没给 `testedTypeName:` → 诊断「类名不以 Tests 结尾,写明 testedTypeName:」并给 Fix-It。 +- **baseline**:参数写 `X.self` 时取 `X`,否则取「词干 + `Baseline`」。 +- **只收字面量**:`testedTypeName:` 不是字符串字面量(含插值)、`baseline:` 不是 `类型.self` → 诊断落在参数上。 +- **挂错地方**:挂在非 class 声明上 → 诊断。 +- **全名**:生成代码写 `Swift.String`、`Swift.Set`、`SwiftSectionFixtureSupport.FixtureSuite`。 +- **隔离**:套件类继承 `@MainActor` 的 `MachOSwiftSectionFixtureTests`,协议也是 `@MainActor`,生成成员不另加隔离标注。 +- **扫描器**:`SuiteBehaviorVisitor.visit(_ node: ClassDeclSyntax)` 先查 `node.attributes` 里名字最后一段是 `FixtureSuite` 的属性;有 `testedTypeName:` 字符串字面量就用它,否则用类名词干;没有该属性才走现有的静态成员读取。 + +## 替代方案考量 + +- **把宏实现放进现有的 `SwiftSectionMacros`**:少一个 target,但生产代码链接的插件会带上测试用的宏。否决。 +- **只用基类或协议扩展给默认值**:协议扩展能给 `testedTypeName` 一个按类型名推的默认实现(运行时 `String(describing: Self.self)` 去掉 `Tests`),但 `registeredTestMethodNames` 要引用 baseline 类型,运行时拿不到,且扫描器按源码读不到运行时默认值。否决。 +- **做成宏后不改扫描器、保留手写的 `testedTypeName`**:省一行都不到。否决。 + +## 影响 + +### 源码兼容性(source compatibility) + +只改测试支持与测试,对外 product 不变。 + +### ABI 兼容性(条件项) + +不适用 —— 本库以 SPM 源码分发,使用方每次重新编译。 + +### 下游影响 + +无:新宏 target 与测试支持都不是 product。`0104-shared-macho-testing-support` 落地时,`MachOSwiftSectionFixtureTests` 变成共享基类的子类,`@FixtureSuite` 不受影响;两份提案改到同一批测试文件(这份改类声明,那份改 `acrossAllReaders` 调用),先落地的一份之后,另一份在合并时解冲突。 + +### 文档与示例 + +`AGENTS.md` 的「添加夹具测试」步骤与 `FixtureTestingAndContinuousIntegration.md`。 + +## API 演进与废弃策略 + +- `package` 级别的宏,只给本包测试用,没有对外承诺。 +- 不保留旧写法的兼容:迁移在同一批完成,扫描器两种写法都认,所以中途也不会坏。 + +## 落地步骤 + +1. **宏与展开测试**(完成)—— `Package.swift`、`SwiftSectionTestingMacros`、宏声明、`FixtureSuiteMacroTests` + - 行为:`defaultsTakeTheTestedTypeAndBaselineFromTheClassName` + - 行为:`anExplicitTestedTypeNameKeepsTheBaselineFromTheClassName` + - 行为:`anExplicitBaselineIsUsedAsWritten` + - 行为:`aClassNameWithoutTestsAsksForTheTestedTypeName`(诊断加 Fix-It) + - 行为:`aNonLiteralArgumentIsRejected` + - 行为:`theMacroAddsTheFixtureSuiteConformance` +2. **扫描器认宏**(完成)—— `SuiteBehaviorScanner`、样例源码与测试 + - 行为:`scannerReadsTheTestedTypeNameFromTheMacroArgument` + - 行为:`scannerTakesTheClassNameStemWhenTheMacroHasNoArgument` + - 行为:`scannerStillReadsAStaticTestedTypeName` +3. **迁移 170 个套件**(完成)—— `Tests/MachOSwiftSectionTests/Fixtures/**` + - 行为:覆盖率不变式测试照常通过,迁移前后 `allFixtureSuites` 各套件的 `testedTypeName` 与 `registeredTestMethodNames` 逐个相等 + - 行为:`SuiteBehaviorScanner` 认出的「被测类型 → 测试方法 → 行为」与迁移前逐条相同 +4. **文档**(完成)—— `AGENTS.md`、`FixtureTestingAndContinuousIntegration.md` + - 收尾判断:实现说明不必单写,`AGENTS.md` 的步骤与宏的文档注释够用;没有新术语。 + +## 决策日志 + +| 日期 | 变更 | 说明 | +|------|------|------| +| 2026-11-20 | Created as Draft | 用户问能否给测试代码加便捷的宏减少样板。只读调研统计了两个包测试里的重复写法:值得做成宏的是 176 个夹具套件开头的固定 5 行;`acrossAllReaders` 改用普通函数重载(归 `0104-shared-macho-testing-support`)。用户选择把这个宏另写一份本包提案。 | +| 2026-11-20 | 宏实现放新 target `SwiftSectionTestingMacros` | 生产代码链接的 `SwiftSectionMacros` 插件不带测试用的宏。 | +| 2026-11-20 | 宏与协议同名 `FixtureSuite` | 照 Observation 的 `Observable` 先例,`@FixtureSuite` 读起来就是「这是一个夹具套件」。 | +| 2026-11-20 | 状态 → Accepted | 用户批准,开始实现。 | +| 2026-11-20 | 第 1、2 步完成 | 宏的 6 个展开测试与扫描器的 9 个测试在 MacBook 上通过(Ultra 负载过高,按规则分流)。 | +| 2026-11-20 | 套件数更正:171 个,迁 170 个 | 提案里的 176 是 grep 把扫描器样例文本里的几个类也数进去了。`CoroFunctionPointerTests` 自己编夹具、没有 baseline,注册名单是字面量,套不上宏,保持手写。 | +| 2026-11-20 | 实现完成,待用户看过后收尾 | 在 MacBook 上按 CI 的 ad-hoc 签名编出 `SymbolTestsCore`,跑 `swift test --skip IntegrationTests`:`MachOSwiftSectionCoverageInvariantTests`、宏与扫描器的测试全部通过。另有 150 组失败——夹具套件的 `offset()`、`layout()` 等与 baseline 写死的偏移不符,以及 `SymbolicDemanglerTests` 找不到 iOS 26.5 模拟器运行时——在同一台机器、同一份夹具上切到 `next` 跑同一批,失败逐条相同,是 MacBook 的环境(夹具与 baseline 的产物不一致、没装该运行时),不是本次引入的。Ultra 负载过高(1 分钟负载约 90–107),没在 Ultra 上跑。文档:`AGENTS.md` 与 `FixtureTestingAndContinuousIntegration.md` 已写明用法;不另写实现说明;没有新术语。 | +| 2026-11-20 | 与 Swift 6 迁移一起落地 | 用户看过分支后决定与 [0101-swift6-mode-and-upcoming-features](0101-swift6-mode-and-upcoming-features.md) 同批落地:本分支先快进合入 `next`,Swift 6 那一支合在它之上;合并后的构建与全量测试在两者合并的结果上统一跑,过了再一起推送。 | +| 2026-11-20 | 状态 → Implemented,编号 0100 | 落地时取号:远端共享分支上最大编号是 0099。收尾判断:不另写实现说明或使用指南,`AGENTS.md` 的步骤、`FixtureTestingAndContinuousIntegration.md` 的一节与宏的文档注释已经够用;没有新术语,术语表不动。演进账本记第 145 节。没有后续项。 | diff --git a/Documentations/Evolutions/0101-swift6-mode-and-upcoming-features.html b/Documentations/Evolutions/0101-swift6-mode-and-upcoming-features.html new file mode 100644 index 000000000..e6fa9871d --- /dev/null +++ b/Documentations/Evolutions/0101-swift6-mode-and-upcoming-features.html @@ -0,0 +1,500 @@ + + + + + + +0101 - MachO 系列库统一 Swift 6 语言模式并开启三项 upcoming feature + + + + +
+ +
+

MachOSwiftSectionEvolutions0101

+

0101 MachO 系列库统一 Swift 6 语言模式并开启三项 upcoming feature

+
+
状态
Implemented
+
最后更新
2026-11-20
+
项目类型
库(源码分发)
+
原文
0101-swift6-mode-and-upcoming-features.md
+
+
+ + + +
+ +
+

摘要

+

六个 MachO 系列包里有五个已经在 Swift 6 语言模式下编译,complete strict concurrency checking 早已按错误执行;唯一的例外是 MachOKit(fork),它的清单还是 swift-tools-version: 5.10。本提案做两件事:把 MachOKit 升到 tools 6.0,让它也进入 Swift 6 语言模式(实测零错误,Sources 里零并发诊断;停在 6.0 而不是 6.2,是为了 fork 的 CI 所用的 Swift 6.0 工具链还读得了清单);然后在六个包的每个 Swift target 上开启 ExistentialAny、MemberImportVisibility、InferIsolatedConformances 三项 upcoming feature(编译器把它们标为 Swift 7 默认开启),开关在每份清单末尾用一个循环统一加,不逐个 target 写。

+

源码改动 723 处(717 个 fix-it 加 6 处预修),绝大部分是补 import 与补 any,源码与测试都由 swift package --build-system native migrate 自动改出;另有 6 处工具处理不了、要先手工改好,它写成 internal import 的补丁按各仓库的惯例改回普通 import。同为 Swift 7 默认的 NonisolatedNonsendingByDefault、InternalImportsByDefault、ImmutableWeakCaptures,以及独立的 StrictMemorySafety,量过之后明确不做。

+
+ +
+

要你定

+
+

已落地,没有要定的事

+
    +
  1. 六个仓库都已合进各自的集成分支(MachOKitExtensions 推 main),本提案取号 0101、状态 Implemented,账本第 146 节。与 @FixtureSuite 宏(0100)同批落地。
  2. +
+
+
+

没问用户就采用的假设

+
    +
  • 三项特性也开在 MachOKit fork 上(49 个文件补 import),不提给上游。
  • +
  • MachOKit 用 tools 6.0(fork 的 CI 要 Swift 6.0 读得了清单)。
  • +
  • 测试 target 与 IntegrationTests 一起开。
  • +
  • 各仓库不为此单独发版,随下一次正常发版带出。
  • +
  • 本库最后跑一遍渲染 A/B,用来兜住名字遮蔽一类不报错的变化。
  • +
+
+
+ +
+

架构图

+
    +
  • 新增
  • +
  • 修改
  • +
  • 删除
  • +
  • 不变
  • +
+
+ + + Package.swift settings, per package + packagelanguage modeupcoming features (every Swift target) + + MachOKit (fork) + Swift 5 → 6 (tools 6.0) + + ExistentialAny · MemberImportVisibility · InferIsolatedConformances + 9 Swift-6-era settings + ExistentialAny (MachOKit target only) + + swift-semantic-string + Swift 6 (tools 6.2) + + ExistentialAny · MemberImportVisibility · InferIsolatedConformances + + swift-demangling + Swift 6 (tools 6.2) + + the same three (Lifetimes experimental kept) + + MachOKitExtensions + Swift 6 (tools 6.2) + + the same three + + MachOObjCSection + Swift 6 (tools 6.2) + + the same three + + MachOSwiftSection + Swift 6 (tools 6.3) + + the same three (statics at Package.swift:1541, now used) + +
+

改了什么:每个包的编译设置。开关在每份清单末尾用同一个循环追加;swift-demangling、MachOKitExtensions、MachOObjCSection 与本库放在末尾的 Tuist 块之前。

+ +
+ + Pre-fix what migrate mode cannot expressMachOSwiftSection: 4 imports + 2 Swift.Error + swift package --build-system native migrate …sources and tests together; MachOSwiftSection fails at the manifest step by design + git checkout Package.swift; internal import X → import Xunless the package already imports X internally + Commit the fix-its; add the loop to Package.swiftfeatures on for every Swift target + Fix what the builds report(any P)? for Swift 6.3; Swift.Error where Semantic is imported + swift build --build-tests → swift testzero errors (Xcode 27.2 and 26.6) + MachOKit: CI on Xcode 16.2 and Linux Swift 6.0.3workflow_dispatch on the feature branch + MachOSwiftSection: rendering A/B, Tuist workspacebyte-identical dump and interface against next + + + + + + + + +
+

迁移流程:每个包相同,本库多一步预修。

+
+ +
+

改动地图

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
文件 / 类型动作改什么为什么步骤
MachOSwiftSection Documentations/Evolutions/0101-swift6-mode-and-upcoming-features.md、同名 .html新增本提案与网页版唯一提案1
MachOSwiftSection Documentations/Evolutions/README.md、Documentations/README.md修改登记本提案索引1
MachOKitExtensions、MachOObjCSection Documentations/Evolutions/README.md修改各加一行 cross-repository 指向本提案跨仓库提案的约定1
MachOKit Package.swift:1修改swift-tools-version 5.10 → 6.0进入 Swift 6 语言模式;6.0 而不是 6.2,CI 的 Swift 6.0 工具链才读得了2
MachOKit Package.swift:76、:145–171 · extension SwiftSetting修改 删除MachOKit target 不再拼 SwiftSetting.allCases;删掉九项 Swift 6 默认特性与 CaseIterable 扩展;末尾加统一开关循环Swift 6 模式下那九项是空操作;与另外五个包同一写法2
MachOKit Sources/MachOKit/**(49 个文件)修改补 56 处 import:55 处 internal import FileIO / FileIOBinary,1 处普通 importMemberImportVisibility2
MachOKit Tests/MachOKitTests/MachOPrintTests.swift · testFindSymbolByName修改期望的 thunk 名字换成带 Yb 的 Swift 6 manglingSwift 6 模式下未调用的枚举 case 引用推断为 @Sendable(SE-0418)2
swift-semantic-string Package.swift(末尾)修改加统一开关循环开启三项特性3
swift-semantic-string AnyComponent.swift、FrozenSemanticString+Codable.swift、SemanticString+Conformances.swift修改补 6 处 anyExistentialAny3
swift-demangling Package.swift(Tuist 块之前)修改加统一开关循环开启三项特性3
swift-demangling Sources/DemanglingTestingSupport/Required.swift:8修改error: Error? → error: (any Error)?ExistentialAny;括号是 Swift 6.3 要求的3
swift-demangling DefectRegressionTests.swift、NodeTests.swift、TransientRemangleParityTests.swift修改补 3 处 import SwiftStdlibToolboxMemberImportVisibility3
MachOKitExtensions Package.swift(Tuist 块之前)修改加统一开关循环开启三项特性4
MachOKitExtensions RequiredNonOptional.swift:8、String+.swift、DependencyLoadName.swift修改(any Error)?、2 处 import两项特性4
MachOKitExtensions Tests/(5 个文件)修改2 处 any、3 处 import两项特性4
MachOObjCSection Package.swift(Tuist 块之前)修改加统一开关循环开启三项特性5
MachOObjCSection Sources/、Tests/(33 个文件)修改38 个 fix-it:36 处 import(FileIO、MachOKitExtensions 沿用已有的 internal import),2 处 any两项特性5
MachOSwiftSection TypeAttributeInferrer.swift、ABIDiffer.swift修改加 import SwiftObjCInterop、import MachOSwiftSection迁移模式下 switch 报不完备、.enum 解析错6
MachOSwiftSection ObjCAPIRequests.swift:293、ABIEvolutionRequest.swift:179修改: Error → : Swift.Errorimport Semantic 让 Error 解析成 Semantic.Error6
MachOSwiftSection Sources/**、Tests/**(420 个文件)修改migrate 的 605 个 fix-it:import、any、33 处 nonisolated conformance;266 处 internal import 改回普通 import三项特性6
MachOSwiftSection Package.swift:1541–1548 之后、Tuist 块之前修改加统一开关循环,用已有常量开启三项特性6
MachOSwiftSection 两个测试文件修改加 import OrderedCollections迁移模式下 .values 解析错6
MachOSwiftSection NodePrintable.swift:68修改(any NodePrintableDelegate)?Swift 6.4 的 fix-it 写法 Swift 6.3 不接受6
MachOSwiftSection Tests/(14 个文件)修改28 处类型位置的 Error → Swift.Errorimport Semantic 让裸 Error 解析成 Semantic.Error6
MachOSwiftSection Documentations/Internal/ProjectEvolutionLog.md修改加一节账本9
+
+
+ +
+

提议方案与非目标

+
    +
  1. MachOKit 进 Swift 6 语言模式。第 1 行改成 // swift-tools-version: 6.0,tools 6.x 不声明 swiftLanguageModes 时默认 Swift 6。不用 6.2:fork 的 CI 在 Xcode 16.2 与 Linux Swift 6.0.3 上编,6.2 的清单它们读不了;编译器不认识的特性名会被忽略,6.0 照样能编。删掉九项 Swift 6 已默认开启的 upcoming setting 与 CaseIterable 扩展;AccessLevelOnImport 保留。
  2. +
  3. 六个包的每个 Swift target 统一开启三项特性。每份清单在 let package = Package(...) 之后加一个循环,给除 system、binary、plugin 以外的所有 target 追加同一组设置;本库沿用 Package.swift:1541 已有的常量。
  4. +
  5. 源码由 migrate 改,前后各补一手。先改好 6 处预修;在清单还没开特性时跑 swift package --build-system native migrate,源码与测试一起改;丢弃它对清单的改动;把 internal import X 改回普通 import X,除非仓库本来就 internal import 这个模块;最后加开关,正式开启后编一遍确认零错误。
  6. +
  7. 每加一条 import Semantic,就检查裸写的 Error、Numeric、Argument。类型位置写 Swift.Error;转型与 catch 模式逐个看;「cast always fails」警告按错误对待。
  8. +
  9. 从下往上落地,不为此单独发版。设置只影响包自身的编译,不改公开 API。
  10. +
+
+

非目标

+
    +
  • 不开 NonisolatedNonsendingByDefault、InternalImportsByDefault、ImmutableWeakCaptures、StrictMemorySafety。
  • +
  • 不动 FrameworkToolbox(不属于 MachO 系列)。
  • +
  • 不给 swift-semantic-string 的 Error、Numeric、Argument 改名(公开 API 破坏)。
  • +
  • 不清理现有的 @unchecked Sendable(本库 84 处)与 nonisolated(unsafe)(37 处)。
  • +
  • 不采用 typed throws、~Copyable、Span 等新语言特性。
  • +
  • 不把这些改动提给上游 p-x9/MachOKit。
  • +
+
+
+ +
+

详细设计

+
+ 统一开关 +
+
let upcomingFeatureSettings: [SwiftSetting] = [
+    .enableUpcomingFeature("ExistentialAny"),
+    .enableUpcomingFeature("MemberImportVisibility"),
+    .enableUpcomingFeature("InferIsolatedConformances"),
+]
+
+for target in package.targets where target.type != .system && target.type != .binary && target.type != .plugin {
+    target.swiftSettings = (target.swiftSettings ?? []) + upcomingFeatureSettings
+}
+

swift-semantic-string 与 MachOKit 写在清单末尾;swift-demangling、MachOKitExtensions、MachOObjCSection 写在末尾的 Tuist 块之前;本库写在 extension SwiftSetting 之后、Tuist 块之前,数组里用已有的 .existentialAny、.memberImportVisibility、.inferIsolatedConformances。

+
+
+
+ 迁移命令与 internal import 的处理 +
+
queued-build swift package --build-system native \
+    --scratch-path /Volumes/DerivedData/Agents.noindex/claude/SwiftPM/MachOSwiftSection-Swift6UpcomingFeatures-Migrate \
+    migrate --to-feature ExistentialAny,MemberImportVisibility,InferIsolatedConformances
+git checkout -- Package.swift
+

不带 --target 就连测试一起改;--build-system native 不能省。本库退出码是 1 属正常(改清单失败),以 Applied N fix-its 为准。对每一行新加的 internal import X:仓库原来有 internal import X 的保留,没有的改成普通 import X。

+
+
+
+ +
+

调研

+

2026-11-20 在 Ultra(Xcode 27.2,Swift 6.4.2)上把六个包的当前提交各自 clone,以每个包为根编 swift build --build-tests;新特性用 SE-0486 的迁移模式(:migrate)只出警告,按诊断组计数。

+
+ 三项要开的特性:各包改动处数(源码 / 测试) +
+
+ + + + + + + + + + +
包ExistentialAnyMemberImportVisibilityInferIsolatedConformances
MachOKit已开启(0)56 / 00 / 0
MachOKitExtensions1 / 22 / 30 / 0
MachOObjCSection0 / 215 / 210 / 0
swift-demangling1 / 00 / 30 / 0
swift-semantic-string6 / 00 / 00 / 0
MachOSwiftSection57 / 41245 / 2350 / 33
+
+
+
+
+ 量过、决定不做的四项 +
+
+ + + + + + + + +
特性改动处(源码 / 测试)不做的原因
NonisolatedNonsendingByDefault778 / 347改运行语义:RuntimeViewer 从主线程调用时解析会跑到主线程
InternalImportsByDefault4,124 行 import没有迁移模式;约一半必须保持 public import;下游可能编不过
ImmutableWeakCaptures约 0收益近乎为零
StrictMemorySafety2,440 / 658不属于 Swift 6 或 7;几千处 unsafe 标注只会是噪音
+
+
+
+
+ swift package migrate 的实际表现与迁移的坑 +
+
    +
  • 本库清单写成 extension Target 上的静态常量,migrate 改清单那一步失败,源码照样改好;清单一律手改。
  • +
  • 默认构建系统下 migrate 不改测试(450 条测试警告、0 个 fix-it);--build-system native 下一遍改完源码与测试。
  • +
  • native 构建系统下它常写 internal import X,与别的文件的普通 import X 冲突(本库 17 个文件报访问级别有歧义)。
  • +
  • 迁移模式本身有 4 处硬错误(switch 不完备、.enum 解析成实例成员、两处 .values 落到 dynamic member lookup),构建一失败 migrate 就一处都不改,所以要预修。
  • +
  • swift-semantic-string 公开声明了 Error、Numeric、Argument;文件直接 import Semantic 后裸 Error 就是 Semantic.Error:源码 2 处、测试 14 个文件编不过,改成 Swift.Error。
  • +
  • Swift 6.4 的 fix-it 写出 any P?,Swift 6.3 要求 (any P)?:三处。
  • +
  • MachOKit 进 Swift 6 模式后,测试二进制里一个 curry thunk 的 mangling 多了 Yb(SE-0418),按名字找它的测试要跟着改。
  • +
+
+
+
+ +
+

替代方案

+
+ 八条,都否了或改了形状 +
+
    +
  • MachOKit 只加 StrictConcurrency:Swift 5 模式下只是警告,约束力不够。
  • +
  • MachOKit 用 swiftLanguageVersions: [.version("6")]:写法与兄弟包不一致,上游冲突也省不掉。
  • +
  • MachOKit 用 tools 6.2:草案原定;fork 的 CI 用 Swift 6.0,读不了。改为 6.0。
  • +
  • 测试照警告手改或写批量脚本:草案原定;--build-system native 的 migrate 就能改测试。
  • +
  • 逐个 target 写或让 migrate 改清单:容易漏;migrate 在本库清单上直接失败。选统一循环。
  • +
  • 四项全开:用户选了只开三项低风险的。
  • +
  • 不开 MemberImportVisibility:它是「依赖写在自己的 import 里」的来源,坑都已找全。保留。
  • +
  • 给 Semantic.Error 改名:公开 API 破坏,不在本次范围。
  • +
+
+
+
+ +
+

影响

+
    +
  • 源码兼容性:纯新增。六个包都不改任何公开声明的签名;upcoming feature 只作用于开启它的 target 本身,不传给下游。
  • +
  • ABI:不适用,SPM 源码分发。
  • +
  • 下游:RuntimeViewer、MachOKitUI、SymbolViewer 不用改代码。上游 p-x9/MachOKit 不提交,合上游 tag 时清单两处会冲突,按 fork 写法解决。
  • +
  • 文档:账本加一节、索引登记;CLAUDE.md 预计不加条目,落地时再判断。
  • +
  • API 演进:没有废弃的 API,不需要 major 跃迁,不单独发版。
  • +
+
+ +
+

落地步骤

+
    +
  1. 提案进集成分支,跨仓库登记。(已完成)
  2. +
  3. MachOKit 进 Swift 6 并开三项特性。(已完成)Ultra 上 27.2 与 26.6 都编过;测试只剩基线上同样失败的 5 个环境用例;CI 在 Xcode 16.2 与 Linux Swift 6.0.3 上通过。
  4. +
  5. swift-semantic-string 与 swift-demangling。(已完成)两个 Xcode 都编过,测试全过。
  6. +
  7. MachOKitExtensions。(已完成)两个 Xcode 都编过,测试全过。
  8. +
  9. MachOObjCSection。(已完成)两个 Xcode 都编过;测试里 MachOObjCSectionTests 这个 XCTest 类读用户本机的一个文件,在基线上同样崩溃,跳过它后其余全过。
  10. +
  11. 本库:预修、migrate、开关。(已完成)全部 target 在 27.2 与 26.6 下都编过。
  12. +
  13. (并入第 6 步)
  14. +
  15. 本库全量验证。(已完成)Xcode 26.6 下 554 个 suite、2,906 个测试全过;渲染 A/B 84 对逐字节一致;Tuist 工作区编过。
  16. +
  17. 落地。(已完成)六个仓库按各自流程合进集成分支,提案取号 0101、改 Implemented,账本第 146 节。MachOKitExtensions rebase 到含 C++ 类索引的 main 后补了两个 import 与一处 any;与 0100 合并后,宏的测试补了 SwiftSyntaxBuilder 的 import。合并结果 27.2 与 26.6 都编过,26.6 下 2,915 个测试全过。
  18. +
+
+ +
+

决策日志

+
+ 14 条,最近一条:Implemented +
+
+ + + + + + + + + + + + + + + + + + + +
日期变更说明
2026-11-20Created as Draft用户要求把 MachO 系列库迁到 Swift 6、开启严格并发,并评估开启全部新特性的改动量。实测五个包已是 Swift 6 模式,只有 MachOKit 停在 Swift 5 且切换后零错误;六项 Swift 7 默认特性逐项量过之后,用户选定「MachOKit 切 Swift 6 + ExistentialAny、MemberImportVisibility、InferIsolatedConformances」,另外三项与 StrictMemorySafety 不做
2026-11-20Accepted用户批准,开始实现
2026-11-20MachOKit 用 tools 6.0草案定的 6.2 会让 fork 的 CI(Xcode 16.2、Linux Swift 6.0.3)读不了清单;6.0 同样默认 Swift 6 模式。手动触发的 CI 两项都通过
2026-11-20测试也交给 migrate默认构建系统下 migrate 不改测试;--build-system native 下一遍改完源码与测试,手改与批量脚本都不需要了
2026-11-20internal import 改回普通 importnative 构建系统下 migrate 写的 internal import X 与已有的普通 import X 冲突(本库 17 个文件)。仓库已有 internal import 先例的保留,其余改成普通 import
2026-11-20any P? 改成 (any P)?Swift 6.4 的 fix-it 写法在 Swift 6.3(CI 的 Xcode 26.6)下报错;三处
2026-11-2014 个测试文件写 Swift.Errormigrate 给 93 个文件加了 import Semantic,其中 14 个测试文件里有类型位置的裸 Error,全部改成 Swift.Error;源码里没有,也没有「转型永远失败」的警告
2026-11-20MachOKit 一个测试的期望符号名Swift 6 模式下 curry thunk 的 mangling 多了 Yb(SE-0418),testFindSymbolByName 改为新名字;其余 5 个失败在基线上同样失败
2026-11-20验证结果六个包用 Xcode 27.2 与 26.6 都编过;swift-semantic-string、swift-demangling、MachOKitExtensions 测试全过;MachOKit 只剩基线同样失败的 5 个环境用例;MachOObjCSection 跳过读用户本机文件的那个 XCTest 类后全过;本库 2,906 个测试全过;渲染 A/B 84 对逐字节一致;Tuist 工作区 warm 与 build 成功;fork 的 CI 通过
2026-11-20文档判断不配使用指南或实现说明,没有新术语,CLAUDE.md 不加条目;账本一节留到正式收尾
2026-11-20实现完成,待用户看过后收尾六个仓库的功能分支都已推送
2026-11-20落地:MachOKitExtensions 补改rebase 到含 C++ 类索引(它的 0006)的 origin/main;那批代码补了 MachOReading、MachOResolving 两个 import 与一处 any,27.2 与 26.6 都编过、没有警告,测试全过
2026-11-20落地:与 0100 同批宏先进 next,本分支把它合进来;宏的测试补 SwiftSyntaxBuilder 的 import 与依赖。合并结果 27.2 与 26.6 都编过,26.6 下 555 个 suite、2,915 个测试全过;渲染 A/B 不重跑(合进来的只有测试);swift-demangling 在最终提交上 651 个测试全过
2026-11-20Implemented六个仓库合进集成分支,取号 0101,账本第 146 节;文档判断不变。后续项:MachOKit 的 DyldCacheConcurrentReadTests.swift 还有 3 条并发警告,没改
+
+
+
+
+ +
+
+ + diff --git a/Documentations/Evolutions/0101-swift6-mode-and-upcoming-features.md b/Documentations/Evolutions/0101-swift6-mode-and-upcoming-features.md new file mode 100644 index 000000000..f13438891 --- /dev/null +++ b/Documentations/Evolutions/0101-swift6-mode-and-upcoming-features.md @@ -0,0 +1,340 @@ +# 0101 - MachO 系列库统一 Swift 6 语言模式并开启三项 upcoming feature + +- **状态**: Implemented +- **作者**: JH +- **创建日期**: 2026-11-20 +- **最后更新**: 2026-11-20 +- **所属愿景**: 无 +- **关联提案**: 无 +- **跨仓库**: 本提案是 MachOKit(fork)、swift-semantic-string、swift-demangling、MachOKitExtensions、MachOObjCSection 与本库共用的唯一提案。MachOKitExtensions 与 MachOObjCSection 的提案索引各加一行 cross-repository 指向这里(落地步骤第 1 步);另外三个仓库没有提案目录,不加。 +- **实现分支 / PR**: 六个仓库都是 `feature/swift6-mode-and-upcoming-features`。MachOKitExtensions 从 `origin/main` 切(它只有 `main`,本地那条没推过的 `next` 不能用),其余五个从各自的 `next` 切。 +- **配套文档**: 无 —— 没有新的调用方契约,迁移的坑记在本提案里(决策日志「文档判断」) +- **网页版**: 同目录同名的 `.html` + +## 摘要 + +六个 MachO 系列包里有五个已经在 Swift 6 语言模式下编译,complete strict concurrency checking 早已按错误执行;唯一的例外是 MachOKit(fork),它的清单还是 `swift-tools-version: 5.10`。本提案做两件事:把 MachOKit 升到 tools 6.0,让它也进入 Swift 6 语言模式(实测零错误,Sources 里零并发诊断;停在 6.0 而不是 6.2,是为了 fork 的 CI 所用的 Swift 6.0 工具链还读得了清单);然后在六个包的每个 Swift target 上开启 `ExistentialAny`、`MemberImportVisibility`、`InferIsolatedConformances` 三项 upcoming feature(编译器把它们标为 Swift 7 默认开启),开关在每份清单末尾用一个循环统一加,不逐个 target 写。源码改动 723 处(717 个 fix-it 加 6 处预修),绝大部分是补 `import` 与补 `any`,源码与测试都由 `swift package --build-system native migrate` 自动改出;另有 6 处工具处理不了、要先手工改好,它写成 `internal import` 的补丁按各仓库的惯例改回普通 `import`。同为 Swift 7 默认的 `NonisolatedNonsendingByDefault`、`InternalImportsByDefault`、`ImmutableWeakCaptures`,以及独立的 `StrictMemorySafety`,量过之后明确不做(见「非目标」)。 + +## 动机 + +**MachOKit 是整条栈里唯一不做 complete concurrency checking 的一层,而它被并发读得最狠。** 上层的读取路径会从多个线程同时读 MachOKit:同一份定义可以被任意多个任务并行打印(提案 0066),交叉引用的整 cache 扫描用 28 个线程(`CrossReferenceAnalysis`),MachOKit 自己的测试里也有 `Tests/MachOKitTests/DyldCacheConcurrentReadTests.swift`。fork 里修过一次懒加载缓存的竞态(MachOKit 0.55.102 一带)。今天 MachOKit 新写的全局可变状态、跨线程传的非 Sendable 值,编译器在 Swift 5 模式下一声不吭;另外五个包同样的写法会直接编不过。实测表明这一层其实已经是 Swift 6 干净的(见前期调研),差的只是清单里的模式声明。 + +**本库清单早就为这几项特性备好了设置,却一直没用上。** `Package.swift:1541` 的 `extension SwiftSetting` 定义了 `existentialAny`、`internalImportsByDefault`、`memberImportVisibility`、`inferIsolatedConformances`、`nonisolatedNonsendingByDefault`、`immutableWeakCaptures` 六个常量,全仓库没有一处引用。 + +**每个文件依赖哪些模块,今天写在源码里的和实际用到的对不上,模块一搬家就暴露。** 不开 `MemberImportVisibility` 时,只要某个模块被同一进程里任何地方加载过,它给已有类型加的 extension 成员在所有文件里都能用,哪怕文件根本没 import 它。实测本库有 480 处这样的用法(Sources 245、Tests 235)。近一年模块搬了三轮(提案 0055 按层分组、0097 拆层、0098 把三层迁出本库),每轮都要在编译失败之后才补 import。更要紧的是,名字解析结果随「碰巧加载了哪些模块」而变:探针里有两处现在就靠这种可见性才解析成今天的意思(`TypeAttributeInferrer.swift:143` 的 `switch` 只在看得见 `SwiftObjCInterop` 时才是完备的,`ABIDiffer.swift:289` 的 `.enum` 只在看得见 `MachOSwiftSection` 时才是枚举 case 而不是别处 extension 加的同名实例成员)。开了这项特性,每个文件的依赖都写在它自己的 import 里。 + +**`any` 关键字项目里已经在用,只是没人强制。** `CLAUDE.md` 要求打印路径把 existential 写成 `any P`(提案 0092),MachOKit 的 target 也早就开了 `ExistentialAny`;本库源码里还有 57 处、测试里 41 处没写 `any` 的 existential。开了之后由编译器统一要求。 + +**`InferIsolatedConformances` 将来会默认开启,现在开的代价最小。** 它决定 global-actor 隔离类型的 conformance 是否自动推断为隔离的。六个包的 Sources 里一处受影响的都没有,只有本库 `Tests/IntegrationTests` 里 33 处(6 个文件)。现在开就是把这 33 处标好,以后不用等到 Swift 7 模式时再回头处理。 + +## 前期调研 + +**方法。** 2026-11-20 在 `JHs-Mac-Studio-Ultra`(Xcode 27.2,Swift 6.4.2)上,把六个包的当前提交(MachOKit `af92491`、MachOKitExtensions `249897b`、MachOObjCSection `4796434`、swift-demangling `815fe91`、swift-semantic-string `f14caa4`、本库 `73c9ccb7`)各自 clone 到 `/Volumes/DerivedData/Agents.noindex/claude/Probes/Swift6Migration/`,以每个包为根各编一次 `swift build --build-tests`,依赖都解析远端版本。新特性用 SE-0486 的迁移模式(`-enable-upcoming-feature <名字>:migrate`)开启,只出带 fix-it 的警告、不挡编译,加 `-print-diagnostic-groups` 按诊断组计数,只统计包根目录下的文件。日志与改过的 clone 都还留在那个目录下。 + +**各包当前的语言模式。** 从 SwiftPM 生成的 PIF 读每个 target 的 `SWIFT_VERSION`:MachOKitExtensions、MachOObjCSection、swift-demangling、swift-semantic-string 与本库的 target 都是 `6`(tools-version 6.x 且没声明 `swiftLanguageModes` 时 SwiftPM 默认 Swift 6),MachOKit 的四个 target 是 `5`。不在本次范围内的 FrameworkToolbox 的 `FoundationToolbox` 也是 `5`。 + +**编译器认得哪些特性。** `swiftc -print-supported-features` 列出的 upcoming feature 里,`enabled_in: 7` 的有六个:`ExistentialAny`、`InternalImportsByDefault`、`MemberImportVisibility`、`InferIsolatedConformances`、`NonisolatedNonsendingByDefault`、`ImmutableWeakCaptures`;其中 `ExistentialAny`、`MemberImportVisibility`、`InferIsolatedConformances`、`NonisolatedNonsendingByDefault` 四个标了 migratable,可以用迁移模式和 `swift package migrate`。另有可选的 `StrictMemorySafety`(`-strict-memory-safety`),不属于任何语言模式。 + +**MachOKit 进 Swift 6 模式。** 两次编译:Swift 5 模式加 `-strict-concurrency=complete`,Sources 零并发诊断,Tests 3 条警告(`DyldCacheConcurrentReadTests.swift` 里 2 条 `SendableClosureCaptures`、1 条 `AddPreconcurrencyImport`);直接 `-swift-version 6`(从构建数据库核实过 MachOKit、MachOArchiveKit、MachOKitReadable、MachOKitTests 四个 target 都拿到了 `-swift-version 6`),全部编过,零错误,只剩同样那 2 条测试警告和 1 条无关的 deprecation 警告。上游 p-x9/MachOKit 的 `main` 同样是 tools 5.10、没开严格并发;fork 比上游多 35 个提交、少 40 个。 + +**三项要开的特性,各包的改动处数(源码 / 测试):** + +| 包 | `ExistentialAny` | `MemberImportVisibility` | `InferIsolatedConformances` | +|---|---|---|---| +| MachOKit | 已开启(0) | 56 / 0(49 个文件) | 0 / 0 | +| MachOKitExtensions | 1 / 2 | 2 / 3 | 0 / 0 | +| MachOObjCSection | 0 / 2 | 15 / 21 | 0 / 0 | +| swift-demangling | 1 / 0 | 0 / 3 | 0 / 0 | +| swift-semantic-string | 6 / 0 | 0 / 0 | 0 / 0 | +| MachOSwiftSection | 57 / 41(73 个文件) | 245 / 235(373 个文件) | 0 / 33(全在 `IntegrationTests`) | + +本库 `MemberImportVisibility` 的 245 处源码里有 189 处在测试基线生成器 `Sources/TestSupport/SwiftSectionFixtureSupport`,真正的库模块只有五十来处。 + +**量过、决定不做的四项(源码 / 测试):** + +| 特性 | 改动处 | 不做的原因 | +|---|---|---| +| `NonisolatedNonsendingByDefault` | 778 / 347,本库占 729 / 234 | 改的是运行语义:每个 nonisolated async 函数改为在调用方的 actor 上执行。RuntimeViewer 从主线程调用库入口时,解析工作会跑到主线程;保留现状要给上千个函数逐个加 `@concurrent` | +| `InternalImportsByDefault` | 4,124 行 import(约 1,400 个文件) | 没有迁移模式,只能手改;约一半必须保持 `public import`;下游可能因失去传递可见性而编不过 | +| `ImmutableWeakCaptures` | 约 0(全仓库只有本库 4 处 `[weak` 捕获) | 收益近乎为零,单独开不值得占一次提交;随将来的 Swift 7 模式一起处理 | +| `StrictMemorySafety` | 2,440 / 658 | 不属于 Swift 6 或 7;这是一个以 unsafe pointer 为本的二进制解析库,几千处 `unsafe` 标注只会是噪音 | + +`InternalImportsByDefault` 的「约一半必须保持 public」是这样量的:在 clone 里把 Sources 的每条 import 改成 `public import`、清单里只给本包 target 开这项特性,再数编译器报的 `UnusedImportAccess`(「public import 没被公开声明用到」)。MachOKit 320 条里 194 条可降为 internal,MachOKitExtensions 232 / 122,MachOObjCSection 320 / 157,swift-demangling 36 / 28,swift-semantic-string 6 / 2,本库 3,210 条里至少 1,513 条(有两个测试支撑文件因探针跳过了 `@testable import` 而没编完)。直接用 `-Xswiftc -enable-upcoming-feature InternalImportsByDefault` 不可行:它会连第三方依赖一起改导入规则,swift-fileio 等先编不过。 + +**`swift package migrate` 的实际表现(在本库 clone 上试跑):** + +- 非测试 target:在 258 个文件里套用了 300 个 fix-it(diff +304 / −57),然后在改清单那一步失败:本库的 target 写成 `extension Target` 上的静态常量,工具找不到 target(`unable to find target named 'Utilities' in package`),所以清单必须手改。退出码是 1,但源码已经改好。 +- 测试 target:默认的构建系统(SwiftPM 6.4 起是 Swift Build)下一处都不改。它确实编了测试、也打出了 450 条测试里的迁移警告,可显式 `--target <全部测试 target>`、换全新构建目录,都是 `Applied 0 fix-its`。改用旧的构建系统(`swift package --build-system native migrate …`)就正常:探针里测试 target 套用了 303 个 fix-it(160 个文件);正式实现时不带 `--target` 跑一遍,源码与测试一起改完(本库 605 个 fix-it、420 个文件)。 +- **native 构建系统下,`migrate` 补的 import 常常带 `internal`。** 在仓库已经 `internal import` 过的模块上(MachOKit 的 `FileIO`、`FileIOBinary`,MachOObjCSection 的 `FileIO`、`MachOKitExtensions`)这是对的;但它对别的模块也写 `internal import X`,而 Swift 6 不许同一个模块里一个文件写 `internal import X`、另一个文件写普通的 `import X`(`ambiguous implicit access level for import of 'Foundation'; it is imported as 'internal' elsewhere`),本库因此 17 个文件编不过。默认构建系统的那次探针补的都是普通 `import`。 +- 构建一失败就一处都不改。`MemberImportVisibility` 的迁移模式并不只出警告:本库有 4 处直接报错,必须先手工补 import,`migrate` 才跑得起来: + + | 位置 | 报错 | 补什么 | + |---|---|---| + | `Sources/Declaration/SwiftAttributeInference/TypeAttributeInferrer.swift:143` | `switch must be exhaustive`(枚举 case 看不见) | `import SwiftObjCInterop` | + | `Sources/Output/SwiftDiffing/ABIDiffer.swift:289` | `instance member 'enum' cannot be used on type 'TypeContextDescriptorWrapper'` | `import MachOSwiftSection` | + | `Tests/SwiftInterfaceTests/ExtensionContainerUnificationTests.swift:164` | `.values` 落到了 dynamic member lookup | `import OrderedCollections` | + | `Tests/SwiftIndexingTests/SymbolTestsCoreIntegrationTests.swift:135` | 同上 | `import OrderedCollections` | + +- **`migrate` 补的 import 会遮蔽标准库的名字。** swift-semantic-string 公开声明了 `struct Error`(`Sources/Semantic/Components/Error.swift:8`)和 `struct Numeric`,与 `Swift.Error`、`Swift.Numeric` 同名;还有 `Argument`,与 ArgumentParser 的同名。文件一旦直接 `import Semantic`,裸写的 `Error` 就解析成 `Semantic.Error`。`migrate` 给本库 6 个文件加了 `import Semantic`,其中两处因此编不过:`Sources/Commands/SwiftSectionKit/ObjC/ObjCAPIRequests.swift:293` 与 `Sources/Commands/SwiftSectionKit/Swift/ABIEvolutionRequest.swift:179`(`enum …Error: Error` 被当成以 `Semantic.Error` 为 raw type),改成 `Swift.Error` 就好。危险的是不报错的情形:`catch let error as Error`、`is Error` 这类转型照样能编,只是变成永远失败的转型,编译器只给一条警告。 +- 补完上面 6 处、`migrate` 跑完、清单里手加开关之后,Sources 全部编过;测试 target 从第一个失败的文件开始逐个报缺 import(`TypeNameRetentionTests.swift` 缺 `MachOKit`、`SymbolicationTests.swift` 缺 `MachOKitExtensions`),与警告清单一致。 + +**清单里给 C target 加 `swiftSettings` 是无害的。** `InternalImportsByDefault` 那轮探针在六份清单末尾用同一个循环给所有 target 追加了设置,包括 `MachOKitC`、`MachOSwiftSectionC`、`SwiftSymbolsRegistration` 这些 C target,六个包都照常编过。 + +## 提议方案 + +1. **MachOKit 进 Swift 6 语言模式。** `Package.swift` 第 1 行改成 `// swift-tools-version: 6.0`。tools 6.x 不声明 `swiftLanguageModes` 时默认 Swift 6,不必另写。不跟另外五个兄弟包一样用 6.2:fork 的 CI(`.github/workflows/ci.yml`)在 Xcode 16.2 与 Linux 的 Swift 6.0.3 上编,2026-08 的提交「preserve Swift 6.0 dependency compatibility」也专门为 Swift 6.0 工具链保留了依赖范围;6.2 的清单 6.0 读不了。编译器不认识的 upcoming feature 名字(`MemberImportVisibility` 要 6.1,`InferIsolatedConformances` 要 6.2)会被忽略,所以 6.0 照样能编。清单末尾的 `extension SwiftSetting` 里那九项 Swift 6 已经默认开启的 upcoming feature(`ForwardTrailingClosures` 到 `GlobalConcurrency`)在 Swift 6 模式下是空操作,删掉;`SwiftSetting.allCases` 的 `CaseIterable` 扩展随之删除,改用下面的统一开关。`AccessLevelOnImport` 实验特性(只在 debug 开)保留不动,实现时如果编译器提示它多余再删。 +2. **六个包的每个 Swift target 统一开启三项特性。** 每份清单在 `let package = Package(...)` 之后加一个循环,给除 `system`、`binary`、`plugin` 以外的所有 target 追加同一组设置;本库沿用 `Package.swift:1541` 已有的常量。test、macro、executable target 都包括在内,`IntegrationTests` 也开(它只编译不运行)。 +3. **源码由 `migrate` 改,前后各补一手。** 先手工改好「前期调研」里那 6 处(4 处补 import、2 处 `Swift.Error`);再在清单还没开特性时跑 `swift package --build-system native migrate --to-feature ExistentialAny,MemberImportVisibility,InferIsolatedConformances`,源码与测试一起改(补 import、补 `any`、给 `IntegrationTests` 的 conformance 标 `nonisolated`)。本库在改清单那一步报错是预期的,以它报告的「Applied N fix-its」为准,`Package.swift` 的改动丢弃。然后把它写成 `internal import X` 的补丁改回普通 `import X`,除非这个仓库本来就 `internal import` 这个模块。最后才加清单里的开关,正式开启后编一遍确认零错误。 +4. **每加一条 `import Semantic`,就检查那个文件里裸写的 `Error`、`Numeric`、`Argument`。** 类型位置一律写成 `Swift.Error` / `Swift.Numeric`;`as Error`、`is Error` 之类的转型与 `catch` 模式逐个看。编译器的「cast always fails」警告按错误对待。 +5. **从下往上落地,不为此单独发版。** 顺序是 MachOKit、swift-semantic-string、swift-demangling、MachOKitExtensions、MachOObjCSection、本库。这些设置只影响包自身的编译,不改任何公开 API,下游用的仍是已发布的版本,所以各仓库照各自的流程合进集成分支即可,随下一次正常发版带出去。 + +### 非目标 + +- 不开 `NonisolatedNonsendingByDefault`、`InternalImportsByDefault`、`ImmutableWeakCaptures`,也不开 `StrictMemorySafety`(原因见「前期调研」的第二张表)。 +- 不动 FrameworkToolbox:它不属于 MachO 系列,`FoundationToolbox` 停在 Swift 5 模式与本提案无关。 +- 不给 swift-semantic-string 的 `Error`、`Numeric`、`Argument` 改名:那是公开 API 的破坏性改动,下游全都要跟着改。本提案只在调用点写全限定名。 +- 不清理现有的 `@unchecked Sendable`(本库 84 处)与 `nonisolated(unsafe)`(本库 37 处):它们大多是锁保护的状态,部署目标 macOS 10.15 用不了 `Mutex`;它们在 Swift 6 模式下本来就合法。 +- 不采用其他 Swift 6 时代的新语言特性(typed throws、`~Copyable`、`Span` 之类),那是逐处设计取舍,不是开关。 +- 不把这些改动提给上游 p-x9/MachOKit:开关与补 import 只为我们自己的检查,按「fork 自用改动不提上游」的约定留在 fork。 + +## 改动地图 + +| 文件 / 类型 | 动作 | 改什么 | 为什么 | 步骤 | +|---|---|---|---|---| +| MachOSwiftSection `Documentations/Evolutions/0101-swift6-mode-and-upcoming-features.md`、同名 `.html` | 新增 | 本提案与网页版 | 唯一提案 | 1 | +| MachOSwiftSection `Documentations/Evolutions/README.md`、`Documentations/README.md` | 修改 | 登记本提案 | 索引 | 1 | +| MachOKitExtensions、MachOObjCSection `Documentations/Evolutions/README.md` | 修改 | 各加一行 cross-repository 指向本提案 | 跨仓库提案的约定 | 1 | +| MachOKit `Package.swift:1` | 修改 | `swift-tools-version` 5.10 → 6.0 | 进入 Swift 6 语言模式;6.0 而不是 6.2,CI 的 Swift 6.0 工具链才读得了 | 2 | +| MachOKit `Package.swift:76`、`:145–171` · `extension SwiftSetting` | 修改 / 删除 | MachOKit target 不再拼 `SwiftSetting.allCases`;删掉九项 Swift 6 默认特性与 `CaseIterable` 扩展;末尾加统一开关循环 | Swift 6 模式下那九项是空操作;与另外五个包同一写法 | 2 | +| MachOKit `Sources/MachOKit/**`(49 个文件) | 修改 | 补 56 处 import:55 处 `internal import FileIO` / `FileIOBinary`(MachOKit 本来就这样 import 这两个模块),1 处普通 import | `MemberImportVisibility` | 2 | +| MachOKit `Tests/MachOKitTests/DyldCacheConcurrentReadTests.swift` | 修改(可选) | 消掉 2 条 `SendableClosureCaptures` 与 1 条 `AddPreconcurrencyImport` 警告 | Swift 6 模式下仍是警告,不挡编译 | 2 | +| MachOKit `Tests/MachOKitTests/MachOPrintTests.swift` · `testFindSymbolByName` | 修改 | 期望的 thunk 名字换成带 `Yb` 的 Swift 6 mangling | Swift 6 模式下未调用的枚举 case 引用推断为 `@Sendable`(SE-0418) | 2 | +| swift-semantic-string `Package.swift`(第 94 行之后) | 修改 | 加统一开关循环 | 开启三项特性 | 3 | +| swift-semantic-string `Sources/Semantic/Components/AnyComponent.swift`、`Frozen/FrozenSemanticString+Codable.swift`、`SemanticString+Conformances.swift` | 修改 | 补 6 处 `any` | `ExistentialAny` | 3 | +| swift-demangling `Package.swift`(`let package` 之后、Tuist 块之前) | 修改 | 加统一开关循环 | 开启三项特性 | 3 | +| swift-demangling `Sources/DemanglingTestingSupport/Required.swift:8` | 修改 | `error: Error?` → `error: (any Error)?` | `ExistentialAny`;括号是 Swift 6.3 要求的 | 3 | +| swift-demangling `Tests/DemanglingTests/DefectRegressionTests.swift`、`NodeTests.swift`、`TransientRemangleParityTests.swift` | 修改 | 补 3 处 `import SwiftStdlibToolbox`(`migrate` 写成 `internal`,改回普通 import) | `MemberImportVisibility` | 3 | +| MachOKitExtensions `Package.swift`(`let package` 之后、Tuist 块之前) | 修改 | 加统一开关循环 | 开启三项特性 | 4 | +| MachOKitExtensions `Sources/MachOKitExtensions/RequiredNonOptional.swift:8`、`String+.swift`,`Sources/MachODependencies/DependencyLoadName.swift` | 修改 | `(any Error)?`、2 处 import(`BinaryParseSupport` 改回普通 import) | 两项特性 | 4 | +| MachOKitExtensions `Tests/`(5 个文件:`FixupResolutionMemoTests`、`SelfBindResolutionTests`、`CPlusPlusSymbolIndexCensusTests`、`DependencyLoadNameTests`、`SymbolIndexStoreTests`) | 修改 | 2 处 `any`、3 处 import | 两项特性 | 4 | +| MachOObjCSection `Package.swift`(`let package` 之后、Tuist 块之前) | 修改 | 加统一开关循环 | 开启三项特性 | 5 | +| MachOObjCSection `Sources/`、`Tests/`(33 个文件) | 修改 | 38 个 fix-it:36 处 import(其中 `internal import FileIO` 6 处、`internal import MachOKitExtensions` 12 处沿用本库已有写法,`ObjCTypeDecodeKit`、`ObjCMetadataSource` 改回普通 import)、2 处 `any` | 两项特性 | 5 | +| MachOSwiftSection `Sources/Declaration/SwiftAttributeInference/TypeAttributeInferrer.swift` | 修改 | 加 `import SwiftObjCInterop` | 迁移模式下第 143 行的 `switch` 报不完备 | 6 | +| MachOSwiftSection `Sources/Output/SwiftDiffing/ABIDiffer.swift` | 修改 | 加 `import MachOSwiftSection` | 迁移模式下第 289 行 `.enum` 解析错 | 6 | +| MachOSwiftSection `Sources/Commands/SwiftSectionKit/ObjC/ObjCAPIRequests.swift:293`、`Sources/Commands/SwiftSectionKit/Swift/ABIEvolutionRequest.swift:179` | 修改 | `: Error` → `: Swift.Error` | `migrate` 补的 `import Semantic` 让 `Error` 解析成 `Semantic.Error` | 6 | +| MachOSwiftSection `Sources/**`、`Tests/**`(420 个文件,其中 `SwiftSectionFixtureSupport` 约 176 个) | 修改 | `swift package --build-system native migrate` 的 605 个 fix-it:import、`any`、`IntegrationTests` 的 33 处 `nonisolated` conformance;`migrate` 写成 `internal import` 的 266 处全部改回普通 import | 三项特性 | 6 | +| MachOSwiftSection `Package.swift:1541–1548` 之后、`:1550` 的 Tuist 块之前 | 修改 | 加统一开关循环,用已有的 `.existentialAny`、`.memberImportVisibility`、`.inferIsolatedConformances` | 开启三项特性;放在 Tuist 块之前,Tuist 改写 target 时设置已经在了 | 6 | +| MachOSwiftSection `Tests/SwiftInterfaceTests/ExtensionContainerUnificationTests.swift`、`Tests/SwiftIndexingTests/SymbolTestsCoreIntegrationTests.swift` | 修改 | 加 `import OrderedCollections` | 迁移模式下 `.values` 解析错 | 6 | +| MachOSwiftSection `Sources/Output/SwiftPrinting/NodePrintables/NodePrintable.swift:68` | 修改 | `any NodePrintableDelegate?` → `(any NodePrintableDelegate)?` | Swift 6.4 的 fix-it 写法 Swift 6.3 不接受 | 6 | +| MachOSwiftSection `Tests/`(14 个文件:`OpaqueWitnessDumpAnnotationTests`、`SymbolTestsCoreIntegrationTests`、`CrossImageOpaqueReferenceTests`、`DiffRendererHeaderFailureTests`、`ExtensionContextTypeNameTests`、`LegacyDyldInfoBindTests`、`OpaqueConstraintRenderingTests`、`OpaqueParameterDepthTests`、`OpaqueParameterInMultiDepthExtensionTests`、`OpaqueParameterWithoutProtocolRequirementTests`、`PrintFailureEventTests`、`ProjectedOpaqueMemberWitnessTests`、`PropertyWrapperSynthesizedMemberTests`、`GenericTypeNameSubstitutionTests`) | 修改 | 28 处类型位置的 `Error` → `Swift.Error` | `migrate` 补的 `import Semantic` 让裸 `Error` 解析成 `Semantic.Error` | 6 | +| MachOSwiftSection `Documentations/Internal/ProjectEvolutionLog.md` | 修改 | 加一节 | 账本 | 9 | + +## 架构图 + +改了什么:每个包的编译设置。 + +```text +package language mode upcoming features (every Swift target) +----------------------- --------------------- ------------------------------------------------------ +MachOKit (fork) - Swift 5 (tools 5.10) - 9 Swift-6-era features (MachOKit target only) + + Swift 6 (tools 6.0) - ExistentialAny (MachOKit target only) + + ExistentialAny, MemberImportVisibility, InferIsolatedConformances +swift-semantic-string Swift 6 (tools 6.2) + ExistentialAny, MemberImportVisibility, InferIsolatedConformances +swift-demangling Swift 6 (tools 6.2) Lifetimes (experimental, two targets, kept) + + ExistentialAny, MemberImportVisibility, InferIsolatedConformances +MachOKitExtensions Swift 6 (tools 6.2) + ExistentialAny, MemberImportVisibility, InferIsolatedConformances +MachOObjCSection Swift 6 (tools 6.2) + ExistentialAny, MemberImportVisibility, InferIsolatedConformances +MachOSwiftSection Swift 6 (tools 6.3) + ExistentialAny, MemberImportVisibility, InferIsolatedConformances + (statics already declared at Package.swift:1541, now used) +``` + +每份清单里开关的位置: + +```text +Package.swift + let package = Package(name:, platforms:, products:, dependencies:, targets: [...]) ++ let upcomingFeatureSettings: [SwiftSetting] = [ExistentialAny, MemberImportVisibility, InferIsolatedConformances] ++ for target in package.targets where type is not system / binary / plugin { ++ target.swiftSettings = (target.swiftSettings ?? []) + upcomingFeatureSettings ++ } + // swift-demangling, MachOKitExtensions, MachOObjCSection, MachOSwiftSection: + // the Tuist block (TUIST_MAPS_LOCAL_PACKAGE_TESTS) stays after the loop +``` + +迁移流程(每个包相同,本库多一步预修): + +```text +pre-fix sites migrate mode cannot express (MachOSwiftSection: 4 imports + 2 Swift.Error) + -> swift package --build-system native migrate --to-feature ... + (sources and tests together; MachOSwiftSection fails at the manifest step by design) + -> git checkout Package.swift; turn each added `internal import X` into `import X` + unless the package already imports X internally + -> commit the fix-its; then add the loop to Package.swift + -> swift build --build-tests (features on, zero errors) -> swift test + -> DEVELOPER_DIR=Xcode-26.6 swift build --build-tests (CI toolchain, Swift 6.3) + -> MachOKit only: CI on Xcode 16.2 and Linux Swift 6.0.3 (workflow_dispatch) +``` + +## 详细设计 + +**统一开关**(swift-semantic-string、MachOKit 写在清单末尾;swift-demangling、MachOKitExtensions、MachOObjCSection 写在末尾的 Tuist 块之前,前面加一段 `// MARK: - Upcoming features` 注释): + +```swift +let upcomingFeatureSettings: [SwiftSetting] = [ + .enableUpcomingFeature("ExistentialAny"), + .enableUpcomingFeature("MemberImportVisibility"), + .enableUpcomingFeature("InferIsolatedConformances"), +] + +for target in package.targets where target.type != .system && target.type != .binary && target.type != .plugin { + target.swiftSettings = (target.swiftSettings ?? []) + upcomingFeatureSettings +} +``` + +本库写在 `extension SwiftSetting`(`Package.swift:1541`)之后、Tuist 块(`:1550`)之前,用已有常量: + +```swift +let upcomingFeatureSettings: [SwiftSetting] = [ + .existentialAny, + .memberImportVisibility, + .inferIsolatedConformances, +] + +for target in package.targets where target.type != .system && target.type != .binary && target.type != .plugin { + target.swiftSettings = (target.swiftSettings ?? []) + upcomingFeatureSettings +} +``` + +`static let` 在 `extension SwiftSetting` 里声明、在顶层代码里引用,清单求值顺序没有问题;另外三个未用的常量(`internalImportsByDefault`、`nonisolatedNonsendingByDefault`、`immutableWeakCaptures`)留着,将来开时直接加进数组。 + +**MachOKit 清单**改后的相关部分: + +```swift +// swift-tools-version: 6.0 + +// ... + .target( + name: "MachOKit", + dependencies: [ + // unchanged + ], + swiftSettings: [ + .enableExperimentalFeature("AccessLevelOnImport", .when(configuration: .debug)), + ] + ), +// ... + +let upcomingFeatureSettings: [SwiftSetting] = [ + .enableUpcomingFeature("ExistentialAny"), + .enableUpcomingFeature("MemberImportVisibility"), + .enableUpcomingFeature("InferIsolatedConformances"), +] + +for target in package.targets where target.type != .system && target.type != .binary && target.type != .plugin { + target.swiftSettings = (target.swiftSettings ?? []) + upcomingFeatureSettings +} +``` + +原来的 `extension SwiftSetting { static let forwardTrailingClosures … }` 与 `extension SwiftSetting: @retroactive CaseIterable` 整段删除,循环放在清单末尾、binary-parse-support 依赖处理之后,前面加一段注释说明 6.0 的取舍与「不认识的特性名会被忽略」。 + +**迁移命令**(以本库为例,在 Ultra 的功能 worktree 里,`queued-build` 前缀照写): + +```bash +queued-build swift package --build-system native \ + --scratch-path /Volumes/DerivedData/Agents.noindex/claude/SwiftPM/MachOSwiftSection-Swift6UpcomingFeatures-Migrate \ + migrate --to-feature ExistentialAny,MemberImportVisibility,InferIsolatedConformances +git checkout -- Package.swift +``` + +不带 `--target` 就连测试一起改;`--build-system native` 不能省,默认的构建系统改不了测试(见前期调研)。本库退出码是 1 属正常(改清单失败),看输出里的 `Applied N fix-its in M files`;另外五个包退出码是 0,但它们改出的清单同样丢弃,统一用手写的循环。迁移用单独的构建目录,与之后用默认构建系统的验证构建分开。日志带 ANSI 颜色与 OSC 8 超链接,按 `[#组名]` 计数前要先去掉转义;同一条诊断会打印两遍(一行摘要、一行带源码框的),按「文件:行:列 + 文字」去重。 + +**`internal import` 的处理**:对 `migrate` 新加的每一行 `internal import X`,看这个仓库的 Sources 与 Tests 里原来有没有 `internal import X`。有(MachOKit 的 `FileIO`、`FileIOBinary`,MachOObjCSection 的 `FileIO`、`MachOKitExtensions`)就保留;没有就改成普通 `import X`,与仓库里绝大多数 import 一致,也不会和别的文件里的普通 `import X` 冲突。补了 `import Semantic` 的文件按「提议方案」第 4 条检查。 + +## 替代方案考量 + +- **MachOKit 保持 tools 5.10,只加 `.enableUpcomingFeature("StrictConcurrency")`。** Swift 5 模式下这只给 complete checking 的警告,不是错误;以后新代码出问题只是多一条警告,达不到另外五个包的约束力。否。 +- **MachOKit 保持 tools 5.10,靠 `swiftLanguageVersions: [.version("6")]` 进 Swift 6。** 能少改一行,但 `swiftLanguageVersions` 在 tools 6 已废弃改名,与五个兄弟包写法不一致,跟上游同步时第 1 行的冲突也省不掉(上游以后升 tools-version 照样冲突)。否。 +- **MachOKit 升到 tools 6.2,与五个兄弟包一致。** 草案原本这样定;实现时发现 fork 的 CI 用 Xcode 16.2 与 Linux 的 Swift 6.0.3,6.2 的清单它们读不了。改为 6.0。 +- **测试 target 照警告清单手改,或写脚本批量补 import。** 草案原本这样定(本库测试约 310 处、180 个文件);实现时发现 `migrate` 换成 native 构建系统就能改测试,不再需要手改或脚本。 +- **逐个 target 写 `swiftSettings:`,或让 `swift package migrate` 改清单。** 本库有 53 个 target,MachOKitExtensions 24 个、MachOObjCSection 19 个,逐个写容易漏,新加的 target 也得记着写;`migrate` 在本库的清单上直接失败。统一循环一处搞定,新 target 自动带上。选循环。 +- **四项全开(再加 `NonisolatedNonsendingByDefault` 与 `InternalImportsByDefault`)。** 2026-11-20 的调研结果摆给用户之后,用户选了只开三项低风险的。理由见「前期调研」第二张表。 +- **只开 `ExistentialAny` 与 `InferIsolatedConformances`,不开 `MemberImportVisibility`。** 后者是三项里改动最大、坑最多的(4 处迁移模式硬错误、`Semantic.Error` 遮蔽),但它正是动机里「每个文件的依赖写在自己的 import 里」的来源,而且坑都已经在探针里找全并给出了改法。保留。 +- **给 swift-semantic-string 的 `Error` 改名,从根上避开遮蔽。** 公开 API 的破坏性改动,下游(本库、RuntimeViewer)都得跟着改,不属于这次的范围。只在调用点写 `Swift.Error`;改名另行考虑。 + +## 影响 + +### 源码兼容性(source compatibility) + +**纯新增**——六个包都不改任何公开声明的签名。`any` 关键字、补的 import、`Swift.Error` 全限定、`nonisolated` conformance 都不改变声明的类型。MachOKit 换语言模式不改变它的公开 API:它的类型的 Sendable 标注早已写好(Swift 5 模式下就在),全局函数与类型没有 global actor 隔离,Swift 6 模式下推断出的隔离与今天相同。 + +upcoming feature 只作用于开启它的 target 本身的编译,不传给依赖它的包:下游即使不开这三项,也照样能用这六个包。 + +### ABI 兼容性(条件项) + +不适用 —— 六个包都以 SPM 源码分发,使用方每次重新编译。 + +### 下游影响 + +- **本仓库**:所有 target 都开三项特性,包括 `IntegrationTests`(只编译不运行)、`SwiftSectionMacros`(macro target)、`swift-section` 等 executable target。 +- **RuntimeViewer、MachOKitUI、SymbolViewer**:它们从源码编这六个包,编的时候用的是各包自己的设置,所以不用改任何代码;RuntimeViewer 的 Tuist workspace 重新生成后带上新设置。它们自己的 target 不受影响。 +- **Tuist 开发 workspace**(`./TuistScript.sh`):Tuist 读 `Package.swift` 求值后的结果,循环加的设置会照常映射过去;最后一步编一遍确认。 +- **上游 p-x9/MachOKit**:不提交。fork 的清单第 1 行与 `extension SwiftSetting` 一段与上游不同,以后合上游 tag 时这两处会冲突,按 fork 的写法解决。 + +### 文档与示例 + +- 本库 `Documentations/Internal/ProjectEvolutionLog.md` 加一节;两个提案索引登记本提案;MachOKitExtensions、MachOObjCSection 的索引加 cross-repository 行。 +- `CLAUDE.md` / `AGENTS.md` 不加条目:开了特性之后,漏写 `any` 或漏 import 会被编译器当场指出,agent 不会默默写错。唯一不报错的是 `Semantic.Error` 遮蔽下的转型,但那会有「cast always fails」警告;落地时再判断是否值得在本库 `CLAUDE.md` 加一句。 +- 没有 DocC、README 或示例代码受影响。 + +## API 演进与废弃策略 + +- 没有被替代或废弃的 API。 +- 不需要 semver major 跃迁;各仓库不必为此单独发版,随下一次正常发版带出。 + +## 落地步骤 + +1. **提案进集成分支,跨仓库登记** —— 改动地图第 1–3 行 + - 行为:`proposalIsListedInBothIndexes`、`siblingIndexesPointAtTheProposal` +2. **MachOKit 进 Swift 6 并开三项特性**(fork 的 `.worktrees/MachOKit-Swift6UpcomingFeatures`,从 `next` 切) —— 第 4–7 行 + - 行为:`machOKitTargetsCompileInSwift6Mode`、`machOKitBuildsWithAllThreeUpcomingFeatures`、`machOKitTestsPassSkippingAotCachePrintTests`(已知 5 个环境失败照旧)、`machOKitBuildsWithXcode26_6`、`machOKitCIPassesOnSwift6_0`(手动触发 fork 的 `ci.yml`:Xcode 16.2 与 Linux Swift 6.0.3)、`findSymbolByNameLooksUpTheSwift6Mangling` +3. **swift-semantic-string 与 swift-demangling 开三项特性** —— 第 8–12 行 + - 行为:`semanticStringBuildsAndTestsWithUpcomingFeatures`、`demanglingBuildsAndTestsWithUpcomingFeatures`、`demanglingLifetimesFeatureStillEnabledInBothTargets`、两者 `buildsWithXcode26_6` +4. **MachOKitExtensions 开三项特性**(从 `origin/main` 切) —— 第 13–15 行 + - 行为:`machOKitExtensionsBuildsAndTestsWithUpcomingFeatures`、`buildsWithXcode26_6` +5. **MachOObjCSection 开三项特性** —— 第 16–18 行 + - 行为:`machOObjCSectionBuildsAndTestsWithUpcomingFeatures`、`buildsWithXcode26_6` +6. **本库:预修、migrate、开关** —— 第 19–24 行 + - 行为:`preFixedSitesCompileUnderMigrationMode`、`migrateAppliesSourceAndTestFixIts`、`noModuleIsImportedAtTwoAccessLevels`、`noFileImportingSemanticSpellsBareErrorOrNumeric`、`optionalExistentialsAreParenthesizedForSwift6_3`、`allTargetsBuildWithUpcomingFeatures`(含 `IntegrationTests`,Xcode 27.2 与 26.6 都编) +7. **(并入第 6 步)** 草案里「测试照警告手改」这一步不再需要:`--build-system native` 的 `migrate` 连测试一起改了。 +8. **本库全量验证** —— 不改代码 + - 行为:`fullSuitePassesSkippingIntegrationTests`、`fullSuitePassesWithXcode26_6`、`renderingABVerificationIsByteIdentical`(`SystemFrameworkRenderingVerification.md` 的三条腿,对照组为 `next`;补 import 只改名字解析,A/B 用来兜住遮蔽一类不报错的变化)、`tuistWorkspaceGeneratesAndBuilds`、`noCastAlwaysFailsWarning` +9. **落地** —— 第 26 行 + - 行为:六个仓库按各自流程合进集成分支(MachOKitExtensions 推 `main`),本提案取号、状态改 Implemented,账本加一节 + +构建与测试一律远程在 Ultra 上跑(公司那台不编这些工程),产物目录用 `/Volumes/DerivedData/Agents.noindex/claude/SwiftPM/<包名>`;第 2–5 步的仓库互不依赖,可以并行。 + +**收尾时必须判断两件事**(判断结果写进决策日志,不允许沉默跳过): + +- **要不要配套专题文章** —— 不需要:没有新的调用方契约;迁移时踩到的坑已在本提案里写全(决策日志「文档判断」)。 +- **有没有引入新术语** —— 没有。 + +九步都已完成:验证结果见决策日志「验证结果」,落地时的补改与合并后的验证见「落地」两行。 + +## 决策日志 + +| 日期 | 变更 | 说明 | +|------|------|------| +| 2026-11-20 | Created as Draft | 用户要求把 MachO 系列库迁到 Swift 6、开启严格并发,并评估开启全部新特性的改动量。实测发现五个包已是 Swift 6 模式,只有 MachOKit 停在 Swift 5 且切换后零错误;Swift 7 默认的六项特性逐项量过之后,用户选定「MachOKit 切 Swift 6 + `ExistentialAny`、`MemberImportVisibility`、`InferIsolatedConformances`」,另外三项与 `StrictMemorySafety` 不做 | +| 2026-11-20 | Accepted | 用户批准,开始实现 | +| 2026-11-20 | MachOKit 用 tools 6.0 | 草案定的 6.2 会让 fork 的 CI(Xcode 16.2、Linux Swift 6.0.3)读不了清单;6.0 同样默认 Swift 6 模式。手动触发的 CI 两项都通过,证明 Swift 6.0 在 Swift 6 模式下能编、不认识的特性名被忽略 | +| 2026-11-20 | 测试也交给 `migrate` | 默认构建系统下 `migrate` 不改测试(450 条测试警告、0 个 fix-it);`--build-system native` 下一遍就改完源码与测试,草案里的手改与批量脚本都不需要了 | +| 2026-11-20 | `internal import` 改回普通 import | native 构建系统下 `migrate` 会写 `internal import X`,在本库与已有的普通 `import X` 冲突(17 个文件报访问级别有歧义)。规则:仓库对这个模块已有 `internal import` 先例的保留,其余改成普通 import | +| 2026-11-20 | `any P?` 改成 `(any P)?` | Swift 6.4 的 fix-it 写出的 `any P?` 在 Swift 6.3(CI 的 Xcode 26.6)下报错;swift-demangling、MachOKitExtensions、本库各一处 | +| 2026-11-20 | 14 个测试文件写 `Swift.Error` | 除了预修的两处,`migrate` 还给 93 个文件加了 `import Semantic`,其中 14 个测试文件里有类型位置的裸 `Error`(`struct …Error: Error`、`any Error`、`(any Error).self`),全部改成 `Swift.Error`;源码里没有,也没有出现「转型永远失败」的警告 | +| 2026-11-20 | MachOKit 一个测试的期望符号名 | `MachOPrintTests.testFindSymbolByName` 按名字找测试二进制里的一个 curry thunk;Swift 6 模式把对 `LoadCommand.dylib` 的未调用引用推断为 `@Sendable`(SE-0418),mangling 多了 `Yb`,测试改为新名字。其余失败的 5 个用例在基线上同样失败(`libclang_rt.osx.a` 不存在等环境原因) | +| 2026-11-20 | 验证结果 | 全部在 Ultra 上跑。六个包用 Xcode 27.2 与 26.6 都编过(含全部测试目标)。测试:swift-semantic-string、swift-demangling、MachOKitExtensions 全过;MachOKit 只剩基线上同样失败的 5 个环境用例;MachOObjCSection 的 `MachOObjCSectionTests` 这个 XCTest 类在 `setUp` 读用户本机的 `/Users/JH/Downloads/iOS18.5-SwiftUI`,在基线上同样崩溃,跳过它后其余全过;本库在 Xcode 26.6 下 554 个 suite、2,906 个测试全过。渲染 A/B(基线 `next`,三条腿含归档 cache 26.6 与 15.5、模拟器 runtime、进程内 MachOImage)84 对逐字节一致。Tuist 工作区 `warm` 与 `build` 都成功。fork 的 CI 在 Xcode 16.2 与 Linux Swift 6.0.3 上通过 | +| 2026-11-20 | 文档判断 | 不配使用指南或实现说明:没有新的调用方契约,迁移时踩到的坑都写在本提案里;没有新术语;`CLAUDE.md` 不加条目,漏写 `any` 或漏 import 编译器当场报错,`Semantic.Error` 遮蔽也会让类型位置编不过。账本一节留到正式收尾时随取号一起写 | +| 2026-11-20 | 实现完成,待用户看过后收尾 | 六个仓库的功能分支都已推送 | +| 2026-11-20 | 落地:MachOKitExtensions 补改 | 落地前把功能分支 rebase 到 `origin/main`,那里多了 C++ 类索引(它的提案 0006)。那批代码没在三项特性下编过:`CPlusPlusClassIndexStore.swift` 缺 `MachOReading`、`MachOResolving` 两个 import,`ClassIndexTestImages.swift` 有一处裸写的 `Error`。补上后 Xcode 27.2 与 26.6 都编过、没有警告,测试全过 | +| 2026-11-20 | 落地:与 0100 同批 | 用户看过后决定与 `@FixtureSuite` 宏([0100](0100-fixture-suite-macro.md))一起落地:宏先进 `next`,本分支再把 `next` 合进来。宏的测试 `FixtureSuiteMacroTests` 在 `MemberImportVisibility` 下缺 `SwiftSyntaxBuilder`,补了 import,并让测试 target 显式依赖它。合并结果用 Xcode 27.2 与 26.6 都编过,26.6 下的警告与合并前相同;Xcode 26.6 下 `swift test --skip IntegrationTests` 555 个 suite、2,915 个测试全过。渲染 A/B 不重跑:合进来的只有测试与只给测试用的宏。swift-demangling 在最终提交上补跑测试,651 个全过 | +| 2026-11-20 | Implemented | 六个仓库合进各自的集成分支(MachOKitExtensions 推 `main`),取号 0101,账本第 146 节。「文档判断」一行的结论不变。后续项:MachOKit 的 `DyldCacheConcurrentReadTests.swift` 在 Swift 6 下还有 3 条并发警告(2 条 `SendableClosureCaptures`、1 条 `AddPreconcurrencyImport`),不挡编译,没改 | diff --git a/Documentations/Evolutions/0102-multiline-type-formatting.html b/Documentations/Evolutions/0102-multiline-type-formatting.html new file mode 100644 index 000000000..949ccdc8c --- /dev/null +++ b/Documentations/Evolutions/0102-multiline-type-formatting.html @@ -0,0 +1,522 @@ + + + + + + +0102 - 长类型拆行:放不下的类型按括号结构拆成多行 + + + +
+ +
+

MachOSwiftSectionEvolutions0102

+

0102 长类型拆行:放不下的类型按括号结构拆成多行

+
+
状态
Implemented
+
最后更新
2026-11-21
+
项目类型
库
+
原文
0102-multiline-type-formatting.md
+
+
+ + + +
+ +
+

摘要

+

新增一个公开的格式化值类型 MultilineTypeFormatting(SwiftDeclarationRendering),把已经打印好的 Swift 源码(SemanticString)里放不下的类型按括号拆成多行:一个类型一行放得下就不动;放不下时,整个类型照 TypeAliasFormatter 的结构规则拆开——有两个及以上参数的泛型参数列表每个参数一行,单参数泛型、元组、函数类型与声明的参数列表、[…] 集合语法糖只在里面有拆开的部分时才拆。它只插入换行和缩进,文字、semantic type、identifier 和各种 region 原样保留。

+

swift-section dump / interface 新增 --multiline-types 与 --maximum-line-width,InterfaceRequest / DumpRequest 新增同名字段;默认关闭,关闭时输出逐字节不变。RuntimeViewer 在拿到一个定义的完整打印之后调用一次即可,打印器本身一行不改。

+
+ +
+

要你定

+
+

已落地

+
    +
  1. 无待定事项;RuntimeViewer 的接入由它自己的提案落地。
  2. +
+
+
+

没问你、自己定的(可推翻)

+
    +
  • 默认宽度 100 列(swift-format 的默认值),行首缩进不计入。
  • +
  • CLI 参数名 --multiline-types 与 --maximum-line-width;只给宽度不给开关算用法错误。
  • +
  • diff、evolution、snapshot 与 ObjC 输出不接。
  • +
  • RuntimeViewer 的开关与调用留给它自己的后续改动。
  • +
+
+
+ +
+

方案

+
    +
  1. 一行的内容宽度不超过 maximumLineWidth 就原样保留。内容宽度是这一行的字符数减去行首缩进,所以拆不拆与嵌套深度无关,嵌套定义的契约自然成立。
  2. +
  3. 超宽的行解析成括号树。只在 .standard 类型的 atom 里找括号;字符串字面量、反引号标识符、// 之后的内容是文字;-> 不是括号。括号不配对就整行原样保留。
  4. +
  5. 找出放不下的类型。不在其它泛型参数列表里面的泛型参数列表算作一个类型的最外层;它的 > 落在第 maximumLineWidth 列之后,这个类型就算放不下。
  6. +
  7. 放不下的类型按结构规则拆。有两个及以上参数的泛型参数列表一律每个参数一行;单参数泛型、元组、函数类型的参数列表、[…] 只在某个元素已是多行时才拆。
  8. +
  9. 外层括号跟着拆。函数声明的参数列表、enum case payload、元组、泛型签名(紧跟在声明名后面的 <…>,以及里面写着 where、A: P 或 == 的 <…>)、attribute 参数,只在某个元素已是多行时才拆。
  10. +
  11. 拆开的列表这样排。开括号留在原行末尾;参数另起一行,缩进为行首缩进加 4 个空格乘以嵌套层数;, 变成 ,;闭括号另起一行回到上一层。
  12. +
+
extension SettingsApp.SettingsNavigationSplitView: SwiftUI.View {
+    typealias Body = SwiftUI.ModifiedContent<
+        SwiftUI.ModifiedContent<
+            SwiftUI.SceneBridgeReader<
+                SwiftUI.SubscriptionView<
+                    Combine.PassthroughSubject<
+                        Any,
+                        Swift.Never
+                    >,
+                    SwiftUI.NavigationSplitView<
+                        SwiftUI.ModifiedContent<
+                            SettingsApp.SettingsSidebarList,
+                            SwiftUI.ToolbarRemovingModifier
+                        >,
+                        SettingsApp.SettingsSecondaryColumn
+                    >
+                >
+            >,
+            SwiftUI._EnvironmentKeyWritingModifier<Swift.Bool>
+        >,
+        SwiftUI.OnTestViewModifier
+    >
+}
+
+// fits: unchanged
+var result: Swift.Result<Swift.Int, Swift.Error>
+
+

做不到的

+

SwiftUI 的 ModifiedContent 链向左嵌套,二十多层 modifier 拆开后第一个参数仍会缩进二十多层;压平这种链要按语义改写类型,不属于排版,本提案不做。

+
+

非目标

+
    +
  • 不改打印器;默认关闭时所有输出逐字节不变,fixture baseline 与渲染 A/B 不受影响。
  • +
  • diff、evolution、snapshot 不接(按行标记增删、JSON);ObjC 输出不接。
  • +
  • 不单独按行宽拆长参数列表;参数列表只在某个参数的类型被拆开时随之拆开。
  • +
  • 不做 TypeAliasFormatter 的单参数泛型展开、其它缩进宽度与图形视图。
  • +
  • RuntimeViewer 的设置界面与接入不在本提案里实现。
  • +
+
+ +
+

架构图

+
    +
  • 新增
  • +
  • 修改
  • +
  • 不变
  • +
+
+ + + Printers (unchanged) + SwiftDeclarationPrinter + Dumpable.dump(using:in:) + + + RuntimeViewer (follow-up) + RuntimeSwiftSectioncalls format(_:) before caching + + + SwiftSectionKit + InterfaceRequest + DumpRequest / DumpSession + + + swift-section + InterfaceCommand + DumpCommand + + + SwiftDeclarationRendering + MultilineTypeFormattingpublic struct · format(_:) + +Lines (width gate) + +BracketTree (parse a line) + +Layout (break, emit atoms) + + + + + + + makeRequest() + + format(_:) — RuntimeViewer follow-up + +
+

打印器照旧输出一行一个声明;调用方在交出产物前调用一次 format(_:)。三个文件都是 MultilineTypeFormatting 的 internal 扩展。

+
format(source)
+└── for each line (atoms split at "\n" keep type + identifier)
+    ├── content width (minus leading indentation) <= maximumLineWidth ──► copy unchanged
+    └── BracketTree(line)          (.standard atoms only; strings, backticks, "//", "->" are text)
+        ├── nil (unbalanced) ──► copy unchanged
+        └── Layout
+            ├── outermost generic argument list whose ">" lies past the width ──► long type
+            ├── inside a long type: generic argument list with >= 2 arguments ──► break
+            ├── any list with a multi-line element ──► break        (bottom-up)
+            └── emit "<" "\n" indent(L + 4k) element "," "\n" … "\n" indent(L + 4(k - 1)) ">"
+
+ +
+

改动地图

+
+ + + + + + + + + + + + + + + + + + + + + + + +
文件 / 类型动作改什么为什么步骤
Sources/Output/SwiftDeclarationRendering/MultilineTypeFormatting.swift · MultilineTypeFormatting新增公开 struct:maximumLineWidth、init(maximumLineWidth:)、format(_:)dump 与 interface 共用的位置,RuntimeViewer 已依赖这个 product1
MultilineTypeFormatting+Lines.swift · Line(internal)新增按 \n 切行(atom 保留 type 与 identifier)、算行首缩进与内容宽度、拼回规则 1:宽度不超的行直接复制1
MultilineTypeFormatting+BracketTree.swift · BracketTree(internal)新增只扫 .standard atom 解析括号树;字符串、反引号、//、-> 当文字;不配对返回 nil规则 22
MultilineTypeFormatting+Layout.swift · Layout(internal)新增判定长类型、自下而上决定拆哪些列表、生成 atom(插入的 atom 沿用相邻括号或逗号的 identifier)规则 3–63
Tests/SwiftDeclarationRenderingTests/MultilineTypeFormattingTests.swift新增行切分、解析、排版的单元测试每步的行为清单1–3
Tests/SwiftDeclarationRenderingTests/MultilineTypeFormattingPreservationTests.swift新增type 与 identifier 不变、可还原原文、幂等、与缩进可交换、region 读回不变「只加换行和缩进」的承诺4
Tests/SwiftInterfaceTests/NestedDefinitionRegionContractTests.swift修改新变体 everyOptionFormattedAsMultilineTypes:两份打印都按 30 列格式化后再比较;另加 formattedVariantBreaksTheFixtureTypes嵌套定义契约在格式化后仍成立;复用这个套件的整套比较4
Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift修改新字段 multilineTypeFormatting,printRoot() 之后调用interface 的唯一出口5
Sources/Commands/SwiftSectionKit/Swift/DumpRequest.swift修改新字段;DumpSession.dump 拿到声明后调用dump 的唯一出口5
Tests/SwiftSectionKitTests/MultilineTypeFormattingRequestTests.swift新增两个请求打开与关闭时的输出接入正确、关闭时不变5
Package.swift · swift-section、SwiftSectionKitTests修改各加 SwiftDeclarationRendering 直接依赖Kit 不重新导出模块,调用方自己导入5
Tuist/CommandLine/Project.swift修改命令行依赖加 SwiftDeclarationRenderingTuist 工程与清单同步5
Sources/Executables/swift-section/Models/MultilineTypeOptionGroup.swift新增--multiline-types、--maximum-line-width,validate(),换成请求要的值两个子命令共用一组参数6
Sources/Executables/swift-section/Commands/InterfaceCommand.swift、DumpCommand.swift修改引入上面那组参数,makeRequest() 映射CLI 是 SwiftSectionKit 的包装6
Tests/SwiftSectionCommandTests/MultilineTypesFlagTests.swift新增映射与校验(退出码 64)CLI 两侧都要有测试6
AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md修改两个新 flag 与默认宽度CLI 改动同批更新6
Documentations/SwiftSectionKit.md、Internal/Modules/SwiftSectionKit.md修改新字段调用方指南与模块参考7
CLAUDE.md修改SwiftDeclarationRendering 一条补一句模块清单与代码同步7
ProjectEvolutionLog.md、Glossary.md、两份 README修改账本、术语、索引文档纪律7
+
+
+ +
+

详细设计

+
+ 公开 API +
+
public struct MultilineTypeFormatting: Hashable, Sendable {
+    /// The widest a line's content may be, in characters; indentation does not count.
+    public var maximumLineWidth: Int
+
+    /// - Precondition: `maximumLineWidth > 0`.
+    public init(maximumLineWidth: Int = 100)
+
+    /// `source` with its long types laid out over several lines.
+    public func format(_ source: SemanticString) -> SemanticString
+}
+
+extension InterfaceRequest {
+    public var multilineTypeFormatting: MultilineTypeFormatting?
+}
+
+extension DumpRequest {
+    public var multilineTypeFormatting: MultilineTypeFormatting?
+}
+
--multiline-types              Break a type that runs past the line width over several lines, at its brackets.
+--maximum-line-width <columns> The widest a line may be, not counting its indentation, before
+                               --multiline-types breaks its types. (default: 100)
+
+
+
+ 行与宽度 +
+
    +
  • 先把 source.components 按 \n 切成行;含 \n 的 atom 在 \n 处切开,各段保留原 type 与 identifier。
  • +
  • 行首缩进 L 是行首连续空格数(跨 atom 计);内容宽度是这一行的 Character 数减去 L。
  • +
  • 内容宽度不超的行原样复制,不解析。
  • +
  • 行之间互不影响;括号跨行的输入每行单独看都不配对,因此原样保留——这就是幂等的原因。
  • +
+
+
+
+ 括号树 +
+
    +
  • 只有 .standard atom 参与扫描;类型名、声明名(含 interface 里的运算符名)、注释等 atom 整体是文字。
  • +
  • " 与反引号之间是文字;// 之后到行末是文字;-> 是箭头;深度大于 0 时的 , 分隔元素。
  • +
  • < 前面(跳过空白)的 atom 是 .type(_, .declaration)、.function(.declaration) 或 .member(.declaration) 时,这个列表是泛型参数子句,否则是泛型参数列表。闭括号读到时再看一次:有一项在自己这一层写着 where、: (冒号后带空格)或 ==,是 dump 写在类型名后面的泛型签名(_ConditionalContent< where A: P, B: Q>),也按参数子句处理。
  • +
  • 括号不配对或未关闭返回 nil,整行原样保留;dump 里的 static func < infix(…) 就走这条路。
  • +
+
+
+
+ 排版与生成 +
+
    +
  • 不在任何泛型参数列表里面的泛型参数列表,> 的内容列号大于 maximumLineWidth 时,标为长类型的根。
  • +
  • 自下而上:长类型内部元素数不少于 2 的泛型参数列表拆;任何列表有元素是多行时拆;其余不拆。
  • +
  • 拆开的列表:开括号后插入 \n 与 L + 4k 个空格;, 换成 , 再插入换行与缩进;闭括号前插入 \n 与 L + 4(k − 1) 个空格。
  • +
  • 插入的 atom 都是 .standard:开括号与逗号之后的换行和缩进取那个开括号或逗号的 identifier,闭括号之前的取闭括号的 identifier,region 不会被切断。
  • +
  • 有一行被改时,结果按 atom 一个元素重建,不保留输入的元素边界;没有行被改时直接返回输入本身。
  • +
  • 空列表 () 从不拆。
  • +
+
+
+
+ 保持性承诺 +
+
    +
  1. 内容宽度不超的行逐 atom 不变。
  2. +
  3. 去掉插入的换行与缩进、把 , 还原成 , ,得到与输入相同的文字。
  4. +
  5. 每个原有字符所在 atom 的 semantic type 与 identifier 不变;冻结后各种 region 分离结果不变。
  6. +
  7. 幂等:format(format(x)) == format(x)。
  8. +
  9. 与缩进可交换,由此嵌套定义的契约在格式化后仍成立。
  10. +
+
+
+
+ +
+

调研

+
+ 七条查证过的事实 +
+
    +
  • 两套打印器。interface 走 SwiftPrinting(BoundGenericNodePrintable.swift:66 写 <、, 、>),dump 走上游 swift-demangling 的 NodePrinter(经 DemangleResolver.swift:31)。两边的括号与逗号都是 .standard 的独立 atom。
  • +
  • typealias Body 一行。renderMergedAssociatedTypeRecords(SwiftDeclarationPrinter+Headers.swift:305)把整个类型接在 typealias X = 后面同一行。
  • +
  • region 编码在 identifier 上。插入不带编码的 atom 会把同一个 region 切成两个。
  • +
  • 嵌套定义契约。removingIndentation(levels:) 按字节删每行开头 levels * 4 个空格;拆不拆不能取决于缩进深度。
  • +
  • 运算符。上游把 infixOperator 写成 "< infix" 这种 .standard atom(NodePrinter.swift:499)。
  • +
  • 调用方的出口。RuntimeViewer 拼好 newInterfaceString 后缓存(RuntimeSwiftSection.swift:364),已依赖 SwiftDeclarationRendering;InterfaceRequest.swift:225 的 printRoot();DumpRequest.swift:513 的 DumpSession.dump。
  • +
  • TypeAliasFormatter 的规则。多参数 < 一律展开;单参数、(、[ 只在子元素多行时展开;-> 不算括号。仓库没有 license 文件,只借用规则、不复制代码。
  • +
+
+
+
+ +
+

替代方案

+
+ 六条被否的路径 +
+
    +
  • 纯按行宽逐层决定。同一个类型在不同深度排版不同;用户否掉。
  • +
  • 完全照 TypeAliasFormatter、不看行宽。每个 Swift.Result<Swift.Int, Swift.Error> 都被拆成四行;用户否掉。
  • +
  • 在打印器里写换行或断点标记。两套打印器要各改一遍,上游 NodePrinterTarget 要加要求并发版;memoize 的片段会带上依赖列号的决定。
  • +
  • 做成打印配置项、由每个公开入口格式化。二十来个公开入口互相调用,要么重复格式化要么拆分每个入口;dump 还要另接。
  • +
  • 在纯文本上格式化。丢掉 semantic type、identifier 与 region。
  • +
  • 扫描所有 atom 的所有字符。运算符名、私有类型名 (Visitor in $…) 也含括号。
  • +
+
+
+
+ +
+

影响

+
    +
  • 源码兼容性:纯新增;新字段与 init 参数默认 nil。
  • +
  • ABI:不适用,SPM 源码分发。
  • +
  • RuntimeViewer(后续):设置里加开关,在 RuntimeSwiftSection.swift:364 缓存前调用 format,开关变化时清 interfaceByObject 缓存;不必改依赖。
  • +
  • 文档:agent 插件 skill、SwiftSectionKit 调用方指南与模块参考、CLAUDE.md 模块清单;发版时写 changelog。
  • +
  • API 演进:以后的选项(单参数展开、缩进宽度)作为带默认值的属性加进 struct。
  • +
+
+ +
+

落地步骤

+
    +
  1. 骨架:类型、行切分与宽度闸门 —— emptySourceIsUnchanged、linesWithinWidthAreUnchangedAtomForAtom、contentWidthIgnoresLeadingIndentation、atomsContainingLineBreaksAreSplitKeepingTypeAndIdentifier、nonPositiveWidthIsAPreconditionFailure
  2. +
  3. 括号树 —— genericArgumentListsNestInsideParenthesesAndBrackets、angleBracketAfterDeclarationNameIsGenericParameterClause、arrowIsNotAClosingBracket、bracketsInsideStringLiteralsAreText、bracketsInsideBackticksAreText、bracketsAfterLineCommentAreText、bracketsInNonStandardAtomsAreText、unbalancedLineIsLeftUnchanged、operatorDeclarationFromDumpIsLeftUnchanged
  4. +
  5. 排版与生成 —— multiArgumentGenericBreaksOneArgumentPerLine、singleArgumentGenericStaysInlineUnlessItsArgumentBreaks、tupleBreaksOnlyWhenAnElementBreaks、functionTypeParametersBreakOnlyWhenAParameterBreaks、collectionSugarBreaksOnlyWhenAnElementBreaks、typeThatFitsStaysOnOneLineInAnOverlongLine、overlongLineWithoutLongTypeIsUnchanged、declarationParameterListBreaksWhenAParameterTypeBreaks、genericParameterClauseDoesNotBreakForHavingTwoParameters、continuationLinesIndentFromTheLineIndentation、separatorLosesItsSpaceWhenBroken、swiftUIBodyIsLaidOutByStructure
  6. +
  7. 保持性与嵌套定义契约 —— formattingKeepsSemanticTypesAndIdentifiers、removingInsertedBreaksRestoresTheOriginalText、formattingIsIdempotent、formattingCommutesWithIndentation、annotationAndVisibilityRegionsReadBackUnchanged、nestedDefinitionTakenOutOfFormattedParentEqualsFormattedChildPrint
  8. +
  9. SwiftSectionKit 接入 —— interfaceRequestFormatsLongTypesWhenAsked、dumpRequestFormatsEachDeclarationWhenAsked、requestsWithoutFormattingPrintAsBefore、interfaceWrittenToFileIsFormattedToo
  10. +
  11. CLI 与 agent 插件 —— multilineTypesFlagMapsOntoTheRequest、maximumLineWidthMapsOntoTheRequest、maximumLineWidthWithoutMultilineTypesIsAUsageError、nonPositiveMaximumLineWidthIsAUsageError;插件 skill 的 flag 都存在于 --help
  12. +
  13. 文档 —— 索引、账本、术语表、模块清单与代码一致
  14. +
+

验证:每步构建通过、本步新测试通过;收尾跑 swift test --skip IntegrationTests 全量。打印器不改、默认关闭,渲染 A/B 不适用;另对一份真实 SwiftUI interface 打开格式化,留档耗时与效果。

+
+ +
+

决策日志

+
+ 13 条,最近一条:Implemented +
+
+ + + + + + + + + + + + + + + + + +
日期变更说明
2026-11-21Created as DraftRuntimeViewer 里 SwiftUI 视图的 typealias Body 印成一行几千个字符,看不出泛型的层级,需要像展开括号一样按层拆行。
2026-11-21规则选定放得下的类型不动,放不下的类型整个按 TypeAliasFormatter 的结构规则拆;适用于所有类型位置;元组与函数类型的括号同样处理。
2026-11-21接入方式做成调用方在出口调用一次的纯格式化函数,不改打印器、不加打印配置项。
2026-11-21宽度不计缩进同一个声明在任何嵌套深度都拆得一样,marksNestedDefinitions 的契约不受影响。
2026-11-21Accepted用户批准,开始实现。功能分支 feature/multiline-type-formatting,从 next 切出。
2026-11-21闭括号前的换行取闭括号的 identifier闭括号前面紧挨的常是带类型引用 identifier 的类型名,换行不该算进那个引用。
2026-11-21不保留元素边界元素边界没有公开读取接口;format 用于打印完成的结果,没有行被改时返回输入本身。
2026-11-21嵌套定义契约测试并入现有套件给 NestedDefinitionRegionContractTests 加格式化变体,复用整套比较;宽度取 30 列,fixture 的长泛型类型不多。
2026-11-21调用方直接依赖 SwiftDeclarationRenderingKit 不重新导出模块;swift-section 与 SwiftSectionKitTests 各加一条依赖,Tuist 命令行工程同步。
2026-11-21尖括号里写着要求的是泛型签名对系统 SwiftUI 跑 dump 时发现 _ConditionalContent< where A: P, B: Q> 被当成两个参数拆开;补规则并先写了变红的测试。
2026-11-21不跑全量,以定向测试交付机器负载高,全量两次开跑都停掉了,且没法把测试进程限制在指定核数;用户决定以本提案涉及的八个定向套件交付。
2026-11-21实现完成不另写实现说明;新术语 long type / multiline type formatting 登记进术语表;SwiftSectionKit 指南(中英)、模块参考、agent 插件 skill、模块清单、账本同批更新。
2026-11-21Implemented落地为 0102,演进账本第 148 节;合进 next 并推送。RuntimeViewer 的接入由它自己的提案落地。
+
+
+
+
+ +
+
+ + diff --git a/Documentations/Evolutions/0102-multiline-type-formatting.md b/Documentations/Evolutions/0102-multiline-type-formatting.md new file mode 100644 index 000000000..c5d374e98 --- /dev/null +++ b/Documentations/Evolutions/0102-multiline-type-formatting.md @@ -0,0 +1,414 @@ +# 0102 - 长类型拆行:放不下的类型按括号结构拆成多行 + +- **状态**: Implemented +- **作者**: JH +- **创建日期**: 2026-11-21 +- **最后更新**: 2026-11-21 +- **所属愿景**: 无 +- **关联提案**: RuntimeViewer 的提案 `multiline-type-formatting`(生成选项里的「Break Long Types」,见它的 [提案索引](https://github.com/MxIris-Reverse-Engineering/RuntimeViewer/blob/next/Documentations/Evolutions/README.md)) +- **实现分支 / PR**: `feature/multiline-type-formatting`(已合进 `next`) +- **配套文档**: 不另写——规则与保持性承诺在本提案与 `MultilineTypeFormatting` 的文档注释里;调用方用法在 [SwiftSectionKit.md](../SwiftSectionKit.md) +- **网页版**: 同目录同名的 `.html` + +## 摘要 + +新增一个公开的格式化值类型 `MultilineTypeFormatting`(`SwiftDeclarationRendering`),把已经打印好的 Swift 源码(`SemanticString`)里放不下的类型按括号拆成多行:一个类型一行放得下就不动;放不下时,整个类型照 [TypeAliasFormatter](https://github.com/OpenSwiftUIProject/TypeAliasFormatter) 的结构规则拆开——有两个及以上参数的泛型参数列表每个参数一行,单参数泛型、元组、函数类型与声明的参数列表、`[…]` 集合语法糖只在里面有拆开的部分时才拆。它只插入换行和缩进,文字、semantic type、identifier 和各种 region 原样保留。`swift-section dump` / `interface` 新增 `--multiline-types` 与 `--maximum-line-width`,`InterfaceRequest` / `DumpRequest` 新增同名字段;默认关闭,关闭时输出逐字节不变。RuntimeViewer 在拿到一个定义的完整打印之后调用一次即可,打印器本身一行不改。 + +## 动机 + +SwiftUI 视图的 `Body`、modifier 链、`TupleView` 之类的类型在二进制里是完整展开的泛型树,打印出来是一整行。RuntimeViewer 里打开 Preferences.app 的 `SettingsApp.SettingsNavigationSplitView`,`extension … : SwiftUI.View` 里的 `typealias Body = SwiftUI.ModifiedContent` 挤在一起,看不出哪个参数属于哪一层。dump 与 CLI 的 interface 输出同样如此,同类问题也出现在任何带长泛型的成员签名、`where` 子句和关联类型 witness 上。 + +这类类型只能靠拆行看懂层级。社区里已有专门的工具(TypeAliasFormatter:粘贴一个 typealias,按括号结构排版),说明这个需求是真实存在的;但它工作在纯文本上,复制出来、粘进去、再对照回来,丢掉了 RuntimeViewer 的语法着色、跳转链接与各种 region。本提案把同样的排版放进库里,直接作用在打印结果上。 + +## 前期调研 + +- **类型由两套打印器拼成 `SemanticString`。** interface 走本仓库的 `SwiftPrinting`(`TypeNodePrinter` 等,`Sources/Output/SwiftPrinting/NodePrinter/TypeNodePrinter.swift:8`),泛型参数列表由 `printBoundGenericNoSugar` 写出(`Sources/Output/SwiftPrinting/NodePrintables/BoundGenericNodePrintable.swift:66`:`printChildren(typeList, prefix: "<", suffix: ">", separator: ", ")`);dump 走上游 swift-demangling 的 `NodePrinter`,经 `DemangleResolver.options`(`Sources/Output/SwiftDeclarationRendering/DemangleResolver.swift:31`)。两边写括号和逗号都用不带 context 的 `write(_:)`,`SemanticString` 把它记成 `.standard` 类型的独立 atom(`swift-semantic-string/Sources/Semantic/SemanticString+Conformances.swift:32`),而类型名、模块名、关键字、声明名、注释各有自己的 semantic type。 +- **`typealias Body` 这一行是怎么拼出来的。** `renderMergedAssociatedTypeRecords`(`Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift:305`)依次写 `Indent`、`typealias`、名字、`=`,再把 `resolver.resolve(for:)` 打印出的整个类型接在同一行(`:318`–`:326`)。成员签名里的类型则由 `FunctionNodePrinter` / `VariableNodePrinter` 在打印整条声明时递归写出,没有单独的「一个类型」的 `SemanticString`。 +- **region 编码在 atom 的 `identifier` 上。** `AnnotationRegion`、`VisibilityRegion`、`DefinitionRegion` 都不占文字,而是把标记写进每个 atom 的 `identifier`,冻结后再分离出来(`swift-semantic-string/Sources/Semantic/AnnotationRegions/AnnotationRegion.swift` 的类型注释);同一种 region 中间夹进一个不带编码的 atom,会被读成两个。所以插入的换行与缩进 atom 必须沿用相邻 atom 的 `identifier`。 +- **嵌套定义的契约只允许缩进随层级变化。** `marksNestedDefinitions` 承诺:父定义打印里深度为 `d` 的子定义,取出后 `removingIndentation(levels: d + 1)`,等于子定义单独打印的结果(`Sources/Output/SwiftPrinting/SwiftDeclarationPrintConfiguration.swift:198`–`:236`)。`removingIndentation` 按字节从每个非空行开头删 `levels * 4` 个空格(`swift-semantic-string/Sources/Semantic/Frozen/FrozenSemanticString+Indentation.swift:28`–`:61`)。因此拆不拆一行,不能取决于这一行缩进了多深——否则同一个子定义在父定义里和单独打印时会拆得不一样。 +- **运算符名在 dump 里是带 `<` 的 `.standard` atom。** 上游 `NodePrinter` 把 `infixOperator` 写成 `"\(name) infix"`(`swift-demangling/Sources/Demangling/Node/Printer/NodePrinter.swift:499`),`static func < infix(…)` 里的 `<` 和泛型括号同为 `.standard`。扫描器必须容忍括号不配对的行,而不是猜。 +- **宿主是怎么拿到一个定义的。** RuntimeViewer 把一个运行时对象的所有打印(`printTypeDefinition`、`printExtensionDefinition`、`printProtocolDefinition`)拼进一个 `newInterfaceString`,再缓存成 `RuntimeObjectInterface`(RuntimeViewer `RuntimeViewerCore/Sources/RuntimeViewerCore/Core/RuntimeSwiftSection.swift:284`–`:364`),且它已经依赖 `SwiftDeclarationRendering` product(同仓库 `RuntimeViewerCore/Package.swift:178`)。SwiftSectionKit 里 interface 在 `InterfaceRequest.run` 拿到 `builder.printRoot()` 的整份结果(`Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift:225`),dump 在 `DumpSession.dump` 一次处理一个顶层声明(`Sources/Commands/SwiftSectionKit/Swift/DumpRequest.swift:513`–`:530`)。三处都是「打印完、交出去之前」的唯一出口。 +- **TypeAliasFormatter 的规则。** 它的 `Renderer`(`Packages/TypeAliasFormatterCore/Sources/TypeAliasFormatterCore/TypeAliasFormatter.swift`):`<` 有两个及以上参数时一律展开、每个参数一行;只有一个参数时保持一行,除非某个参数已是多行;`(` 与 `[` 只在某个元素是多行时展开;`->` 不算括号;反引号里的内容不解析;另有 `expandSingleArguments` 选项把单参数泛型也展开。它不看行宽,任何输入都整个排版。该仓库没有 license 文件,本提案只借用规则,不复制代码。 +- **用户选定的规则。** 本次澄清提问里比较过三种:纯按行宽逐层决定、完全照 TypeAliasFormatter、两者结合。选定两者结合:放得下的类型不动(`Swift.Result` 这类短类型不会在每个签名里被拆成四行),放不下的类型整个按结构规则拆(同一个类型无论嵌在第几层,拆出来的形状都一样)。适用于所有出现类型的位置,元组与函数类型的括号一起处理。 + +## 提议方案 + +在 `SwiftDeclarationRendering` 里加一个纯函数式的格式化值类型: + +```swift +let formatting = MultilineTypeFormatting(maximumLineWidth: 100) +let formatted = formatting.format(printedDefinition) +``` + +它逐行处理输入,规则如下: + +1. **一行的内容宽度不超过 `maximumLineWidth` 就原样保留。** 内容宽度是这一行的字符数减去行首缩进——缩进不计入,所以拆不拆与嵌套深度无关,嵌套定义的契约自然成立。 +2. **超宽的行解析成括号树。** 只在 `.standard` 类型的 atom 里找括号;类型名、模块名、关键字、声明名、注释等其它 atom 整体当作文字。字符串字面量、反引号标识符、`//` 之后的内容是文字;`->` 不是括号。括号不配对(例如 dump 里的运算符声明)就整行原样保留。 +3. **找出放不下的类型。** 不在其它泛型参数列表里面的泛型参数列表,算作一个类型的最外层;它的 `>` 落在第 `maximumLineWidth` 列之后,这个类型就算放不下。只有泛型参数列表会触发拆行;行之所以超宽是因为别的东西(一长串参数、行尾注释),这一行不动。 +4. **放不下的类型按结构规则拆。** 在这个类型内部:有两个及以上参数的泛型参数列表一律每个参数一行;单参数的泛型参数列表、元组、函数类型的参数列表、`[…]` 集合语法糖,只在某个元素已是多行时才拆。 +5. **外层括号跟着拆。** 类型之外的括号——函数声明的参数列表、enum case 的 payload、元组、泛型签名(紧跟在声明名后面的 `<…>`,以及里面写着 `where`、`A: P` 或 `==` 的 `<…>`)、attribute 的参数——只在某个元素已是多行时才拆,否则保持一行。泛型签名因此不会仅仅因为有两项就被拆开。 +6. **拆开的列表这样排。** 开括号留在原行末尾;每个参数另起一行,缩进为这一行的行首缩进加 4 个空格乘以嵌套层数;参数之间的 `, ` 变成 `,`;闭括号另起一行,缩进回到上一层。 + +截图里那个 `Body` 的开头一段,按默认宽度格式化后是这样: + +```swift +extension SettingsApp.SettingsNavigationSplitView: SwiftUI.View { + typealias Body = SwiftUI.ModifiedContent< + SwiftUI.ModifiedContent< + SwiftUI.SceneBridgeReader< + SwiftUI.SubscriptionView< + Combine.PassthroughSubject< + Any, + Swift.Never + >, + SwiftUI.NavigationSplitView< + SwiftUI.ModifiedContent< + SettingsApp.SettingsSidebarList, + SwiftUI.ToolbarRemovingModifier + >, + SettingsApp.SettingsSecondaryColumn + > + > + >, + SwiftUI._EnvironmentKeyWritingModifier + >, + SwiftUI.OnTestViewModifier + > +} +``` + +同一个文件里放得下的类型不受影响: + +```swift +var result: Swift.Result +var selection: SwiftUI.Binding> +``` + +函数签名里有一个类型放不下时,参数列表随之拆开,其余参数保持一行: + +```swift +func update( + model: Swift.Result, + content: SwiftUI.ModifiedContent< + SwiftUI.TupleView<…>, + SwiftUI._EnvironmentKeyWritingModifier + > +) -> Swift.Bool +``` + +接入点只有调用方的出口:`InterfaceRequest` 与 `DumpRequest` 各加一个 `multilineTypeFormatting: MultilineTypeFormatting?` 字段(默认 `nil`),在交出产物前调用一次;CLI 的 `dump` 与 `interface` 加 `--multiline-types` 与 `--maximum-line-width `。RuntimeViewer 在 `RuntimeSwiftSection` 缓存 `RuntimeObjectInterface` 之前调用一次(下游后续改动,不在本提案的实现范围内)。打印器、`SwiftDeclarationPrintConfiguration` 与 `DeclarationRenderConfiguration` 都不改。 + +### 非目标 + +- **不改打印器。** `SwiftPrinting`、`SwiftDump`、上游 swift-demangling 与 swift-semantic-string 一行不动;默认关闭时所有输出逐字节不变,fixture baseline 与渲染 A/B 不受影响。 +- **diff、evolution、snapshot 不接。** diff 与 evolution 的输出按行标记增删,拆行会让一个声明的标记散到多行;snapshot 是 JSON。这三个请求不加字段。 +- **ObjC 输出不接。** `swift-section objc …` 打印的是 Objective-C 头文件,没有本提案要拆的 Swift 泛型。 +- **不单独拆长参数列表。** 一个函数声明有十个短参数而超宽,本提案不拆它;参数列表只在某个参数的类型被拆开时随之拆开。按行宽拆参数列表是另一个功能。 +- **不做 TypeAliasFormatter 的其它能力。** 单参数泛型也展开的 `expandSingleArguments`、2 / 8 空格或 Tab 缩进、类型树的图形视图都不做;`MultilineTypeFormatting` 是 struct,以后要加选项时加带默认值的属性即可。 +- **不解决 SwiftUI modifier 链缩进很深的问题。** `ModifiedContent, M>` 是向左嵌套的,二十多层 modifier 拆开后第一个参数会缩进二十多层。把这种链压平成一层需要按语义改写类型,不属于排版。 +- **RuntimeViewer 的设置界面与接入不在本提案里实现。** 本提案只交付库与 CLI;RuntimeViewer 的开关、调用与缓存失效由它自己的改动完成。 + +## 改动地图 + +| 文件 / 类型 | 动作 | 改什么 | 为什么 | 步骤 | +|---|---|---|---|---| +| `Sources/Output/SwiftDeclarationRendering/MultilineTypeFormatting.swift` · `MultilineTypeFormatting` | 新增 | 公开 struct:`maximumLineWidth`、`init(maximumLineWidth:)`、`format(_:)`;`format` 逐行调用下面三块 | dump 与 interface 共用的位置,RuntimeViewer 已依赖这个 product | 1 | +| `Sources/Output/SwiftDeclarationRendering/MultilineTypeFormatting+Lines.swift` · `MultilineTypeFormatting.Line`(internal) | 新增 | 把 atom 序列按 `\n` 切成行(切开的 atom 保留 type 与 identifier)、算行首缩进与内容宽度、把处理后的行拼回去 | 规则 1:宽度不超的行不解析,直接复制 | 1 | +| `Sources/Output/SwiftDeclarationRendering/MultilineTypeFormatting+BracketTree.swift` · `MultilineTypeFormatting.BracketTree`(internal) | 新增 | 把一行解析成括号树:只扫 `.standard` atom,字符串、反引号、`//`、`->` 当文字;括号种类分为泛型参数列表、泛型参数子句、圆括号、方括号;不配对返回 `nil` | 规则 2 | 2 | +| `Sources/Output/SwiftDeclarationRendering/MultilineTypeFormatting+Layout.swift` · `MultilineTypeFormatting.Layout`(internal) | 新增 | 判定放不下的类型、自下而上决定哪些列表拆开、按规则 6 生成 atom(插入的换行与缩进沿用相邻括号或逗号 atom 的 identifier) | 规则 3–6 | 3 | +| `Tests/SwiftDeclarationRenderingTests/MultilineTypeFormattingTests.swift` | 新增 | 行切分、解析、排版的单元测试,输入用手工拼的 `SemanticString`,形状与两套打印器的输出一致 | 每步的行为清单 | 1–3 | +| `Tests/SwiftDeclarationRenderingTests/MultilineTypeFormattingPreservationTests.swift` | 新增 | 保持性测试:semantic type 与 identifier 不变、去掉插入的换行能还原原文、幂等、与缩进可交换、region 读回不变 | 规则 6 的「只加换行和缩进」承诺 | 4 | +| `Tests/SwiftInterfaceTests/NestedDefinitionRegionContractTests.swift` | 修改 | 新变体 `everyOptionFormattedAsMultilineTypes`:父定义的打印与子定义自己的打印都按 30 列格式化后再比较;另加 `formattedVariantBreaksTheFixtureTypes`,确认 fixture 在这个宽度下真的有类型被拆开 | 嵌套定义契约在格式化后仍成立;复用这个套件的整套比较(文字、span、identifier、三种 region) | 4 | +| `Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift` · `InterfaceRequest` | 修改 | 新字段 `multilineTypeFormatting`(init 参数默认 `nil`),`run` 里 `printRoot()` 之后、写文件或交给 output 之前调用 | interface 的唯一出口 | 5 | +| `Sources/Commands/SwiftSectionKit/Swift/DumpRequest.swift` · `DumpRequest`、`DumpSession` | 修改 | 新字段 `multilineTypeFormatting`;`DumpSession.dump` 拿到 `dumpedDeclaration` 后调用 | dump 的唯一出口,一次一个顶层声明 | 5 | +| `Tests/SwiftSectionKitTests/MultilineTypeFormattingRequestTests.swift` | 新增 | 两个请求打开与关闭字段时的输出 | 接入正确、关闭时不变 | 5 | +| `Package.swift` · `swift-section`、`SwiftSectionKitTests` | 修改 | 两个 target 各加 `SwiftDeclarationRendering` 直接依赖 | SwiftSectionKit 不重新导出任何模块,调用方构造 `MultilineTypeFormatting` 要自己导入它 | 5 | +| `Tuist/CommandLine/Project.swift` · `commandLineDependencies` | 修改 | 加 `.external(name: "SwiftDeclarationRendering")` | 项目规定 `swift-section` 的新依赖同步进 Tuist 工程;测试目标的依赖由 `Package.swift` 末尾的映射自动带上 | 5 | +| `Sources/Executables/swift-section/Models/MultilineTypeOptionGroup.swift` · `MultilineTypeOptionGroup` | 新增 | `--multiline-types` flag、`--maximum-line-width ` option;`validate()` 拒绝单独给宽度和非正数宽度;`multilineTypeFormatting` 把两者换成请求要的值;帮助里的默认宽度取自 `MultilineTypeFormatting()` | 两个子命令共用一组参数,照 `ObjCMemberOptionGroup` 的做法放进 option group | 6 | +| `Sources/Executables/swift-section/Commands/InterfaceCommand.swift`、`DumpCommand.swift` | 修改 | `@OptionGroup(title: "Long Types")` 引入上面那组参数,`makeRequest()` 映射到 `multilineTypeFormatting` | CLI 是 SwiftSectionKit 的包装 | 6 | +| `Tests/SwiftSectionCommandTests/MultilineTypesFlagTests.swift` | 新增 | flag 映射到请求、校验错误的退出码 64 | CLI 两侧都要有测试 | 6 | +| `AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md` | 修改 | 写明两个新 flag 与默认宽度 | CLI 改动要同批更新这份 skill | 6 | +| `Documentations/SwiftSectionKit.md`、`Documentations/Internal/Modules/SwiftSectionKit.md` | 修改 | 两个请求的新字段 | 调用方指南与模块参考 | 7 | +| `CLAUDE.md` | 修改 | SwiftDeclarationRendering 一条补一句它还提供 `MultilineTypeFormatting` | 模块清单与代码同步 | 7 | +| `Documentations/Internal/ProjectEvolutionLog.md`、`Documentations/Glossary.md`、`Documentations/README.md`、`Documentations/Evolutions/README.md` | 修改 | 账本一节、术语 multiline type formatting / long type、索引 | 文档纪律 | 7 | + +## 架构图 + +改了什么: + +```text +SwiftDeclarationRendering ++ ├── MultilineTypeFormatting.swift public struct, format(_:) ++ ├── MultilineTypeFormatting+Lines.swift split atoms into lines, width gate ++ ├── MultilineTypeFormatting+BracketTree.swift parse one line into a bracket tree ++ └── MultilineTypeFormatting+Layout.swift decide breaks, emit atoms +SwiftSectionKit +~ ├── Swift/InterfaceRequest.swift + multilineTypeFormatting, applied after printRoot() +~ └── Swift/DumpRequest.swift + multilineTypeFormatting, applied per declaration in DumpSession +swift-section +~ ├── Commands/InterfaceCommand.swift + --multiline-types, --maximum-line-width +~ └── Commands/DumpCommand.swift + --multiline-types, --maximum-line-width +SwiftPrinting, SwiftDump, swift-demangling, swift-semantic-string (unchanged) +``` + +数据流: + +```text +SwiftDeclarationPrinter / Dumpable (unchanged: one line per declaration) + │ SemanticString + ▼ ++ MultilineTypeFormatting.format(_:) (only when the caller opts in) + │ SemanticString: same text, types, identifiers, regions; long types broken + ▼ +InterfaceRequest / DumpSession ──► SwiftSectionOutput / file +RuntimeSwiftSection (RuntimeViewer, follow-up) ──► RuntimeObjectInterface cache +``` + +`format(_:)` 内部: + +```text +format(source) +└── for each line (atoms split at "\n" keep type + identifier) + ├── content width (minus leading indentation) <= maximumLineWidth ──► copy unchanged + └── BracketTree(line) (.standard atoms only; strings, backticks, "//", "->" are text) + ├── nil (unbalanced) ──► copy unchanged + └── Layout + ├── outermost generic argument list whose ">" lies past the width ──► long type + ├── inside a long type: generic argument list with >= 2 arguments ──► break + ├── any list with a multi-line element ──► break (bottom-up) + └── emit "<" "\n" indent(L + 4k) element "," "\n" … "\n" indent(L + 4(k - 1)) ">" +``` + +## 详细设计 + +### 公开 API + +```swift +/// Lays the long types of printed Swift source out over several lines. +/// +/// A type that runs past `maximumLineWidth` is broken at its brackets: every +/// generic argument list with two or more arguments puts each argument on a +/// line of its own, and a single-argument generic list, a tuple, a parameter +/// list or collection sugar breaks only when one of its elements spans +/// several lines. A type that fits, and every line that fits, stays as +/// printed. +/// +/// Formatting only adds line breaks and indentation, and drops the space of +/// each `, ` between broken elements: the text otherwise, every component's +/// semantic type and identifier, and so every visibility, definition and +/// annotation region, stay as they were. +public struct MultilineTypeFormatting: Hashable, Sendable { + /// The widest a line's content may be, in characters. A line's own + /// indentation does not count, so a declaration breaks the same way at + /// any nesting depth. + public var maximumLineWidth: Int + + /// - Precondition: `maximumLineWidth > 0`. + public init(maximumLineWidth: Int = 100) + + /// `source` with its long types laid out over several lines. + public func format(_ source: SemanticString) -> SemanticString +} +``` + +`SwiftSectionKit`: + +```swift +extension InterfaceRequest { + /// Lays long types out over several lines; `nil` prints every type on one line. + public var multilineTypeFormatting: MultilineTypeFormatting? { get set } +} + +extension DumpRequest { + public var multilineTypeFormatting: MultilineTypeFormatting? { get set } +} +``` + +两个请求的 memberwise `init` 各加一个参数 `multilineTypeFormatting: MultilineTypeFormatting? = nil`,放在 `commentTransformers` 之前,与现有的带默认值参数同列。 + +CLI(`dump` 与 `interface` 相同): + +```text +--multiline-types Break a type that runs past the line width over several lines, at its brackets. +--maximum-line-width The widest a line may be, not counting its indentation, before + --multiline-types breaks its types. (default: 100) +``` + +`validate()`:给了 `--maximum-line-width` 却没给 `--multiline-types`,或宽度不是正数,抛 `ValidationError`(退出码 64)。 + +### 行与宽度 + +- `format` 先把 `source.components` 按 `\n` 切成行。一个 atom 内含 `\n` 时在 `\n` 处切开,各段保留原 atom 的 `type` 与 `identifier`;`\n` 本身单独成段,原样输出。 +- 行首缩进是这一行开头连续空格的个数 `L`(跨 atom 计)。内容宽度是这一行的 `Character` 数减去 `L`。 +- 内容宽度不超过 `maximumLineWidth` 的行,其 atom 原样复制,不做任何解析。绝大多数行走这条路,`format` 的开销主要是一次按行扫描。 +- 行之间互不影响:括号跨行的输入(例如已经格式化过的输出)里,每一行单独看都不配对,因此原样保留——这正是 `format` 幂等的原因。 + +### 括号树 + +```swift +extension MultilineTypeFormatting { + enum BracketKind { + case genericArguments // "<" after anything but a declaration name + case genericParameters // "<" right after a declaration name + case parentheses // "(": tuples, function types, parameter lists, attribute arguments + case squareBrackets // "[": array and dictionary sugar + } + + indirect enum BracketTreeNode { + /// A run of a line's characters that is not a bracket, located by atom index and range. + case text(AtomRun) + /// A bracketed list: the opening and closing brackets' locations and the elements between the commas. + case list(kind: BracketKind, opening: AtomPosition, closing: AtomPosition, separators: [AtomPosition], elements: [[BracketTreeNode]]) + } +} +``` + +- 只有 `.standard` atom 参与扫描;其它 semantic type 的 atom 整体是一个 `text`。这样类型名、声明名(包括 interface 里的运算符名)、注释里的括号都不会被当成结构。 +- 在 `.standard` atom 里:`"` 开始一个字符串字面量,到未转义的 `"` 结束;反引号同理;`//` 之后到行末都是文字;`-` 紧跟 `>` 是箭头,不关闭任何列表;`<`、`(`、`[` 开列表,`>`、`)`、`]` 必须关闭同种列表;深度大于 0 时的 `,` 分隔元素。 +- `<` 前面(跳过空白)的 atom 的 semantic type 是 `.type(_, .declaration)`、`.function(.declaration)` 或 `.member(.declaration)` 时,这个列表是 `genericParameters`;否则是 `genericArguments`。闭括号读到时再看一次:有一项在自己这一层(不算嵌在里面的列表)写着 `where` 这个词、`: `(冒号后带空格)或 `==`,这是 dump 写在类型名后面的泛型签名(`_ConditionalContent< where A: P, B: Q>`、`make`),也改为 `genericParameters`。类型参数里不会出现这三种:模块选择器的 `::` 与 dump 的 `(extension in M):` 前缀冒号后没有空格,元组的标签在它自己的列表里。 +- 关闭括号与种类不符、或行末仍有未关闭的列表,返回 `nil`,整行原样保留。dump 里的 `static func < infix(…)` 就走这条路。 + +### 排版 + +- **放不下的类型。** 只看「不在任何 `genericArguments` 里面」的 `genericArguments` 列表:它的闭括号 `>` 的内容列号(相对行首缩进,从 1 数)大于 `maximumLineWidth`,就把它标为长类型的根。列号按这一行原样打印时的位置算。 +- **决定拆哪些列表**,自下而上: + - 长类型根及其内部的 `genericArguments`,元素数不少于 2 时拆。 + - 任何列表,有元素是多行时拆(元素多行 = 元素里有被拆的列表)。 + - 其余不拆。长类型根之外的 `genericArguments` 内部不会有被拆的列表,因此整体保持一行。 +- **生成 atom。** 对每个要拆的列表,嵌套层数 `k` 是它自身加上包住它的被拆列表的个数: + - 开括号 atom 原样输出,后面插入 `\n` 与 `L + 4k` 个空格的缩进 atom; + - 每个元素去掉首尾空白后输出; + - 元素之间的分隔:原来的 `, `(或 `,`)atom 换成只含 `,` 的 atom(type 与 identifier 不变),后面插入 `\n` 与缩进; + - 闭括号前插入 `\n` 与 `L + 4(k − 1)` 个空格; + - 插入的 atom 都是 `.standard`。开括号与逗号之后的换行和缩进取那个开括号或逗号 atom 的 `identifier`;闭括号之前的换行和缩进取闭括号 atom 的 `identifier`——不取它前面那个元素的,因为元素的最后一个 atom 往往是带着类型引用 identifier 的类型名,换行不该算进那个引用。括号若和别的字符在同一个 atom 里,就在括号处切开,各段保留原 type 与 identifier。 + - 有任何一行被改时,结果按 atom 一个元素重建(`SemanticString(components:)`),不保留输入的元素边界——公开 API 读不到元素边界;所以 `format` 用在打印完成的结果上,不用在还要拼进容器的半成品上。没有任何一行被改时直接返回输入本身。 +- 一个列表为空(`()`)时从不拆。 + +### 保持性 + +以下性质是公开承诺,各有测试: + +1. 内容宽度不超的行逐 atom 不变。 +2. 去掉插入的换行与缩进、把被改的 `,` 还原成 `, `,得到与输入相同的文字。 +3. 每个原有字符所在 atom 的 semantic type 与 identifier 不变;冻结后各种 region 分离出来与格式化前相同(位置随文字平移)。 +4. 幂等:`format(format(x)) == format(x)`。 +5. 与缩进可交换:把输入每个非空行多缩进 4 个空格再格式化,等于先格式化再多缩进 4 个空格。由此,格式化后的父定义里取出的嵌套定义,等于嵌套定义单独打印再格式化。 + +## 替代方案考量 + +- **纯按行宽、逐层决定(Wadler / Oppen 式的 group)。** 每个括号列表一行放得下就不拆。否:同一个类型嵌在不同深度时排版不同;短的多参数泛型时拆时不拆,读者没法靠形状认出结构。用户在澄清提问里否掉了。 +- **完全照 TypeAliasFormatter,不看行宽。** 否:适用于所有类型位置后,每个 `Swift.Result`、`Swift.Dictionary<…>` 都会被拆成多行,整份 interface 变长数倍。用户在澄清提问里否掉了。 +- **在打印器里拆:打印泛型参数时直接写换行或「可断点」标记。** 否:类型来自两套打印器(本仓库的 `SwiftPrinting` 与上游 swift-demangling 的 `NodePrinter`),要改两处并给上游的 `NodePrinterTarget` 加要求——这个协议刻意不给默认实现,加一条要求就要上游发版、所有 target 都改;打印器按节点身份 memoize 的片段会带上依赖列号的排版决定;嵌套定义契约要求的「只有缩进随层级变化」也得在递归里处处维护。 +- **做成 `SwiftDeclarationPrintConfiguration` 的选项,由每个公开打印入口在返回前格式化。** 否:公开入口有二十来个且互相调用(嵌套类型会再次进入 `printTypeDefinition`),要么重复格式化,要么把每个入口拆成「公开入口 + 内部实现」;dump 的 `DeclarationRenderConfiguration` 还得另接一遍。三个真正的调用方(两个请求、RuntimeViewer)都只有一个出口,在出口调用一次更简单。 +- **在纯文本上格式化(照搬 TypeAliasFormatter 的做法)。** 否:会丢掉 semantic type、identifier 与 region,RuntimeViewer 的着色、跳转与嵌套定义拆分都依赖它们。 +- **扫描所有 atom 的所有字符。** 否:interface 里运算符名、私有类型名 `(Visitor in $…)` 等 atom 也含括号;只扫 `.standard` atom,再对不配对的行放弃,误判面最小。 + +## 影响 + +### 源码兼容性(source compatibility) + +纯新增。`MultilineTypeFormatting` 是新类型;`InterfaceRequest` 与 `DumpRequest` 的新字段和 init 参数都有默认值 `nil`,现有调用点不受影响;CLI 新增的两个参数不改变任何已有参数的含义与默认输出。 + +### ABI 兼容性(条件项) + +不适用 —— 本库以 SPM 源码分发,使用方每次重新编译。 + +### 下游影响 + +- 本仓库:`SwiftDeclarationRendering` 加文件;`SwiftSectionKit` 与 `swift-section` 加字段与参数。打印器、索引、ABI 层不动。 +- **RuntimeViewer**:要用这个功能,需要在设置里加一个开关(可附宽度),在 `RuntimeSwiftSection` 生成 `RuntimeObjectInterface` 之前(`RuntimeSwiftSection.swift:364`)调用 `format`,并在开关变化时清掉 `interfaceByObject` 缓存。它已依赖 `SwiftDeclarationRendering`,不必改依赖声明。这是 RuntimeViewer 自己的后续改动。 +- MachOKitUI、SymbolViewer:不受影响。 + +### 文档与示例 + +- `AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md`:两个新 flag。 +- `Documentations/SwiftSectionKit.md`(调用方指南)与 `Documentations/Internal/Modules/SwiftSectionKit.md`:新字段。 +- `CLAUDE.md` 的模块清单:SwiftDeclarationRendering 一条。 +- 发版时 `Changelogs/.md` 写一条。 + +## API 演进与废弃策略 + +- 不替代任何旧 API,没有废弃。 +- 以后要加 TypeAliasFormatter 的「单参数泛型也展开」、其它缩进宽度等选项时,给 `MultilineTypeFormatting` 加带默认值的存储属性,现有调用点不变;不把它改成 enum。 +- 不需要 semver major 跃迁。 + +## 落地步骤 + +1. **骨架:类型、行切分与宽度闸门**(已完成) —— 改动地图第 1、2、5 行 + - 行为:`emptySourceIsUnchanged` + - 行为:`linesWithinWidthAreUnchangedAtomForAtom` + - 行为:`contentWidthIgnoresLeadingIndentation` + - 行为:`atomsContainingLineBreaksAreSplitKeepingTypeAndIdentifier` + - 行为:`nonPositiveWidthIsAPreconditionFailure`(exit test) +2. **括号树**(已完成) —— 改动地图第 3、5 行 + - 行为:`genericArgumentListsNestInsideParenthesesAndBrackets` + - 行为:`angleBracketAfterDeclarationNameIsGenericParameterClause` + - 行为:`arrowIsNotAClosingBracket` + - 行为:`bracketsInsideStringLiteralsAreText` + - 行为:`bracketsInsideBackticksAreText` + - 行为:`bracketsAfterLineCommentAreText` + - 行为:`bracketsInNonStandardAtomsAreText`(类型名、声明名、注释 atom) + - 行为:`unbalancedLineIsLeftUnchanged` + - 行为:`operatorDeclarationFromDumpIsLeftUnchanged`(`static func < infix(…)`) +3. **排版与生成**(已完成) —— 改动地图第 4、5 行 + - 行为:`multiArgumentGenericBreaksOneArgumentPerLine` + - 行为:`singleArgumentGenericStaysInlineUnlessItsArgumentBreaks` + - 行为:`tupleBreaksOnlyWhenAnElementBreaks` + - 行为:`functionTypeParametersBreakOnlyWhenAParameterBreaks` + - 行为:`collectionSugarBreaksOnlyWhenAnElementBreaks` + - 行为:`typeThatFitsStaysOnOneLineInAnOverlongLine` + - 行为:`overlongLineWithoutLongTypeIsUnchanged`(十个短参数、行尾长注释) + - 行为:`declarationParameterListBreaksWhenAParameterTypeBreaks` + - 行为:`genericParameterClauseDoesNotBreakForHavingTwoParameters` + - 行为:`continuationLinesIndentFromTheLineIndentation` + - 行为:`separatorLosesItsSpaceWhenBroken` + - 行为:`swiftUIBodyIsLaidOutByStructure`(本提案「提议方案」一节的例子) +4. **保持性与嵌套定义契约**(已完成) —— 改动地图第 6、7 行 + - 行为:`formattingKeepsSemanticTypesAndIdentifiers` + - 行为:`insertedLineBreaksCarryTheIdentifierOfTheirBracketOrComma` + - 行为:`unchangedLinesAroundAChangedLineKeepTheirComponents` + - 行为:`removingInsertedBreaksRestoresTheOriginalText` + - 行为:`formattingIsIdempotent` + - 行为:`formattingCommutesWithIndentation` + - 行为:`annotationAndVisibilityRegionsReadBackUnchanged` + - 行为:`NestedDefinitionRegionContractTests` 的 `everyOptionFormattedAsMultilineTypes` 变体(进程内与文件两种读取器) + - 行为:`formattedVariantBreaksTheFixtureTypes` +5. **SwiftSectionKit 接入**(已完成) —— 改动地图第 8、9、10 行与依赖清单两行 + - 行为:`requestsFormatNothingUnlessAsked` + - 行为:`interfaceRequestFormatsLongTypesWhenAsked`(产物等于把不格式化的产物整份格式化) + - 行为:`dumpRequestFormatsEachDeclarationWhenAsked`(每个声明等于把它不格式化的打印格式化) + - 行为:`interfaceWrittenToFileIsFormattedToo` +6. **CLI 与 agent 插件**(已完成) —— 改动地图第 11、12、13 行与 `MultilineTypeOptionGroup` 一行 + - 行为:`formattingIsOffByDefault` + - 行为:`multilineTypesFlagMapsOntoTheRequest` + - 行为:`maximumLineWidthMapsOntoTheRequest` + - 行为:`usageMistakesAreValidationErrors`(只给宽度、宽度不是正数,两个子命令都是退出码 64) + - 行为:`helpNamesTheDefaultWidth` + - 行为:插件 skill 里出现的每个 flag 都存在于对应子命令的 `--help`(逐个核对过);`claude plugin validate` 两项通过 +7. **文档**(已完成) —— 改动地图第 14、15、16 行 + - 行为:文档索引、账本、术语表、模块清单与代码一致;`SwiftSectionKit_zh.md` 与英文版同步 + +验证:每步 `swift build` 通过、本步新测试通过;收尾跑 `swift test --skip IntegrationTests` 全量。打印器不改、默认关闭,渲染 A/B 不适用(照 `SystemFrameworkRenderingVerification.md` 的判据,它针对改动打印、索引或读取器的重构),但会对一份真实 SwiftUI interface 打开格式化,记录 `format` 的耗时与输出行数,作为性能与效果的留档。 + +**收尾时必须判断两件事**(判断结果写进决策日志,不允许沉默跳过): + +- **要不要配套专题文章** —— 规则 1–6 与保持性承诺若在实现中出现代码看不出来的取舍(例如列号的算法、region 编码在切分 atom 时的处理),写一篇 `Documentations/Internal/MultilineTypeFormatting.md` 实现说明,登记到头部的「配套文档」。 +- **有没有引入新术语** —— 预计引入 multiline type formatting、long type(放不下的类型)两条,登记进 `Documentations/Glossary.md`。 + +## 决策日志 + +| 日期 | 变更 | 说明 | +|------|------|------| +| 2026-11-21 | Created as Draft | RuntimeViewer 里 SwiftUI 视图的 `typealias Body` 印成一行几千个字符,看不出泛型的层级,需要像展开括号一样按层拆行。 | +| 2026-11-21 | 规则选定 | 澄清提问后用户选定:一行放得下的类型不动,放不下的类型整个按 TypeAliasFormatter 的结构规则拆;适用于所有出现类型的位置;元组与函数类型的括号同样处理。纯按行宽和完全照 TypeAliasFormatter 两种都被否掉,理由见「替代方案考量」。 | +| 2026-11-21 | 接入方式 | 做成调用方在出口调用一次的纯格式化函数,不改打印器、不加打印配置项:两套打印器、互相调用的公开入口与嵌套定义契约都让「在打印器里拆」代价过高。 | +| 2026-11-21 | 宽度不计缩进 | 内容宽度减去行首缩进,使同一个声明在任何嵌套深度都拆得一样,`marksNestedDefinitions` 的契约不受影响。 | +| 2026-11-21 | Accepted | 用户批准,开始实现。功能分支 `feature/multiline-type-formatting`,从 `next` 切出。 | +| 2026-11-21 | 闭括号前的换行取闭括号的 identifier | 详细设计原写「取前一个括号或逗号的」;闭括号前面紧挨的是元素末尾,常是带类型引用 identifier 的类型名,换行不该算进那个引用的 span,所以改取闭括号自己的。 | +| 2026-11-21 | 不保留元素边界 | `SemanticString` 的元素边界没有公开读取的接口,有一行被改时结果按 atom 一个元素重建;文档注释写明 `format` 用于打印完成的结果。没有行被改时返回输入本身,边界原样。 | +| 2026-11-21 | 嵌套定义契约测试并入现有套件 | 改动地图原计划新建 `MultilineTypeFormattingNestedDefinitionTests.swift`;改为给 `NestedDefinitionRegionContractTests` 加一个格式化变体,直接复用它对文字、span、identifier 与三种 region 的整套比较。宽度取 30 列:fixture 的长泛型类型不多(主要是 `GenericFieldLayout` 各嵌套类型的字段),40 列下只有 4 个根类型有改动,30 列下新增约一百行。 | +| 2026-11-21 | 调用方直接依赖 `SwiftDeclarationRendering` | `SwiftSectionKit` 不重新导出任何模块,它的公开字段类型 `MultilineTypeFormatting` 由调用方自己导入:`swift-section` 与 `SwiftSectionKitTests` 各加一条直接依赖,Tuist 的命令行工程同步加上。不为一个类型在 Kit 里开 `@_exported`,与 Kit 现有字段(`Transformer.SwiftConfiguration` 等)的做法一致。 | +| 2026-11-21 | 尖括号里写着要求的是泛型签名 | 对系统 SwiftUI 跑 `dump --multiline-types` 时发现:dump 把受约束扩展的上下文印成 `_ConditionalContent< where A: P, B: Q>`,这个 `<…>` 跟在类型名后面,被当成两个泛型参数拆开了。规则补一条:`<…>` 里有一项在自己这一层写着 `where`、`A: P`(冒号后带空格)或 `==`,就是泛型签名,按泛型参数子句处理(只在元素已是多行时才拆)。模块选择器的 `::` 与 dump 的 `(extension in M):` 前缀冒号后都没有空格,不受影响。先写了变红的测试 `angleBracketsHoldingRequirementsAreAGenericSignature`、`genericSignatureIsNotBrokenForItsRequirements`,修复后通过;另加 `moduleSelectorsAndExtensionContextsLeaveAnArgumentList`、`moduleSelectorsStillBreakAsArguments` 守住不误判。 | +| 2026-11-21 | 不跑全量,以定向测试交付 | 机器负载高,全量两次开跑都停掉了;`swift test` 没法把进程限制在指定核数(`SWT_EXPERIMENTAL_MAXIMUM_PARALLELIZATION_WIDTH` 只限同时跑几个测试,测试内部建索引照样铺满全部核)。用户决定以定向测试交付:本提案涉及的八个套件都通过。功能默认关闭、打印器未改,关闭时的输出由构造保证不变。 | +| 2026-11-21 | 实现完成,待用户看过后收尾 | 文档判断:不另写实现说明,规则与取舍都在本提案和 `MultilineTypeFormatting` 的文档注释里;新术语 long type / multiline type formatting 已登记进 `Documentations/Glossary.md`;`SwiftSectionKit.md`(中英)、`Modules/SwiftSectionKit.md`、agent 插件 skill、`AGENTS.md` 模块清单、演进账本同批更新。RuntimeViewer 的开关与调用是它自己的后续改动。 | +| 2026-11-21 | Implemented | 用户决定正式收尾:落地为 0102,演进账本第 148 节;合进 `next` 并推送。RuntimeViewer 的接入另由它自己的提案落地。 | diff --git a/Documentations/Evolutions/0103-cross-reference-test-scan-load.html b/Documentations/Evolutions/0103-cross-reference-test-scan-load.html new file mode 100644 index 000000000..72e654ccf --- /dev/null +++ b/Documentations/Evolutions/0103-cross-reference-test-scan-load.html @@ -0,0 +1,473 @@ + + + + + + +0103 - 跨引用测试的整份 cache 扫描限并发,Tuist 工作区里扫描模块在 Debug 下开优化 + + + + +
+ +
+

MachOSwiftSectionEvolutions0103

+

0103 跨引用测试的整份 cache 扫描限并发,Tuist 工作区里扫描模块在 Debug 下开优化

+
+
状态
Implemented
+
最后更新
2026-11-21
+
项目类型
库
+
原文
0103-cross-reference-test-scan-load.md
+
+
+ + + +
+ +
+

摘要

+

CrossReferenceAnalysisTests 里有四个测试辅助函数用不设上限的 DispatchQueue.concurrentPerform 扫描整份 dyld shared cache,Debug 构建下每次跑测试都把机器的全部核心占满好几分钟。本提案做两件事:

+
    +
  1. 测试限并发:新增全进程共用的扫描名额 ImageScanConcurrency,默认 max(2, 核心数 / 2),四处扫描改走它;Swift Testing 并行跑多个套件时,所有扫描加起来也不超过名额。另加源码扫描测试,禁止以后绕过它直接调 concurrentPerform。
  2. +
  3. Debug 提速:Tuist 开发工作区里,让 MachOCodeReferences、ARM64InstructionDecoding 在 Debug 配置下也用 -O 编译,去掉每条指令一次的 Swift 运行时元数据查找。
  4. +
+

库的公开 API、原生 MachOSwiftSection.xcworkspace、swift test 与 CI 的行为都不变。

+
+ +
+

要你定

+
+

已批准并实现,没有待定的事

+

开头约 35 秒仍会用满核心(Swift Testing 同时跑着二十多个测试);用户决定保持现状,不另外限制测试运行器的并行度。

+
+
+

实测结果(Ultra,Debug,-only-testing:CrossReferenceAnalysisTests)

+
    +
  • 耗时:约 14 分钟 → 约 1.5 分钟;xctest 累计 CPU 时间:约 234 分钟 → 约 14 分钟(约 17 倍)。
  • +
  • 四处扫描同时占用的线程不超过名额(采样最多 8 个,名额 14);开头约 35 秒的满核来自 Swift Testing 自身的并行。
  • +
  • Tuist 的 base 设置盖得过按配置写的 -Onone,后备写法没用上。
  • +
+
+
+ +
+

架构图

+
    +
  • 新增
  • +
  • 修改
  • +
  • 删除
  • +
  • 不变
  • +
+ +
+ + + Tests/CrossReferenceAnalysisTests/ + CrossReferenceAnalyzerTestsimagesReferencing(_:among:) + SwiftTypeReferenceTestsimagesReferencing(_:among:) + ObjectiveCClassReferenceTestsimagesReferencing(_:at:among:) + FunctionStartOutsideTextTestsimagesWithAStartOutsideText() + concurrentPerformevery core, per call + ImageScanConcurrencymax(2, cores / 2)process-wide permits + + + + + ImageScanConcurrencyTests + ParallelScanSourceTests + ScanThroughputBenchmarkTests (opt-in, unchanged) + + + Tuist/Package.swift targetSettings + optimizedScanSettings + MachOCodeReferencesDebug: -Onone → -O + ARM64InstructionDecodingDebug: -Onone → -O + CrossReferenceAnalysisDebug: -Onone (unchanged) + ObjCCodeReferencesDebug: -Onone (unchanged) + + + +
+

改了什么:四处调用点改走共用名额;Tuist 清单给两个扫描模块在 Debug 下开 -O。

+ +
+ + suite A concurrentPerform(n) + suite B concurrentPerform(m) + suite C concurrentPerform(k) + workers ≤ budget per calleach pulls the next indexfrom a shared cursor + permits (DispatchSemaphore)value = maximumConcurrentScansshared by every call in the process + scan one image, then signal() + + + + + + images being scanned at once, all suites together ≤ maximumConcurrentScans + +
+

名额在并行的套件之间共用:每次调用最多起「名额」个工作者,每扫一个镜像先取一个名额。

+ +
+ + + before: MachOCodeReferences at -Onone + ReferenceScanner.scanFunction(at:) + IndexingIterator<Range<Int>>.next() unspecialized + swift_getTupleTypeMetadata2 + one global lock, 28 threads contend + + + + + after: MachOCodeReferences at -O + ReferenceScanner.scanFunction(at:) + specialized, inlined integer loop + no runtime metadata lookup per instruction + + +
+

Debug 下热路径为什么慢:未特化的区间循环每走一步都查一次元组元数据,28 个线程争同一把锁。

+
+ +
+

改动地图

+
+ + + + + + + + + + + + + + + + + +
文件 / 类型动作改什么为什么步骤
Tests/CrossReferenceAnalysisTests/ImageScanConcurrency.swift · ImageScanConcurrency新增进程共用的名额 maximumConcurrentScans 与信号量,入口 concurrentPerform(iterations:execute:);私有的 IterationCursor四处扫描共用一份上限,并行的套件不叠加2
…/ImageScanConcurrencyTests.swift · ImageScanConcurrencyTests新增四个行为测试钉住「每个下标只跑一次」与「同时进行的不超过名额」2
…/CrossReferenceAnalyzerTests.swift · imagesReferencing(_:among:)修改DispatchQueue.concurrentPerform → ImageScanConcurrency.concurrentPerform不限并发的整份 cache 扫描3
…/SwiftTypeReferenceTests.swift · imagesReferencing(_:among:)修改同上同上3
…/ObjectiveCClassReferenceTests.swift · imagesReferencing(_:at:among:)修改同上同上(这次采样抓到的那处)3
…/FunctionStartOutsideTextTests.swift · imagesWithAStartOutsideText()修改同上同上3
…/ParallelScanSourceTests.swift · ParallelScanSourceTests新增禁止名额与基准之外直接调 DispatchQueue.concurrentPerform(;theScanDiscriminates以后新写的测试默认会照抄旧写法3
Tuist/Package.swift · optimizedScanSettings新增两个扫描模块 SWIFT_OPTIMIZATION_LEVEL = -O,并入 mergingSettings(...)Debug 下扫描的时间过半花在运行时元数据查找4
Documentations/Internal/TuistDevelopment.md修改「已知的坑」加一条:两个扫描模块在 Debug 下也开 -O,要调试时从名单里临时拿掉再生成Tuist 工作区与原生 workspace 的有意差异5
Documentations/Internal/FixtureTestingAndContinuousIntegration.md修改新增小节「整份 cache 扫描共用一份并发名额(2026-11-21)」记录设计来历5
AGENTS.md(CLAUDE.md 是它的符号链接)修改测试规则块加一条:并行扫描很多镜像的测试走 ImageScanConcurrency.concurrentPerformagent 默认会照抄旧写法5
Documentations/Internal/ProjectEvolutionLog.md修改落地时追加一节,节号按落地规则取每个非平凡批次记一节落地
Documentations/Evolutions/README.md、Documentations/README.md修改登记本提案索引现在 / 落地
+
+
+ +
+

详细设计

+
+ ImageScanConcurrency +
+
enum ImageScanConcurrency {
+    static let maximumConcurrentScans = max(2, ProcessInfo.processInfo.activeProcessorCount / 2)
+
+    private static let permits = DispatchSemaphore(value: maximumConcurrentScans)
+
+    static func concurrentPerform(iterations: Int, execute body: (Int) -> Void) {
+        guard iterations > 0 else { return }
+        let cursor = IterationCursor(iterationCount: iterations)
+        DispatchQueue.concurrentPerform(iterations: min(maximumConcurrentScans, iterations)) { _ in
+            while let index = cursor.next() {
+                permits.wait()
+                defer { permits.signal() }
+                body(index)
+            }
+        }
+    }
+}
+
    +
  • 每次调用也限工作者数:只靠信号量的话,多出来的线程全阻塞在 permits.wait() 上,workqueue 还会补新线程;先限工作者数,阻塞线程就有上界。
  • +
  • 不会卡死:名额只在扫一个镜像期间持有,扫描是同步 CPU 工作,不等线程池;调用线程即便是 cooperative thread,等的也是不需要池线程的扫描线程归还名额。嵌套调用会卡死,文档注释写明禁止。
  • +
  • CI:3 核 runner 上 3 / 2 = 1,取下限 2。
  • +
+
+
+
+ 调用点与源码扫描测试 +
+

四处调用点只把 DispatchQueue.concurrentPerform(iterations:) 换成 ImageScanConcurrency.concurrentPerform(iterations:),闭包体、ImageIndexCollector 与 flagsBase 写法都不变。

+

ParallelScanSourceTests 照 MemoryAccessScanTests 的写法:从 #filePath 取本 target 目录,逐行扫 .swift 文件、跳过注释行,匹配 DispatchQueue.concurrentPerform(;允许名单是 ImageScanConcurrency.swift 与 ScanThroughputBenchmarkTests.swift。

+
+
+
+ Tuist/Package.swift 与后备写法 +
+
let optimizedScanSettings: [String: Settings] = Dictionary(
+    ["MachOCodeReferences", "ARM64InstructionDecoding"].map { targetName in
+        (targetName, Settings.settings(base: ["SWIFT_OPTIMIZATION_LEVEL": "-O"]))
+    },
+    uniquingKeysWith: { first, _ in first }
+)
+

并入 mergingSettings(...);键与其它几组不重叠。若第 4 步发现 base 覆盖不了生成工程里按配置写的 -Onone,改用 Settings.settings(configurations: [.debug(name: .debug, settings: ["SWIFT_OPTIMIZATION_LEVEL": "-O"])]),并让 mergingSettings 连 configurations 一起合并。

+
+
+
+ 怎么量 +
+
    +
  • 同机没有别的测试在跑时量,TUIST_SCRIPT_ROOT 用 agent 专属目录。
  • +
  • 先 queued-build ./TuistScript.sh build --scheme "MachOSwiftSection Tests" 排除编译,再 queued-build ./TuistScript.sh test --scheme "MachOSwiftSection Tests" -- -only-testing:CrossReferenceAnalysisTests。
  • +
  • 每 10 秒读一次 ps -o %cpu=,time= -p <xctest pid>,取峰值与最后的累计 CPU 时间;墙钟时间取 .xcresult。成败只认原始退出码。
  • +
+
+
+
+ +
+

调研

+
+ 采样数据与代码位置 +
+
    +
  • 2026-11-21,Ultra(28 核):xctest 持续 2369% CPU,跑了 8 分多钟仍未结束;28 个工作线程全在 ObjectiveCClassReferenceTests.imagesReferencing → CrossReferenceAnalyzer.references(to:inImageAt:) → ReferenceScanner.scanFunction(at:)。
  • +
  • 工作线程约 11 600 个样本:栈顶是元组元数据缓存 LockingConcurrentMap<TupleCacheEntry>::getOrInsert 的 4762 个(约 41%);经过 swift_getTupleTypeMetadata2 的约 46%,泛型元数据实例化约 13%。
  • +
  • 热点循环:RegisterFile.swift:148(for register in 0 ... 18)、RegisterFile.swift:48、ReferenceScanner.swift:150 与 :292(逐条指令的循环),都在 MachOKitExtensions 的 MachOCodeReferences。
  • +
  • 栈顶前 30 名里的自家函数只来自 MachOCodeReferences 与 ARM64InstructionDecoding;两者都没有 assert,-O 不丢检查。
  • +
  • Release 下整份 cache 两三秒扫完(AGENTS.md);Debug 要几分钟(ObjectiveCClassReferenceTests 注释)。
  • +
  • 先例:ConcurrentDefinitionPrintingTests.taskGroupWidth = max(2, activeProcessorCount / 2);测试 target 部署到 macOS 14,用 NSLock 而不是 Mutex。
  • +
  • Tuist 生成的工程在每个 target 的每个配置里写 SWIFT_OPTIMIZATION_LEVEL;base 能否覆盖未验证。
  • +
+
+
+
+ +
+

替代方案

+
+ 7 条,均已否决 +
+
    +
  • 改 MachOKitExtensions 的热点循环:swift test 也受益,但收益只有元数据那块、要发新版、写法变别扭;留作以后的选项。
  • +
  • 整个 Debug 工作区开 -O / 用 Release 跑测试:失去所有模块的调试能力,Release 还要另开 testability,范围远超问题。
  • +
  • CrossReferenceAnalysis、ObjCCodeReferences 也开 -O:采样里不是瓶颈;前者是本包最常调试的代码,还有一处 assert。
  • +
  • 每次调用各自限宽:并行的套件加起来又是满核。
  • +
  • 四个套件串行化:.serialized 只管套件内部,跨套件要重组结构。
  • +
  • 降低 QoS:CPU 照样占满;.background 会压到能效核,慢很多。
  • +
  • 用 concurrentMap(maximumConcurrency:):async、跑在 cooperative pool 上,且上限按调用各算各的。
  • +
+
+
+
+ +
+

影响

+
    +
  • 源码兼容性:纯新增,库的公开 API 不变。
  • +
  • ABI:不适用 —— 本库以 SPM 源码分发。
  • +
  • 下游:无;Tuist/Package.swift 只用于本仓库的开发工作区。
  • +
  • 并行的功能分支:feature/shared-macho-testing-support 也改了 FunctionStartOutsideTextTests.swift,合并时可能有小冲突。
  • +
  • API 演进:不适用,不需要版本号跃迁。
  • +
+
+ +
+

落地步骤

+
    +
  1. 量基线(不改代码)—— baselineWallTimeCpuTimeAndPeakAreRecordedInTheProposal
  2. +
  3. 加名额与测试 —— everyIterationRunsExactlyOnce、noMoreThanTheBudgetRunAtOnce、twoCallsAtOnceShareTheBudget、zeroIterationsReturnWithoutRunning;临时换回裸 concurrentPerform 确认上限相关的两条会失败
  4. +
  5. 四处调用点改走名额,加源码扫描测试 —— everyParallelScanGoesThroughTheSharedBudget、theScanDiscriminates,原有测试全部通过
  6. +
  7. Tuist 里两个模块开 -O —— debugConfigurationCompilesTheScanModulesOptimized、crossReferenceAnalysisStaysUnoptimizedInDebug;不通过就启用后备写法
  8. +
  9. 复测并更新文档 —— wholeCacheScansStayWithinTheBudget、wallTimeAndCpuTimeAreRecordedAgainstTheBaseline;原定的「xctest 峰值不超过名额」没有成立(开头约 35 秒是 Swift Testing 自身的并行);复测采样后决定不扩大 -O 名单
  10. +
+

收尾判断:预计不需要专题文章(设计来历进 FixtureTestingAndContinuousIntegration.md,Tuist 差异进 TuistDevelopment.md),不引入新术语。

+
+ +
+

决策日志

+
+ 15 条,最近一条:Implemented +
+
+ + + + + + + + + + + + + + + + + + + +
日期变更说明
2026-11-21Created as DraftUltra 上跑 Debug 测试时 xctest 长时间占满 28 核。采样定位到两个原因:四处不限并发的整份 cache 扫描,以及 Debug 下扫描循环每条指令都查一次运行时元数据。用户决定两项都改:测试限并发;Debug 提速走 Tuist 配置,不改 MachOKitExtensions 源码。按轻量档写提案。
2026-11-21Accepted用户批准,开始实现。
2026-11-21测量时临时套用另一分支的修复next 上 ./TuistScript.sh test 编不过:SwiftSectionTestingMacrosTests 报 Unable to resolve module dependency: 'SwiftSectionTestingMacros'。feature/shared-macho-testing-support 已经修了(Tuist 映射测试时把依赖宏 target 的测试也拿掉,改 Package.swift 两行),还没合进 next。本分支只在工作区里临时套用这两行来测量,不提交;改前改后在同样条件下量。
2026-11-21基线Ultra,next 的代码,Tuist Debug,-only-testing:CrossReferenceAnalysisTests:124 个测试用时 841 秒(Swift Testing 的报告);xctest 累计 CPU 时间约 234 分钟(约 14 030 秒,平均约 17 个核心);ps 读到的 %cpu 峰值 2356%。同机另有一个会话的 swift test 占着约 4 个核心。3 个失败是新 worktree 缺 SymbolTestsCore 夹具,按 AGENTS.md 链接主检出的 DerivedData 后解决,与本提案无关。
2026-11-21第 2 步验证入口临时换成裸 concurrentPerform 时,两条上限测试失败;只按调用限宽、不共用名额时,只有 twoCallsAtOnceShareTheBudget 失败,证明这条测试抓得住「名额必须全进程共用」。正式实现四条全过。
2026-11-21第 3 步验证把一处调用点临时改回 DispatchQueue.concurrentPerform 时 everyParallelScanGoesThroughTheSharedBudget 失败,恢复后通过。四个重型套件单独复测一次要十几分钟,与第 4 步之后的整批复测合并进行。
2026-11-21第 4 步验证base 里的 SWIFT_OPTIMIZATION_LEVEL 盖过了 Tuist 按配置写的值,后备写法不需要:重新生成后,MachOKitExtensions.xcodeproj 里 MachOCodeReferences、ARM64InstructionDecoding 的 Debug 配置是 -O,同工程没进名单的 MachOAddressResolution 仍是 -Onone;本包 MachOSwiftSection.xcodeproj 里 CrossReferenceAnalysis 的 Debug 仍是 -Onone。
2026-11-21第 5 步复测同一台 Ultra,同样条件(机器上没有别的测试在跑):127 个测试全部通过(3 个跳过);xctest 存活约 91 秒,累计 CPU 时间约 829 秒(基线约 14 030 秒,约 17 倍);第二次复测 93 秒、843 秒,结果一致。构建日志里 MachOCodeReferences 的编译命令带 -O。
2026-11-21偏离:开头约 35 秒仍满核ps 读到的 %cpu 在头 35 秒达到约 2500%,之后降到 300% 以下。在第 6 秒与第 20 秒各采样 3 秒:占着线程的是二十多个不同的测试(FileModeTests 建文件模式分析器、各种预筛测试、LargeStackThreadPool 的工作线程),每个测试一个线程,是 Swift Testing 按核心数并行跑测试,不是四处扫描。限制测试运行器自身的并行度超出本提案范围,原定的「峰值不超过名额」改为「四处扫描不超过名额」,
2026-11-21不扩大 -O 名单复测时在第 61 秒采样:只剩三个 FileModeTests 在跑,时间花在 ICU 正则与字符串查找上,运行时元数据查找已不显著,CrossReferenceAnalysis、ObjCCodeReferences 开 -O 收益不大,维持原名单。
2026-11-21收尾判断不需要专题文章:设计来历写进 FixtureTestingAndContinuousIntegration.md 的新小节,Tuist 差异写进 TuistDevelopment.md 的新小节,规则写进 AGENTS.md。没有引入新术语。
2026-11-21完整验证Tuist workspace 的 MachOSwiftSection Tests 整个 scheme(Debug,Ultra,带测量时同样临时套用的 Package.swift 两行):3005 个通过、0 失败、7 个跳过,634 秒。
2026-11-21实现完成,待用户看过后收尾功能分支已推送并在本地合进 next 的常驻检出(不推送);测量时临时套用的 Package.swift 两行没有提交。
2026-11-21不限制测试运行器的并行度用户决定保持现状:满核时间已从 14 分钟缩到开头约 35 秒,不再另写提案限制 Swift Testing 同时跑的测试数。
2026-11-21Implemented合进 next 并推送,编号 0103。没有新术语;不另写专题文章(设计来历在 FixtureTestingAndContinuousIntegration.md 与 TuistDevelopment.md 的新小节);演进账本记为第 149 节。next 上 ./TuistScript.sh test 编不过的问题(SwiftSectionTestingMacrosTests)不归本提案,由 feature/shared-macho-testing-support 修。
+
+
+
+
+ +
+
+ + diff --git a/Documentations/Evolutions/0103-cross-reference-test-scan-load.md b/Documentations/Evolutions/0103-cross-reference-test-scan-load.md new file mode 100644 index 000000000..4a93c4d6b --- /dev/null +++ b/Documentations/Evolutions/0103-cross-reference-test-scan-load.md @@ -0,0 +1,330 @@ +# 0103 - 跨引用测试的整份 cache 扫描限并发,Tuist 工作区里扫描模块在 Debug 下开优化 + +- **状态**: Implemented +- **作者**: JH +- **创建日期**: 2026-11-21 +- **最后更新**: 2026-11-21 +- **所属愿景**: 无 +- **关联提案**: [0099-tuist-workspace](0099-tuist-workspace.md)(本提案改的 Tuist 开发工作区) +- **实现分支 / PR**: `feature/cross-reference-test-scan-load`(从 `next` 切出,worktree `.worktrees/MachOSwiftSection-CrossReferenceTestScanLoad`) +- **配套文档**: 不另写专题文章;设计来历在 [FixtureTestingAndContinuousIntegration.md](../Internal/FixtureTestingAndContinuousIntegration.md) 的「整份 cache 扫描共用一份并发名额」,Tuist 一侧在 [TuistDevelopment.md](../Internal/TuistDevelopment.md) 的「扫描模块在 Debug 下也开优化」 +- **网页版**: 同目录同名的 `.html` + +## 摘要 + +`CrossReferenceAnalysisTests` 里有四个测试辅助函数用不设上限的 `DispatchQueue.concurrentPerform` 扫描整份 dyld shared cache,Debug 构建下每次跑测试都把机器的全部核心占满好几分钟。本提案做两件事: + +1. **测试限并发**:测试 target 里新增一个全进程共用的扫描名额 `ImageScanConcurrency`,默认 `max(2, 核心数 / 2)`,四处扫描改走它;Swift Testing 并行跑多个套件时,所有扫描加起来也不超过这个名额。另加一个源码扫描测试,禁止以后在这个 target 里绕过它直接调 `concurrentPerform`。 +2. **Debug 提速**:Tuist 开发工作区里,让采样中占满时间的两个扫描模块 `MachOCodeReferences`、`ARM64InstructionDecoding`(都在 MachOKitExtensions)在 Debug 配置下也用 `-O` 编译,去掉 Debug 下每条指令一次的 Swift 运行时元数据查找。 + +库的公开 API、原生 `MachOSwiftSection.xcworkspace`、`swift test` 与 CI 的行为都不变。 + +## 动机 + +- **跑一次测试,机器被占满好几分钟。** 2026-11-21 在 Ultra(M3 Ultra,28 核)上用 `./TuistScript.sh test` 跑 Debug 测试,xctest 进程持续占 2369% CPU(约 24 个核心),采样时已经跑了 8 分多钟、仍未结束。这台机器上 `queued-build` 不限核,测试期间同机的编译、其他 agent 会话和前台应用都被挤占。 +- **占满核心的是测试辅助函数,不是库本身。** 对 xctest 采样 3 秒(`sample 3`),28 个工作线程全部落在 `ObjectiveCClassReferenceTests.imagesReferencing(_:at:among:)` 里的 `concurrentPerform` → `CrossReferenceAnalyzer.references(to:inImageAt:)` → `ReferenceScanner.scanFunction(at:)`。四个同类辅助函数(见「前期调研」)都按镜像数开满并发,没有上限。 +- **Debug 下扫描慢在 Swift 运行时,而不是扫描算法。** 同一份采样里,工作线程约 11 600 个样本中,栈顶是 `LockingConcurrentMap::getOrInsert`(元组类型元数据缓存,带锁)的有 4762 个(约 41%);经过 `swift_getTupleTypeMetadata2` 的帧合计 5380 个(约 46%),再加泛型元数据实例化约 1510 个(约 13%)。来源是扫描热路径上的 `for … in` 区间循环:`-Onone` 下它们走 libswiftCore 里未特化的 `IndexingIterator.next()`,每走一步都要查一次元组元数据,28 个线程争同一把锁。按 AGENTS.md 的记载,Release 下整份 macOS shared cache 两三秒扫完;`ObjectiveCClassReferenceTests` 的注释则写明 Debug 构建「扫整份 cache 要几分钟」。 +- **只限并发不够。** 限到一半核心后,同样的工作要跑更久;不把 Debug 下的这份运行时开销去掉,测试总时长会明显变长。两件事要一起做。 + +## 前期调研 + +- **四处不限并发的整份 cache 扫描**(路径相对 `Tests/CrossReferenceAnalysisTests/`,行号取自 `next` 25c4515c): + - `CrossReferenceAnalyzerTests.swift:259` · `imagesReferencing(_:among:)` —— 调用者预筛的抽样复查 + - `SwiftTypeReferenceTests.swift:324` · `imagesReferencing(_:among:)` —— Swift 类型引用的预筛复查 + - `ObjectiveCClassReferenceTests.swift:196` · `imagesReferencing(_:at:among:)` —— ObjC 类引用的预筛复查(这次采样抓到的就是它) + - `FunctionStartOutsideTextTests.swift:25` · `imagesWithAStartOutsideText()` —— 对每个镜像建一次函数表 +- **不在范围内的 `concurrentPerform`**:`ScanThroughputBenchmarkTests.swift:48/64/90` 是吞吐基准,套件带 `.enabled(if: ScanThroughputBenchmarkEnvironment.outputPath != nil)`,要设 `CROSS_REFERENCE_BENCHMARK_OUTPUT` 才跑,量的就是全核吞吐;库内 `Sources/Support/Utilities/ConcurrentMap.swift`、`Sources/Commands/SwiftSectionKit/CrossReferences/ReferencesRequest.swift:146`、`Sources/Symbols/SwiftSymbols/SwiftSymbolIndexStore.swift:1757` 与 MachOKitExtensions 的 `RenamedReexportIndex.swift:45` 是给 CLI 与宿主用的,应当用满核心。 +- **Swift Testing 并行跑套件**:上面四处分属四个套件,`.serialized` 只约束套件内部。每次调用各自限宽的话,几个套件同时扫描时会叠加回满核,所以名额必须是全进程共用的。 +- **既有先例**:`Tests/SwiftPrintingTests/ConcurrentDefinitionPrintingTests.swift:70` 的 `taskGroupWidth = max(2, ProcessInfo.processInfo.activeProcessorCount / 2)`;收集结果的 `ImageIndexCollector`(`CrossReferenceAnalyzerTests.swift:325`)用 `NSLock`。测试 target 的部署版本在 SwiftPM 与 Tuist 下都是 macOS 14(`Tuist/Package.swift` 的 `testTargetSettings`),用不了要求 macOS 15 的 `Synchronization.Atomic` / `Mutex`,沿用 `NSLock`。 +- **热点循环的位置**(MachOKitExtensions 主检出,`Sources/Analysis/MachOCodeReferences/Scanning/`): + - `RegisterFile.swift:148` · `clobberCallerSavedRegisters()` 的 `for register in 0 ... 18` + - `RegisterFile.swift:48` · `Snapshot.meet(_:)` 的 `for register in 0 ..< RegisterFile.registerCount` + - `ReferenceScanner.swift:150`、`:292` · `scanFunction(at:)` 里逐条指令的 `for instructionIndex in 0 ..< instructionCount` + - 采样栈顶里自家函数还有 `RegisterFile.Snapshot.agrees(with:on:)`、`ReferenceScanner.scanFunction(at:)`(MachOCodeReferences)与 `ARM64InstructionWord.conditionalBranchTarget(_:at:)`(ARM64InstructionDecoding)。前 30 名里没有 `CrossReferenceAnalysis` 与 `ObjCCodeReferences` 的函数。 +- **开 `-O` 不会丢掉检查**:`MachOCodeReferences`、`ARM64InstructionDecoding` 里没有 `assert` / `assertionFailure`(`-O` 会去掉它们),`MachOCodeReferences` 的两处 `precondition` 在 `-O` 下保留。本包的 `CrossReferenceAnalysis` 有一处 `assert`,这也是它不进名单的原因之一。 +- **Tuist 工作区里这两个模块从源码编**:TuistDevelopment.md 写明原生 workspace 里的五个上游库(含 MachOKitExtensions)在两种依赖模式下都从源码编、不进二进制缓存,`PackageSettings.targetSettings` 按 target 名对它们生效(已有先例:`restatedTraitDefinitions` 给远程包 Capstone 加设置)。 +- **Tuist 生成的工程把优化级别写在每个配置里**:现有生成结果 `…/Dependencies//tuist-derived/Projects/MachOKitExtensions/MachOKitExtensions.xcodeproj/project.pbxproj` 中,每个 target 的 Debug 配置写 `SWIFT_OPTIMIZATION_LEVEL = "-Onone"`、Release 写 `"-O"`。**未验证**:`targetSettings` 的 `base` 是否覆盖这个按配置写的值。落地第 4 步先验证,不行就改用按配置的设置(见「详细设计」)。 +- **实测收益**(落地第 1、5 步,同一台 Ultra、同样条件):`CrossReferenceAnalysisTests` 从约 14 分钟降到约 1.5 分钟,xctest 累计 CPU 时间从约 234 分钟降到约 14 分钟(约 17 倍)。开头约 35 秒仍会用满核心,那是 Swift Testing 同时跑着二十多个测试,不是这四处扫描(见决策日志)。 + +## 提议方案 + +1. 测试 target 新增 `ImageScanConcurrency`:一个进程内共用的计数信号量(`DispatchSemaphore`,值为 `maximumConcurrentScans`),加一个与 `DispatchQueue.concurrentPerform(iterations:execute:)` 同形的入口。每次调用最多起 `maximumConcurrentScans` 个工作者,从共享游标领下一个下标,每扫一个镜像前先取一个名额、扫完归还。所以不管同时有几个套件在扫,正在扫描的镜像总数都不超过名额。 +2. 四处辅助函数把 `DispatchQueue.concurrentPerform(iterations:)` 换成 `ImageScanConcurrency.concurrentPerform(iterations:)`,闭包体不动。 +3. 新增源码扫描测试 `ParallelScanSourceTests`:这个 target 里除 `ImageScanConcurrency.swift` 与 `ScanThroughputBenchmarkTests.swift` 外,出现 `DispatchQueue.concurrentPerform(` 就失败;照项目惯例配一个 `theScanDiscriminates` 证明扫描本身能区分。 +4. `Tuist/Package.swift` 新增 `optimizedScanSettings`,给 `MachOCodeReferences`、`ARM64InstructionDecoding` 设 `SWIFT_OPTIMIZATION_LEVEL = -O`,并入 `PackageSettings.targetSettings`。本包自己的 `CrossReferenceAnalysis` 保持 Debug 不优化。 +5. 改前、改后各量一次 `CrossReferenceAnalysisTests` 的墙钟时间、xctest 的累计 CPU 时间与 CPU 占用峰值,写回本提案。 + +### 非目标 + +- **不改库代码**:不改 MachOKitExtensions 里的热点循环。那条路让 `swift test` 与原生 workspace 也受益,但要发 MachOKitExtensions 新版,这次不做(见「替代方案」)。 +- **不动库内与 CLI 的并发**:`ConcurrentMap`、`ReferencesRequest`、`SwiftSymbolIndexStore`、`RenamedReexportIndex` 照旧用满核心。 +- **不动吞吐基准**:`ScanThroughputBenchmarkTests` 要手动开启,量的就是全核吞吐。 +- **不改原生 workspace、`swift test` 与 CI**:CI 的 runner 只有 3 核,名额算出来是 2,与现在差别不大;CI 用 `swift test`,不经 Tuist,所以 `-O` 设置也碰不到它。 +- **名额不做成可配置**:不加环境变量;真要调,改 `maximumConcurrentScans` 一处。 +- **不改 RuntimeViewer 的 Tuist 工作区**:它有自己的 `TuistScript.sh` 与清单。 + +## 改动地图 + +| 文件 / 类型 | 动作 | 改什么 | 为什么 | 步骤 | +|---|---|---|---|---| +| `Tests/CrossReferenceAnalysisTests/ImageScanConcurrency.swift` · `ImageScanConcurrency` | 新增 | 进程共用的名额 `maximumConcurrentScans` 与信号量,入口 `concurrentPerform(iterations:execute:)`;私有的 `IterationCursor`(`NSLock` 保护的下一个下标) | 四处扫描共用一份上限,并行的套件不叠加 | 2 | +| `Tests/CrossReferenceAnalysisTests/ImageScanConcurrencyTests.swift` · `ImageScanConcurrencyTests` | 新增 | 四个行为测试(见落地步骤 2) | 钉住「每个下标只跑一次」与「同时进行的不超过名额」 | 2 | +| `Tests/CrossReferenceAnalysisTests/CrossReferenceAnalyzerTests.swift` · `imagesReferencing(_:among:)` | 修改 | `DispatchQueue.concurrentPerform` → `ImageScanConcurrency.concurrentPerform` | 不限并发的整份 cache 扫描 | 3 | +| `Tests/CrossReferenceAnalysisTests/SwiftTypeReferenceTests.swift` · `imagesReferencing(_:among:)` | 修改 | 同上 | 同上 | 3 | +| `Tests/CrossReferenceAnalysisTests/ObjectiveCClassReferenceTests.swift` · `imagesReferencing(_:at:among:)` | 修改 | 同上 | 同上(这次采样抓到的那处) | 3 | +| `Tests/CrossReferenceAnalysisTests/FunctionStartOutsideTextTests.swift` · `imagesWithAStartOutsideText()` | 修改 | 同上 | 同上 | 3 | +| `Tests/CrossReferenceAnalysisTests/ParallelScanSourceTests.swift` · `ParallelScanSourceTests` | 新增 | 扫本 target 源码,禁止名额与基准之外直接调 `DispatchQueue.concurrentPerform(`;`theScanDiscriminates` | 以后新写的整份 cache 测试默认会照抄 `concurrentPerform`,靠测试拦住 | 3 | +| `Tuist/Package.swift` · `optimizedScanSettings` | 新增 | 两个扫描模块 `SWIFT_OPTIMIZATION_LEVEL = -O`,并入 `mergingSettings(...)` | Debug 下扫描的时间过半花在运行时元数据查找 | 4 | +| `Documentations/Internal/TuistDevelopment.md` | 修改 | 「已知的坑」加一条:两个扫描模块在 Debug 下也开 `-O`,在 Tuist 里对它们打断点会看到优化后的代码;要调试时从名单里临时拿掉再生成 | 这是 Tuist 工作区与原生 workspace 的一处有意差异 | 5 | +| `Documentations/Internal/FixtureTestingAndContinuousIntegration.md` | 修改 | 新增一小节「整份 cache 扫描共用一份并发名额(2026-11-21)」:为什么要全进程共用、名额怎么算、哪些地方例外 | 记录设计来历 | 5 | +| `AGENTS.md`(`CLAUDE.md` 是指向它的符号链接) | 修改 | 「writing or modifying tests」块加一条:并行扫描很多镜像的测试走 `ImageScanConcurrency.concurrentPerform`,不直接调 `DispatchQueue.concurrentPerform` | agent 默认会照抄旧写法 | 5 | +| `Documentations/Internal/ProjectEvolutionLog.md` | 修改 | 落地时追加一节,节号按落地规则取 | 项目要求每个非平凡批次记一节 | 落地 | +| `Documentations/Evolutions/README.md`、`Documentations/README.md` | 修改 | 登记本提案(现在一次,落地改名时一次) | 索引 | 现在 / 落地 | + +## 架构图 + +改了什么: + +```text +Tests/CrossReferenceAnalysisTests/ + CrossReferenceAnalyzerTests.imagesReferencing(_:among:) + SwiftTypeReferenceTests.imagesReferencing(_:among:) + ObjectiveCClassReferenceTests.imagesReferencing(_:at:among:) + FunctionStartOutsideTextTests.imagesWithAStartOutsideText() +- └── DispatchQueue.concurrentPerform(iterations:) (every core, per call) ++ └── ImageScanConcurrency.concurrentPerform(iterations:) (one process-wide budget) ++ ImageScanConcurrency maximumConcurrentScans = max(2, activeProcessorCount / 2) ++ ImageScanConcurrencyTests ++ ParallelScanSourceTests no bare concurrentPerform outside the budget and the benchmark + ScanThroughputBenchmarkTests unchanged (opt-in, every core) + +Tuist/Package.swift PackageSettings.targetSettings ++ optimizedScanSettings ++ MachOCodeReferences SWIFT_OPTIMIZATION_LEVEL = -O (Debug too) ++ ARM64InstructionDecoding SWIFT_OPTIMIZATION_LEVEL = -O (Debug too) + CrossReferenceAnalysis unchanged (-Onone in Debug) + ObjCCodeReferences unchanged (-Onone in Debug) +``` + +名额怎么在并行的套件之间共用: + +```text +suite A ─ concurrentPerform(iterations: 1600) ─┐ workers ≤ maximumConcurrentScans per call +suite B ─ concurrentPerform(iterations: 110) ─┼─ each worker: cursor.next() → permits.wait() +suite C ─ concurrentPerform(iterations: 1700) ─┘ → scan one image → permits.signal() + +permits = DispatchSemaphore(value: maximumConcurrentScans) shared by every call in the process +⇒ images being scanned at once, across all suites ≤ maximumConcurrentScans +``` + +Debug 下热路径为什么慢(改前)与开 `-O` 后(改后): + +```text +ReferenceScanner.scanFunction(at:) MachOCodeReferences, -Onone +- for instructionIndex in 0 ..< instructionCount +- IndexingIterator>.next() libswiftCore, unspecialized +- Range.formIndex(after:) witness +- swift_getTupleTypeMetadata2 locked global cache, 28 threads contend ++ for instructionIndex in 0 ..< instructionCount MachOCodeReferences, -O ++ specialized and inlined integer loop no runtime metadata lookup +``` + +## 详细设计 + +### `ImageScanConcurrency` + +```swift +import Foundation + +/// How many images the test target's parallel scans may read at once: half of +/// the cores, at least two. A Debug scan of the whole shared cache keeps every +/// core it is given busy for minutes, and Swift Testing runs the suites holding +/// these scans in parallel — so the budget is one for the whole process, not +/// one per call, or four suites at once would add up to every core again. +enum ImageScanConcurrency { + static let maximumConcurrentScans = max(2, ProcessInfo.processInfo.activeProcessorCount / 2) + + private static let permits = DispatchSemaphore(value: maximumConcurrentScans) + + /// Runs `body` once for every index in `0 ..< iterations`, the way + /// `DispatchQueue.concurrentPerform(iterations:execute:)` does, with at most + /// `maximumConcurrentScans` bodies running at once across the process. + /// + /// `body` must not call this function again: a nested call waits for a + /// permit while its caller holds one, and with every permit held that way + /// nothing is ever released. + static func concurrentPerform(iterations: Int, execute body: (Int) -> Void) { + guard iterations > 0 else { return } + let cursor = IterationCursor(iterationCount: iterations) + DispatchQueue.concurrentPerform(iterations: min(maximumConcurrentScans, iterations)) { _ in + while let index = cursor.next() { + permits.wait() + defer { permits.signal() } + body(index) + } + } + } +} + +/// Hands out each index of `0 ..< iterationCount` once, to whichever worker asks first. +private final class IterationCursor: @unchecked Sendable { + private let lock = NSLock() + private let iterationCount: Int + private var nextIndex = 0 + + init(iterationCount: Int) { + self.iterationCount = iterationCount + } + + func next() -> Int? { + lock.lock() + defer { lock.unlock() } + guard nextIndex < iterationCount else { return nil } + defer { nextIndex += 1 } + return nextIndex + } +} +``` + +- **为什么每次调用也限工作者数**:只靠信号量的话,`concurrentPerform` 仍按核心数起线程,多出来的线程全阻塞在 `permits.wait()` 上;内核的 workqueue 看到线程阻塞还会补新线程。先把每次调用的工作者限到名额以内,阻塞的线程数就有上界(同时在扫的套件数 × 名额)。 +- **为什么不会卡死**:名额只在扫一个镜像的期间持有,扫描是同步的 CPU 工作,不等任何线程池上的工作,持有者总会归还。调用线程可能是 Swift Testing 的 cooperative thread(同步测试函数跑在它上面,`concurrentPerform` 也在调用线程上执行迭代),它在 `permits.wait()` 上等的是别的扫描线程归还名额,而那些线程不需要 cooperative pool。这与 AGENTS.md「不要让 cooperative thread 不设超时地等需要池线程的工作」不冲突。嵌套调用会卡死,文档注释写明禁止;四处调用点的闭包体都不嵌套。 +- **CI**:runner 3 核,`activeProcessorCount / 2 = 1`,取下限 2。CI 跑的是 `swift test`,同样经过这份名额。 + +### 调用点(以 `ObjectiveCClassReferenceTests` 为例) + +```swift +// before +DispatchQueue.concurrentPerform(iterations: imageIndices.count) { position in + let imageIndex = imageIndices[position] + … +} +// after +ImageScanConcurrency.concurrentPerform(iterations: imageIndices.count) { position in + let imageIndex = imageIndices[position] + … +} +``` + +闭包体、收集结果的 `ImageIndexCollector` 与 `FunctionStartOutsideTextTests` 的 `flagsBase` 写法都不变。 + +### `ParallelScanSourceTests` + +照 `MemoryAccessScanTests` 的写法:从 `#filePath` 取本 target 目录,逐行扫 `.swift` 文件,跳过 `//` 开头的行,匹配 `DispatchQueue.concurrentPerform(`;`ImageScanConcurrency.swift` 与 `ScanThroughputBenchmarkTests.swift` 两个文件名在允许名单里。`theScanDiscriminates` 断言:`DispatchQueue.concurrentPerform(iterations: n) {` 命中,`ImageScanConcurrency.concurrentPerform(iterations: n) {` 与注释行不命中。 + +### `Tuist/Package.swift` + +```swift + // A Debug build of the cross-reference scan spends most of its time in the Swift runtime, not in + // the scan: an unspecialized range loop looks tuple metadata up on every instruction, under one + // lock every thread shares, so CrossReferenceAnalysisTests' whole-cache scans take minutes instead + // of the seconds a Release build needs. The scan's two hottest modules compile optimized in every + // configuration here; this package's own CrossReferenceAnalysis stays debuggable. + // (Evolution proposal cross-reference-test-scan-load.) + let optimizedScanSettings: [String: Settings] = Dictionary( + ["MachOCodeReferences", "ARM64InstructionDecoding"].map { targetName in + (targetName, Settings.settings(base: ["SWIFT_OPTIMIZATION_LEVEL": "-O"])) + }, + uniquingKeysWith: { first, _ in first } + ) +``` + +并入 `PackageSettings(targetSettings: mergingSettings(warningSettings, restatedTraitDefinitions, testTargetSettings, testingSupportSettings, optimizedScanSettings), …)`。`mergingSettings` 合并的是各自的 build setting 键,`SWIFT_OPTIMIZATION_LEVEL` 与其它几组的键不重叠,它头上「keys never overlap」的注释仍然成立。 + +**`base` 覆盖不了按配置写的值时的后备**(第 4 步验证结果决定):改成 + +```swift +Settings.settings(configurations: [.debug(name: .debug, settings: ["SWIFT_OPTIMIZATION_LEVEL": "-O"])]) +``` + +并让 `mergingSettings` 连同 `configurations` 一起合并(现在它只合并 `base`,会把 `configurations` 丢掉)。这条后备只在验证失败时启用,结果记入决策日志。 + +### 怎么量 + +- 在不跑其它测试的时候量(同机别的 xctest 会争核心),`TUIST_SCRIPT_ROOT=/Volumes/DerivedData/Agents.noindex/claude/Tuist-MachOSwiftSection`。 +- 先 `queued-build ./TuistScript.sh build --scheme "MachOSwiftSection Tests"`,把编译排除在外;再 `queued-build ./TuistScript.sh test --scheme "MachOSwiftSection Tests" -- -only-testing:CrossReferenceAnalysisTests`。 +- 测试期间每 10 秒读一次 `ps -o %cpu=,time= -p `:取 `%cpu` 的峰值,以及进程结束前最后一次的累计 CPU 时间;墙钟时间取 `.xcresult` 里这个 target 的总耗时。 +- 测试成败按全局规则只认原始退出码。 + +## 替代方案考量 + +- **改 MachOKitExtensions 里的热点循环**(把 `for … in` 区间循环改成 Debug 下不查元数据的写法):`swift test`、原生 workspace 与 CI 都受益,但收益只有元数据那一块(估计快一倍左右,未实测),要发 MachOKitExtensions 新版本,热路径上的写法也变得不自然,以后新写的循环还会再犯。这次选了 Tuist 配置,这条留作以后 `swift test` 也嫌慢时的选项。 +- **整个 Debug 工作区开 `-O`,或用 Release 跑测试**:失去所有模块的调试能力;Release 下 `@testable import` 还要额外开 `ENABLE_TESTABILITY`,二进制缓存按配置分份,整套都要重做。范围远超问题本身。 +- **`CrossReferenceAnalysis`、`ObjCCodeReferences` 也开 `-O`**:采样栈顶的前 30 名里没有它们;`CrossReferenceAnalysis` 是本包自己的代码,最常被调试,还有一处 `assert` 会被 `-O` 去掉。等第 5 步的采样说明它们也是瓶颈再加。 +- **每次调用各自限宽,不共用名额**:Swift Testing 并行跑四个套件时,加起来又是满核。 +- **把四个套件串行化**:`.serialized` 只管套件内部;要跨套件串行得把它们挪进同一个父套件,改动面大,而且把不扫描的测试也拖慢了。 +- **降低扫描线程的 QoS 而不限并发**:CPU 照样占满,只是让出优先级;Apple Silicon 上 `.background` 还会把工作压到能效核,测试会慢很多。 +- **用库里现成的 `concurrentMap(maximumConcurrency:)`**(`Sources/Support/Utilities/BoundedConcurrentMap.swift`):它是 async 的 task group,测试是同步函数;在 cooperative thread 上跑这种同步的重活正是 AGENTS.md 要避免的;它的上限也是每次调用各算各的。 + +## 影响 + +### 源码兼容性(source compatibility) + +**纯新增**。改动全在测试 target 与 Tuist 开发清单里,库的公开 API 不变。 + +### ABI 兼容性(条件项) + +不适用 —— 本库以 SPM 源码分发,使用方每次重新编译。 + +### 下游影响 + +- 本仓库:只有 `CrossReferenceAnalysisTests`(四处调用点与三个新文件)和 Tuist 工作区的生成结果。 +- 下游仓库:无。`Tuist/Package.swift` 只用于本仓库的开发工作区,RuntimeViewer、MachOKitUI 等用的是 SwiftPM 清单。 +- **并行进行的功能分支**:`feature/shared-macho-testing-support` 也改了 `FunctionStartOutsideTextTests.swift`(19 行),合并时可能有小冲突;本提案只改其中一行调用。 + +### 文档与示例 + +- `Documentations/Internal/TuistDevelopment.md`、`Documentations/Internal/FixtureTestingAndContinuousIntegration.md`、`AGENTS.md`:见改动地图。 +- `Documentations/Internal/ProjectEvolutionLog.md`:落地时追加一节。 +- README、DocC、示例代码:无需改动(不涉及用法)。 + +## API 演进与废弃策略 + +不适用 —— 没有新增、修改或废弃任何公开 API,不需要版本号跃迁。 + +## 落地步骤 + +1. **量基线** —— 不改代码(已完成,数字见决策日志) + - 行为:`baselineWallTimeCpuTimeAndPeakAreRecordedInTheProposal`(按「怎么量」在 `next` 上量一次,数字写进决策日志) +2. **加名额与它的测试** —— 改动地图第 1、2 行(已完成) + - 行为:`everyIterationRunsExactlyOnce`(1000 次迭代,每个下标恰好执行一次) + - 行为:`noMoreThanTheBudgetRunAtOnce`(闭包里记录同时在跑的数目,最大值不超过 `maximumConcurrentScans`) + - 行为:`twoCallsAtOnceShareTheBudget`(两个线程同时调用,合计同时在跑的数目不超过名额) + - 行为:`zeroIterationsReturnWithoutRunning` + - 实现时临时把入口换成裸 `DispatchQueue.concurrentPerform`,确认后三条里与上限有关的两条会失败(证明测试抓得住),再换回来;这一步不提交。 +3. **四处调用点改走名额,加源码扫描测试** —— 改动地图第 3–7 行(已完成;四个套件原有的测试在第 5 步的整批复测里一起验证) + - 行为:`everyParallelScanGoesThroughTheSharedBudget` + - 行为:`theScanDiscriminates` + - 行为:四个套件原有的测试照旧全部通过 +4. **Tuist 里两个扫描模块开 `-O`** —— 改动地图第 8 行(已完成) + - 行为:`debugConfigurationCompilesTheScanModulesOptimized`(重新生成后,生成的 `MachOKitExtensions.xcodeproj` 里 `MachOCodeReferences`、`ARM64InstructionDecoding` 的 Debug 配置是 `-O`,构建日志里它们的编译命令带 `-O`) + - 行为:`crossReferenceAnalysisStaysUnoptimizedInDebug` + - 验证不通过就启用「详细设计」里的后备写法,再验证一次 +5. **复测并更新文档** —— 改动地图第 9–11 行(已完成) + - 行为:`wholeCacheScansStayWithinTheBudget`(采样里,四处扫描同时占用的线程不超过名额)。原先写的「xctest 的 `%cpu` 峰值不超过名额」没有成立:开头约 35 秒是 Swift Testing 自身的并行,见决策日志 + - 行为:`wallTimeAndCpuTimeAreRecordedAgainstTheBaseline` + - 复测时再采样一次;`CrossReferenceAnalysis` 或 `ObjCCodeReferences` 的帧占比明显时,把结论记进决策日志,再决定要不要扩大 `-O` 名单 + +**收尾时必须判断两件事**(判断结果写进决策日志,不允许沉默跳过): + +- **要不要配套专题文章** —— 预计不需要:设计来历写进 FixtureTestingAndContinuousIntegration.md 的新小节,Tuist 差异写进 TuistDevelopment.md 的「已知的坑」。 +- **有没有引入新术语** —— 预计没有:「扫描名额」只在本提案与那一小节里用,不登记术语表。 + +## 决策日志 + +| 日期 | 变更 | 说明 | +|------|------|------| +| 2026-11-21 | Created as Draft | Ultra 上跑 Debug 测试时 xctest 长时间占满 28 核。采样定位到两个原因:四处不限并发的整份 cache 扫描,以及 Debug 下扫描循环每条指令都查一次运行时元数据。用户决定两项都改:测试限并发;Debug 提速走 Tuist 配置,不改 MachOKitExtensions 源码。按轻量档写提案。 | +| 2026-11-21 | Accepted | 用户批准,开始实现。 | +| 2026-11-21 | 测量时临时套用另一分支的修复 | `next` 上 `./TuistScript.sh test` 编不过:`SwiftSectionTestingMacrosTests` 报 `Unable to resolve module dependency: 'SwiftSectionTestingMacros'`。`feature/shared-macho-testing-support` 已经修了(Tuist 映射测试时把依赖宏 target 的测试也拿掉,改 `Package.swift` 两行),还没合进 `next`。本分支只在工作区里临时套用这两行来测量,不提交;改前改后在同样条件下量。 | +| 2026-11-21 | 基线 | Ultra,`next` 的代码,Tuist Debug,`-only-testing:CrossReferenceAnalysisTests`:124 个测试用时 841 秒(Swift Testing 的报告);xctest 累计 CPU 时间约 234 分钟(约 14 030 秒,平均约 17 个核心);`ps` 读到的 `%cpu` 峰值 2356%。同机另有一个会话的 `swift test` 占着约 4 个核心。3 个失败是新 worktree 缺 `SymbolTestsCore` 夹具,按 AGENTS.md 链接主检出的 `DerivedData` 后解决,与本提案无关。 | +| 2026-11-21 | 第 2 步验证 | 入口临时换成裸 `concurrentPerform` 时,两条上限测试失败;只按调用限宽、不共用名额时,只有 `twoCallsAtOnceShareTheBudget` 失败,证明这条测试抓得住「名额必须全进程共用」。正式实现四条全过。 | +| 2026-11-21 | 第 3 步验证 | 把一处调用点临时改回 `DispatchQueue.concurrentPerform` 时 `everyParallelScanGoesThroughTheSharedBudget` 失败,恢复后通过。四个重型套件单独复测一次要十几分钟,与第 4 步之后的整批复测合并进行。 | +| 2026-11-21 | 第 4 步验证 | `base` 里的 `SWIFT_OPTIMIZATION_LEVEL` 盖过了 Tuist 按配置写的值,后备写法不需要:重新生成后,`MachOKitExtensions.xcodeproj` 里 `MachOCodeReferences`、`ARM64InstructionDecoding` 的 Debug 配置是 `-O`,同工程没进名单的 `MachOAddressResolution` 仍是 `-Onone`;本包 `MachOSwiftSection.xcodeproj` 里 `CrossReferenceAnalysis` 的 Debug 仍是 `-Onone`。 | +| 2026-11-21 | 第 5 步复测 | 同一台 Ultra,同样条件(机器上没有别的测试在跑):127 个测试全部通过(3 个跳过);xctest 存活约 91 秒,累计 CPU 时间约 829 秒(基线约 14 030 秒,约 17 倍);第二次复测 93 秒、843 秒,结果一致。构建日志里 `MachOCodeReferences` 的编译命令带 `-O`。 | +| 2026-11-21 | 偏离:开头约 35 秒仍满核 | `ps` 读到的 `%cpu` 在头 35 秒达到约 2500%,之后降到 300% 以下。在第 6 秒与第 20 秒各采样 3 秒:占着线程的是二十多个不同的测试(`FileModeTests` 建文件模式分析器、各种预筛测试、`LargeStackThreadPool` 的工作线程),每个测试一个线程,是 Swift Testing 按核心数并行跑测试,不是四处扫描。限制测试运行器自身的并行度超出本提案范围,原定的「峰值不超过名额」改为「四处扫描不超过名额」。 | +| 2026-11-21 | 不扩大 `-O` 名单 | 复测时在第 61 秒采样:只剩三个 `FileModeTests` 在跑,时间花在 ICU 正则与字符串查找上,运行时元数据查找已不显著,`CrossReferenceAnalysis`、`ObjCCodeReferences` 开 `-O` 收益不大,维持原名单。 | +| 2026-11-21 | 收尾判断 | 不需要专题文章:设计来历写进 FixtureTestingAndContinuousIntegration.md 的新小节,Tuist 差异写进 TuistDevelopment.md 的新小节,规则写进 AGENTS.md。没有引入新术语。 | +| 2026-11-21 | 完整验证 | Tuist workspace 的 `MachOSwiftSection Tests` 整个 scheme(Debug,Ultra,带测量时同样临时套用的 `Package.swift` 两行):3005 个通过、0 失败、7 个跳过,634 秒。 | +| 2026-11-21 | 实现完成,待用户看过后收尾 | 功能分支已推送并在本地合进 `next` 的常驻检出(不推送);测量时临时套用的 `Package.swift` 两行没有提交。 | +| 2026-11-21 | 不限制测试运行器的并行度 | 用户决定保持现状:满核时间已从 14 分钟缩到开头约 35 秒,不再另写提案限制 Swift Testing 同时跑的测试数。 | +| 2026-11-21 | Implemented | 合进 `next` 并推送,编号 0103。没有新术语;不另写专题文章(配套文档见头部);演进账本记为第 149 节。`next` 上 `./TuistScript.sh test` 编不过的问题(`SwiftSectionTestingMacrosTests`)不归本提案,由 `feature/shared-macho-testing-support` 修。 | diff --git a/Documentations/Evolutions/0104-shared-macho-testing-support.html b/Documentations/Evolutions/0104-shared-macho-testing-support.html new file mode 100644 index 000000000..61759c67a --- /dev/null +++ b/Documentations/Evolutions/0104-shared-macho-testing-support.html @@ -0,0 +1,441 @@ + + + + + + +0104 - 测试支持的通用部分迁入 MachOKitExtensions:两个包共用 MachOFixtureSupport 与 MachOTestingSupport + + + + +
+
+

MachOSwiftSectionEvolutions0104

+

0104 测试支持的通用部分迁入 MachOKitExtensions:两个包共用 MachOFixtureSupport 与 MachOTestingSupport

+
+
状态
Implemented
+
最后更新
2026-11-21
+
项目类型
库
+
原文
0104-shared-macho-testing-support.md
+
+
+ +
+
+

摘要

+

把本包测试支持里与 Swift 无关的部分搬到 MachOKitExtensions(下称 MKE),作为两个对外 product 发布,两个包从此共用一套。MachOFixtureSupport 不依赖 Testing:dyld cache 路径、打开 cache 与镜像、按本机架构选 slice、取进程内镜像、测试运行时用 xcrun 现编 dylib(clang 与 swiftc 都支持)、只转发不加逻辑的包装读取器。MachOTestingSupport 依赖 Testing:按镜像互斥的 trait ExclusiveImageAccess、测试基类 MachOFileTests / MachOImageTests / DyldCacheTests,以及从本包 MachOSwiftSectionFixtureTests 泛化出来、不绑定夹具的基类与闭包式跨读取器写法 acrossAllReaders。本包的 MachOSwiftSectionFixtureTests 变成它的子类,218 个子类与 429 处 acrossAllReaders 调用不动;MKE 自己十几处重复的辅助与约 25 个参数化的跨读取器测试改用共享版本。取本机 cache 统一为整个进程共用一份。MKE 先发 3.1.0(C++ 类恢复),本提案在 MKE 3.2.0 发布,本包随后改依赖。

+
+ +
+

要你定

+

已落地,没有待定的事

  1. MachOKitExtensions 的部分随 3.2.0 发布;本包的部分合进 next。
  2. 后续项:FixtureCompiler 还替代不了的约 25 处现编,留待以后另议(见决策日志)。
+
+ +
+

架构图

+
  • 新增
  • 修改
  • 不变
+
+ + + MachOKitExtensions (package) + MachOKit, MachOFoundation, MachOReading, ...unchanged + MachOFixtureSupport (product, no Testing) + DyldSharedCachePath, MachOImageName / MachOFileName (structs) + HostSlice, ProcessImages, DyldCache+Fixture + FixtureCompiler (clang, swiftc) + ForwardingReader, TestActor, ProcessMemory, print() + MachOTestingSupport (product, Testing) + ExclusiveImageAccess + MachOFileTests, MachOImageTests, DyldCacheTests + MachOFixture, MachOFixtureTests (acrossAllReaders ...) + Tests/*duplicated helpers replaced; ~25 tests to acrossAllReaders + + + MachOSwiftSection (package) + SwiftSectionFixtureSupport + - DyldSharedCachePath, generic Extensions, name enums + ~ MachOFileName / MachOImageName: SymbolTests extensions + Baseline, Coverage, Snapshot (unchanged) + SwiftSectionTestingSupport + - ExclusiveImageAccess, base classes, TestActor, ProcessMemory + ~ MachOSwiftSectionFixtureTests : MachOFixtureTests + ~ 17 *Fixture.swift compile through FixtureCompiler + ForwardingMachOReader (unchanged) + Tests (17 targets)429 acrossAllReaders, 218 subclasses unchanged + + + + +
+

本包两个 support target 改为依赖 MachOKitExtensions 的两个新 product,搬走的文件删除;Swift 专用部分不动。

+ +

一个夹具测试的调用链

+
SomeSuite : MachOSwiftSectionFixtureTests (MSS) : MachOFixtureTests (MKE)
+ ├─ class var fixture -> MachOFixture(SymbolTestsCore path, anchored at MSS's #filePath; dlopen)
+ ├─ MachOFixtureTests.init
+ │   ├─ hostSlice(of: url) -> machOFile;  dlopen + MachOImage -> machOImage
+ │   └─ MachOContext(machOFile), MachOContext(machOImage), InProcessContext
+ └─ acrossAllReaders(file: { ... machOFile ... }, image: { ... machOImage ... })
+     └─ #expect(fromFile == fromImage)
+
+
+

改动地图

+
文件 / 类型动作改什么为什么步骤
MKE Package.swift修改新增 target 与 product MachOFixtureSupport、MachOTestingSupport,测试 target MachOTestingSupportTests;各测试 target 加依赖;Tuist 适配块留在文件末尾对外发布1
MKE Sources/TestSupport/MachOFixtureSupport/(DyldSharedCachePath、MachOImageName、MachOFileName、XcodeMachOFileName、DyldCache+Fixture、HostSlice、ProcessImages、FixtureCompiler、ForwardingReader、TestActor、ProcessMemory、Printing)新增从本包搬来并改为 public;名字类型改成 struct;.current 不写死;锚点由调用方传;编译器统一 clang 与 swiftc共用的夹具支持1、2
MKE Sources/TestSupport/MachOTestingSupport/(ExclusiveImageAccess、MachOFileTests、MachOImageTests、DyldCacheTests、XcodeMachOFileTests、MachOFixture、MachOFixtureTests)新增搬来并改为 open / public;新的夹具基类与跨读取器写法,含成对传入、单个闭包的重载共用的测试基类与 trait1、2
MKE Tests/MachOTestingSupportTests/新增搬来 DyldSharedCachePathTests、ExclusiveImageAccessTests;新增 FixtureCompilerTests、HostSliceTests、MachOFixtureTestsTests共享库自己的测试1、2
MKE Tests/MachOKitExtensionsTests/(FixupResolutionMemoTests、SelfBindResolutionTests、DyldCacheImageSearchTests、DyldCacheImageIdentifierTests、DyldCacheSubCacheLookupTests、MachOReaderWrapperTests、Support/ForwardingReader.swift、Support/ChainedFixupsFixture.swift)修改 / 删除现编 dylib、本机 cache、归档 cache 路径、选 slice、包装读取器改用共享版本去重3
MKE Tests/MachOSymbolsTests/、MachODependenciesTests/、MachOAddressResolutionTests/、MachOReadingTests/修改同上去重3
MKE Tests/CPlusPlusSymbolsTests/(ClassIndexTestImages.swift 删除,CPlusPlusClassIndexStoreTests、CPlusPlusSymbolIndexStoreTests、ImagePointerSlotsTests、普查、ClassIndexDemoTests、CPlusPlusVirtualFunctionNamingTests)修改 / 删除夹具镜像改用 MachOFixtureTests 子类;约 25 个参数化测试改写成 acrossAllReaders;现编 dylib 改用 FixtureCompiler统一写法3
MKE Documentations/Internal/TestingSupport.md、README.md、索引新增 / 修改两个 product 的用法与契约(只能链接到测试 target、锚点由调用方传、共用本机 cache)对外说明4
本包 Package.swift修改两个 support target 依赖 MKE 的新 product;去掉不再需要的依赖改依赖5
本包 Sources/TestSupport/SwiftSectionFixtureSupport/(DyldSharedCachePath、Extensions 的通用部分、MachOFileName、MachOImageName、XcodeMachOFileName)删除 / 修改删掉搬走的;MachOFileName / MachOImageName 只剩 SymbolTests 条目的 extension;本包的 #filePath 锚点在这里传给 MKE改用共享版本5
本包 Sources/TestSupport/SwiftSectionTestingSupport/(ExclusiveImageAccess、MachOFileTests、MachOImageTests、DyldCacheTests、XcodeMachOFileTests、TestActor、ProcessMemory、MachOSwiftSectionFixtureTests、17 个 *Fixture.swift)删除 / 修改删掉搬走的;ExclusiveImageAccess 只剩按本包镜像名的便捷初始化;夹具基类改成 MachOFixtureTests 子类;夹具的编译改用 FixtureCompiler改用共享版本5
本包 Tests/MachOSwiftSectionTests/ 里只差变量名的 478 处 acrossAllReaders / acrossAllContexts修改改成成对传入、单个闭包的重载去掉重复的 image: 闭包5
本包测试里 57 个手写 xcrun 的文件、70 处手写选 slice修改改用 FixtureCompiler、HostSlice去重5
本包 TuistScript.sh修改testing_support_names 挪到 if role != "own-path" 之前远程模式下给 MKE 的 MachOTestingSupport 补 TestingMacros 插件路径5
本包 Tests/SwiftSectionTestingSupportTests/修改删掉随代码搬走的两个测试去重5
本包用 DyldCache(path: .current) 的 25 处复查依赖新实例的显式开一份,其余改用共用实例行为统一后的复查5
本包 AGENTS.md、Documentations/Internal/FixtureTestingAndContinuousIntegration.md、Documentations/Internal/Modules/README.md、ProjectEvolutionLog.md修改测试支持的来源、ExclusiveImageAccess 与 acrossAllReaders 的出处、锚点规则文档同步6
+ +
+ +
+

提议方案

+
  1. MKE 新增两个 product(3.2.0):
    • MachOFixtureSupport(Sources/TestSupport/MachOFixtureSupport,不 import Testing):DyldSharedCachePath、MachOImageName / MachOFileName / XcodeMachOFileName(可扩展的 struct)、打开 cache 与镜像的扩展、hostSlice(of:)、取进程内镜像(按锚点地址 dladdr、按名字)、「cache 里的文件与进程内同一镜像」成对返回、FixtureCompiler(clang 与 swiftc,同一份源码与参数只编一次,进程结束时清理临时目录)、ForwardingReader、TestActor、ProcessMemory、.print()。
    • MachOTestingSupport(Sources/TestSupport/MachOTestingSupport,import Testing,依赖前者与 MachOReading):ExclusiveImageAccess、MachOFileTests、MachOImageTests、DyldCacheTests、XcodeMachOFileTests,以及新的 MachOFixtureTests。
  2. 测试基类原样搬:保留「继承基类拿到镜像」的写法,只改访问级别(open / public)与上面列出的必要改动。改成 Swift Testing trait 的写法以后另写提案。
  3. **MachOFixtureTests:不绑定夹具的基类**。子类用一个 MachOFixture 值说明夹具从哪来(磁盘路径,或进程里某个锚点地址所在的镜像,以及是否要 dlopen);基类据此建出 machOFile、machOImage 与 fileContext、imageContext、inProcessContext,提供 acrossAllReaders、acrossAllContexts、usingInProcessOnly,签名与本包现在的一致。
  4. 本机 cache 统一为进程共用:DyldSharedCachePath.current 与 DyldCacheTests 都经 FullDyldCache.cachedHost / DyldCache.host 的 URL,不写死路径;确实需要新实例的测试显式开一份(DyldCache(path:) 照旧可用)。
  5. 跨读取器统一用闭包式:MKE 约 25 个 @Test(arguments: Reader.allCases) 的测试改写成 MachOFixtureTests 子类里的 acrossAllReaders,比对两种读取器的结果相等后再断言。
  6. 成对传入、单个闭包的重载:本包 486 处 acrossAllReaders / acrossAllContexts 调用里,480 处的 image: 闭包只是把 file: 闭包里的读取器与被测对象换成 image 版(按读取器命名的被测对象也算在内)。新增两个同名重载,被测对象成对传入、只写一个闭包:acrossAllReaders(fileSubject, imageSubject) { $0.offset };acrossAllContexts(fileSubject, imageSubject) { subject, context in try subject.mangledTypeName(in: context) },context 是 any ReadingContext,被测 API 收 some ReadingContext 时经 SE-0352 隐式打开。先编译验证这两种写法对两种读取器与三种上下文都写得通,再把只差变量名的调用改成单闭包形式(实际改了 478 处);三闭包形式保留给 8 处:6 处带 inProcess:(多一层 asPointerWrapper),2 处被测 API 的结果类型依赖上下文的 associated type,打开 any ReadingContext 后推不出类型。名字不变,本包按标识符识别跨读取器测试的 SuiteBehaviorScanner(:150)不受影响。
  7. MKE 自己的重复辅助全部换成共享版本(动机一节的表)。
  8. 本包随后改依赖:两个 support target 依赖 MKE 的新 product,删掉搬走的文件;MachOFileName / MachOImageName 的 SymbolTests 条目改为对 MKE struct 的 extension;ExclusiveImageAccess 保留一个按本包镜像名的便捷初始化;MachOSwiftSectionFixtureTests 改成 MachOFixtureTests 的子类;17 个 Swift 夹具与 57 个测试文件里手写的 xcrun 调用改用 FixtureCompiler,70 处手写的选 slice 改用 HostSlice;DyldCache(path: .current) 的 25 处改为共用实例后,逐个复查依赖新实例的测试。
  9. Tuist 开发 workspace(提案 0099):TuistScript.sh 只给角色是 own-path 的包扫描「import Testing 的普通 target」并补 TestingMacros 插件路径(:686-689 的 if role != "own-path" 之后)。远程模式下 MKE 是 own-remote,它的 MachOTestingSupport 用了 #expect 等宏,编到它时会报 plugin for module 'TestingMacros' not found。改法:把 testing_support_names 那几行挪到 if role != "own-path" 之前(own-remote 包的检出目录已记在 packages.tsv)。在 Ultra 上用 ./TuistScript.sh test 跑一次远程模式验证。这一条由维护 0099 的会话提醒。
  10. 发版顺序:MKE 先收尾 C++ 类恢复发 3.1.0;本提案的 MKE 部分从收尾后的 main 切分支,发 3.2.0;本包在 3.2.0 发布后改依赖(之前用 USING_LOCAL_DEPENDENCIES=1 本地验证)。
+

非目标

+
  • 把测试基类改成 Swift Testing trait 的写法。
  • 搬 Swift 专用的支持代码(夹具内容、baseline、coverage、快照对比、SymbolTestsCore 相关)。
  • 搬测试本身(CrossReferenceAnalysisTests 等依赖本包与 MachOObjCSection 的模块)。
  • 统一两个包的 ForwardingMachOReader / ForwardingReader:协议层级不同,本包那份保留。
  • @FixtureSuite 宏(本包 170 个夹具套件开头的固定 5 行):只涉及本包的 Swift 夹具覆盖率体系,另写一份本包的提案。
  • 把 acrossAllReaders 做成宏:每处只重复约一行,宏得按 fileX→imageX 的命名约定改写标识符,脆弱,也会让按标识符识别测试的扫描器失效;用上面的普通函数重载代替。
  • MachOObjCSection、MachOKitUI 等其他仓库的测试改用新 product:各自另议。
  • 给 MKE 加 CI(MKE 0003 记下的后续项,另写提案)。
+ +
+ +
+

详细设计

+
+ 公开 API(实现后) +
+
// MachOFixtureSupport
+public struct DyldSharedCachePath: Hashable, Sendable, CustomStringConvertible {
+    public let path: String
+    public let versionLabel: String
+    public init(path: String, versionLabel: String)
+    public var url: URL { get }
+    /// This Mac's cache, as the system locates it (`FullDyldCache.cachedHost`), labeled `current`.
+    public static var current: DyldSharedCachePath { get }
+    public static func macOS(_ version: String) -> DyldSharedCachePath
+    public static func iOS(_ version: String) -> DyldSharedCachePath
+}
+
+public struct MachOImageName: Hashable, Sendable, ExpressibleByStringLiteral {
+    public let name: String
+    public init(_ name: String)
+    public static let SwiftUI: MachOImageName       // spelled like the image: .AppKit, .Foundation, …
+}
+
+public struct MachOFileName: Hashable, Sendable {
+    /// A path, absolute or relative to `anchor` — the caller's `#filePath`.
+    public init(path: String, relativeTo anchor: URL? = nil)
+    public let url: URL
+    public static let Finder: MachOFileName         // system files: .Dock, .Freeform, simulator runtimes, …
+}
+
+public struct XcodeMachOFileName: Hashable, Sendable {
+    public init(location: Location, name: String)
+    public static func sharedFrameworks(_ framework: SharedFrameworks) -> XcodeMachOFileName   // and frameworks(_:), plugins(_:)
+    public var url: URL { get }
+}
+
+public func loadFromFile(named fileName: MachOFileName) throws -> File
+extension MachOImage { public init?(named imageName: MachOImageName) }
+extension DyldCache { public convenience init(path: DyldSharedCachePath) throws; public func machOFile(named: MachOImageName) -> MachOFile? }
+extension FullDyldCache { public convenience init(path: DyldSharedCachePath) throws; public func machOFile(named: MachOImageName) -> MachOFile? }
+
+public enum HostSlice {
+    public static var processCPU: CPU { get }
+    /// The slice of a file for this process's CPU: same type and subtype, else same type.
+    public static func machOFile(at url: URL) throws -> MachOFile
+    public static func machOFile(in file: File, path: String = "") throws -> MachOFile
+    public static func slice(among slices: [MachOFile]) -> MachOFile?
+}
+
+public enum ProcessImages {
+    public static func image(containing address: UnsafeRawPointer) -> MachOImage?
+    public static func path(ofImageContaining address: UnsafeRawPointer) -> String?
+    public static func image(atPath path: String) -> MachOImage?
+    /// The image of this Mac's cache at `path`, and the same image loaded here.
+    public static func cacheFileAndLoadedImage(path: String) throws -> (file: MachOFile, image: MachOImage)
+}
+
+public struct FixtureCompiler: Sendable {           // macOS only
+    public enum Language: Sendable { case c, cPlusPlus, swift }
+    public static let shared: FixtureCompiler
+    /// Compiles `source` into `lib<name>.dylib` (install name `@rpath/lib<name>.dylib`) once per
+    /// process for the same name, language, kind, sources and arguments; the directory goes away
+    /// when the process exits. Architecture, optimization and target come in `arguments`.
+    public func dynamicLibrary(named name: String, language: Language, source: String, arguments: [String] = []) throws -> URL
+    public func dynamicLibrary(named name: String, language: Language, sourceFiles: [FixtureSourceFile], arguments: [String] = []) throws -> URL
+    /// The main executable `name`.
+    public func executable(named name: String, language: Language, source: String, arguments: [String] = []) throws -> URL
+    public func executable(named name: String, language: Language, sourceFiles: [FixtureSourceFile], arguments: [String] = []) throws -> URL
+    public var productsDirectory: URL { get }
+}
+
+/// A file of a build, written under `name`; its extension tells the driver how to read it.
+public struct FixtureSourceFile: Hashable, Sendable {
+    public init(name: String, contents: String)
+}
+
+public struct ForwardingReader<Base: MachORepresentableWithCache, Declaration: ForwardingReaderDeclaration>: MachORepresentableWithCache
+
+/// `print()` on `CustomStringConvertible` and `Error`, quiet when `MACHO_TESTING_SILENT=1`.
+public enum TestOutput { public static let isSilent: Bool }
+
+// MachOTestingSupport
+public struct ExclusiveImageAccess: SuiteTrait, TestTrait, TestScoping {
+    public init(_ imageName: String)
+}
+
+public struct MachOFixture: Sendable {
+    public init(fileURL: URL, imageName: String, loadsIntoProcess: Bool)
+    public init(imageContaining anchor: UnsafeRawPointer)
+}
+
+@MainActor
+open class MachOFixtureTests: Sendable {
+    open class var fixture: MachOFixture { get }
+    public let machOFile: MachOFile
+    public let machOImage: MachOImage
+    public let fileContext: MachOContext<MachOFile>
+    public let imageContext: MachOContext<MachOImage>
+    public let inProcessContext: InProcessContext
+    public init() async throws
+    public func acrossAllReaders<Value: Equatable>(file: () throws -> Value, image: () throws -> Value, inProcess: (() throws -> Value)? = nil, sourceLocation: SourceLocation = #_sourceLocation) throws -> Value
+    public func acrossAllContexts<Value: Equatable>(file: () throws -> Value, image: () throws -> Value, inProcess: (() throws -> Value)? = nil, sourceLocation: SourceLocation = #_sourceLocation) throws -> Value
+    public func usingInProcessOnly<Value: Equatable>(_ work: (InProcessContext) throws -> Value, sourceLocation: SourceLocation = #_sourceLocation) throws -> Value
+
+    /// The same work on the subject each reader gives: `work` runs on
+    /// `fileSubject`, then on `imageSubject`, and the results must agree.
+    public func acrossAllReaders<Subject, Value: Equatable>(_ fileSubject: Subject, _ imageSubject: Subject, sourceLocation: SourceLocation = #_sourceLocation, _ work: (Subject) throws -> Value) throws -> Value
+    /// The same, reading through each subject's context: `fileContext` for
+    /// `fileSubject`, `imageContext` for `imageSubject`.
+    public func acrossAllContexts<Subject, Value: Equatable>(_ fileSubject: Subject, _ imageSubject: Subject, sourceLocation: SourceLocation = #_sourceLocation, _ work: (Subject, any ReadingContext) throws -> Value) throws -> Value
+    /// The same work on each reader itself: `machOFile`, then `machOImage`.
+    public func acrossAllReaders<Value: Equatable>(sourceLocation: SourceLocation = #_sourceLocation, _ work: (any MachORepresentableWithCache) throws -> Value) throws -> Value
+}
+
+// MachOFileTests, MachOImageTests, DyldCacheTests (the current cache is `FullDyldCache.cachedHost`),
+// XcodeMachOFileTests: open classes with `open class var` hooks, `public init() async throws`.
+
  • 签名以本包现有的为准,只把泛型参数改成完整的单词(本包的 T 换成 Value),调用点不变;MachOFixtureTests 的初始化因此保持 async throws。
  • 上面的接口是实现后的样子;与开工前草稿的出入(versionLabel、静态成员的拼写、第三个 acrossAllReaders 重载、.print() 的静默开关等)逐条记在决策日志。
  • FixtureCompiler 按「名字 + 语言 + 源码 + 参数」缓存产物,失败也缓存,锁保护;每份产物一个目录,失败时错误带命令与编译器 stderr 的全部内容。
  • MachOFixtureTests.fixture 的默认实现 fatalError,提醒子类必须给出夹具;读不到夹具时初始化抛 MachOFixtureError。
  • 契约与用法写在 MachOKitExtensions 的实现说明 Internal/TestingSupport.md。
+
+
+ +
+ +
+

动机

+
  • 两个包各写一套,而且在分叉。 自 MKE 2.0.0 接过 Mach-O 层以后,MKE 的测试没有可用的测试支持,只能各写各的(下表,路径相对 MKE 的 Tests/)。同一件事在两边实现不同:
+
辅助本包MKE
取本机 cacheDyldCache(path: .current),路径写死在 Cryptexes(DyldSharedCachePath.swift:45),每次重新打开(DyldCacheTests.swift:30-32)FullDyldCache.cachedHost,由系统定位、整个进程只打开一次(Sources/MachOKitExtensions/Cached/FullDyldCache+Cached.swift:13-27);另有 3 处写死 Cryptexes 路径(DyldCacheImageSearchTests.swift:161、MachOAddressResolutionTests.swift:18、SharedDyldCacheOpeningTests.swift:30)
选 slice固定选 .arm64,否则取第一个(MachOFileTests.swift:19)按进程的 CPU 类型与去掉标志位的子类型匹配(CPlusPlusSymbolsTests/ClassIndexTestImages.swift:50-63);另有 3 处手写 loadFromFile 的 switch
现编 dylib17 个 *Fixture.swift 各自复制一份 Process 加 Pipe 的 swiftc 调用,结束时清理临时目录(如 ExistentialAnyFixture.swift:100-140)5 份 clang 调用(FixupResolutionMemoTests.swift:122-176、SelfBindResolutionTests.swift:80-115、ClassIndexTestImages.swift:70-159、ClassIndexDemoTests.swift:34-60 等),不清理
归档 cache 路径DyldSharedCachePath.macOS(_:) / iOS(_:)3 份各写一遍(DyldCacheImageIdentifierTests.swift:7-11、CacheRootDependencyClosureTests.swift:10-11、MachOAddressResolutionTests.swift:81)
跨读取器acrossAllReaders,429 处,但写死 SymbolTestsCore@Test(arguments: Reader.allCases) 参数化,约 25 处
包装读取器ForwardingMachOReader,约束在本包的协议上Support/ForwardingReader.swift,约束在 MachORepresentableWithCache,internal
+
  • MKE 的新功能还在继续加重复。 C++ 类恢复(MKE draft-cplusplus-class-hierarchy)一次就新增了两份现编 dylib、一份选 slice、两份「cache 文件加进程内同一镜像」。
  • 这些代码本该在 MKE。 0003 定下 MachO 前缀的模块归 MKE,本包的测试支持为此从 MachOFixtureSupport / MachOTestingSupport 改名为 SwiftSection…(MKE 0003 的 :102),两个名字现在空着。
+
+ +
+

调研

+
+ 可搬与不可搬的文件、用量与约束 +
+

本包的测试支持(Sources/TestSupport/,三个 target,都不是 product,Package.swift:1020-1080)

+
  • SwiftSectionFixtureSupport:不 import Testing,baseline-generator 也用它。依赖 MachOKit、Demangling、SwiftSyntax 三件套、MKE 的 MachOFoundation / MachOReading / MachOResolving,以及本包的 SwiftSymbols、SwiftDump、SwiftDeclaration、SwiftIndexing、SwiftPrinting、SwiftInterface、MachOSwiftSectionC 和 TestingSupportC。
  • SwiftSectionTestingSupport:放 Testing 基类,另依赖 MachOSwiftSection、SwiftSpecialization、Semantic。
  • SwiftSectionTestingSupportC:CDemangleTree.cpp。
  • 17 个测试 target 依赖 SwiftSectionTestingSupport(Package.swift:1069-1411),CrossReferenceAnalysisTests 只依赖 FixtureSupport。
+

哪些可以搬(只依赖 MachOKit、Foundation、Testing 或 MKE 已有的模块)

+
文件去处要改的
FixtureSupport/DyldSharedCachePath.swift(无 import)MachOFixtureSupport.current 改由本机 cache 的 URL 得出,不写死 Cryptexes
FixtureSupport/Extensions.swift(只 import MachOKit;UniformTypeIdentifiers 在 :3 导入了没用)MachOFixtureSupportloadFromFile(named:) 的 #filePath 锚点(:9)改由调用方传入;DyldCache/FullDyldCache 的 init(path:)、machOFile(named:)、受 SILENT_TEST 控制的 .print() 原样
FixtureSupport/MachOFileName.swift、MachOImageName.swiftMachOFixtureSupport封闭的 package enum 改成「struct 加静态成员」,SymbolTests 的条目(MachOFileName.swift:20-26、MachOImageName.swift:26-27)留在本包用 extension 补
FixtureSupport/XcodeMachOFileName.swift(Foundation、Darwin)MachOFixtureSupport同上改成 struct
TestingSupport/ExclusiveImageAccess.swift(只 import Testing)MachOTestingSupport只留按 String 的初始化;按本包镜像名的便捷初始化(:89-95)留在本包
TestingSupport/TestActor.swift、ProcessMemory.swift(Foundation)MachOFixtureSupport无
TestingSupport/MachOFileTests.swift、MachOImageTests.swift、DyldCacheTests.swift、XcodeMachOFileTests.swift(MachOKit、MachOFoundation、FixtureSupport)MachOTestingSupport选 slice 改用统一的按进程 CPU 匹配;DyldCacheTests 的 .current 改为共用的本机 cache
TestingSupport/MachOSwiftSectionFixtureTests.swift 的跨读取器部分(acrossAllReaders :104-118、acrossAllContexts :121-135、usingInProcessOnly :147-152,上下文来自 MKE 的 MachOReading)MachOTestingSupport 的新基类 MachOFixtureTests夹具改由子类描述;SymbolTestsCore 的加载(:18-19、:70)留在本包的子类里
SwiftSectionTestingSupportTests 里的 DyldSharedCachePathTests、ExclusiveImageAccessTestsMKE 新测试 target MachOTestingSupportTests跟着代码走
+

不搬:ForwardingMachOReader(约束在 MachOSwiftSectionRepresentableWithCache,:5、:27)、DemangleOptions、DumpableTests / Snapshot*Tests、CommentStructureContract、SwiftIndexEventCollector、DefinitionName+DeclaredNameForTesting、URL+(依赖 swift-dependencies)、FixtureLoadError、InProcessMetadataPicker、177 个 Baseline 文件、5 个 Coverage 文件、17 个 Swift 夹具的内容(只把编译那段换成共享的编译器)、TestingSupportC、ContinuousIntegrationTestFilterTests。

+

用量(本包 Tests/ 计数):acrossAllReaders 429、继承 MachOSwiftSectionFixtureTests 218、usingInProcessOnly 73、acrossAllContexts 68、.print() 44、ExclusiveImageAccess( 42、继承 MachOFileTests 37、machOFile(named:) 32、DyldCache(path: .current 25、继承 MachOImageTests 13、继承 DyldCacheTests 5。

+

测试本身不搬:本包的 CrossReferenceAnalysisTests 测的是 MKE 的 MachOCodeReferences 等模块,但几乎每个文件都 import 本包的 CrossReferenceAnalysis 与 MachOObjCSection 的 ObjCCodeReferences,MKE 不能依赖它们。

+

约束

+
  • 跨包使用只能是 public。全局 write-tests skill 的默认做法是包内 TestingSupport target、package 访问级别、不进 products;要给别的包用时另拆对外 product,对外 API 尽量小,能不 import Testing 就不 import(references/testing-support.md 第 11 节)。拆成不依赖 Testing 的 MachOFixtureSupport 与依赖 Testing 的 MachOTestingSupport 正是这条规则,也是本包当年的拆法(Package.swift:1020-1050 的注释)。
  • MKE 的 Package.swift 末尾有 Tuist 适配块,只在 TUIST_MAPS_LOCAL_PACKAGE_TESTS=1 时给「被测试依赖、但不在 product 里」的 target 补 product。两个新 target 是正式 product,无条件声明,不靠它。
  • 本包 AGENTS.md 规定 #filePath 定位源码的深度(0055),MachOFileName 从 Sources/<Group>/<Target> 往上爬三层到包根。搬到 MKE 后锚点必须由调用方传入。
  • 本包 AGENTS.md 规定共享整进程状态的套件都要声明 ExclusiveImageAccess(.TheFixture)。trait 搬走后,规则与用法不变,只是类型来自 MKE。
+
+
+
+ +
+

替代方案

+
+ 7 条被否的路 +
+
  • 只在 MKE 内部统一,本包不动:改动小,但两套继续分叉;用户选择两个包一起统一。
  • 一个 product:简单,但只想要路径与打开镜像的使用方也要链接 Testing;用户选择拆两个。
  • 测试基类顺便改成 Swift Testing trait:更现代,但本包 55 个、218 个子类都要改写,风险高;用户选择原样搬,改写另议。
  • 保留「每次重开」与「共用」两种取 cache 的入口:不动行为,但两套写法并存;用户选择统一为共用。
  • 跨读取器统一用参数化:每种读取器在报告里单独成用例,但本包 429 处都要改写;用户选择闭包式。
  • 夹具用值类型组合:更现代,但与「基类原样搬」不一致、两种形状并存;用户选择泛化基类。
  • 与 C++ 类恢复一起发 3.1.0:少发一个版本,但推迟已做完的功能;用户选择 C++ 先发。
+
+
+
+ +
+

影响

+

源码兼容性(source compatibility)

+
  • MKE:纯新增两个 product;改的只有 MKE 自己的测试。
  • 本包:只改测试支持与测试,对外 product 不变。测试代码的 import 从本包的 support target 换成 MKE 的 product(经本包 support target 的 @_exported import 转出,多数测试文件不用改)。
+

ABI 兼容性(条件项)

+

不适用 —— 两个包都以 SPM 源码分发,使用方每次重新编译。

+

下游影响

+
  • MKE 3.2.0 新增 product,不影响现有使用方(RuntimeViewer、MachOObjCSection、MachOKitUI)。
  • MachOObjCSection、MachOKitUI 的测试以后可以改用这两个 product,各自另议。
  • 本包依赖 MKE 的版本下限升到 3.2.0。
+

文档与示例

+

MKE 新增实现说明 Internal/TestingSupport.md、README 的 product 表;本包 AGENTS.md 里 ExclusiveImageAccess 与 acrossAllReaders 两条规则注明类型来自 MKE,FixtureTestingAndContinuousIntegration.md 更新锚点规则。

+

API 演进与废弃策略

+
  • 本包搬走的类型直接删除,不留废弃期:它们是 package 级别,只有本包自己的测试在用,同一批次改完。
  • MKE 新 product 的公开 API 尽量小;名字类型用 struct 加静态成员,以后加镜像不破坏调用方。
  • semver:MKE 3.2.0(minor);本包对外 product 不变,随下一个常规版本。
+
+ +
+

落地步骤

+

MKE(3.2.0,从 C++ 类恢复收尾后的 main 切出):

+
  1. 两个 product 的骨架与搬来的代码(完成)—— MKE Package.swift、Sources/TestSupport/MachOFixtureSupport/、Sources/TestSupport/MachOTestingSupport/、Tests/MachOTestingSupportTests/
    • 行为:currentCachePathIsTheOneTheSystemLocates
    • 行为:archivedCachePathsKeepTheirLayout
    • 行为:hostSliceMatchesTheProcessSubtype
    • 行为:exclusiveImageAccessSerializesSuitesOfOneImage(搬来)
    • 行为:imageNamesAndFileNamesTakeExtensions
  2. 夹具基类与编译器(完成)—— MachOFixture、MachOFixtureTests、FixtureCompiler
    • 行为:fixtureTestsBuildBothReadersAndAllContextsFromAFile
    • 行为:fixtureTestsReachAnImageOfThisProcessByAnAnchor
    • 行为:acrossAllReadersReportsWhichReaderDiverged
    • 行为:compilerBuildsEachSourceOncePerProcess
    • 行为:compilerFailureCarriesTheDiagnostics
    • 行为:compilerBuildsSwiftAndCPlusPlus
    • 行为:pairedSubjectsRunOneClosureOnEachReader
    • 行为:pairedSubjectsOpenTheContextForAnAPITakingSomeReadingContext(编译验证单闭包写法)
  3. MKE 的测试改用共享版本(完成)—— 动机一节的表,以及 Tests/CPlusPlusSymbolsTests/
    • 行为:MKE 全部测试照常通过,跨读取器的约 25 个测试改写为 acrossAllReaders 后断言不变
    • 行为:仓库里不再有 Process 调用 xcrun 的测试辅助、写死 Cryptexes 路径的常量、手写的选 slice
  4. MKE 文档与发版(完成,3.2.0)—— Internal/TestingSupport.md、README、索引;发 3.2.0
+

本包(MKE 3.2.0 发布后,从 next 切出):

+
  1. 改依赖、删重复(完成)—— 本包 Package.swift、Sources/TestSupport/、Tests/SwiftSectionTestingSupportTests/、DyldCache(path: .current) 的 25 处
    • 行为:本包全部测试(IntegrationTests 除外,照 AGENTS.md)照常通过
    • 行为:SymbolTestsCoreFixtureLoadsThroughTheSharedBaseClass
    • 行为:17 个 Swift 夹具经 FixtureCompiler 编出、结果与改前一致
    • 行为:478 处跨读取器调用改成单闭包形式后,SuiteBehaviorScanner 认出的跨读取器测试数不变
    • 行为:./TuistScript.sh test 的远程模式在 Ultra 上编过 MKE 的 MachOTestingSupport
  2. 本包文档(完成)—— AGENTS.md、FixtureTestingAndContinuousIntegration.md、Modules/README.md、ProjectEvolutionLog.md
+

收尾判断:MKE 写实现说明(两个 product 的契约:只能链接到测试 target、锚点由调用方传、共用本机 cache);不写使用指南;本包与 MKE 都没有新术语要登记(ExclusiveImageAccess、acrossAllReaders 已在本包术语里)。

+ +
+ +
+

决策日志

+
+ 39 条,最近一条:Implemented,取号 0104 +
+
日期变更说明
2026-11-20Created as Draft用户希望把本包 TestingSupport 的通用部分搬到 MachOKitExtensions,统一两个包的测试用例。先由只读调研查清可搬与不可搬的部分、两边的重复与分叉,再经两轮澄清提问定下方案。
2026-11-20两个包一起统一,走完整档用户选择。否决:只统一 MKE 内部;先不做。
2026-11-20拆成 MachOFixtureSupport(无 Testing)与 MachOTestingSupport(Testing)用户选择。否决:一个 product。依据 write-tests skill 对外 product 的规则与本包当年的拆法。
2026-11-20测试基类原样搬用户选择。否决:顺便改成 Swift Testing trait(另议)。
2026-11-20本机 cache 统一为进程共用用户选择。否决:两种入口并存。本包依赖新实例的测试逐个复查。
2026-11-20跨读取器统一用闭包式 acrossAllReaders用户选择。否决:统一用参数化(本包 429 处要改写)。
2026-11-20夹具基类泛化为 MachOFixtureTests用户选择。否决:值类型组合(两种形状会并存)。
2026-11-20MKE 先发 C++ 类恢复(3.1.0),本提案随 3.2.0用户选择。否决:一起发 3.1.0。
2026-11-20按事实或先例自定的四条名字类型改成 struct、#filePath 锚点由调用方传(跨包后锚点位置变了);FixtureCompiler 同时支持 clang 与 swiftc,本包 17 个与 MKE 5 个复制的编译代码都改用它;测试本身不搬(依赖本包与 MachOObjCSection 的模块);提案由本包维护(0098 先例),用户确认。
2026-11-20状态 → Accepted用户批准。实现等 MachOKitExtensions 的 C++ 类恢复收尾、发 3.1.0 之后开始。
2026-11-20加入成对传入、单个闭包的 acrossAllReaders / acrossAllContexts 重载用户问能否加宏减少测试样板。调研:486 处跨读取器调用里 480 处的 image: 闭包只是换了变量名,但每处只重复约一行;做成宏要按命名约定改写标识符,也会让按标识符识别测试的扫描器失效。用户选择改用普通函数重载,并把能改的调用改过去。另一处值得用宏的样板——170 个夹具套件开头的固定 5 行——用户选择另写一份本包提案(@FixtureSuite)。
2026-11-20加入 TuistScript.sh 的改动维护提案 0099 的会话提醒:远程模式下 MKE 是 own-remote,不在扫描 TestingMacros 插件路径的范围内,新的 MachOTestingSupport 会编不过。
2026-11-20用量更正本包手写 xcrun 的测试文件是 57 个(原写 17 个 Swift 夹具),手写选 slice 70 处;都改用共享版本。
2026-11-20状态 → In Progress用户批准开工。前置都已就位:MachOKitExtensions 3.1.0 已发布;@FixtureSuite(0100)与 Swift 6 迁移(0101)已落地,两个包的每个 Swift target 都开启了 ExistentialAny、MemberImportVisibility、InferIsolatedConformances,新代码照这三项写。先做 MachOKitExtensions 的第 1–4 步;第 4 步的发版(3.2.0)不在开工的授权内,做到文档为止,发版另行确认。
2026-11-20MKE 第 1、2 步完成,合成一个提交两步共用测试 target,第 1 步的选 slice 测试要用第 2 步的编译器造一个三架构的 fat 库,分开提交得各编一遍。新 target MachOTestingSupportTests 的 20 个测试在 Ultra 上通过(Xcode 27.2)。
2026-11-20DyldSharedCachePath 保留 versionLabel,rawValue 改名 path本包 ABIEvolutionTests 按它给版本轴命名。本包自己命名的几个 cache(iOS_18_5 等,路径在本机的 Generic 卷上)不搬,第 5 步用 extension 补回。
2026-11-20名字类型的静态成员照镜像本名拼写(.SwiftUI、.Foundation),不按详细设计的草稿写成 .foundation成员的值就是镜像名;本包几百处调用照旧编译,第 5 步只补 SymbolTests 那几条。XcodeMachOFileName 也改成 struct(位置加名字),用静态函数保留 .sharedFrameworks(.SourceKitSupport) 的写法;找不到文件时不再 fatalError,读取时报错。
2026-11-20.print() 的静默开关改为运行时环境变量 MACHO_TESTING_SILENT=1原来是编译条件 SILENT_TEST,由本包清单加在自己的 target 上,搬到 MKE 后到不了 MKE 的模块。第 5 步要让本包 CI(以及 Tuist 的测试 scheme)设这个变量。
2026-11-20MachOFixtureTests 的初始化保持 async throws;新增第三个重载 acrossAllReaders { machO in … }前者照本包现有签名,有子类写了 override init() async throws。后者把两个读取器本身交给同一个闭包:MKE 的 C++ 测试要比的就是读取器,而 MachOFile 与 MachOImage 不能当成同一个泛型参数传给成对的重载。
2026-11-20实现细节自定FixtureCompiler 每份产物单独一个目录,库之间用 -L、-l 链接,strip -x 改用链接参数 -Wl,-x;失败的结果也缓存。HostSlice 先找同 CPU 类型且子类型相同的 slice,再退到同类型,再找不到就报错,不再像本包那样退到第一个 slice;单架构文件不论 CPU 都直接用。MachOFixture(imageContaining:) 用 dladdr 拿到镜像的文件路径,所以不支持 shared cache 里的镜像(那种用 ProcessImages.cacheFileAndLoadedImage(path:))。读不到夹具时抛 MKE 的 MachOFixtureError;本包第 5 步可以在子类里把它换成带重编说明的 FixtureLoadError。DyldCacheTests 读本机 cache 时用 FullDyldCache.cachedHost 和它的 mainCache。ExclusiveImageAccess 在 MKE 只有按字符串的初始化,同提案。
2026-11-20MKE 第 3 步完成ClassIndexTestImages 与测试里那份 ForwardingReader 删掉;5 处现编库改用 FixtureCompiler;写死 Cryptexes 的 3 处与归档 cache 的 3 处改用 DyldSharedCachePath;手写选 slice 的 6 处改用 HostSlice。ChainedFixupsFixture 故意读每一个 slice(要覆盖 x86_64 与 arm64e 两种指针格式),不算选 slice,保留。CPlusPlusClassIndexStoreTests 改成 MachOFixtureTests 的子类,17 个参数化测试改写为 acrossAllReaders,实际数比提案估的约 25 个少。
2026-11-20跨读取器比较的是去掉偏移的形状同一份数据在文件里与加载后的偏移不同,C++ 测试先把类与 vtable 投影成 ClassShape、VirtualTableShape 再比较;偏移之间的关系在闭包里各自算成布尔值或距离返回。改写时查出一处读取器之间的真实差别:另一个镜像里的基类,文件读出绑定所写的 libc++.1.dylib,进程里读出 dyld 找到符号的 libc++abi.dylib(被 libc++ 重新导出)。原测试只查名字含 libc++,两边都满足,属于既有行为,不是这次引入的;形状里只记「在另一个镜像」,各读取器分别判断是不是 libc++。
2026-11-20MKE 第 4 步的文档完成,实现完成(MKE 部分),待用户看过后收尾新增实现说明 Internal/TestingSupport.md,README 的 product 表加两行,文档索引与提案索引登记(提案索引是跨仓库行)。验证在 Ultra 上(Xcode 27.2):MKE 全量 swift test 271 个测试通过,原始退出码 0;带 CPLUSPLUS_CLASS_CENSUS_FRAMEWORKS 的 TSTables 与 Espresso 普查也通过(断言精确计数)。发 3.2.0 不在开工的授权内,等用户确认;第 5、6 步等 3.2.0 发布后在本包做。
2026-11-20FixtureCompiler 的锁改用 FrameworkToolbox 的 OSToolbox.Mutex,MKE 因此新增依赖 FrameworkToolbox(只有 MachOFixtureSupport 用)用户要求:不用 NSLock,尽量不写 @unchecked Sendable。标准库的 Mutex 要 macOS 15、OSAllocatedUnfairLock 要 macOS 13,MKE 的下限是 macOS 10.15,OSToolbox 的 Mutex 用法相同、没有版本限制。产物目录与退出时清理改成两个全局 let;ProcessMemory 的格式化器改为用时现建,去掉 nonisolated(unsafe);测试里 MachOFixtureTests 子类多写的 @unchecked Sendable 删掉(MainActor 基类本就 Sendable)。MKE 全量测试通过,退出码 0。本包第 5 步同样不要再写 NSLock。
2026-11-20MKE 其余模块的 NSLock 也一并换成 OSToolbox.Mutex,随 3.2.0 发布用户决定:FrameworkToolbox 本来就是 MSS 与 RuntimeViewer 的依赖。19 个文件、7 个库 target;每段临界区的范围保持不变(先查、出锁构建、再进锁写回的照旧);能被编译器认作 Sendable 的类型去掉了 @unchecked,还持有 DyldCache、FullDyldCache、指针的 5 个保留并写明原因。非 Sendable 的值存进锁时用 withLockUnchecked(6 处),各有注释。MKE 全量测试与 TSTables、Espresso 普查通过,退出码 0。
2026-11-20MKE 撤掉 Linux 支持OSToolbox 的 Mutex 基于 os_unfair_lock,只在 Apple 平台上有,换锁后 Linux 编不过。用户选择撤掉承诺(否决:给 OSToolbox 补 Linux 实现;在 MKE 里按平台分开用标准库的 Mutex)。此前从没有 Linux CI,也没在 Linux 上验证过。MachOObjCSection 依赖 MKE,它对 Linux 的承诺随之失效。
2026-11-20MKE 的 Sources/ 按层分组,两个测试支持 target 在 Sources/TestSupport/ 下用户要求照本包 0055 分组,MKE 另写了提案 0007-group-sources-by-layer,同一分支、随 3.2.0。本提案改动地图里 MKE 的源码路径随之更新。
2026-11-21MKE 部分合入 MachOKitExtensions main 并推送,未发版用户看过后收尾:测试支持的两个 product、MKE 测试改用它们、全部 NSLock 换成 Mutex、撤掉 Linux 与 Sources/ 分组(MKE 0007)一起进了 main,最终代码上 MKE 全量测试通过。3.2.0 还没发;本包第 5、6 步等它发布后在本分支继续。
2026-11-21第 5 步的已知缺口:FixtureCompiler 还不能完全替代本包的 CompiledFixture本包 Tests/CrossReferenceAnalysisTests/CompiledFixture.swift 的 build(libraryName:sources:compilerArguments:isExecutable:) 能编可执行文件(FileModeTests、FunctionStartOutsideTextTests 两处用 isExecutable: true)、一次编多个源文件、按参数指定架构;MKE 3.1.0 之后的 FixtureCompiler 只把单个源字符串编成动态库。要么在发 3.2.0 之前给 FixtureCompiler 补可执行文件与多源文件,要么这几处在本包保留自己的辅助,待用户定。另:next 上新进的 FunctionStartOutsideTextTests.anIndexKeepsTheReferencesOfAFunctionBelowText 用到 CompiledFixture.build(…isExecutable:) 与 InstructionEncoding.branchWithLink(at:to:),第 5 步若搬走或改名它们,这条测试一起改,本分支合 next 时会遇到它。
2026-11-21FixtureCompiler 补上可执行文件与多源文件,MKE 3.2.0 发布用户选择发版前先补:新增 executable(named:language:source:arguments:)、两个收 sourceFiles: [FixtureSourceFile] 的重载,单段源码的写法不变;本包 CompiledFixture.build 的可执行文件、多源文件与指定架构(经参数 -arch)都能用它替代。CompiledFixture.load 的链接后改写、重新签名、再加载留在本包,在复制出的产物上做(共享编译器的产物是缓存,不能原地改)。MKE 全量测试通过,原始退出码 0;随后在 main 上打 3.2.0(附注 tag,同以往不建 Release 页面)。本包第 5、6 步可以开始。
2026-11-21第 5 步第一部分:测试支持改接 MKE 3.2.0MKE 下限升到 3.2.0;两个 support target 依赖并 re-export MachOFixtureSupport / MachOTestingSupport,搬走的 12 个文件删除;SymbolTests 的文件名与镜像名、本包命名的 cache、按本包名字的 ExclusiveImageAccess 初始化留在本包作 extension。ExclusiveImageAccess 的 key 取镜像名(文件名取路径最后一段去扩展名),同一夹具按文件或按镜像声明仍互斥,新测试 ExclusiveImageAccessKeyTests 钉住这一点。MachOSwiftSectionFixtureTests 改为 MachOFixtureTests 的子类,读不到夹具时把 MachOFixtureError 转成带重编说明的 FixtureLoadError。MKE 也有公开的 DeclaredWrapper / UndeclaredWrapper,与本包同名标记冲突,ForwardingMachOReader 改用 MKE 的标记(读取器本身留在本包)。CI 加 MACHO_TESTING_SILENT: 1。swift test --skip IntegrationTests 2,914 个通过,退出码 0(基线 2,916:删 4 个搬走的测试,加 2 个);IntegrationTests 与可执行文件都编过。
2026-11-21第 5 步第二部分:现编与选 slice 改用共享版本41 处现编改用 FixtureCompiler(5 个 Swift 夹具、交叉引用测试 11 处、其余 25 处),源文件名一律照旧(private 判别符由文件名哈希得出);约 66 处手写选 slice 改用 HostSlice,故意选 arm64e 的 StandaloneFileReferenceDumpTests 照旧。CompiledFixture 只剩 load:经共享编译器编出后复制一份再改写、重签名、加载,不碰共享的缓存产物;build 与 buildSwift 删除。改过去的库 install name 从绝对临时路径变成 @rpath/lib<名字>.dylib;ReferenceKindAndRouteTests 的 Swift 库因模块名必须是 Fixture 改叫 libFixture.dylib(没有断言读文件名)。约 25 处共享编译器表达不了,保留手写,见后续项。swift test --skip IntegrationTests 2,914 个通过,退出码 0。
2026-11-21后续项:FixtureCompiler 还替代不了的现编留着手写的约 25 处要的是:产物名与 Swift 模块名不同(lib<模块>-<变体> 之类);-emit-module、.swiftinterface、bridging header、modulemap 写到调用方选的路径;编完再 strip / codesign;先编 .o 再链接;另一套工具链(DEVELOPER_DIR)或 --sdk iphonesimulator;放进假系统根里由 install name 决定的路径。要全部收掉,FixtureCompiler 得加模块名参数、编译前就能拿到的产物目录和一个后处理步骤,留待以后另议(MKE 次版本)。
2026-11-21第 5 步第三部分:跨读取器调用改成单闭包486 处调用里 478 处改成成对传入、单个闭包(acrossAllReaders 418 处、acrossAllContexts 60 处),8 处保留三闭包:6 处带 inProcess:,2 处 functionAddress(in:) 的结果类型是 Context.Address?,依赖上下文的 associated type,打开 any ReadingContext 后推不出类型(AccessibleFunctionRecordTests、AsyncFunctionPointerTests 的 fromContext)。提案原估 480 / 6。SuiteBehaviorScanner 只看函数体与所在类里有没有这两个名字,前后对比 793 个测试方法,分类(跨读取器 593、只用进程内 61、只注册不读 139)与每个方法里的调用次数都不变。断言一行未动;swift test --skip IntegrationTests 2,914 个通过,退出码 0。
2026-11-21第 5 步第四部分:本机 cache 共用、Tuist 远程模式DyldCache(path: .current) 等 27 处只读本机 cache,全部改用 FullDyldCache.cachedHost(要 DyldCache 的取它的 mainCache),GenericSpecializationFixture 也一并改;FileMappingTests 要在调低的描述符上限下打开这些文件,保留新实例并注明。缓存按镜像路径与 UUID 分,不认实例,共用不改变缓存行为。TuistScript.sh 的 testing_support_names 扫描挪到 if role != "own-path" 之前,own-remote 的包也扫;Workspace.swift 在设了 MACHO_SWIFT_SECTION_SILENT_TEST=1 时给测试 scheme 的环境加 MACHO_TESTING_SILENT=1;TuistDevelopment.md 同步。swift test --skip IntegrationTests 2,914 个通过,退出码 0。./TuistScript.sh test 远程模式退出码 65,没走到 MKE 的 MachOTestingSupport:SwiftSectionTestingMacrosTests 的 @testable import SwiftSectionTestingMacros 在 Tuist 里解析不到宏 target。这个测试 target 随 0100 进入 next,Tuist 的适配段没处理依赖宏 target 的测试,是 next 上已有的问题,与本提案无关;已确认远程模式的扫描结果含 MachOTestingSupport、生成的工程带 TestingMacros 插件路径、scheme 带 MACHO_TESTING_SILENT=1。这一条验证待那个问题修好后补跑。
2026-11-21修好 Tuist workspace 的宏测试,补跑远程模式用户选择在本分支一起修:清单末尾的 Tuist 适配段把依赖宏 target 的测试也拿掉(与依赖可执行 target 的测试同样处理),宏的展开测试只在 swift test 里跑。三个上游库清单末尾的同一段代码按约定该一起改,它们没有宏 target,这次没同步,TuistDevelopment.md 记了这一点。./TuistScript.sh test 远程模式退出码 0(TEST SUCCEEDED,约 26 分钟,2,953 个测试),编过了 MKE 的 MachOTestingSupport。
2026-11-21实现完成,待用户看过后收尾第 5、6 步都已完成。文档:AGENTS.md(Sources/ 一节的锚点、测试一节的测试支持来源与本机 cache、ExclusiveImageAccess 的 key、静默变量、新增套件时的写法)、FixtureTestingAndContinuousIntegration.md(路径锚定与新的一节)、Modules/README.md、TuistDevelopment.md、ProjectEvolutionLog.md(节号落地时定)。不另写实现说明(契约在 MachOKitExtensions 的 TestingSupport.md),没有新术语。后续项:FixtureCompiler 还替代不了的约 25 处现编(见上)。
2026-11-21Tuist 适配段的「宏 target」一条同步到三个上游库用户选择保持四份一致:MachOKitExtensions main、MachOObjCSection next、swift-demangling next 各一个提交并推送;三者都没有宏 target,设与不设 TUIST_MAPS_LOCAL_PACKAGE_TESTS 时清单解析结果与改前相同。不发版。
2026-11-21状态 → Implemented,取号 0104用户看过后收尾,合进 next 并推送。next 上先落地了 0103(跨引用测试的整份 cache 扫描限并发),所以本提案取号 0104、演进账本记为第 150 节。合并前把最新 next 合进本分支:只有 Documentations/README.md 与演进账本冲突,两边都保留;0103 新规则(CrossReferenceAnalysisTests 里不直接调 DispatchQueue.concurrentPerform,由 ParallelScanSourceTests 检查)合并后仍满足。合并结果上在 Ultra(Xcode 27.2)重跑:swift test --skip IntegrationTests 2,971 个通过,退出码 0;./TuistScript.sh test 远程模式 3,003 个通过、0 失败、7 个跳过,退出码 0。next 上 ./TuistScript.sh test 因 SwiftSectionTestingMacrosTests 编不过的问题随本提案修好。文档判断:不另写实现说明或使用指南(两个 product 的契约在 MachOKitExtensions 的 TestingSupport.md),没有新术语;MachOKitExtensions 里指向本提案的链接一并改成 0104。后续项照旧:FixtureCompiler 还替代不了的约 25 处现编。
+
+
+ +
+ +
+
+ + diff --git a/Documentations/Evolutions/0104-shared-macho-testing-support.md b/Documentations/Evolutions/0104-shared-macho-testing-support.md new file mode 100644 index 000000000..506015728 --- /dev/null +++ b/Documentations/Evolutions/0104-shared-macho-testing-support.md @@ -0,0 +1,393 @@ +# 0104 - 测试支持的通用部分迁入 MachOKitExtensions:两个包共用 MachOFixtureSupport 与 MachOTestingSupport + +- **状态**: Implemented +- **作者**: JH +- **创建日期**: 2026-11-20 +- **最后更新**: 2026-11-21 +- **所属愿景**: 无 +- **关联提案**: [0003(MachOKitExtensions)move-macho-infrastructure-modules](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Evolutions/0003-move-macho-infrastructure-modules.md)(`MachO` 前缀的模块归 MachOKitExtensions,本包的测试支持因此改名 `SwiftSection…`);[0098 move-cross-reference-layers](0098-move-cross-reference-layers.md)(跨仓库迁移、由本包维护唯一提案的先例);MachOKitExtensions 的 [0006-cplusplus-class-hierarchy](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Evolutions/0006-cplusplus-class-hierarchy.md)(它新加的测试辅助是本提案要合并的重复代码之一,已随 3.1.0 发布);[0100-fixture-suite-macro](0100-fixture-suite-macro.md)(同一次讨论拆出的本包宏);[0101-swift6-mode-and-upcoming-features](0101-swift6-mode-and-upcoming-features.md)(两个包开启的三项 upcoming feature,新代码照它们写) +- **实现分支 / PR**: 两个仓库同名 `feature/shared-macho-testing-support`。MachOKitExtensions 从 `main` 切出(3.1.0 与 Swift 6 迁移之后),worktree 在 `.worktrees/MachOKitExtensions-SharedMachOTestingSupport`;本包从 `next` 切出(0100、0101 之后),worktree 在 `.worktrees/MachOSwiftSection-SharedMachOTestingSupport`,第 5、6 步等 MachOKitExtensions 3.2.0 发布后在这里做 +- **配套文档**: MachOKitExtensions 的实现说明 [Internal/TestingSupport.md](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Internal/TestingSupport.md)(落地前在它的功能分支上) +- **网页版**: 同目录同名的 `.html` + +## 摘要 + +把本包测试支持里与 Swift 无关的部分搬到 MachOKitExtensions(下称 MKE),作为两个对外 product 发布,两个包从此共用一套。`MachOFixtureSupport` 不依赖 Testing:dyld cache 路径、打开 cache 与镜像、按本机架构选 slice、取进程内镜像、测试运行时用 `xcrun` 现编 dylib(clang 与 swiftc 都支持)、只转发不加逻辑的包装读取器。`MachOTestingSupport` 依赖 Testing:按镜像互斥的 trait `ExclusiveImageAccess`、测试基类 `MachOFileTests` / `MachOImageTests` / `DyldCacheTests`,以及从本包 `MachOSwiftSectionFixtureTests` 泛化出来、不绑定夹具的基类与闭包式跨读取器写法 `acrossAllReaders`。本包的 `MachOSwiftSectionFixtureTests` 变成它的子类,218 个子类与 429 处 `acrossAllReaders` 调用不动;MKE 自己十几处重复的辅助与约 25 个参数化的跨读取器测试改用共享版本。取本机 cache 统一为整个进程共用一份。MKE 先发 3.1.0(C++ 类恢复),本提案在 MKE 3.2.0 发布,本包随后改依赖。 + +## 动机 + +- **两个包各写一套,而且在分叉。** 自 MKE 2.0.0 接过 Mach-O 层以后,MKE 的测试没有可用的测试支持,只能各写各的(下表,路径相对 MKE 的 `Tests/`)。同一件事在两边实现不同: + + | 辅助 | 本包 | MKE | + |---|---|---| + | 取本机 cache | `DyldCache(path: .current)`,路径写死在 Cryptexes(`DyldSharedCachePath.swift:45`),每次重新打开(`DyldCacheTests.swift:30-32`) | `FullDyldCache.cachedHost`,由系统定位、整个进程只打开一次(`Sources/MachOKitExtensions/Cached/FullDyldCache+Cached.swift:13-27`);另有 3 处写死 Cryptexes 路径(`DyldCacheImageSearchTests.swift:161`、`MachOAddressResolutionTests.swift:18`、`SharedDyldCacheOpeningTests.swift:30`) | + | 选 slice | 固定选 `.arm64`,否则取第一个(`MachOFileTests.swift:19`) | 按进程的 CPU 类型与去掉标志位的子类型匹配(`CPlusPlusSymbolsTests/ClassIndexTestImages.swift:50-63`);另有 3 处手写 `loadFromFile` 的 switch | + | 现编 dylib | 17 个 `*Fixture.swift` 各自复制一份 `Process` 加 `Pipe` 的 swiftc 调用,结束时清理临时目录(如 `ExistentialAnyFixture.swift:100-140`) | 5 份 clang 调用(`FixupResolutionMemoTests.swift:122-176`、`SelfBindResolutionTests.swift:80-115`、`ClassIndexTestImages.swift:70-159`、`ClassIndexDemoTests.swift:34-60` 等),不清理 | + | 归档 cache 路径 | `DyldSharedCachePath.macOS(_:)` / `iOS(_:)` | 3 份各写一遍(`DyldCacheImageIdentifierTests.swift:7-11`、`CacheRootDependencyClosureTests.swift:10-11`、`MachOAddressResolutionTests.swift:81`) | + | 跨读取器 | `acrossAllReaders`,429 处,但写死 SymbolTestsCore | `@Test(arguments: Reader.allCases)` 参数化,约 25 处 | + | 包装读取器 | `ForwardingMachOReader`,约束在本包的协议上 | `Support/ForwardingReader.swift`,约束在 `MachORepresentableWithCache`,internal | + +- **MKE 的新功能还在继续加重复。** C++ 类恢复(MKE 0006)一次就新增了两份现编 dylib、一份选 slice、两份「cache 文件加进程内同一镜像」。 +- **这些代码本该在 MKE。** 0003 定下 `MachO` 前缀的模块归 MKE,本包的测试支持为此从 `MachOFixtureSupport` / `MachOTestingSupport` 改名为 `SwiftSection…`(MKE 0003 的 `:102`),两个名字现在空着。 + +## 前期调研 + +**本包的测试支持**(`Sources/TestSupport/`,三个 target,都不是 product,`Package.swift:1020-1080`) + +- `SwiftSectionFixtureSupport`:不 import Testing,`baseline-generator` 也用它。依赖 MachOKit、Demangling、SwiftSyntax 三件套、MKE 的 MachOFoundation / MachOReading / MachOResolving,以及本包的 SwiftSymbols、SwiftDump、SwiftDeclaration、SwiftIndexing、SwiftPrinting、SwiftInterface、MachOSwiftSectionC 和 TestingSupportC。 +- `SwiftSectionTestingSupport`:放 Testing 基类,另依赖 MachOSwiftSection、SwiftSpecialization、Semantic。 +- `SwiftSectionTestingSupportC`:`CDemangleTree.cpp`。 +- 17 个测试 target 依赖 `SwiftSectionTestingSupport`(`Package.swift:1069-1411`),CrossReferenceAnalysisTests 只依赖 FixtureSupport。 + +**哪些可以搬**(只依赖 MachOKit、Foundation、Testing 或 MKE 已有的模块) + +| 文件 | 去处 | 要改的 | +|---|---|---| +| `FixtureSupport/DyldSharedCachePath.swift`(无 import) | `MachOFixtureSupport` | `.current` 改由本机 cache 的 URL 得出,不写死 Cryptexes | +| `FixtureSupport/Extensions.swift`(只 import MachOKit;`UniformTypeIdentifiers` 在 `:3` 导入了没用) | `MachOFixtureSupport` | `loadFromFile(named:)` 的 `#filePath` 锚点(`:9`)改由调用方传入;`DyldCache`/`FullDyldCache` 的 `init(path:)`、`machOFile(named:)`、受 `SILENT_TEST` 控制的 `.print()` 原样 | +| `FixtureSupport/MachOFileName.swift`、`MachOImageName.swift` | `MachOFixtureSupport` | 封闭的 `package enum` 改成「struct 加静态成员」,SymbolTests 的条目(`MachOFileName.swift:20-26`、`MachOImageName.swift:26-27`)留在本包用 extension 补 | +| `FixtureSupport/XcodeMachOFileName.swift`(Foundation、Darwin) | `MachOFixtureSupport` | 同上改成 struct | +| `TestingSupport/ExclusiveImageAccess.swift`(只 import Testing) | `MachOTestingSupport` | 只留按 `String` 的初始化;按本包镜像名的便捷初始化(`:89-95`)留在本包 | +| `TestingSupport/TestActor.swift`、`ProcessMemory.swift`(Foundation) | `MachOFixtureSupport` | 无 | +| `TestingSupport/MachOFileTests.swift`、`MachOImageTests.swift`、`DyldCacheTests.swift`、`XcodeMachOFileTests.swift`(MachOKit、MachOFoundation、FixtureSupport) | `MachOTestingSupport` | 选 slice 改用统一的按进程 CPU 匹配;`DyldCacheTests` 的 `.current` 改为共用的本机 cache | +| `TestingSupport/MachOSwiftSectionFixtureTests.swift` 的跨读取器部分(`acrossAllReaders` `:104-118`、`acrossAllContexts` `:121-135`、`usingInProcessOnly` `:147-152`,上下文来自 MKE 的 MachOReading) | `MachOTestingSupport` 的新基类 `MachOFixtureTests` | 夹具改由子类描述;SymbolTestsCore 的加载(`:18-19`、`:70`)留在本包的子类里 | +| `SwiftSectionTestingSupportTests` 里的 `DyldSharedCachePathTests`、`ExclusiveImageAccessTests` | MKE 新测试 target `MachOTestingSupportTests` | 跟着代码走 | + +**不搬**:`ForwardingMachOReader`(约束在 `MachOSwiftSectionRepresentableWithCache`,`:5`、`:27`)、`DemangleOptions`、`DumpableTests` / `Snapshot*Tests`、`CommentStructureContract`、`SwiftIndexEventCollector`、`DefinitionName+DeclaredNameForTesting`、`URL+`(依赖 swift-dependencies)、`FixtureLoadError`、`InProcessMetadataPicker`、177 个 Baseline 文件、5 个 Coverage 文件、17 个 Swift 夹具的内容(只把编译那段换成共享的编译器)、TestingSupportC、`ContinuousIntegrationTestFilterTests`。 + +**用量**(本包 `Tests/` 计数):`acrossAllReaders` 429、继承 `MachOSwiftSectionFixtureTests` 218、`usingInProcessOnly` 73、`acrossAllContexts` 68、`.print()` 44、`ExclusiveImageAccess(` 42、继承 `MachOFileTests` 37、`machOFile(named:)` 32、`DyldCache(path: .current` 25、继承 `MachOImageTests` 13、继承 `DyldCacheTests` 5。 + +**测试本身不搬**:本包的 `CrossReferenceAnalysisTests` 测的是 MKE 的 `MachOCodeReferences` 等模块,但几乎每个文件都 import 本包的 `CrossReferenceAnalysis` 与 MachOObjCSection 的 `ObjCCodeReferences`,MKE 不能依赖它们。 + +**约束** + +- 跨包使用只能是 `public`。全局 write-tests skill 的默认做法是包内 `TestingSupport` target、`package` 访问级别、不进 products;要给别的包用时另拆对外 product,对外 API 尽量小,能不 import Testing 就不 import(`references/testing-support.md` 第 11 节)。拆成不依赖 Testing 的 `MachOFixtureSupport` 与依赖 Testing 的 `MachOTestingSupport` 正是这条规则,也是本包当年的拆法(`Package.swift:1020-1050` 的注释)。 +- MKE 的 `Package.swift` 末尾有 Tuist 适配块,只在 `TUIST_MAPS_LOCAL_PACKAGE_TESTS=1` 时给「被测试依赖、但不在 product 里」的 target 补 product。两个新 target 是正式 product,无条件声明,不靠它。 +- 本包 `AGENTS.md` 规定 `#filePath` 定位源码的深度(0055),`MachOFileName` 从 `Sources//` 往上爬三层到包根。搬到 MKE 后锚点必须由调用方传入。 +- 本包 `AGENTS.md` 规定共享整进程状态的套件都要声明 `ExclusiveImageAccess(.TheFixture)`。trait 搬走后,规则与用法不变,只是类型来自 MKE。 + +## 提议方案 + +1. **MKE 新增两个 product**(3.2.0): + - `MachOFixtureSupport`(`Sources/TestSupport/MachOFixtureSupport`,不 import Testing):`DyldSharedCachePath`、`MachOImageName` / `MachOFileName` / `XcodeMachOFileName`(可扩展的 struct)、打开 cache 与镜像的扩展、`hostSlice(of:)`、取进程内镜像(按锚点地址 `dladdr`、按名字)、「cache 里的文件与进程内同一镜像」成对返回、`FixtureCompiler`(clang 与 swiftc,同一份源码与参数只编一次,进程结束时清理临时目录)、`ForwardingReader`、`TestActor`、`ProcessMemory`、`.print()`。 + - `MachOTestingSupport`(`Sources/TestSupport/MachOTestingSupport`,import Testing,依赖前者与 MachOReading):`ExclusiveImageAccess`、`MachOFileTests`、`MachOImageTests`、`DyldCacheTests`、`XcodeMachOFileTests`,以及新的 `MachOFixtureTests`。 +2. **测试基类原样搬**:保留「继承基类拿到镜像」的写法,只改访问级别(`open` / `public`)与上面列出的必要改动。改成 Swift Testing trait 的写法以后另写提案。 +3. **`MachOFixtureTests`:不绑定夹具的基类**。子类用一个 `MachOFixture` 值说明夹具从哪来(磁盘路径,或进程里某个锚点地址所在的镜像,以及是否要 `dlopen`);基类据此建出 `machOFile`、`machOImage` 与 `fileContext`、`imageContext`、`inProcessContext`,提供 `acrossAllReaders`、`acrossAllContexts`、`usingInProcessOnly`,签名与本包现在的一致。 +4. **本机 cache 统一为进程共用**:`DyldSharedCachePath.current` 与 `DyldCacheTests` 都经 `FullDyldCache.cachedHost` / `DyldCache.host` 的 URL,不写死路径;确实需要新实例的测试显式开一份(`DyldCache(path:)` 照旧可用)。 +5. **跨读取器统一用闭包式**:MKE 约 25 个 `@Test(arguments: Reader.allCases)` 的测试改写成 `MachOFixtureTests` 子类里的 `acrossAllReaders`,比对两种读取器的结果相等后再断言。 +6. **成对传入、单个闭包的重载**:本包 486 处 `acrossAllReaders` / `acrossAllContexts` 调用里,480 处的 `image:` 闭包只是把 `file:` 闭包里的读取器与被测对象换成 image 版(按读取器命名的被测对象也算在内)。新增两个同名重载,被测对象成对传入、只写一个闭包:`acrossAllReaders(fileSubject, imageSubject) { $0.offset }`;`acrossAllContexts(fileSubject, imageSubject) { subject, context in try subject.mangledTypeName(in: context) }`,`context` 是 `any ReadingContext`,被测 API 收 `some ReadingContext` 时经 SE-0352 隐式打开。先编译验证这两种写法对两种读取器与三种上下文都写得通,再把只差变量名的调用改成单闭包形式(实际改了 478 处);三闭包形式保留给 8 处:6 处带 `inProcess:`(多一层 `asPointerWrapper`),2 处被测 API 的结果类型依赖上下文的 associated type,打开 `any ReadingContext` 后推不出类型。名字不变,本包按标识符识别跨读取器测试的 `SuiteBehaviorScanner`(`:150`)不受影响。 +7. **MKE 自己的重复辅助全部换成共享版本**(动机一节的表)。 +8. **本包随后改依赖**:两个 support target 依赖 MKE 的新 product,删掉搬走的文件;`MachOFileName` / `MachOImageName` 的 SymbolTests 条目改为对 MKE struct 的 extension;`ExclusiveImageAccess` 保留一个按本包镜像名的便捷初始化;`MachOSwiftSectionFixtureTests` 改成 `MachOFixtureTests` 的子类;17 个 Swift 夹具与 57 个测试文件里手写的 `xcrun` 调用改用 `FixtureCompiler`,70 处手写的选 slice 改用 `HostSlice`;`DyldCache(path: .current)` 的 25 处改为共用实例后,逐个复查依赖新实例的测试。 +9. **Tuist 开发 workspace**(提案 0099):`TuistScript.sh` 只给角色是 own-path 的包扫描「import Testing 的普通 target」并补 TestingMacros 插件路径(`:686-689` 的 `if role != "own-path"` 之后)。远程模式下 MKE 是 own-remote,它的 `MachOTestingSupport` 用了 `#expect` 等宏,编到它时会报 `plugin for module 'TestingMacros' not found`。改法:把 `testing_support_names` 那几行挪到 `if role != "own-path"` 之前(own-remote 包的检出目录已记在 `packages.tsv`)。在 Ultra 上用 `./TuistScript.sh test` 跑一次远程模式验证。这一条由维护 0099 的会话提醒。 +10. **发版顺序**:MKE 先收尾 C++ 类恢复发 3.1.0;本提案的 MKE 部分从收尾后的 `main` 切分支,发 3.2.0;本包在 3.2.0 发布后改依赖(之前用 `USING_LOCAL_DEPENDENCIES=1` 本地验证)。 + +### 非目标 + +- 把测试基类改成 Swift Testing trait 的写法。 +- 搬 Swift 专用的支持代码(夹具内容、baseline、coverage、快照对比、SymbolTestsCore 相关)。 +- 搬测试本身(`CrossReferenceAnalysisTests` 等依赖本包与 MachOObjCSection 的模块)。 +- 统一两个包的 `ForwardingMachOReader` / `ForwardingReader`:协议层级不同,本包那份保留。 +- `@FixtureSuite` 宏(本包 170 个夹具套件开头的固定 5 行):只涉及本包的 Swift 夹具覆盖率体系,另写一份本包的提案(已随 [0100-fixture-suite-macro](0100-fixture-suite-macro.md) 落地)。 +- 把 `acrossAllReaders` 做成宏:每处只重复约一行,宏得按 `fileX`→`imageX` 的命名约定改写标识符,脆弱,也会让按标识符识别测试的扫描器失效;用上面的普通函数重载代替。 +- MachOObjCSection、MachOKitUI 等其他仓库的测试改用新 product:各自另议。 +- 给 MKE 加 CI(MKE 0003 记下的后续项,另写提案)。 + +## 改动地图 + +| 文件 / 类型 | 动作 | 改什么 | 为什么 | 步骤 | +|---|---|---|---|---| +| MKE `Package.swift` | 修改 | 新增 target 与 product `MachOFixtureSupport`、`MachOTestingSupport`,测试 target `MachOTestingSupportTests`;各测试 target 加依赖;Tuist 适配块留在文件末尾 | 对外发布 | 1 | +| MKE `Sources/TestSupport/MachOFixtureSupport/`(`DyldSharedCachePath`、`MachOImageName`、`MachOFileName`、`XcodeMachOFileName`、`DyldCache+Fixture`、`HostSlice`、`ProcessImages`、`FixtureCompiler`、`ForwardingReader`、`TestActor`、`ProcessMemory`、`Printing`) | 新增 | 从本包搬来并改为 `public`;名字类型改成 struct;`.current` 不写死;锚点由调用方传;编译器统一 clang 与 swiftc | 共用的夹具支持 | 1、2 | +| MKE `Sources/TestSupport/MachOTestingSupport/`(`ExclusiveImageAccess`、`MachOFileTests`、`MachOImageTests`、`DyldCacheTests`、`XcodeMachOFileTests`、`MachOFixture`、`MachOFixtureTests`) | 新增 | 搬来并改为 `open` / `public`;新的夹具基类与跨读取器写法,含成对传入、单个闭包的重载 | 共用的测试基类与 trait | 1、2 | +| MKE `Tests/MachOTestingSupportTests/` | 新增 | 搬来 `DyldSharedCachePathTests`、`ExclusiveImageAccessTests`;新增 `FixtureCompilerTests`、`HostSliceTests`、`MachOFixtureTestsTests` | 共享库自己的测试 | 1、2 | +| MKE `Tests/MachOKitExtensionsTests/`(`FixupResolutionMemoTests`、`SelfBindResolutionTests`、`DyldCacheImageSearchTests`、`DyldCacheImageIdentifierTests`、`DyldCacheSubCacheLookupTests`、`MachOReaderWrapperTests`、`Support/ForwardingReader.swift`、`Support/ChainedFixupsFixture.swift`) | 修改 / 删除 | 现编 dylib、本机 cache、归档 cache 路径、选 slice、包装读取器改用共享版本 | 去重 | 3 | +| MKE `Tests/MachOSymbolsTests/`、`MachODependenciesTests/`、`MachOAddressResolutionTests/`、`MachOReadingTests/` | 修改 | 同上 | 去重 | 3 | +| MKE `Tests/CPlusPlusSymbolsTests/`(`ClassIndexTestImages.swift` 删除,`CPlusPlusClassIndexStoreTests`、`CPlusPlusSymbolIndexStoreTests`、`ImagePointerSlotsTests`、普查、`ClassIndexDemoTests`、`CPlusPlusVirtualFunctionNamingTests`) | 修改 / 删除 | 夹具镜像改用 `MachOFixtureTests` 子类;约 25 个参数化测试改写成 `acrossAllReaders`;现编 dylib 改用 `FixtureCompiler` | 统一写法 | 3 | +| MKE `Documentations/Internal/TestingSupport.md`、`README.md`、索引 | 新增 / 修改 | 两个 product 的用法与契约(只能链接到测试 target、锚点由调用方传、共用本机 cache) | 对外说明 | 4 | +| 本包 `Package.swift` | 修改 | 两个 support target 依赖 MKE 的新 product;去掉不再需要的依赖 | 改依赖 | 5 | +| 本包 `Sources/TestSupport/SwiftSectionFixtureSupport/`(`DyldSharedCachePath`、`Extensions` 的通用部分、`MachOFileName`、`MachOImageName`、`XcodeMachOFileName`) | 删除 / 修改 | 删掉搬走的;`MachOFileName` / `MachOImageName` 只剩 SymbolTests 条目的 extension;本包的 `#filePath` 锚点在这里传给 MKE | 改用共享版本 | 5 | +| 本包 `Sources/TestSupport/SwiftSectionTestingSupport/`(`ExclusiveImageAccess`、`MachOFileTests`、`MachOImageTests`、`DyldCacheTests`、`XcodeMachOFileTests`、`TestActor`、`ProcessMemory`、`MachOSwiftSectionFixtureTests`、17 个 `*Fixture.swift`) | 删除 / 修改 | 删掉搬走的;`ExclusiveImageAccess` 只剩按本包镜像名的便捷初始化;夹具基类改成 `MachOFixtureTests` 子类;夹具的编译改用 `FixtureCompiler` | 改用共享版本 | 5 | +| 本包 `Tests/MachOSwiftSectionTests/` 里只差变量名的 478 处 `acrossAllReaders` / `acrossAllContexts` | 修改 | 改成成对传入、单个闭包的重载 | 去掉重复的 `image:` 闭包 | 5 | +| 本包测试里 57 个手写 `xcrun` 的文件、70 处手写选 slice | 修改 | 改用 `FixtureCompiler`、`HostSlice` | 去重 | 5 | +| 本包 `TuistScript.sh` | 修改 | `testing_support_names` 挪到 `if role != "own-path"` 之前 | 远程模式下给 MKE 的 `MachOTestingSupport` 补 TestingMacros 插件路径 | 5 | +| 本包 `Tests/SwiftSectionTestingSupportTests/` | 修改 | 删掉随代码搬走的两个测试 | 去重 | 5 | +| 本包用 `DyldCache(path: .current)` 的 25 处 | 复查 | 依赖新实例的显式开一份,其余改用共用实例 | 行为统一后的复查 | 5 | +| 本包 `AGENTS.md`、`Documentations/Internal/FixtureTestingAndContinuousIntegration.md`、`Documentations/Internal/Modules/README.md`、`ProjectEvolutionLog.md` | 修改 | 测试支持的来源、`ExclusiveImageAccess` 与 `acrossAllReaders` 的出处、锚点规则 | 文档同步 | 6 | + +## 架构图 + +改了什么: + +```text +MachOKitExtensions (package) + MachOKit, MachOKitExtensions, MachOFoundation, MachOReading, ... (unchanged) ++ MachOFixtureSupport (product, no Testing) ++ DyldSharedCachePath, MachOImageName/MachOFileName (extensible structs) ++ HostSlice, ProcessImages, DyldCache+Fixture, FixtureCompiler (clang, swiftc) ++ ForwardingReader, TestActor, ProcessMemory, print() ++ MachOTestingSupport (product, Testing) -> MachOFixtureSupport, MachOReading ++ ExclusiveImageAccess, MachOFileTests, MachOImageTests, DyldCacheTests ++ MachOFixture, MachOFixtureTests (acrossAllReaders, acrossAllContexts, usingInProcessOnly) +~ Tests/* -> MachOFixtureSupport / MachOTestingSupport + +MachOSwiftSection (package) +~ SwiftSectionFixtureSupport -> + MachOFixtureSupport +- DyldSharedCachePath, generic Extensions, MachOFileName/MachOImageName enums +~ MachOFileName/MachOImageName extensions: SymbolTests entries +~ SwiftSectionTestingSupport -> + MachOTestingSupport +- ExclusiveImageAccess, MachOFileTests, MachOImageTests, DyldCacheTests, TestActor, ProcessMemory +~ MachOSwiftSectionFixtureTests : MachOFixtureTests (SymbolTestsCore fixture) +~ 17 *Fixture.swift compile through FixtureCompiler + Baseline, Coverage, Snapshot, ForwardingMachOReader, ... (unchanged) +``` + +一个夹具测试的调用链: + +```text +SomeSuite : MachOSwiftSectionFixtureTests (MSS) : MachOFixtureTests (MKE) + ├─ class var fixture -> MachOFixture(SymbolTestsCore path, anchored at MSS's #filePath; dlopen) + ├─ MachOFixtureTests.init + │ ├─ hostSlice(of: url) -> machOFile; dlopen + MachOImage -> machOImage + │ └─ MachOContext(machOFile), MachOContext(machOImage), InProcessContext + └─ acrossAllReaders(file: { ... machOFile ... }, image: { ... machOImage ... }) + └─ #expect(fromFile == fromImage) +``` + +## 详细设计 + +```swift +// MachOFixtureSupport +public struct DyldSharedCachePath: Hashable, Sendable, CustomStringConvertible { + public let path: String + public let versionLabel: String + public init(path: String, versionLabel: String) + public var url: URL { get } + /// This Mac's cache, as the system locates it (`FullDyldCache.cachedHost`), labeled `current`. + public static var current: DyldSharedCachePath { get } + public static func macOS(_ version: String) -> DyldSharedCachePath + public static func iOS(_ version: String) -> DyldSharedCachePath +} + +public struct MachOImageName: Hashable, Sendable, ExpressibleByStringLiteral { + public let name: String + public init(_ name: String) + public static let SwiftUI: MachOImageName // spelled like the image: .AppKit, .Foundation, … +} + +public struct MachOFileName: Hashable, Sendable { + /// A path, absolute or relative to `anchor` — the caller's `#filePath`. + public init(path: String, relativeTo anchor: URL? = nil) + public let url: URL + public static let Finder: MachOFileName // system files: .Dock, .Freeform, simulator runtimes, … +} + +public struct XcodeMachOFileName: Hashable, Sendable { + public init(location: Location, name: String) + public static func sharedFrameworks(_ framework: SharedFrameworks) -> XcodeMachOFileName // and frameworks(_:), plugins(_:) + public var url: URL { get } +} + +public func loadFromFile(named fileName: MachOFileName) throws -> File +extension MachOImage { public init?(named imageName: MachOImageName) } +extension DyldCache { public convenience init(path: DyldSharedCachePath) throws; public func machOFile(named: MachOImageName) -> MachOFile? } +extension FullDyldCache { public convenience init(path: DyldSharedCachePath) throws; public func machOFile(named: MachOImageName) -> MachOFile? } + +public enum HostSlice { + public static var processCPU: CPU { get } + /// The slice of a file for this process's CPU: same type and subtype, else same type. + public static func machOFile(at url: URL) throws -> MachOFile + public static func machOFile(in file: File, path: String = "") throws -> MachOFile + public static func slice(among slices: [MachOFile]) -> MachOFile? +} + +public enum ProcessImages { + public static func image(containing address: UnsafeRawPointer) -> MachOImage? + public static func path(ofImageContaining address: UnsafeRawPointer) -> String? + public static func image(atPath path: String) -> MachOImage? + /// The image of this Mac's cache at `path`, and the same image loaded here. + public static func cacheFileAndLoadedImage(path: String) throws -> (file: MachOFile, image: MachOImage) +} + +public struct FixtureCompiler: Sendable { // macOS only + public enum Language: Sendable { case c, cPlusPlus, swift } + public static let shared: FixtureCompiler + /// Compiles `source` into `lib.dylib` (install name `@rpath/lib.dylib`) once per + /// process for the same name, language, kind, sources and arguments; the directory goes away + /// when the process exits. Architecture, optimization and target come in `arguments`. + public func dynamicLibrary(named name: String, language: Language, source: String, arguments: [String] = []) throws -> URL + public func dynamicLibrary(named name: String, language: Language, sourceFiles: [FixtureSourceFile], arguments: [String] = []) throws -> URL + /// The main executable `name`. + public func executable(named name: String, language: Language, source: String, arguments: [String] = []) throws -> URL + public func executable(named name: String, language: Language, sourceFiles: [FixtureSourceFile], arguments: [String] = []) throws -> URL + public var productsDirectory: URL { get } +} + +/// A file of a build, written under `name`; its extension tells the driver how to read it. +public struct FixtureSourceFile: Hashable, Sendable { + public init(name: String, contents: String) +} + +public struct ForwardingReader: MachORepresentableWithCache + +/// `print()` on `CustomStringConvertible` and `Error`, quiet when `MACHO_TESTING_SILENT=1`. +public enum TestOutput { public static let isSilent: Bool } + +// MachOTestingSupport +public struct ExclusiveImageAccess: SuiteTrait, TestTrait, TestScoping { + public init(_ imageName: String) +} + +public struct MachOFixture: Sendable { + public init(fileURL: URL, imageName: String, loadsIntoProcess: Bool) + public init(imageContaining anchor: UnsafeRawPointer) +} + +@MainActor +open class MachOFixtureTests: Sendable { + open class var fixture: MachOFixture { get } + public let machOFile: MachOFile + public let machOImage: MachOImage + public let fileContext: MachOContext + public let imageContext: MachOContext + public let inProcessContext: InProcessContext + public init() async throws + public func acrossAllReaders(file: () throws -> Value, image: () throws -> Value, inProcess: (() throws -> Value)? = nil, sourceLocation: SourceLocation = #_sourceLocation) throws -> Value + public func acrossAllContexts(file: () throws -> Value, image: () throws -> Value, inProcess: (() throws -> Value)? = nil, sourceLocation: SourceLocation = #_sourceLocation) throws -> Value + public func usingInProcessOnly(_ work: (InProcessContext) throws -> Value, sourceLocation: SourceLocation = #_sourceLocation) throws -> Value + + /// The same work on the subject each reader gives: `work` runs on + /// `fileSubject`, then on `imageSubject`, and the results must agree. + public func acrossAllReaders(_ fileSubject: Subject, _ imageSubject: Subject, sourceLocation: SourceLocation = #_sourceLocation, _ work: (Subject) throws -> Value) throws -> Value + /// The same, reading through each subject's context: `fileContext` for + /// `fileSubject`, `imageContext` for `imageSubject`. + public func acrossAllContexts(_ fileSubject: Subject, _ imageSubject: Subject, sourceLocation: SourceLocation = #_sourceLocation, _ work: (Subject, any ReadingContext) throws -> Value) throws -> Value + /// The same work on each reader itself: `machOFile`, then `machOImage`. + public func acrossAllReaders(sourceLocation: SourceLocation = #_sourceLocation, _ work: (any MachORepresentableWithCache) throws -> Value) throws -> Value +} + +// MachOFileTests, MachOImageTests, DyldCacheTests (the current cache is `FullDyldCache.cachedHost`), +// XcodeMachOFileTests: open classes with `open class var` hooks, `public init() async throws`. +``` + +- 签名以本包现有的为准,只把泛型参数改成完整的单词(本包的 `T` 换成 `Value`),调用点不变;`MachOFixtureTests` 的初始化因此保持 `async throws`。 +- 上面的接口是实现后的样子;与开工前草稿的出入(`versionLabel`、静态成员的拼写、第三个 `acrossAllReaders` 重载、`.print()` 的静默开关等)逐条记在决策日志。 +- `FixtureCompiler` 按「名字 + 语言 + 源码 + 参数」缓存产物,失败也缓存,锁保护;每份产物一个目录,失败时错误带命令与编译器 stderr 的全部内容。 +- `MachOFixtureTests.fixture` 的默认实现 `fatalError`,提醒子类必须给出夹具;读不到夹具时初始化抛 `MachOFixtureError`。 +- 契约与用法写在 MachOKitExtensions 的实现说明 `Internal/TestingSupport.md`。 + +## 替代方案考量 + +- **只在 MKE 内部统一,本包不动**:改动小,但两套继续分叉;用户选择两个包一起统一。 +- **一个 product**:简单,但只想要路径与打开镜像的使用方也要链接 Testing;用户选择拆两个。 +- **测试基类顺便改成 Swift Testing trait**:更现代,但本包 55 个、218 个子类都要改写,风险高;用户选择原样搬,改写另议。 +- **保留「每次重开」与「共用」两种取 cache 的入口**:不动行为,但两套写法并存;用户选择统一为共用。 +- **跨读取器统一用参数化**:每种读取器在报告里单独成用例,但本包 429 处都要改写;用户选择闭包式。 +- **夹具用值类型组合**:更现代,但与「基类原样搬」不一致、两种形状并存;用户选择泛化基类。 +- **与 C++ 类恢复一起发 3.1.0**:少发一个版本,但推迟已做完的功能;用户选择 C++ 先发。 + +## 影响 + +### 源码兼容性(source compatibility) + +- MKE:纯新增两个 product;改的只有 MKE 自己的测试。 +- 本包:只改测试支持与测试,对外 product 不变。测试代码的 import 从本包的 support target 换成 MKE 的 product(经本包 support target 的 `@_exported import` 转出,多数测试文件不用改)。 + +### ABI 兼容性(条件项) + +不适用 —— 两个包都以 SPM 源码分发,使用方每次重新编译。 + +### 下游影响 + +- MKE 3.2.0 新增 product,不影响现有使用方(RuntimeViewer、MachOObjCSection、MachOKitUI)。 +- MachOObjCSection、MachOKitUI 的测试以后可以改用这两个 product,各自另议。 +- 本包依赖 MKE 的版本下限升到 3.2.0。 + +### 文档与示例 + +MKE 新增实现说明 `Internal/TestingSupport.md`、README 的 product 表;本包 `AGENTS.md` 里 `ExclusiveImageAccess` 与 `acrossAllReaders` 两条规则注明类型来自 MKE,`FixtureTestingAndContinuousIntegration.md` 更新锚点规则。 + +## API 演进与废弃策略 + +- 本包搬走的类型直接删除,不留废弃期:它们是 `package` 级别,只有本包自己的测试在用,同一批次改完。 +- MKE 新 product 的公开 API 尽量小;名字类型用 struct 加静态成员,以后加镜像不破坏调用方。 +- semver:MKE 3.2.0(minor);本包对外 product 不变,随下一个常规版本。 + +## 落地步骤 + +MKE(3.2.0,从 C++ 类恢复收尾后的 `main` 切出): + +1. **两个 product 的骨架与搬来的代码**(完成)—— MKE `Package.swift`、`Sources/TestSupport/MachOFixtureSupport/`、`Sources/TestSupport/MachOTestingSupport/`、`Tests/MachOTestingSupportTests/` + - 行为:`currentCachePathIsTheOneTheSystemLocates` + - 行为:`archivedCachePathsKeepTheirLayout` + - 行为:`hostSliceMatchesTheProcessSubtype` + - 行为:`exclusiveImageAccessSerializesSuitesOfOneImage`(搬来) + - 行为:`imageNamesAndFileNamesTakeExtensions` +2. **夹具基类与编译器**(完成)—— `MachOFixture`、`MachOFixtureTests`、`FixtureCompiler` + - 行为:`fixtureTestsBuildBothReadersAndAllContextsFromAFile` + - 行为:`fixtureTestsReachAnImageOfThisProcessByAnAnchor` + - 行为:`acrossAllReadersReportsWhichReaderDiverged` + - 行为:`compilerBuildsEachSourceOncePerProcess` + - 行为:`compilerFailureCarriesTheDiagnostics` + - 行为:`compilerBuildsSwiftAndCPlusPlus` + - 行为:`pairedSubjectsRunOneClosureOnEachReader` + - 行为:`pairedSubjectsOpenTheContextForAnAPITakingSomeReadingContext`(编译验证单闭包写法) +3. **MKE 的测试改用共享版本**(完成)—— 动机一节的表,以及 `Tests/CPlusPlusSymbolsTests/` + - 行为:MKE 全部测试照常通过,跨读取器的约 25 个测试改写为 `acrossAllReaders` 后断言不变 + - 行为:仓库里不再有 `Process` 调用 `xcrun` 的测试辅助、写死 Cryptexes 路径的常量、手写的选 slice +4. **MKE 文档与发版**(完成,3.2.0)—— `Internal/TestingSupport.md`、README、索引;发 3.2.0 + +本包(MKE 3.2.0 发布后,从 `next` 切出): + +5. **改依赖、删重复**(完成)—— 本包 `Package.swift`、`Sources/TestSupport/`、`Tests/SwiftSectionTestingSupportTests/`、`DyldCache(path: .current)` 的 25 处 + - 行为:本包全部测试(`IntegrationTests` 除外,照 `AGENTS.md`)照常通过 + - 行为:`SymbolTestsCoreFixtureLoadsThroughTheSharedBaseClass` + - 行为:17 个 Swift 夹具经 `FixtureCompiler` 编出、结果与改前一致 + - 行为:478 处跨读取器调用改成单闭包形式后,`SuiteBehaviorScanner` 认出的跨读取器测试数不变 + - 行为:`./TuistScript.sh test` 的远程模式在 Ultra 上编过 MKE 的 `MachOTestingSupport` +6. **本包文档**(完成)—— `AGENTS.md`、`FixtureTestingAndContinuousIntegration.md`、`Modules/README.md`、`ProjectEvolutionLog.md` + +收尾判断:MKE 写实现说明(两个 product 的契约:只能链接到测试 target、锚点由调用方传、共用本机 cache);不写使用指南;本包与 MKE 都没有新术语要登记(`ExclusiveImageAccess`、`acrossAllReaders` 已在本包术语里)。 + +## 决策日志 + +| 日期 | 变更 | 说明 | +|------|------|------| +| 2026-11-20 | Created as Draft | 用户希望把本包 TestingSupport 的通用部分搬到 MachOKitExtensions,统一两个包的测试用例。先由只读调研查清可搬与不可搬的部分、两边的重复与分叉,再经两轮澄清提问定下方案。 | +| 2026-11-20 | 两个包一起统一,走完整档 | 用户选择。否决:只统一 MKE 内部;先不做。 | +| 2026-11-20 | 拆成 `MachOFixtureSupport`(无 Testing)与 `MachOTestingSupport`(Testing) | 用户选择。否决:一个 product。依据 write-tests skill 对外 product 的规则与本包当年的拆法。 | +| 2026-11-20 | 测试基类原样搬 | 用户选择。否决:顺便改成 Swift Testing trait(另议)。 | +| 2026-11-20 | 本机 cache 统一为进程共用 | 用户选择。否决:两种入口并存。本包依赖新实例的测试逐个复查。 | +| 2026-11-20 | 跨读取器统一用闭包式 `acrossAllReaders` | 用户选择。否决:统一用参数化(本包 429 处要改写)。 | +| 2026-11-20 | 夹具基类泛化为 `MachOFixtureTests` | 用户选择。否决:值类型组合(两种形状会并存)。 | +| 2026-11-20 | MKE 先发 C++ 类恢复(3.1.0),本提案随 3.2.0 | 用户选择。否决:一起发 3.1.0。 | +| 2026-11-20 | 按事实或先例自定的四条 | 名字类型改成 struct、`#filePath` 锚点由调用方传(跨包后锚点位置变了);`FixtureCompiler` 同时支持 clang 与 swiftc,本包 17 个与 MKE 5 个复制的编译代码都改用它;测试本身不搬(依赖本包与 MachOObjCSection 的模块);提案由本包维护(0098 先例),用户确认。 | +| 2026-11-20 | 状态 → Accepted | 用户批准。实现等 MachOKitExtensions 的 C++ 类恢复收尾、发 3.1.0 之后开始。 | +| 2026-11-20 | 加入成对传入、单个闭包的 `acrossAllReaders` / `acrossAllContexts` 重载 | 用户问能否加宏减少测试样板。调研:486 处跨读取器调用里 480 处的 `image:` 闭包只是换了变量名,但每处只重复约一行;做成宏要按命名约定改写标识符,也会让按标识符识别测试的扫描器失效。用户选择改用普通函数重载,并把能改的调用改过去。另一处值得用宏的样板——170 个夹具套件开头的固定 5 行——用户选择另写一份本包提案(`@FixtureSuite`)。 | +| 2026-11-20 | 加入 `TuistScript.sh` 的改动 | 维护提案 0099 的会话提醒:远程模式下 MKE 是 own-remote,不在扫描 TestingMacros 插件路径的范围内,新的 `MachOTestingSupport` 会编不过。 | +| 2026-11-20 | 用量更正 | 本包手写 `xcrun` 的测试文件是 57 个(原写 17 个 Swift 夹具),手写选 slice 70 处;都改用共享版本。 | +| 2026-11-20 | 状态 → In Progress | 用户批准开工。前置都已就位:MachOKitExtensions 3.1.0 已发布;`@FixtureSuite`(0100)与 Swift 6 迁移(0101)已落地,两个包的每个 Swift target 都开启了 `ExistentialAny`、`MemberImportVisibility`、`InferIsolatedConformances`,新代码照这三项写。先做 MachOKitExtensions 的第 1–4 步;第 4 步的发版(3.2.0)不在开工的授权内,做到文档为止,发版另行确认。 | +| 2026-11-20 | MKE 第 1、2 步完成,合成一个提交 | 两步共用测试 target,第 1 步的选 slice 测试要用第 2 步的编译器造一个三架构的 fat 库,分开提交得各编一遍。新 target `MachOTestingSupportTests` 的 20 个测试在 Ultra 上通过(Xcode 27.2)。 | +| 2026-11-20 | `DyldSharedCachePath` 保留 `versionLabel`,`rawValue` 改名 `path` | 本包 `ABIEvolutionTests` 按它给版本轴命名。本包自己命名的几个 cache(`iOS_18_5` 等,路径在本机的 Generic 卷上)不搬,第 5 步用 extension 补回。 | +| 2026-11-20 | 名字类型的静态成员照镜像本名拼写(`.SwiftUI`、`.Foundation`),不按详细设计的草稿写成 `.foundation` | 成员的值就是镜像名;本包几百处调用照旧编译,第 5 步只补 SymbolTests 那几条。`XcodeMachOFileName` 也改成 struct(位置加名字),用静态函数保留 `.sharedFrameworks(.SourceKitSupport)` 的写法;找不到文件时不再 `fatalError`,读取时报错。 | +| 2026-11-20 | `.print()` 的静默开关改为运行时环境变量 `MACHO_TESTING_SILENT=1` | 原来是编译条件 `SILENT_TEST`,由本包清单加在自己的 target 上,搬到 MKE 后到不了 MKE 的模块。第 5 步要让本包 CI(以及 Tuist 的测试 scheme)设这个变量。 | +| 2026-11-20 | `MachOFixtureTests` 的初始化保持 `async throws`;新增第三个重载 `acrossAllReaders { machO in … }` | 前者照本包现有签名,有子类写了 `override init() async throws`。后者把两个读取器本身交给同一个闭包:MKE 的 C++ 测试要比的就是读取器,而 `MachOFile` 与 `MachOImage` 不能当成同一个泛型参数传给成对的重载。 | +| 2026-11-20 | 实现细节自定 | `FixtureCompiler` 每份产物单独一个目录,库之间用 `-L`、`-l` 链接,`strip -x` 改用链接参数 `-Wl,-x`;失败的结果也缓存。`HostSlice` 先找同 CPU 类型且子类型相同的 slice,再退到同类型,再找不到就报错,不再像本包那样退到第一个 slice;单架构文件不论 CPU 都直接用。`MachOFixture(imageContaining:)` 用 `dladdr` 拿到镜像的文件路径,所以不支持 shared cache 里的镜像(那种用 `ProcessImages.cacheFileAndLoadedImage(path:)`)。读不到夹具时抛 MKE 的 `MachOFixtureError`;本包第 5 步可以在子类里把它换成带重编说明的 `FixtureLoadError`。`DyldCacheTests` 读本机 cache 时用 `FullDyldCache.cachedHost` 和它的 `mainCache`。`ExclusiveImageAccess` 在 MKE 只有按字符串的初始化,同提案。 | +| 2026-11-20 | MKE 第 3 步完成 | `ClassIndexTestImages` 与测试里那份 `ForwardingReader` 删掉;5 处现编库改用 `FixtureCompiler`;写死 Cryptexes 的 3 处与归档 cache 的 3 处改用 `DyldSharedCachePath`;手写选 slice 的 6 处改用 `HostSlice`。`ChainedFixupsFixture` 故意读每一个 slice(要覆盖 x86_64 与 arm64e 两种指针格式),不算选 slice,保留。`CPlusPlusClassIndexStoreTests` 改成 `MachOFixtureTests` 的子类,17 个参数化测试改写为 `acrossAllReaders`,实际数比提案估的约 25 个少。 | +| 2026-11-20 | 跨读取器比较的是去掉偏移的形状 | 同一份数据在文件里与加载后的偏移不同,C++ 测试先把类与 vtable 投影成 `ClassShape`、`VirtualTableShape` 再比较;偏移之间的关系在闭包里各自算成布尔值或距离返回。改写时查出一处读取器之间的真实差别:另一个镜像里的基类,文件读出绑定所写的 `libc++.1.dylib`,进程里读出 dyld 找到符号的 `libc++abi.dylib`(被 libc++ 重新导出)。原测试只查名字含 `libc++`,两边都满足,属于既有行为,不是这次引入的;形状里只记「在另一个镜像」,各读取器分别判断是不是 libc++。 | +| 2026-11-20 | MKE 第 4 步的文档完成,实现完成(MKE 部分),待用户看过后收尾 | 新增实现说明 `Internal/TestingSupport.md`,README 的 product 表加两行,文档索引与提案索引登记(提案索引是跨仓库行)。验证在 Ultra 上(Xcode 27.2):MKE 全量 `swift test` 271 个测试通过,原始退出码 0;带 `CPLUSPLUS_CLASS_CENSUS_FRAMEWORKS` 的 TSTables 与 Espresso 普查也通过(断言精确计数)。发 3.2.0 不在开工的授权内,等用户确认;第 5、6 步等 3.2.0 发布后在本包做。 | +| 2026-11-20 | `FixtureCompiler` 的锁改用 FrameworkToolbox 的 `OSToolbox.Mutex`,MKE 因此新增依赖 FrameworkToolbox(只有 `MachOFixtureSupport` 用) | 用户要求:不用 `NSLock`,尽量不写 `@unchecked Sendable`。标准库的 `Mutex` 要 macOS 15、`OSAllocatedUnfairLock` 要 macOS 13,MKE 的下限是 macOS 10.15,OSToolbox 的 `Mutex` 用法相同、没有版本限制。产物目录与退出时清理改成两个全局 `let`;`ProcessMemory` 的格式化器改为用时现建,去掉 `nonisolated(unsafe)`;测试里 `MachOFixtureTests` 子类多写的 `@unchecked Sendable` 删掉(MainActor 基类本就 Sendable)。MKE 全量测试通过,退出码 0。本包第 5 步同样不要再写 `NSLock`。 | +| 2026-11-20 | MKE 其余模块的 `NSLock` 也一并换成 `OSToolbox.Mutex`,随 3.2.0 发布 | 用户决定:FrameworkToolbox 本来就是 MSS 与 RuntimeViewer 的依赖。19 个文件、7 个库 target;每段临界区的范围保持不变(先查、出锁构建、再进锁写回的照旧);能被编译器认作 `Sendable` 的类型去掉了 `@unchecked`,还持有 `DyldCache`、`FullDyldCache`、指针的 5 个保留并写明原因。非 `Sendable` 的值存进锁时用 `withLockUnchecked`(6 处),各有注释。MKE 全量测试与 TSTables、Espresso 普查通过,退出码 0。 | +| 2026-11-20 | MKE 撤掉 Linux 支持 | OSToolbox 的 `Mutex` 基于 `os_unfair_lock`,只在 Apple 平台上有,换锁后 Linux 编不过。用户选择撤掉承诺(否决:给 OSToolbox 补 Linux 实现;在 MKE 里按平台分开用标准库的 `Mutex`)。此前从没有 Linux CI,也没在 Linux 上验证过。MachOObjCSection 依赖 MKE,它对 Linux 的承诺随之失效。 | +| 2026-11-20 | MKE 的 `Sources/` 按层分组,两个测试支持 target 在 `Sources/TestSupport/` 下 | 用户要求照本包 0055 分组,MKE 另写了提案 0007-group-sources-by-layer,同一分支、随 3.2.0。本提案改动地图里 MKE 的源码路径随之更新。 | +| 2026-11-21 | MKE 部分合入 MachOKitExtensions `main` 并推送,未发版 | 用户看过后收尾:测试支持的两个 product、MKE 测试改用它们、全部 `NSLock` 换成 `Mutex`、撤掉 Linux 与 `Sources/` 分组(MKE 0007)一起进了 `main`,最终代码上 MKE 全量测试通过。3.2.0 还没发;本包第 5、6 步等它发布后在本分支继续。 | +| 2026-11-21 | 第 5 步的已知缺口:`FixtureCompiler` 还不能完全替代本包的 `CompiledFixture` | 本包 `Tests/CrossReferenceAnalysisTests/CompiledFixture.swift` 的 `build(libraryName:sources:compilerArguments:isExecutable:)` 能编可执行文件(`FileModeTests`、`FunctionStartOutsideTextTests` 两处用 `isExecutable: true`)、一次编多个源文件、按参数指定架构;MKE 3.1.0 之后的 `FixtureCompiler` 只把单个源字符串编成动态库。要么在发 3.2.0 之前给 `FixtureCompiler` 补可执行文件与多源文件,要么这几处在本包保留自己的辅助,待用户定。另:next 上新进的 `FunctionStartOutsideTextTests.anIndexKeepsTheReferencesOfAFunctionBelowText` 用到 `CompiledFixture.build(…isExecutable:)` 与 `InstructionEncoding.branchWithLink(at:to:)`,第 5 步若搬走或改名它们,这条测试一起改,本分支合 next 时会遇到它。 | +| 2026-11-21 | `FixtureCompiler` 补上可执行文件与多源文件,MKE 3.2.0 发布 | 用户选择发版前先补:新增 `executable(named:language:source:arguments:)`、两个收 `sourceFiles: [FixtureSourceFile]` 的重载,单段源码的写法不变;本包 `CompiledFixture.build` 的可执行文件、多源文件与指定架构(经参数 `-arch`)都能用它替代。`CompiledFixture.load` 的链接后改写、重新签名、再加载留在本包,在复制出的产物上做(共享编译器的产物是缓存,不能原地改)。MKE 全量测试通过,原始退出码 0;随后在 `main` 上打 3.2.0(附注 tag,同以往不建 Release 页面)。本包第 5、6 步可以开始。 | +| 2026-11-21 | 第 5 步第一部分:测试支持改接 MKE 3.2.0 | MKE 下限升到 3.2.0;两个 support target 依赖并 re-export `MachOFixtureSupport` / `MachOTestingSupport`,搬走的 12 个文件删除;SymbolTests 的文件名与镜像名、本包命名的 cache、按本包名字的 `ExclusiveImageAccess` 初始化留在本包作 extension。`ExclusiveImageAccess` 的 key 取镜像名(文件名取路径最后一段去扩展名),同一夹具按文件或按镜像声明仍互斥,新测试 `ExclusiveImageAccessKeyTests` 钉住这一点。`MachOSwiftSectionFixtureTests` 改为 `MachOFixtureTests` 的子类,读不到夹具时把 `MachOFixtureError` 转成带重编说明的 `FixtureLoadError`。MKE 也有公开的 `DeclaredWrapper` / `UndeclaredWrapper`,与本包同名标记冲突,`ForwardingMachOReader` 改用 MKE 的标记(读取器本身留在本包)。CI 加 `MACHO_TESTING_SILENT: 1`。`swift test --skip IntegrationTests` 2,914 个通过,退出码 0(基线 2,916:删 4 个搬走的测试,加 2 个);IntegrationTests 与可执行文件都编过。 | +| 2026-11-21 | 第 5 步第二部分:现编与选 slice 改用共享版本 | 41 处现编改用 `FixtureCompiler`(5 个 Swift 夹具、交叉引用测试 11 处、其余 25 处),源文件名一律照旧(private 判别符由文件名哈希得出);约 66 处手写选 slice 改用 `HostSlice`,故意选 arm64e 的 `StandaloneFileReferenceDumpTests` 照旧。`CompiledFixture` 只剩 `load`:经共享编译器编出后复制一份再改写、重签名、加载,不碰共享的缓存产物;`build` 与 `buildSwift` 删除。改过去的库 install name 从绝对临时路径变成 `@rpath/lib<名字>.dylib`;`ReferenceKindAndRouteTests` 的 Swift 库因模块名必须是 `Fixture` 改叫 `libFixture.dylib`(没有断言读文件名)。约 25 处共享编译器表达不了,保留手写,见后续项。`swift test --skip IntegrationTests` 2,914 个通过,退出码 0。 | +| 2026-11-21 | 后续项:`FixtureCompiler` 还替代不了的现编 | 留着手写的约 25 处要的是:产物名与 Swift 模块名不同(`lib<模块>-<变体>` 之类);`-emit-module`、`.swiftinterface`、bridging header、modulemap 写到调用方选的路径;编完再 `strip` / `codesign`;先编 `.o` 再链接;另一套工具链(`DEVELOPER_DIR`)或 `--sdk iphonesimulator`;放进假系统根里由 install name 决定的路径。要全部收掉,`FixtureCompiler` 得加模块名参数、编译前就能拿到的产物目录和一个后处理步骤,留待以后另议(MKE 次版本)。 | +| 2026-11-21 | 第 5 步第三部分:跨读取器调用改成单闭包 | 486 处调用里 478 处改成成对传入、单个闭包(`acrossAllReaders` 418 处、`acrossAllContexts` 60 处),8 处保留三闭包:6 处带 `inProcess:`,2 处 `functionAddress(in:)` 的结果类型是 `Context.Address?`,依赖上下文的 associated type,打开 `any ReadingContext` 后推不出类型(`AccessibleFunctionRecordTests`、`AsyncFunctionPointerTests` 的 `fromContext`)。提案原估 480 / 6。`SuiteBehaviorScanner` 只看函数体与所在类里有没有这两个名字,前后对比 793 个测试方法,分类(跨读取器 593、只用进程内 61、只注册不读 139)与每个方法里的调用次数都不变。断言一行未动;`swift test --skip IntegrationTests` 2,914 个通过,退出码 0。 | +| 2026-11-21 | 第 5 步第四部分:本机 cache 共用、Tuist 远程模式 | `DyldCache(path: .current)` 等 27 处只读本机 cache,全部改用 `FullDyldCache.cachedHost`(要 `DyldCache` 的取它的 `mainCache`),`GenericSpecializationFixture` 也一并改;`FileMappingTests` 要在调低的描述符上限下打开这些文件,保留新实例并注明。缓存按镜像路径与 UUID 分,不认实例,共用不改变缓存行为。`TuistScript.sh` 的 `testing_support_names` 扫描挪到 `if role != "own-path"` 之前,own-remote 的包也扫;`Workspace.swift` 在设了 `MACHO_SWIFT_SECTION_SILENT_TEST=1` 时给测试 scheme 的环境加 `MACHO_TESTING_SILENT=1`;`TuistDevelopment.md` 同步。`swift test --skip IntegrationTests` 2,914 个通过,退出码 0。`./TuistScript.sh test` 远程模式退出码 65,没走到 MKE 的 `MachOTestingSupport`:`SwiftSectionTestingMacrosTests` 的 `@testable import SwiftSectionTestingMacros` 在 Tuist 里解析不到宏 target。这个测试 target 随 0100 进入 next,Tuist 的适配段没处理依赖宏 target 的测试,是 next 上已有的问题,与本提案无关;已确认远程模式的扫描结果含 `MachOTestingSupport`、生成的工程带 TestingMacros 插件路径、scheme 带 `MACHO_TESTING_SILENT=1`。这一条验证待那个问题修好后补跑。 | +| 2026-11-21 | 修好 Tuist workspace 的宏测试,补跑远程模式 | 用户选择在本分支一起修:清单末尾的 Tuist 适配段把依赖宏 target 的测试也拿掉(与依赖可执行 target 的测试同样处理),宏的展开测试只在 `swift test` 里跑。三个上游库清单末尾的同一段代码按约定该一起改,它们没有宏 target,这次没同步,`TuistDevelopment.md` 记了这一点。`./TuistScript.sh test` 远程模式退出码 0(`TEST SUCCEEDED`,约 26 分钟,2,953 个测试),编过了 MKE 的 `MachOTestingSupport`。 | +| 2026-11-21 | 实现完成,待用户看过后收尾 | 第 5、6 步都已完成。文档:`AGENTS.md`(`Sources/` 一节的锚点、测试一节的测试支持来源与本机 cache、`ExclusiveImageAccess` 的 key、静默变量、新增套件时的写法)、`FixtureTestingAndContinuousIntegration.md`(路径锚定与新的一节)、`Modules/README.md`、`TuistDevelopment.md`、`ProjectEvolutionLog.md`(节号落地时定)。不另写实现说明(契约在 MachOKitExtensions 的 `TestingSupport.md`),没有新术语。后续项:`FixtureCompiler` 还替代不了的约 25 处现编(见上)。 | +| 2026-11-21 | Tuist 适配段的「宏 target」一条同步到三个上游库 | 用户选择保持四份一致:MachOKitExtensions `main`、MachOObjCSection `next`、swift-demangling `next` 各一个提交并推送;三者都没有宏 target,设与不设 `TUIST_MAPS_LOCAL_PACKAGE_TESTS` 时清单解析结果与改前相同。不发版。 | +| 2026-11-21 | 状态 → Implemented,取号 0104 | 用户看过后收尾,合进 `next` 并推送。`next` 上先落地了 0103(跨引用测试的整份 cache 扫描限并发),所以本提案取号 0104、演进账本记为第 150 节。合并前把最新 `next` 合进本分支:只有 `Documentations/README.md` 与演进账本冲突,两边都保留;0103 新规则(`CrossReferenceAnalysisTests` 里不直接调 `DispatchQueue.concurrentPerform`,由 `ParallelScanSourceTests` 检查)合并后仍满足。合并结果上在 Ultra(Xcode 27.2)重跑:`swift test --skip IntegrationTests` 2,971 个通过,退出码 0;`./TuistScript.sh test` 远程模式 3,003 个通过、0 失败、7 个跳过,退出码 0。`next` 上 `./TuistScript.sh test` 因 `SwiftSectionTestingMacrosTests` 编不过的问题随本提案修好。文档判断:不另写实现说明或使用指南(两个 product 的契约在 MachOKitExtensions 的 `TestingSupport.md`),没有新术语;MachOKitExtensions 里指向本提案的链接一并改成 0104。后续项照旧:`FixtureCompiler` 还替代不了的约 25 处现编。 | diff --git a/Documentations/Evolutions/0105-swift-type-indexing-package.html b/Documentations/Evolutions/0105-swift-type-indexing-package.html new file mode 100644 index 000000000..e4a07c1e8 --- /dev/null +++ b/Documentations/Evolutions/0105-swift-type-indexing-package.html @@ -0,0 +1,857 @@ + + + + + + +0105 - 类型索引独立成 swift-type-indexing 包,并接入 MachOObjCSection 与 RuntimeViewer + + + + +
+ +
+

MachOSwiftSectionEvolutions0105

+

0105 类型索引独立成 swift-type-indexing 包,并接入 MachOObjCSection 与 RuntimeViewer

+
+
状态
Implemented
+
最后更新
2026-11-24
+
项目类型
库(跨仓库唯一提案)
+
跨仓库范围
新仓库 swift-type-indexing、swift-apinotes fork(实现中加入)、swift-semantic-string(验收中加入)、MachOObjCSection、MachOSwiftSection(持有本提案)、RuntimeViewer
+
原文
0105-swift-type-indexing-package.md
+
+
+ + + +
+ +
+

摘要

+

把 MachOSwiftSection 的 TypeIndexing target(SDK 模块索引、API notes 索引、ObjC 元数据归属、按 SDK 版本的磁盘缓存)整体搬进新的独立包 swift-type-indexing,模块名仍是 TypeIndexing。新包不依赖 MachOSwiftSection,也不依赖 MachOObjCSection:原来直接调用 ObjCIndexing 补私有类归属的那一层,改成新包声明的协议 DeclaredTypeNameSource,由 MachOObjCSection 实现。

+

搬家同时修两处错误:

+
    +
  • API notes 的改名规则:只有 SwiftPrivate 的类型要加 __ 前缀,有 SwiftName 的直接用它——现在两种都不改名。
  • +
  • sourcekitd 只认 Xcode 的目录结构,只装 Command Line Tools 时找不到。
  • +
+

之后三方接入:

+
    +
  • MachOObjCSection:打印 ObjC 头文件时,按 API notes 在类、协议、category 及其成员上标出 NS_SWIFT_NAME(...) / NS_REFINED_FOR_SWIFT。
  • +
  • MachOSwiftSection:删掉 TypeIndexing target,只留一个薄适配层;swift-section interface --resolve-c-module-names 照常可用,swift-section objc 加一个同类开关。
  • +
  • RuntimeViewer:在找得到对应平台 SDK 的 Mac 上,默认把 __C.UICellConfigurationState 打印成 UIKit.__UICellConfigurationState。索引在 engine 连上后后台预建、进 Report;建好前先显示 __C.,建好后自动刷新;MCP、命令行与导出一起换成解析后的名字。
  • +
+
+ +
+

要你定

+
+

没有待你决定的事

+

提案已批准;swift-apinotes 0.3.0 与 swift-type-indexing 0.1.0 已经批准推送并打了 tag。

+
+
+

agent 自己定的(可以推翻)

+
    +
  • MCP、命令行、导出与 Find 语料构建等索引就绪(或确认不可用)再打印;只有界面先显示 __C.。
  • +
  • 两个开关放在 Generation Options 面板(Swift 组、ObjC 组),不放 Settings:现有打印开关都在这里,随请求发出、进缓存键、命令行也读同一份。
  • +
  • 缓存放 ~/Library/Caches/<App 的 bundle id>/TypeIndex/,不是 RuntimeDerivedDataKind;Delete Derived Data 一起删。
  • +
  • 新仓库不迁移 git 历史;MachOSwiftSection 不保留旧 product 的转发层。
  • +
+
+
+ +
+

架构图

+
    +
  • 新增
  • +
  • 修改
  • +
  • 删除
  • +
  • 移动
  • +
  • 不变
  • +
+ +

模块依赖:改了什么

+
+ + + RuntimeViewer + RuntimeViewerCoreTypeNames/, printers + RuntimeViewerAppCoreReport, refetch + macOS appGeneration Options switches + MCP / CLI / exportwaitsForTypeIndex = true + + + MachOSwiftSection + SwiftSectionKit / CLIobjc --mark-sdk-swift-names + SwiftTypeNameResolutionTypeDatabaseTypeNameResolver + SwiftPrintingSwiftInterface + TypeIndexingmoved to swift-type-indexing + + + MachOObjCSection + ObjCInterfaceprotocol / category take notes + ObjCTypeIndexingObjCDeclaredTypeNames, notes + ObjCDeclarationRenderingNS_SWIFT_NAME, type-level note + ObjCIndexing + + + swift-type-indexing + TypeIndexingrename rule fixedCLT sourcekitd, cache dir + + + third party + SourceKitD + swift-apinotes (fork)0.3.0: ObjC members public + + + + + + + + + + + + +
+

箭头从使用方指向依赖。RuntimeViewerCore 还直接依赖 ObjCTypeIndexing 与 TypeIndexing(建 TypeDatabase、取 ObjC 标注),图里省略;三个新依赖都只在 macOS 上。红色虚线是删掉的旧依赖:MachOSwiftSection 的 TypeIndexing 直接调用 ObjCIndexing。swift-apinotes fork 把 ObjCContext.methods / properties 改成 public 并打 0.3.0,ObjC 成员的标注才有来源。

+ +

新包内部

+
TypeDatabase                                   (actor, no longer generic)
+├── SDKIndexer.discover()           -> .swiftmodule list, .apinotes files       (no sourcekitd)
+├── ModuleInterfaceIndexer          -> type names per module                    (sourcekitd; skipped when missing)
+│   ├── SourceKitManager
+│   │ + └── SourceKitLocator        -> Xcode toolchain | Command Line Tools
+│   └── ModuleIndexCache            ~ directory injected by the caller
+├── APINotesIndex                   ~ SwiftName wins; SwiftPrivate alone -> "__" + C name
+│                                   + ObjC container entries (methods, properties)
+- ├── ObjCInterfaceIndexer (MOS)
++ └── [any DeclaredTypeNameSource]   -> lazy fallback, first image wins
+ +

RuntimeViewer 的建立与刷新

+
+ + service process startslocal / Catalyst / file / framework service,Catalyst helper, standalone CLI host + RuntimeTypeNamesenableInThisProcess() + + + RuntimeSwiftSectionupdateConfiguration(for: options)resolvesImportedTypeNames on + RuntimeTypeIndex.process.requestplatform of LC_BUILD_VERSION, modules theimage links, the image's own ObjC metadata + TypeIndexingAvailabilityavailability(for:)unavailable -> status .unavailable(reason), no batch + + + + batch, after the platform's previous oneReport row "Imported Type Names",toolbar activity + TypeDatabaseindex(dependencies:moduleFilter:)reads/writes ~/Library/Caches/<id>/TypeIndex + + + + generation += 1listeners called + + + next print: RuntimeSwiftSectionsees a new generation, registersTypeDatabaseTypeNameResolver, dropsinterfaceByObject / importedInterfaceByObject + RuntimeEnginebroadcasts RuntimeDataChange.typeNamesResolved(platformName:) + app: ContentTextViewModelflushes RuntimeInterfaceCache, refetches-> UIKit.__UICellConfigurationState + + + + + interface request + UIwaitsForTypeIndex = false + prints now__C.X until the image's batch is done + MCP/CLI/export/Find corpuswaitsForTypeIndex = true + awaits the image's batchthen prints + + + +
+

打印的服务进程(本机、Catalyst、文件、框架四个 service,Catalyst helper,独立的命令行 host)启动时打开索引。Swift section 第一次为一个镜像配置时(开关开着)请求一批:平台取镜像的 LC_BUILD_VERSION,内容是它链接的模块和它自己的 ObjC 元数据;SDK 不可用就记下原因、不排批次。同一平台的批次依次执行,每批完成把平台的 generation 加一:section 下次配置时重新注册解析器、清掉自己的接口缓存,engine 广播 .typeNamesResolved,App 的 ContentTextViewModel 先清 RuntimeInterfaceCache 再重新取。最下面是两类请求:界面立刻打印(这个镜像那一批完成前是 __C.),MCP、命令行、导出与 Find 语料等这个镜像那一批完成再打印。

+
+ +
+

改动地图

+

步骤编号见「落地步骤」。

+ +
+ swift-type-indexing(新仓库) +
+
+ + + + + + + + + + + + + + + + + + + + + +
文件 / 类型动作改什么为什么步骤
Package.swift新增包名 swift-type-indexing,product / target TypeIndexing,测试 target TypeIndexingTests;依赖 SourceKitD、swift-apinotes(from: "0.3.0",本地候选 ../../../Fork/Library/swift-apinotes)、FrameworkToolbox(后两者限 macOS);平台与 MachOSwiftSection 一致(macOS 10.15 / iOS 13 / tvOS 13 / watchOS 6 / visionOS 1);打开 ExistentialAny、MemberImportVisibility、InferIsolatedConformances独立成包;平台声明不能高于 MachOObjCSection,否则 SwiftPM 拒绝解析1
InterfaceDeclarationNode、InterfaceTypeNameExtractor、ModuleIndexCache、ModuleInterfaceIndexer、SDKIndexer、SDKPlatform、SourceKitManager、Subprocess、SupplementaryAPINotes移入原样搬入;package 改 public(只公开调用方需要的,其余 internal);@Loggable 子系统改为 com.mxiris.type-indexing搬家1
APINotesIndex移入 修改用 ImportedTypeNameCategory;改名规则:有 SwiftName 用它(不论 SwiftPrivate),只有 SwiftPrivate 时 "__" + cName;cNamesBySwiftName 同步登记;新增 ObjC 容器的方法、属性条目索引修正改名;给 ObjC 标注提供数据1、2、3
TypeDatabase移入 修改去泛型;index(dependencies:moduleFilter:) 改收 [any DeclaredTypeNameSource],可多次调用(第一次发现 SDK、登记 API notes,之后只补新模块与新依赖);API notes、模块接口、运行时元数据三张表在查询时按优先级查,不再靠写入顺序覆盖;moduleName(forImagePath:) 保持纯函数;构造器加 cacheDirectory:;没有 sourcekitd 时只读缓存;新增 swiftImportAnnotations(forObjCClassNamed:) / forObjCProtocolNamed:去掉对 MachOObjCSection 的依赖;RuntimeViewer 加载新镜像时要追加模块;缓存位置由调用方决定;给 ObjC 标注用1、2、3
DeclaredTypeNameSource新增协议:imagePath、declaredTypeNames() async throws -> [String]取代直接调用 ObjCInterfaceIndexer1
ImportedTypeNameCategory新增objcClass / objcProtocol / valueType / other取代 SwiftPrinting 的 CImportedTypeNameCategory1
SourceKitLocator新增依次试 <developer dir>/Toolchains/XcodeDefault.xctoolchain/usr/lib/sourcekitd.framework/sourcekitd 与 <developer dir>/usr/lib/sourcekitd.framework/sourcekitd;SourceKitManager 改用它支持 Command Line Tools2
TypeIndexingAvailability新增static func availability(for: SDKPlatform):sdkSettings(含 SDK 路径与版本,供 RuntimeViewer 的语料 variant 用)、sourcekitd 路径、不可用原因调用方决定开不开、在界面上说明原因2
SDKPlatform.macCatalyst、SDKSettings.macCatalystVersion、compilerArguments(for:)修改新 case macCatalyst:读 macOS SDK(xcrunSDKName),target ios<SupportedTargets.iosmac.DefaultDeploymentTarget>-macabi,给 sourcekitd 显式补 -Fsystem …/System/iOSSupport/System/Library/Frameworks;SDKIndexer 的 Catalyst 搜索路径先 System/iOSSupport/… 再 macOS 的;缓存目录与 macOS 分开Mac Catalyst 的 UIKit 与其 API notes 只在 iOSSupport 里,原来按 .macOS 索引找不到2、3
SwiftImportAnnotation、ObjCContainerSwiftImportAnnotations、ObjCMemberKey新增单个声明与一个类 / 协议的 API notes 命名标注给 MachOObjCSection 用3
Tests/TypeIndexingTests/*移入 修改7 个文件搬入;TypeDatabase<MachOFile> 改为用假的 DeclaredTypeNameSource;swiftPrivateEntitiesAreAttributedButNotRenamed 改写为新规则搬家;规则修正1、2
DeclaredTypeNameSourceTests、SwiftNameRuleTests、SourceKitLocatorTests、TypeIndexingAvailabilityTests、CacheDirectoryTests、MacCatalystPlatformTests、ObjCSwiftImportAnnotationTests新增见各步骤的行为清单回归测试1、2、3
SDKIntegrationTests新增对本机真实 SDK 的核对,默认关闭:TYPE_INDEXING_SDK_TESTS=1(只读 API notes,约 2 秒),再加 TYPE_INDEXING_SOURCEKIT_TESTS=1 经 sourcekitd 冷生成 Catalyst 的 UIKit 接口(实测 126 秒)单测覆盖不到 SDK 布局与 sourcekitd 参数2、3
README.md、LICENSE、AGENTS.md + CLAUDE.md(符号链接)、Documentations/README.md、提案索引(项目类型:库)、TypeIndexingPipeline.md(从 MachOSwiftSection 移入并更新)新增 移入用法、三层数据源、改名规则、缓存布局、可用性新仓库的文档1、3
.github/workflows/macOS.yml新增照 MachOSwiftSection 的 macOS.yml 配 macOS 构建与测试CI1
SourceKitManager.swift · SourceKitManager、InterfaceDocumentService、SourceKitDInterfaceDocumentService修改每个打开的接口读完就用同一文档名 editor.close(生成失败也关);同时最多生成 2 个;请求经 InterfaceDocumentService 发出;发 0.1.1验收时 SourceKitService 涨到 80 GB(见决策日志)验收
SourceKitManagerTests.swift、TypeIndexingPipeline.md新增 修改替身核对打开与关闭配对、并发上限(去掉任一即失败);文档记下原因与量法回归,文档同批验收
+
+
+
+ +
+ swift-apinotes(fork,实现中加入) +
+
+ + + + + + +
文件 / 类型动作改什么为什么步骤
ObjCContext.swift · ObjCContext.methods / properties修改标 public;打 tag 0.3.00.2.0 里是 internal,包外读不到类与协议的成员,ObjC 成员的标注没有来源3
Tests/APINotesTests/ObjCContextMemberAccessTests.swift新增不带 @testable 读成员(修复前编译失败)回归3
+
+
+
+ +
+ swift-semantic-string(验收中加入) +
+
+ + + + + + +
文件 / 类型动作改什么为什么步骤
SemanticType.swift · SemanticType.macro、Components/Macro.swift · Macro新增宏这一语义类型与它的组件;冻结编码取 22(之前的读者把它当未知编码,显示成 .other);发 0.7.0MachOObjCSection 打印的 NS_SWIFT_NAME / NS_REFINED_FOR_SWIFT 原先只能标成关键字验收
FrozenSemanticStringTests.swift、ReviewFindingsRegressionTests.swift、README.md、AGENTS.md修改类型清单与编码总数加一,冻结与两种 Codable 的往返;文档列出新类型回归,文档同批验收
+
+
+
+ +
+ MachOObjCSection +
+
+ + + + + + + + + + + + + + + + + +
文件 / 类型动作改什么为什么步骤
Package.swift修改.package(local: ../swift-type-indexing, remote: …, from: "0.1.0"),带理由注释;新 target ObjCTypeIndexing(依赖 ObjCIndexing、ObjCDeclarationRendering、TypeIndexing 限 macOS)与同名 product;测试 target ObjCTypeIndexingTests接入新包,且只有新 target 依赖它4
ObjCDeclaredTypeNames<MachO>新增实现 DeclaredTypeNameSource:ObjCInterfaceIndexer(machO:imagePath:) → prepare() → 类、协议、struct、union 名取代 MachOSwiftSection TypeDatabase.indexObjCMetadata(of:) 的那段4
ObjCSwiftImportNotes+TypeDatabase.swift新增init(apiNotesForClassNamed:in:)、init(apiNotesForProtocolNamed:in:)API notes → 标注5
ObjCSwiftImportNotes、Note修改Note 加 swiftName: String?;值上加 declarationNote: Note?;加 merging(_:);渲染 NS_SWIFT_NAME(name)(在 NS_REFINED_FOR_SWIFT 前);新增类型一级的渲染函数标 Swift 命名5
ObjCClassInfo / ObjCProtocolInfo / ObjCCategoryInfo 的 semanticString(using:)修改声明行之前打印类型一级的宏行;category 成员也读标注类型一级宏5
ObjCInterfaceBuilder 的 protocolInterface / markedProtocolInterface / categoryInterface / markedCategoryInterface修改加 swiftImportNotes: 参数(默认空)协议与 category 也能标5
Tests/ObjCInterfaceTests/SwiftImportNotesRenderingTests.swift修改加 NS_SWIFT_NAME、类型一级、协议、category 的用例回归5
Tests/ObjCTypeIndexingTests/*新增ObjCDeclaredTypeNames 对 Foundation 镜像列出 NSObject 等;API notes 转换(临时 .apinotes 驱动)回归4、5
README.md、ObjCSectionCommandLine.md(库调用方一节)、Glossary.md、提案索引(cross-repository 行)修改新 target、新标注、指向本提案文档同批4、5
ObjCSwiftImportNotes.swift修改两个宏由 Keyword 改为 Macro;括号里的 Swift 名仍是普通文本验收时发现它们与 @interface 同为关键字色,Xcode 用宏色(见决策日志)验收
objc-section/Utilities/SemanticString+Color.swift修改.macro 用 Xcode Default 主题的宏色(浅色 #643820、深色 #FD8F3F)命令行配色同步验收
Package.swift(swift-semantic-string)修改临时钉 branch: "feature/swift-type-indexing-package"(注明 TEMPORARY),收尾改为 from: "0.7.0"用到 Macro验收
SwiftImportNotesRenderingTests.swift · macrosAreMacroRuns修改两个宏是 .macro、Swift 名是 .standard(修复前失败)回归验收
+
+
+
+ +
+ MachOSwiftSection(持有本提案) +
+
+ + + + + + + + + + + + + + + + + +
文件 / 类型动作改什么为什么步骤
Package.swift修改删 TypeIndexing target、product、TypeIndexingTests、SourceKitD 与 swift-apinotes 两个依赖;加 swift-type-indexing 本地候选依赖;加 target / product SwiftTypeNameResolution(依赖 SwiftPrinting、SwiftInterface、TypeIndexing 与 ObjCTypeIndexing 限 macOS);SwiftSectionKit、IntegrationTests 改依赖它搬家后的接线6
Sources/Declaration/TypeIndexing/(除适配器外 11 个文件)删除已移入新包搬家6
TypeDatabaseTypeNameResolver新增包一个 TypeDatabase,实现 ModuleNameResolving + CImportedNameResolving,映射 CImportedTypeNameCategory → ImportedTypeNameCategory打印器与新包之间唯一的适配点,RuntimeViewer 也用它6
SwiftInterfaceBuilderTypeNameProvider移动 修改从 Sources/Declaration/TypeIndexing/ 移进 SwiftTypeNameResolution;依赖改为 TypeDatabaseTypeNameResolver 与 ObjCDeclaredTypeNames;buildVersionCommand 改用 MachOKitExtensions 的公开版本名字不变以免动 CLI 调用方6
InterfaceRequest.swift修改import TypeIndexing 改为新模块;APINotesFile(path:) 预校验照旧接线6
ObjCInterfaceCommand.swift、SwiftSectionKit/ObjC/*修改新增 --mark-sdk-swift-names:按镜像平台建 TypeDatabase,把 API notes 标注交给 ObjCInterfaceBuilder;找不到 SDK 时警告并照常输出swift-section objc 的同类开关7
Tests/TypeIndexingTests/删除已移入新包搬家6
TypeNameProviderTests.swift、CommandRequestMappingTests.swift修改import 改名;加 --mark-sdk-swift-names 的映射用例接线6、7
Tests/SwiftTypeNameResolutionTests/TypeDatabaseTypeNameResolverTests.swift新增分类映射、__C 解析经适配器到达打印器回归6
README(product 表等)、文档索引、SupplementaryTypeMappings.md、内部文档(TypeIndexingPipeline.md 删、改为指向新包,ProjectMap.md、Modules/README.md)、术语表、SwiftSectionKit{,_zh}.md、ObjCCommandLine{,_zh}.md、AGENTS.md / CLAUDE.md、swift-section 插件 skill(加 objc 新开关)及其插件清单的 version修改指向新包、新 target、新开关文档同批6、7
Documentations/Evolutions/README.md修改登记本提案索引0
swift-section/Output/StandardStreamOutput.swift修改.macro 的配色与 objc-section 相同objc interface --mark-sdk-swift-names 的宏上色验收
Package.swift(swift-semantic-string)修改临时钉功能分支,收尾改为 from: "0.7.0"与 MachOObjCSection 的钉法一致验收
+
+
+
+ +
+ RuntimeViewer +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
文件 / 类型动作改什么为什么步骤
RuntimeViewerCore/Package.swift修改加 swift-type-indexing(本地候选 ../../swift-type-indexing + 远端,限 macOS);RuntimeViewerCore target 加 TypeIndexing、ObjCTypeIndexing、SwiftTypeNameResolution 三个 product(限 macOS)。实现期间 MachOObjCSection 与 MachOSwiftSection 临时钉 branch: "feature/swift-type-indexing-package",收尾时改回 branch: "next"接线8
Local workspace、.worktrees/swift-type-indexing 链接、LocalDependencies.md修改加 ../swift-type-indexing本地联调8
Tuist.swift、TuistScript.sh修改删 MachOSwiftSection 的 "TypeIndexing",加 "SwiftTypeNameResolution"、MachOObjCSection 的 "ObjCTypeIndexing";swift-type-indexing 加进 SOURCE_DEPENDENCIES 并列出它的 targetTuist 描述同批8
AGENTS.md「Dependency floors」修改加 swift-type-indexing 的版本下限与理由规则8
TypeNames/RuntimeTypeIndex.swift · RuntimeTypeIndex新增actor,每进程一个(static let process,不经 @Dependency);每个 SDKPlatform 一个 TypeDatabase;request(_:) 把一个镜像链接的模块和它自己的 ObjC 元数据排成一批,同平台的批次依次执行;每批完成把平台的 generation 加一并通知监听者;resolution(for:)、swiftImportNotes(forClassNamed:/forProtocolNamed:platform:)、status()进程级共享索引9
TypeNames/RuntimeTypeNames.swift · RuntimeTypeNames新增进程开关 enableInThisProcess()(照 RuntimeDerivedData.enableInThisProcess());platformName(of:) 取镜像第一个 LC_BUILD_VERSION 的平台只有打印的服务进程建索引9
TypeNames/RuntimeTypeIndexLocation.swift新增缓存目录:.app / Contents/XPCServices / Contents/Applications 往上找 .app → ~/Library/Caches/<bundle id>/TypeIndex;不在 App 里 → ~/Library/Caches/runtime-viewer-cli/TypeIndex;测试用临时目录所有进程共用缓存9
TypeNames/RuntimeTypeIndexStatus.swift新增线上类型:每个平台 building(progress) / ready / unavailable(reason)、缓存字节数Report 与工具栏9
TypeNames/RuntimeEngine+TypeNames.swift、Engine/RuntimeEngine+Commands.swift · TypeIndexStatusCommand新增Core 自有命令 typeIndexStatus,路由 .servingEngine,加进 SharedCacheRoutingDeclarationTests 的清单;typeIndexStatus() 经新的 dispatchToServingProcess(_:timeout:) 发出、连接自带 2 秒超时,旧对端答 .empty;startObservingTypeIndex() 把批次完成转成广播;RuntimeTypeNamesCorpusVariant让 App 读状态9
Engine/RuntimeDataChange.swift修改新 case typeNamesResolved(platform: String)通知 App 刷新9
Sections/Swift/RuntimeSwiftSection.swift修改显示打印器与语料打印器都注册 TypeDatabaseTypeNameResolver;updateConfiguration 每次按开关重建解析器列表(不再被 removeAllTypeNameResolvers() 误删);收到索引就绪时清 interfaceByObject / importedInterfaceByObject打印解析后的名字9
RuntimeObjCSection.swift、RuntimeEngine.swift、Search/RuntimeEngine+Search.swift修改类、协议、category 都取 API notes 标注,与 objcSwiftImportNotes(for:) 合并后传入ObjC 标注9
Interfaces/SwiftGenerationOptions.swift修改@Default(true) resolvesImportedTypeNames开关9
Interfaces/RuntimeObjectInterface+GenerationOptions.swift · GenerationOptions修改@Default(true) marksSwiftNamesFromAPINotes(ObjC 头文件的开关,放顶层:objcHeaderOptions 是 MachOObjCSection 的 ObjCGenerationOptions,而这个开关只决定 RuntimeViewer 传不传标注);@Default(false) waitsForTypeIndex开关;非交互的调用方等索引9
RuntimeInterfaceCorpusSnapshot.swift、RuntimeInterfaceCorpusStore.swift修改variant 加 -TypeNames<SDK build> 或 -UnresolvedTypeNames;内存比较加同一条件;语料构建前等索引语料与显示一致9
ServicePluginEntry.swift(本机、Catalyst、文件、框架四个 service 与 Catalyst helper 五个入口)、CommandLineHostServer.start()(只在独立 host)修改进程启动时 RuntimeTypeNames.enableInThisProcess();缓存位置由 RuntimeTypeIndexLocation 从 Bundle.main 推出,不用配置每个打印的进程9
BackgroundWork/TypeIndex/TypeIndexCoordinator.swift新增照 CrossReferencePreparationCoordinator:读状态、isWorkInProgress、close()Report 与 App Nap10
RuntimeEngineBackgroundWork.swift修改创建协调器,并入 isWorkInProgress、activity reporter、close()接入后台工作10
ReportNode.swift、ReportTreeBuilder.swift、ReportViewModel.swift修改新 ReportCategory.importedTypeNames 及其节点;状态、原因、缓存大小Report 可见10
RuntimeEngineActivityReporter.swift、ToolbarActivity.swift、Presentation/SystemSymbol.swift修改新活动种类(每个批次一项,文案 Indexing Imported Type Names)与 Report 图标 shippingbox工具栏进度10
Content/ContentTextViewModel.swift修改收到 .typeNamesResolved 时先在主线程清文档的接口缓存,再重新取当前内容(Base/ViewModel.swift 不用改)建好后自动刷新10
GenerationOptionsViewController.swift修改Swift 组加「Resolve Imported Type Names」,ObjC 组加「Mark Swift Names From SDK」开关10
RuntimeDerivedDataController.swift、RuntimeDerivedDataMaintenance.swift修改量与删都包括 TypeIndex 目录;确认框文案提到它Delete Derived Data 一起删10
MCPBridgeServer.swift、CommandExecutor.swift、Export/RuntimeEngine+Export.swift修改置 waitsForTypeIndex = true输出稳定11
runtime-viewer 插件的 SKILL.md、.claude-plugin/plugin.json、.codex-plugin/plugin.json修改说明 __C. 解析与首次等待;版本 1.3.0 → 1.4.0插件规则11
DerivedData.md、CommandLineInterface.md、提案索引(cross-repository 行)、Documentations/README.md修改新缓存目录、输出变化、索引文档同批8、11
测试(见各步骤的行为清单)新增RuntimeViewerCoreTests 与 RuntimeViewerAppCoreTests 中的对应套件回归9、10、11
RuntimeViewerCore/Package.swift(swift-semantic-string)修改也临时钉功能分支,收尾改回 branch: "next"MachOObjCSection 的功能分支钉着它,两处不一致 SwiftPM 解析不了验收
Settings+Theme.swift · Preset.macro、Style.xcodeMacro修改新颜色槽,@Default 是 Xcode 的宏色对、常规字重;之前存下的自定义主题照样解码主题原本只有七种文字颜色,没有宏色验收
ThemeSettingsView.swift修改编辑器加 Macro 一行,预览加一行 NS_SWIFT_NAME,列表的色块加一格宏色可编辑验收
ThemePreset+ThemeProfile.swift · ResolvedTheme修改.macro 取 preset.macroNSTextView 面板的着色验收
SourceEditorThemeConversion.swift修改.macro 标成 xcode.syntax.identifier.macro.system,xcode.syntax.preprocessor 也取宏色;identifier.macro 仍借给错误色SourceEditor 面板的着色,与 Xcode 的键一致验收
RuntimeSemanticKind.swift修改.macro 归入 .keyword这个枚举跨 engine 边界,加新 case 旧对端解码不了验收
ThemePresetMacroSlotTests、ResolvedThemeTests、RuntimeSemanticKindTests、SemanticRetypingTests 新增一条新增旧预设解码、主题映射(去掉映射即失败)、归并、SourceEditor 把宏重新标成系统宏回归验收
五个锁文件(Debug、Distribution workspace 与 Core、Packages、CommandLine 包)修改三个功能分支的新提交,swift-semantic-string 改钉功能分支钉版本同批验收
+
+
+
+
+ +
+

详细设计

+ +
+ 新包的公开 API +
+
/// One dependency image whose runtime metadata lists the types it declares.
+/// Consulted, in order, only for names the SDK's module interfaces and API
+/// notes do not attribute; the first image that declares a name wins.
+public protocol DeclaredTypeNameSource: Sendable {
+    var imagePath: String { get }
+    func declaredTypeNames() async throws -> [String]
+}
+
+public enum ImportedTypeNameCategory: Sendable, Hashable {
+    case objcClass, objcProtocol, valueType, other
+}
+
+public struct TypeIndexingAvailability: Sendable, Hashable {
+    public enum UnavailabilityReason: Sendable, Hashable {
+        case noDeveloperDirectory
+        case sdkNotInstalled(SDKPlatform)
+    }
+    public let sdkSettings: SDKSettings?          // path, version, build, Mac Catalyst version
+    public let sourceKitPath: String?             // nil: module interfaces skipped
+    public let unavailabilityReason: UnavailabilityReason?
+    public var isAvailable: Bool { unavailabilityReason == nil }
+    public static func availability(for platform: SDKPlatform) -> TypeIndexingAvailability
+}
+
+public enum SDKPlatform: String, CaseIterable, Hashable, Codable, Sendable {
+    case macOS = "macosx"
+    case macCatalyst = "maccatalyst"             // the macOS SDK read through System/iOSSupport
+    case iOS = "iphoneos"
+    // tvOS, watchOS, visionOS, driverKit and the simulators, as before
+}
+
+public struct SwiftImportAnnotation: Sendable, Hashable {
+    public var swiftName: String?                  // SwiftName: the Swift name as is
+    public var isSwiftPrivate: Bool                // without a SwiftName, Swift prefixes "__"
+}
+
+public enum ObjCMemberKey: Sendable, Hashable {
+    case method(selector: String, isClassMethod: Bool)
+    case property(name: String, isClassProperty: Bool)
+}
+
+public struct ObjCContainerSwiftImportAnnotations: Sendable, Hashable {
+    public var declaration: SwiftImportAnnotation?
+    public var members: [ObjCMemberKey: SwiftImportAnnotation]
+}
+
+@available(macOS 13.0, *)
+public actor TypeDatabase {
+    public init(platform: SDKPlatform, cacheDirectory: URL? = nil, supplementaryAPINotesURLs: [URL] = [])
+    public func index(dependencies: [any DeclaredTypeNameSource], moduleFilter: @Sendable (String) -> Bool) async throws
+    public func moduleName(forTypeName typeName: String) async -> String?
+    public func swiftName(forCName cName: String, category: ImportedTypeNameCategory) -> String?
+    public func swiftImportAnnotations(forObjCClassNamed className: String) -> ObjCContainerSwiftImportAnnotations?
+    public func swiftImportAnnotations(forObjCProtocolNamed protocolName: String) -> ObjCContainerSwiftImportAnnotations?
+    public static func moduleName(forImagePath imagePath: String) -> String
+}
+
    +
  • 所有源码仍包在 #if os(macOS) 里。
  • +
  • SDKPlatform 公开,并新增 macCatalyst(落地时发现,见决策日志);SDKSettings(sdkPath、version、productBuildVersion、macCatalystVersion、cacheDirectoryComponent)与 APINotesFile(path:) 一并公开——后者是 swift-section 预检 --supplementary-apinotes 路径用的。
  • +
  • index(dependencies:moduleFilter:) 可多次调用:第一次发现 SDK 并登记 API notes,之后只补新的模块与依赖镜像;因此 API notes 优先于模块接口改为查询时决定(三张表),不再靠写入顺序。
  • +
  • 搬家时保留的三个 register(...) 测试钩子(提案 0009)降为 internal,测试用 @testable import。
  • +
  • 命名照 apple-style-api-design:协议按「是什么」命名,沿用组织里 ObjCMetadataSource 的 Source 后缀;查询读成名词短语(moduleName(forTypeName:));不给 MachOKit 的类型补遵循新包的协议,由 MachOObjCSection 的包装类型实现。
  • +
+
+
+ +
+ 改名规则 +
+
// APINotesIndex.registerEntities(_:declaredIn:into:)
+for entity in entities {
+    let cName = entity.name
+    moduleNamesByCName[cName] = moduleName
+    let swiftName: String? = if let explicitSwiftName = entity.swiftName {
+        explicitSwiftName                         // swift_name wins, no "__"
+    } else if entity.isSwiftPrivate == true {
+        "__" + cName                              // swift_private alone
+    } else {
+        nil
+    }
+    guard let swiftName, swiftName != cName else { continue }
+    self[keyPath: renameTable][cName] = Name(moduleName: moduleName, name: swiftName)
+    cNamesBySwiftName[swiftName] = Name(moduleName: moduleName, name: cName)
+}
+

依据是 Clang importer:有 swift_name 时直接用它并提前返回,只有没有它时才在 swift_private 的声明前加 __。ObjC 成员(Methods: 的 Selector + MethodKind,Properties: 的 Name + PropertyKind)按同样两条规则记进 ObjCContainerSwiftImportAnnotations,但只保存原始的 swiftName / isSwiftPrivate,因为成员一级要打印的是宏,不是推导后的 Swift 名。

+
+
+ +
+ 缓存目录 +
+

ModuleIndexCache 的目录改为 <cacheDirectory>/<platform rawValue>/<SDK 版本-build>/;不传时是 Application Support/swift-type-indexing/SDKIndexer。currentGeneratorVersion 不变(条目格式没变);旧的 Application Support/MachOSwiftSection/SDKIndexer 不再读、也不自动删,新包第一次运行时重建一次。

+
+
+ +
+ MachOObjCSection:Swift 命名标注 +
+
// ObjCTypeIndexing (macOS only)
+public struct ObjCDeclaredTypeNames<MachO: ObjCMetadataSource & Sendable>: DeclaredTypeNameSource {
+    public init(machO: MachO, imagePath: String)
+    public var imagePath: String { get }
+    public func declaredTypeNames() async throws -> [String]
+}
+
+extension ObjCSwiftImportNotes {
+    @available(macOS 13.0, *)
+    public init(apiNotesForClassNamed className: String, in typeDatabase: TypeDatabase) async
+    @available(macOS 13.0, *)
+    public init(apiNotesForProtocolNamed protocolName: String, in typeDatabase: TypeDatabase) async
+}
+
+// ObjCDeclarationRendering
+extension ObjCSwiftImportNotes {
+    public struct Note: Sendable, Hashable {
+        public var isRefinedForSwift: Bool
+        public var swiftName: String?              // + NS_SWIFT_NAME(swiftName)
+    }
+    public var declarationNote: Note?               // + the type itself
+    public func merging(_ other: ObjCSwiftImportNotes) -> ObjCSwiftImportNotes   // other wins per field
+}
+

打印效果:

+
NS_REFINED_FOR_SWIFT
+@interface UICellConfigurationState : UIViewConfigurationState
+@property (nonatomic, getter=isEditing) BOOL editing;
+@end
+
+NS_SWIFT_NAME(PKDrawingReference)
+@interface PKDrawing : NSObject <NSCopying, NSSecureCoding>
+- (instancetype)initWithData:(NSData *)data error:(NSError **)error;
+@end
+
    +
  • 类型一级的宏单独一行,放在 @interface / @protocol 上面(与演进视图打印可用性宏的写法相同);declarationNote 两个字段都有时打成一行 NS_SWIFT_NAME(X) NS_REFINED_FOR_SWIFT。
  • +
  • 成员一级放在 ; 前,NS_SWIFT_NAME(...) 在 NS_REFINED_FOR_SWIFT 前:- (void)foo NS_SWIFT_NAME(bar()) NS_REFINED_FOR_SWIFT;。
  • +
  • 标注不进可折叠区域(与现在的 NS_REFINED_FOR_SWIFT 一致:它是声明的一部分,不是注释)。
  • +
+
+
+ +
+ MachOSwiftSection:适配层与命令行 +
+
@available(macOS 13.0, *)
+public struct TypeDatabaseTypeNameResolver: ModuleNameResolving, CImportedNameResolving {
+    public init(typeDatabase: TypeDatabase)
+    public func moduleName(forTypeName typeName: String) async -> String?
+    public func swiftName(forCName cName: String, category: CImportedTypeNameCategory) async -> String?
+}
+
    +
  • SwiftInterfaceBuilderTypeNameProvider 保留公开名字与构造器签名,内部改为:按镜像平台建 TypeDatabase(LC_BUILD_VERSION 的 macCatalyst 映射到 .macCatalyst;原来映射到 .macOS,Catalyst 镜像因此读不到 UIKit 的 API notes),依赖镜像包成 ObjCDeclaredTypeNames,把查询转给一个 TypeDatabaseTypeNameResolver。
  • +
  • swift-section objc interface --mark-sdk-swift-names:按镜像 LC_BUILD_VERSION 的平台建 TypeDatabase(只读 API notes,moduleFilter 返回 false,所以不碰 sourcekitd),对每个类与协议取 ObjCSwiftImportNotes(apiNotesFor…:in:) 传给 ObjCInterfaceBuilder;找不到 SDK 时打印 warning,输出与不加开关时相同。
  • +
+
+
+ +
+ RuntimeViewer +
+
    +
  • 进程开关:RuntimeTypeNames.enableInThisProcess() 照 RuntimeDerivedData.enableInThisProcess() 的样子:四个 XPC service、Catalyst helper 与独立的命令行 host(CommandLineHostServer.start(),kind == .standalone 时;App 当 host 时打印在 App 的 service 里)在入口处打开。其余进程——App 本身、注入的 payload、iOS 设备、测试——都不打开,照旧印 __C.,也从不读 SDK、不写缓存。忘了调用不会坏事,只是那个进程不解析。
  • +
  • 进程内的索引:RuntimeTypeIndex 是每个打印进程一个的 actor(static let process)。它不经 @Dependency:RuntimeViewerCore 不依赖 swift-dependencies,能碰到它的只有 engine 与 section,和 RuntimeDerivedData 一样。按 SDKPlatform 各持一个 TypeDatabase: +
      +
    • 平台:一律取镜像第一个 LC_BUILD_VERSION 的平台(RuntimeTypeNames.platformName(of:),macCatalyst 映射到 .macCatalyst),共享缓存镜像、磁盘文件与已加载镜像同一条规则。没有这个 load command 的旧镜像不解析。
    • +
    • 批次:RuntimeSwiftSection.updateConfiguration 第一次为一个镜像配置时(resolvesImportedTypeNames 开着)调 request(_:),交出这个镜像链接的模块名(machO.dependencies 的 install name 推出模块名)和它自己的 ObjCDeclaredTypeNames。新模块、新镜像才排一批;平台的第一批同时读 API notes。同一平台的批次串起来依次执行,所以不会重复建。依赖镜像里的私有类型,要等那个依赖自己被打开(后台索引迟早会开)才算进来——不为打印一个镜像去打开它全部依赖的 ObjC 元数据。
    • +
    • 不可用:TypeIndexingAvailability 不可用时记下原因,不排批次,打印器不注册解析器,输出保持 __C.。
    • +
    • 内存:每个打印的服务进程各有一份(本机、Catalyst、每个文件、每个框架实例),落地时量一次 malloc 在用量写进提案(步骤 9)。
    • +
    +
  • +
  • 打印:每批完成把平台的 generation 加一。RuntimeSwiftSection 记着自己注册解析器时的 generation,下次配置时发现变了,就按当前选项重建完整的解析器列表(opaque 解析器 + 类型名解析器,互不误删),清掉 interfaceByObject / importedInterfaceByObject;语料打印器同样按 generation 重建。批次完成时 engine 把监听回调转成 broadcast(.typeNamesResolved(platformName:))(startObservingTypeIndex(),每个 engine 一次)。ObjC 头文件在 marksSwiftNamesFromAPINotes 开着时,把 swiftImportNotes(forClassNamed:/forProtocolNamed:platform:) 的结果与 objcSwiftImportNotes(for:) 合并;category 按它的类查。
  • +
  • 等待:GenerationOptions.waitsForTypeIndex 为 true 时,updateConfiguration 等这个镜像那一批完成再打印;false(界面)时直接打印。MCP(.mcp 预设)、命令行(每种选项来源都置 true)、导出(exportGenerationOptions)等待;Find 语料打印前一律等待(waitForTypeIndex(of:))。等待只在磁盘缓存冷、第一次生成某个 SDK 版本的模块接口时明显。
  • +
  • 兼容性:三个新选项都用 @Default,旧版对端解码时取默认;RuntimeDataChange 新 case 只由新版 Mac 服务发出,旧对端不会收到也不会发出;typeIndexStatus 命令对旧对端没有处理器,XPC 上没有处理器的命令被丢弃而不是回错,所以 typeIndexStatus() 经 dispatchToServingProcess(_:timeout:) 用连接自带的 2 秒超时发出,超时或出错都答 .empty,Report 里不显示这一类。
  • +
  • 语料 variant:RuntimeInterfaceCorpusSnapshot 的 variant 加一段 RuntimeTypeNamesCorpusVariant.component:开着索引、找得到 macOS SDK 时是 TypeNames-<SDK 版本-build>(共享缓存的 macOS 与 Mac Catalyst 镜像都对着 macOS SDK 读),否则 UnresolvedTypeNames。
  • +
  • 缓存位置:RuntimeTypeIndexLocation 从进程的 Bundle.main 往上找第一个是 RuntimeViewer 的 .app(RuntimeDerivedDataLocation.enclosingApplication),用 ~/Library/Caches/<bundle id>/TypeIndex,与 DerivedData 并列;App、它的 XPC service 与内嵌的命令行工具因此共用一份。不在 App 里的命令行工具用 ~/Library/Caches/runtime-viewer-cli/TypeIndex。Delete Derived Data 一并量它、删它(先改名再后台删)。
  • +
  • 界面:Generation Options 面板的 Swift 组「Resolve Imported Type Names」、ObjC 组「Mark Swift Names From SDK」,都默认勾选。Report 新类别「Imported Type Names」(排在 Cross References 之后),每个平台一行:建立中(第几批 / 共几批)、就绪(模块数)、不可用(没有开发者目录 / 没装这个平台的 SDK),类别行带缓存大小;没有平台时整类不显示,没有取消、推出、清除。TypeIndexCoordinator 照 CrossReferencePreparationCoordinator:启动时、每次 .typeNamesResolved、engine 换进程时问一次状态,建立中每 2 秒问一次;建立中算进 isWorkInProgress(防 App Nap),工具栏显示 Indexing Imported Type Names。内容区收到 .typeNamesResolved 先在主线程清文档的接口缓存再重新取,避免缓存自己的清空排在重新取之后。
  • +
+
+
+
+ +
+

调研

+
+ 二进制里为什么没有 Swift 名与模块 +
+
    +
  • Swift 给导入的 ObjC 类做 mangling 时用 ObjC 运行时名(ASTMangler.cpp 的 tryAppendClangName)。UIKit.tbd 里 $s5UIKit24UICellConfigurationStateV19_bridgeToObjectiveCSoABCyF 的 SoABC 直接复用了结构体名那个标识符;PKDrawing、UTType 的符号形状完全相同。
  • +
  • 改名只在 SDK 里:UIKit.apinotes 的 SwiftPrivate: true、PencilKit.apinotes 的 SwiftName: PKDrawingReference。
  • +
+
+
+
+ SDK 统计:为什么不能在二进制层面推断 +
+
+ + + + + + + +
同名又桥接的类型数量例子
__X(SwiftPrivate)6UIKit 的 UICellConfigurationState、UIViewConfigurationState、UIPointerShape……
XReference(SwiftName + SwiftBridge)14PencilKit 8 个、NSDiffableDataSource(Section)Snapshot、UTType、INShortcut
私有框架,SDK 无资料2ASCredentialProvider、WFVariableString
+
+

另有 15 个 __ 类型与对应 Swift 类型不同名(如 NSMorphology ↔ Morphology)。

+
+
+
+ 编译器的改名规则与现有实现的偏差 +
+
    +
  • ImportName.cpp:有 swift_name 时直接用它并提前返回,不加 __;没有时才对 swift_private 加 __。
  • +
  • 现有 APINotesIndex.swift:117 两种都不改名;测试 swiftPrivateEntitiesAreAttributedButNotRenamed 断言了后一种。来历是提案 0009 落地时(2026-08-22)沿用历史实现的保守做法,文档里没有给理由。
  • +
+
+
+
+ sourcekitd 与 Command Line Tools +
+
    +
  • 现有代码拼 <developer dir>/Toolchains/XcodeDefault.xctoolchain/…;Command Line Tools 下 sourcekitd 在 /Library/Developer/CommandLineTools/usr/lib/sourcekitd.framework(本机核对)。
  • +
  • Command Line Tools 自带 MacOSX.sdk,含 iOSSupport 的 UIKit.apinotes;iOS 等其他平台的 SDK 只有 Xcode 里有。
  • +
  • API notes 不需要 sourcekitd,只有「模块接口里的类型名」这一层需要。
  • +
+
+
+
+ 三个仓库的现状要点 +
+
    +
  • MachOSwiftSection:12 个文件里 9 个可原样搬走;APINotesIndex、TypeDatabase 要解耦;适配器留下。CImportedTypeNameCategory 打印器自己也用,不能搬。缓存目录写死、调用方无法指定。组织里没有外部使用方。
  • +
  • MachOObjCSection:Note 只有 isRefinedForSwift;只有类的入口接收标注;包支持 macOS 10.15 而 TypeDatabase 要求 macOS 13。
  • +
  • RuntimeViewer:每个镜像自己的打印器,从未注册类型名解析器;关 opaque 开关会清掉所有解析器;打印都在服务进程;内容区只在对象或选项变化时重取;独立命令行 host 没有 derived data 位置。
  • +
  • swift-apinotes 依赖 MetaCodable(宏包,构建时要 swift-syntax)与 Yams;它和 SourceKitD 已经经 MachOSwiftSection 进了 RuntimeViewer 的依赖图。
  • +
+
+
+
+ +
+

替代方案

+
+ 9 条被否的路径 +
+
    +
  • 二进制层面推断:同名桥接 20 个里 14 个是 XReference,与 __X 无法区分。
  • +
  • 新包留在 MachOSwiftSection:MachOObjCSection 需要同一份数据,却不能反向依赖。
  • +
  • 新包继续依赖 ObjCIndexing:ObjC 一侧接入后会成环,改为协议注入。
  • +
  • ObjC 一侧另起提案:用户选择一并做。
  • +
  • RuntimeViewer 默认关:用户选择找得到 SDK 就自动开。
  • +
  • 界面等建好再显示:用户选择先显示 __C.、后台预建、建好刷新。
  • +
  • MCP / 命令行 / 导出保持 __C.:用户选择一起换。
  • +
  • 开关放 Settings 新分支:要另造一条把设置送进服务进程的通道。
  • +
  • 缓存作为 RuntimeDerivedDataKind:derived data 按 dyld 共享缓存分目录,类型索引按 SDK 版本,两者无关。
  • +
+
+
+
+ +
+

影响

+
+

源码兼容性:MachOSwiftSection 有破坏

+
    +
  • TypeIndexing product 删除(组织里没有外部使用方),改依赖 swift-type-indexing 或 SwiftTypeNameResolution。
  • +
  • SwiftInterfaceBuilderTypeNameProvider 移到 SwiftTypeNameResolution 模块,签名不变。
  • +
  • 打开 --resolve-c-module-names 时输出变化:UIKit.__UICellConfigurationState、PencilKit.PKDrawingReference。
  • +
+
+

MachOObjCSection 为纯新增。四个仓库都以 SPM 源码分发,ABI 不适用。MachOKitUI、SymbolViewer 等其他下游不受影响。

+

RuntimeViewer 用户能看到的变化

+
    +
  • Swift 接口里的 __C.X 变成真实模块与 Swift 名;macOS 与 Mac Catalyst 只要装了 Xcode 或 Command Line Tools,其他平台的文件需要装了对应 SDK 的 Xcode。
  • +
  • ObjC 头文件出现 NS_SWIFT_NAME(...) / NS_REFINED_FOR_SWIFT。
  • +
  • 第一次在某个 SDK 版本上使用时,Report 里有一行「Imported Type Names」在建立;界面先显示 __C.,建好后自动刷新;命令行与 MCP 这期间会等待。
  • +
  • Generation Options 多两个默认勾选的开关;Delete Derived Data 同时删掉类型索引缓存。
  • +
+

版本

+
    +
  • MachOSwiftSection 删 product 属破坏性改动,按 0.x 惯例抬 minor,changelog 写迁移方式。
  • +
  • MachOObjCSection 纯新增,按其惯例抬版本。新包从 0.1.0 起步。
  • +
+
+ +
+

落地步骤

+
    +
  1. 提案入库:MachOSwiftSection 的提案索引登记草案;批准后、开工前,在 MachOObjCSection 与 RuntimeViewer 的提案索引各加一行 cross-repository 链接。无代码。
  2. +
  3. ✅ 建新包并原样搬入(2026-11-23 完成):Package.swift、移入的源码与测试、DeclaredTypeNameSource、ImportedTypeNameCategory、README / LICENSE / AGENTS.md / CI。行为:existingTypeIndexingTestsPassAgainstNonGenericDatabase、declaredTypeNameSourcesAreQueriedLazilyInDependencyOrder、firstImageDeclaringANameWinsTheAttribution、failingSourceIsDroppedAndNotRetried
  4. +
  5. ✅ 改名规则、Command Line Tools 与 Mac Catalyst(2026-11-23 完成):APINotesIndex 改名规则、SourceKitLocator、TypeIndexingAvailability、缓存目录注入;先写测试并确认修复前失败。行为:swiftPrivateWithoutSwiftNameResolvesToDoubleUnderscorePrefix、swiftNameWinsOverSwiftPrivate、plainEntityKeepsItsCName、sourceKitIsFoundInCommandLineToolsLayout、sourceKitIsFoundInXcodeToolchainLayout、missingSourceKitSkipsModuleInterfacesButKeepsAPINotes、availabilityReportsMissingSDK、cacheEntriesAreWrittenUnderTheGivenDirectory、macCatalystSearchesIOSSupportFirst、macCatalystTargetTripleIsMacABI、macCatalystInterfaceGenerationSeesIOSSupportFrameworks、macCatalystCachesApartFromMacOS。实测(SDKIntegrationTests):Catalyst 下 UICellConfigurationState → UIKit / __UICellConfigurationState;macOS 下 PKDrawing → PencilKit / PKDrawingReference;sourcekitd 冷生成 Catalyst 的 UIKit 接口后 UIStackView → UIKit
  6. +
  7. ✅ ObjC 容器的 API notes 查询(2026-11-23 完成;用户批准后 fork 推送并打 0.3.0,新仓库 swift-type-indexing 公开、推送并打 0.1.0):SwiftImportAnnotation、ObjCContainerSwiftImportAnnotations、TypeDatabase.swiftImportAnnotations(…)。行为:classAnnotationCarriesSwiftNameAndSwiftPrivate、methodAnnotationIsKeyedBySelectorAndKind、propertyAnnotationIsKeyedByNameAndKind、protocolAnnotationsAreSeparateFromClassAnnotations。前置:swift-apinotes fork 把 ObjCContext.methods / properties 改成 public,打 0.3.0。新包打 0.1.0 并推送(公开仓库)。
  8. +
  9. ✅ MachOObjCSection 接入新包(2026-11-23 完成):Package.swift、ObjCTypeIndexing、ObjCDeclaredTypeNames。行为:declaredTypeNamesListFoundationClassesProtocolsAndStructs、typeDatabaseAttributesPrivateClassThroughObjCDeclaredTypeNames
  10. +
  11. ✅ ObjC 头文件的 Swift 命名标注(2026-11-23 完成):ObjCSwiftImportNotes 扩展、协议与 category 入口、类型一级宏、API notes 转换。行为:memberSwiftNamePrintsBeforeRefinedForSwift、classDeclarationNotePrintsOnItsOwnLineAboveInterface、protocolInterfaceTakesNotes、categoryMembersTakeNotes、mergingKeepsBothSourcesAndTheArgumentWinsPerField、apiNotesForClassBecomeNotes(临时 .apinotes 驱动)、markedRenderingStillProjectsToPlainRendering
  12. +
  13. ✅ MachOSwiftSection 切换到新包(2026-11-23 完成):删 TypeIndexing、加 SwiftTypeNameResolution、CLI 接线、文档与 skill。行为:resolverMapsEveryPrinterCategory、resolverPrintsResolvedModuleAndSwiftName(假的 TypeDatabase 数据驱动打印器)、resolveCModuleNamesFlagStillMapsToRequest。端到端(维护者手动):swift-section interface --resolve-c-module-names 对 UIKitCore(Catalyst)输出 UIKit.__UICellConfigurationState、对 PencilKit 输出 PencilKit.PKDrawingReference
  14. +
  15. ✅ swift-section objc --mark-sdk-swift-names(2026-11-23 完成;ObjCRequestTests 按 CI 的步骤先用 Xcode 26.6 编出 SymbolTestsCore 夹具再跑,17 条全过)。行为:markSDKSwiftNamesFlagMapsToRequest、missingSDKWarnsAndPrintsUnmarkedOutput。端到端(手动):PencilKit 的 PKDrawing 头文件出现 NS_SWIFT_NAME(PKDrawingReference)
  16. +
  17. ✅ RuntimeViewer 依赖接线(2026-11-23 完成;Tuist.swift 顺带补上 MachOSwiftSection 早已有的 SwiftSectionTestingMacros,next 上 check 本来就因它不过;RuntimeViewerServer.xcodeproj 自带的锁文件在 next 上已过时,重新解析会带进无关升级,没有动):RuntimeViewerCore/Package.swift、Local workspace 与 .worktrees 链接、Tuist、AGENTS.md 依赖下限、三个 workspace 的锁文件(UpdatePackagesScript.sh)。行为:./TuistScript.sh check 通过;Debug workspace 能编过
  18. +
  19. ✅ RuntimeViewer Core(2026-11-23 完成;行为测试按实际做法落在 RuntimeTypeNamesTests、SharedCacheRoutingDeclarationTests 与 MachOSwiftSection、swift-type-indexing 的测试里;各服务进程多出的 malloc 在用量没有量,留作后续):TypeNames/ 目录、RuntimeDataChange 新 case、typeIndexStatus 命令、打印器接线、ObjC 标注合并、三个选项、语料 variant、四个服务与命令行 host 的入口配置。实测:Catalyst 镜像的 API notes 确实来自 iOSSupport;记录每个服务进程多出的 malloc 在用量。行为:typeIndexBuildsOncePerPlatformAndMergesConcurrentRequests、unavailableSDKLeavesImportedNamesUnresolved、resolverSurvivesOpaqueTypeSwitchOff、readyIndexClearsSectionInterfaceCaches、readyIndexBroadcastsTypeNamesResolved、waitingRequestPrintsResolvedNamesOnColdIndex、nonWaitingRequestPrintsImportedPlaceholderOnColdIndex、switchOffPrintsImportedPlaceholder、objcHeaderMergesAPINotesWithRefinedMembers、corpusVariantNamesTypeNameResolution、typeIndexStatusCommandRoutesToServingProcess、olderPeerDecodesOptionsWithDefaults、cacheLocationWalksUpToEnclosingApp(App、XPC service、内嵌命令行三种位置)
  20. +
  21. ✅ RuntimeViewer App(2026-11-23 完成;contentRefetchesOnTypeNamesResolved 即 ContentTextPipelineTests 的「a finished batch of the type index refetches the interface on screen」;Delete Derived Data 的两条没有单独的测试,App 一侧只是把同一个目录交给 RuntimeTypeIndexLocation 的量与删,后者有测试):协调器、Report、工具栏活动、内容刷新、Generation Options 两个开关、Delete Derived Data。行为:typeIndexCoordinatorReportsBuildingReadyAndUnavailable、reportListsImportedTypeNamesPerPlatform、contentRefetchesOnTypeNamesResolved、deleteDerivedDataRemovesTypeIndexDirectory、derivedDataSizeIncludesTypeIndexDirectory
  22. +
  23. ✅ MCP、命令行、导出与插件(2026-11-23 完成;MCP 一条由 RuntimeTypeNamesTests 的「An interactive print does not wait…; MCP's does」覆盖):waitsForTypeIndex、skill、两个插件清单 1.4.0、CommandLineInterface.md。行为:mcpOptionsWaitForTypeIndex、commandLineOptionsWaitForTypeIndex、exportConfigurationWaitsForTypeIndex
  24. +
+

收尾时必须判断两件事,结果写进决策日志:要不要配套专题文章(新包的 TypeIndexingPipeline.md 承担实现说明;RuntimeViewer 预计在 DerivedData.md 加一节类型索引缓存,是否另写实现说明到时判断);有没有引入新术语(预计有「类型索引(type index)」「Swift 命名标注」,登记进各仓库的 Glossary.md)。

+
+ +
+

决策日志

+
+ 32 条,最近一条:落地验证,取号 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
日期变更说明
2026-11-23Created as DraftRuntimeViewer 把 UICellConfigurationState 的桥接类型显示成 __C.UICellConfigurationState。查明二进制只记 ObjC 运行时名、改名只在 SDK 的 API notes 里,而 MachOSwiftSection 已有的 TypeIndexing RuntimeViewer 用不上、且改名规则有误;用户决定把它抽成独立的包,三方接入
2026-11-23否决二进制层面的推断同名又桥接的 20 个 SDK 类型里 14 个是 XReference,与 __X 在二进制里无法区分
2026-11-23ObjC 一侧并入本提案用户选择一并做,而不是另起提案;新包因此不能依赖 MachOObjCSection,ObjC 元数据一层改为协议注入
2026-11-23新仓库名 swift-type-indexing用户选择;模块名仍是 TypeIndexing
2026-11-23RuntimeViewer 找得到 SDK 就自动开用户选择;可用条件从「装了 Xcode」改为「找得到该平台 SDK」,因为 Command Line Tools 也带 macOS SDK 与 sourcekitd(用户指出,本机核对)
2026-11-23ObjC 只标 Swift 命名、不加 @import用户选择
2026-11-23后台预建、先显示 __C.用户选择
2026-11-23提案放在 MachOSwiftSection用户选择;其余三个仓库的索引加 cross-repository 行
2026-11-23MCP、命令行、导出一起换用户选择;为了输出稳定,这些非交互的调用方等索引就绪(agent 自定,可推翻)
2026-11-23开关放 Generation Options 面板agent 自定,可推翻:与现有打印开关同处,随请求发出、进缓存键、命令行也读同一份
2026-11-23共识确认用户确认以上决定,开始写提案
2026-11-23Accepted用户批准,开始实现
2026-11-23swift-apinotes fork 加入范围它的 ObjCContext.methods / properties 在 0.2.0 是 internal,ObjC 成员的标注读不到。改为 public 并打 0.3.0(每个字段一行),比在新包里另写一套 YAML 解析更小;推送与打 tag 和新仓库一起经用户批准
2026-11-23新增 SDKPlatform.macCatalyst提案原定 Catalyst 按 .macOS 索引并「落地时实测确认」:实测 SDKIndexer 不搜 System/iOSSupport,Catalyst UIKit 的 API notes 找不到;sourcekitd 按前端调用解析参数,macabi target 不会自动加 iOSSupport 框架路径(报 Could not load module: UIKit)。新 case 读 macOS SDK、先搜 iOSSupport、显式传 -Fsystem
2026-11-23index 可多次调用、优先级改为查询时决定RuntimeViewer 加载新镜像时要追加模块;原先 API notes 靠写入顺序覆盖模块接口名,追加的接口名会把名字抢回去
2026-11-23可用性返回 sdkSettings 而非 sdkPathRuntimeViewer 的语料 variant 要 SDK 版本与 build,SDKSettings 一并给出
2026-11-23加默认关闭的 SDKIntegrationTests单测覆盖不到真实 SDK 布局与 sourcekitd 参数,上面两个 Catalyst 问题都是实测才发现的;手动开启,不进 CI
2026-11-23MachOObjCSection、MachOSwiftSection、RuntimeViewer 临时钉功能分支MachOObjCSection 0.8.209 要等收尾才发,实现期间 MachOSwiftSection 对它、RuntimeViewer 对两者都钉 branch: "feature/swift-type-indexing-package"(清单里注明 TEMPORARY);收尾时发 0.8.209,MachOSwiftSection 改回 "0.8.209" ..< "0.9.0",RuntimeViewer 改回 branch: "next"
2026-11-23RuntimeViewer 用进程开关,不配置缓存位置原定在各入口「配置缓存位置」。改为 RuntimeTypeNames.enableInThisProcess(),照派生数据的开关:缓存位置能从 Bundle.main 推出,真正要控制的是哪些进程读 SDK、跑 sourcekitd——测试、注入的 payload、App 本身都不该。Catalyst helper 也打开(它跑的是 Catalyst 的 engine);命令行 host 只在独立运行时打开
2026-11-23RuntimeTypeIndex 不经 @Dependency原定 @Dependency + fileprivate static let shared。RuntimeViewerCore 不依赖 swift-dependencies,项目里 RuntimeDerivedData 也是同样的 static 单例
2026-11-23平台一律取 LC_BUILD_VERSION,批次按镜像排原定共享缓存镜像查分区、文件查 RuntimeFile.platform,engine 连上时预建。改为每个镜像第一次打印时排一批(它链接的模块 + 它自己的 ObjC 元数据):一条规则覆盖三种镜像;只为打开了的镜像建,不在连上时为整个共享缓存跑 sourcekitd。依赖镜像的私有类型等那个依赖被打开时才算入
2026-11-23刷新靠 generation,等待放在 section 配置时原定索引就绪时主动通知各 section 清缓存、在 _interface(for:) 里等待。改为 section 下次配置时比较平台的 generation,自己重建解析器、清缓存;waitsForTypeIndex 在 updateConfiguration 里等这个镜像那一批。少一条 actor 之间的回调,也不用记哪些 section 活着
2026-11-23旧对端的状态答 .empty,不显示原定把「无应答」当 .unavailable。旧对端(iOS 设备、注入的进程、旧版本)本来就没有索引,Report 里多一行「不可用」只是噪音;查询经连接自带的 2 秒超时发出,因为没有处理器的命令在 XPC 上被丢弃、不回错,靠任务取消收不了尾
2026-11-23语料 variant 只带 macOS SDK 的版本原定 TypeNames<platform>-<SDK>。服务进程的共享缓存镜像——macOS 与 Mac Catalyst——都对着同一个 macOS SDK 读,一段就够
2026-11-23内容区刷新前自己清一次接口缓存文档的接口缓存在同一事件上清空,但它和内容区的订阅各自调度,先后没有保证;内容区先在主线程清再重新取,读不到批次之前的旧结果
2026-11-23一条既有测试的夹具换类RuntimeViewerCore 现在经 swift-apinotes 静态链接 MetaCodable 的 HelperCoders,它让 ISO8601DateFormatter 遵循 DateFormatConverter;镜像把一个类的遵循列成一个条目,「只采纳私有 @objc 协议的 category 什么都不打印」那条测试的前提因此不成立。夹具改用没有任何依赖扩展的 EnergyFormatter,测试先断言该类只有一个遵循条目
2026-11-23实现完成,待用户看过后收尾新包 0.1.0 与 swift-apinotes 0.3.0 已发;MachOObjCSection、MachOSwiftSection、RuntimeViewer 的功能分支已推送并在本地合进各自的常驻检出(未推送)。验证:MachOSwiftSection 的相关测试与夹具测试通过;RuntimeViewer Core 与应用层的整套测试在 Ultra 上跑过,红的都是记忆中的基线红灯或满载超时,单独重跑通过(TitleActivityIndicatorTests 一条基线必红);./TuistScript.sh check 通过,Tuist workspace 编出整个 App。收尾时发 MachOObjCSection 0.8.209、把临时分支钉改回去
2026-11-23NS_SWIFT_NAME / NS_REFINED_FOR_SWIFT 改用宏色,swift-semantic-string 加入范围用户验收时发现两个宏与 @interface、@end 同为关键字色:MachOObjCSection 把它们打成了 Keyword。查证 Xcode 27.2:Objective-C 的 grammar 从 SourceModel 的 KnownMacros.plist 认出两者(NS_REFINED_FOR_SWIFT 属普通宏、NS_SWIFT_NAME 属函数宏),但只为让解析跳过它们,词法上标成 xcode.syntax.plain;SDK 头文件里的宏色来自索引给的 xcode.syntax.identifier.macro.system(Default (Light) #643820、Default (Dark) #FD8F3F,与预处理语句同色,常规字重)。用户选定完整方案:swift-semantic-string 加 SemanticType.macro 与 Macro(冻结编码 22,之前的读者当普通文本),MachOObjCSection 改用它,RuntimeViewer 主题加可编辑的宏色槽(默认取 Xcode 色,之前存下的自定义主题照样解码),SourceEditor 面板把宏标成 identifier.macro.system,搜索的 RuntimeSemanticKind 把宏归入关键字、线上格式不变;两个命令行的配色同步。收尾因此多两步,排在发 MachOObjCSection 0.8.209 之前:先发 swift-semantic-string 0.7.0,MachOObjCSection 与本仓库把它改回 from: "0.7.0";RuntimeViewer 对它改回 branch: "next"
2026-11-23SourceKitService 不再涨到 80 GB:接口生成完就关闭,同时最多生成 2 个用户验收时发现 RuntimeViewer 的两个服务进程各带一个 SourceKitService,各涨到 80 GB。复现:swift-section interface --uses-system-dyld-shared-cache -n AppKit --resolve-c-module-names(缓存清空),按秒采样新起的 SourceKitService,6 秒、27 个模块时到 27 GB,被设的上限掐断。原因在 SourceKit 源码里(SwiftEditorInterfaceGen.cpp、SwiftEditor.cpp):每次 editor.open.interface 留一个 SwiftInterfaceGenContext(两个 CompilerInstance,载入模块及其全部导入),只有同名的 editor.close 才从 IFaceGenContexts 里删掉;SourceKitManager 每个模块用一个新 UUID 打开、从不关闭,TypeDatabase.index 又把一个镜像的模块一次全提交。用户选了「关闭 + 限并发」:读完响应即关(生成失败也关),同时最多 2 个。同一条复现峰值 413 MB,33 个模块 70 秒全部生成完,名字照常解析。收尾多一步:swift-type-indexing 发 0.1.1,RuntimeViewer 的下限抬到 0.1.1
2026-11-24收尾:发版,临时钉改回用户看过、批准收尾,与叠在上面的 0106 一起落地。swift-semantic-string 发 0.7.0(SemanticType.macro,连同它 next 上已有的 Swift 6 upcoming features),MachOObjCSection 发 0.8.209。MachOObjCSection 与本仓库对 swift-semantic-string 改回 from: "0.7.0",本仓库对 MachOObjCSection 改回 "0.8.209" ..< "0.9.0",对 swift-type-indexing 的下限也抬到 0.1.1(复现那次膨胀用的就是 swift-section interface --resolve-c-module-names);RuntimeViewer 对三个库改回 branch: "next",swift-type-indexing 的下限抬到 0.1.1,五个锁文件只改这几条。MachOObjCSection 自带的锁文件原本就落后于清单(MachOKitExtensions 还在 1.3.0),这次重解析一并对齐。RuntimeViewer 的这些改动提交在它的本地 next:那里还有别的功能先合进来、在等用户看,等它们收尾时一起推
2026-11-24文档与术语判断不另写专题文章:实现说明就是 swift-type-indexing 的 TypeIndexingPipeline.md,RuntimeViewer 的 DerivedData.md 已有类型索引缓存一段。术语:「类型索引(type index)」登记进本仓库与 RuntimeViewer 的术语表;「Swift 命名标注」就是 MachOObjCSection 术语表里已有的「Swift import notes(Swift 导入标注)」,只给它补了本提案的链接
2026-11-24落地验证,取号钉改回发布版本后的本仓库 next,在 Ultra 上构建并跑两份提案相关的测试(CImportedTypeNameSpelling、TypeDatabaseTypeNameResolver、TypeNameProvider、ObjCRequest、CommandRequestMapping、ObjCSectionCommand,5 个测试目标共 90 条),构建与测试的退出码都是 0。MachOObjCSection 0.8.209 的 GitHub CI 没分到 macOS runner,超时判为失败;同样的构建与测试在 Ultra 上用 Xcode 26.6 跑过,退出码都是 0,358 条全过。状态改为 Implemented,编号 0105,演进账本 §151
+
+
+
+
+ +
+
+ + diff --git a/Documentations/Evolutions/0105-swift-type-indexing-package.md b/Documentations/Evolutions/0105-swift-type-indexing-package.md new file mode 100644 index 000000000..dbaeae31d --- /dev/null +++ b/Documentations/Evolutions/0105-swift-type-indexing-package.md @@ -0,0 +1,690 @@ +# 0105 - 类型索引独立成 swift-type-indexing 包,并接入 MachOObjCSection 与 RuntimeViewer + +- **状态**: Implemented +- **作者**: JH +- **创建日期**: 2026-11-23 +- **最后更新**: 2026-11-24 +- **所属愿景**: 无 +- **关联提案**: [0009 TypeIndexing 重启](0009-type-indexing-revival.md)、[0010 补充类型映射](0010-community-type-mapping-bundles.md)、[0096 Swift 优先的导入声明](0096-swift-first-imported-declarations.md)(`ObjCSwiftImportNotes` 的来历) +- **跨仓库范围**: 新仓库 `MxIris-Reverse-Engineering/swift-type-indexing`、swift-apinotes fork(`MxIris-DeveloperTool-Forks/swift-apinotes`,实现中加入,见决策日志)、swift-semantic-string(`SemanticType.macro`,验收中加入,见决策日志)、MachOObjCSection、MachOSwiftSection(本仓库,持有这份唯一的提案)、RuntimeViewer。另外三个仓库的提案索引各加一行「cross-repository」链接指回这里 +- **实现分支 / PR**: 新仓库 `swift-type-indexing` 的 `main`;MachOObjCSection、MachOSwiftSection、RuntimeViewer 各自的 `feature/swift-type-indexing-package`(各从 `next` 切) +- **配套文档**: 实现说明 [TypeIndexingPipeline.md](https://github.com/MxIris-Reverse-Engineering/swift-type-indexing/blob/main/Documentations/Internal/TypeIndexingPipeline.md)(swift-type-indexing);RuntimeViewer 的 `Documentations/DerivedData.md` 讲类型索引缓存放在哪、归谁清理 +- **网页版**: 同目录同名的 `.html` + +## 摘要 + +把本仓库的 `TypeIndexing` target(SDK 模块索引、API notes 索引、ObjC 元数据归属、按 SDK 版本的磁盘缓存)整体搬进新的独立包 `swift-type-indexing`,模块名仍是 `TypeIndexing`。新包不依赖本仓库,也不依赖 MachOObjCSection:原来直接调用 `ObjCIndexing` 补私有类归属的那一层改成新包声明的协议 `DeclaredTypeNameSource`,由 MachOObjCSection 实现。搬家同时修两处错误:API notes 的改名规则(只有 `SwiftPrivate` 的类型要加 `__` 前缀,有 `SwiftName` 的直接用它——现在两种都不改名);sourcekitd 只认 Xcode 的目录结构,装 Command Line Tools 时找不到。之后三方接入:MachOObjCSection 打印 ObjC 头文件时,按 API notes 在类、协议、category 及其成员上标出 `NS_SWIFT_NAME(...)` / `NS_REFINED_FOR_SWIFT`;本仓库删掉 `TypeIndexing` target,只留一个薄适配层,`swift-section interface --resolve-c-module-names` 照常可用,`swift-section objc` 加一个同类开关;RuntimeViewer 在找得到对应平台 SDK 的 Mac 上默认把 `__C.UICellConfigurationState` 打印成 `UIKit.__UICellConfigurationState`,索引在 engine 连上后后台预建、进 Report,建好前先显示 `__C.`、建好后自动刷新,MCP、命令行与导出一起换成解析后的名字。 + +## 动机 + +**现象**。RuntimeViewer 显示 UIKit 的 `UICellConfigurationState` 结构体时,桥接相关的成员都打印成 `__C.UICellConfigurationState`: + +```swift +static func _unconditionallyBridgeFromObjectiveC(_: __C.UICellConfigurationState?) -> UIKit.UICellConfigurationState +func _bridgeToObjectiveC() -> __C.UICellConfigurationState +var _cachedImpl: __C.UICellConfigurationState? +``` + +而 SDK 的 `UIKit.swiftinterface` 写的是 `__UICellConfigurationState`(`_ObjectiveCType = __UICellConfigurationState`)。`__C.UITraitCollection` 之类的普通导入类型同样只显示占位模块 `__C`,不是 `UIKit`。 + +**二进制里本来就没有这些信息**(见前期调研 1、2):Swift 给导入的 ObjC 类做 mangling 时用的是 ObjC 运行时名,Swift 侧的改名只记在 SDK 的 API notes 与头文件里;模块归属同样不在 mangled 名里。所以要显示对,只能借助 SDK——这正是本仓库 `TypeIndexing` 已经在做的事(提案 0009 / 0010),只是: + +1. **RuntimeViewer 用不上它**。RuntimeViewer 不经 `SwiftInterfaceBuilder`,而是自己在每个镜像的 `SwiftDeclarationPrinter` 上注册解析器(`RuntimeViewerCore/Sources/RuntimeViewerCore/Sections/Swift/RuntimeSwiftSection.swift:1933-1936`),从来没有注册过 `TypeIndexing` 的解析器,所以界面、MCP、命令行和导出里全是 `__C.`。 +2. **它不只是「Swift 的」索引**。它的三个数据源里,API notes 与 ObjC 元数据都是 C / Objective-C 一侧的知识;MachOObjCSection 打印 ObjC 头文件时同样需要它(`NS_SWIFT_NAME` / `NS_REFINED_FOR_SWIFT` 在二进制里没有痕迹,`ObjCSwiftImportNotes` 现在只能靠本仓库从 Swift 侧倒推出 `NS_REFINED_FOR_SWIFT`,`NS_SWIFT_NAME` 完全没有来源)。但 MachOObjCSection 是本仓库的依赖,不可能反过来依赖本仓库的 target。 +3. **两处错误**:`SwiftPrivate` 与 `SwiftName` 的改名都没生效;只装 Command Line Tools 的机器上 sourcekitd 路径必然错。 + +**为什么不能只在二进制层面推断**。曾考虑过「Swift 类型与 ObjC 类同名、且遵循 `_ObjectiveCBridgeable`,就推断 ObjC 类在 Swift 里叫 `__X`」。对 macOS 27.2 / iOS SDK 的统计否定了它:同名又桥接的 20 个类型里只有 6 个是 `__X`,14 个是 `XReference`(见前期调研 3),而两者在二进制里一模一样。 + +## 前期调研 + +1. **导入的 ObjC 类按 ObjC 运行时名 mangling**。`swift/lib/AST/ASTMangler.cpp` 的 `tryAppendClangName`(约 3173 行起):「Always use Clang names for imported Clang declarations」,ObjC 类走 `interface->getObjCRuntimeNameAsString()`。SDK 的 `UIKit.tbd` 里 `$s5UIKit24UICellConfigurationStateV19_bridgeToObjectiveCSoABCyF` 的 `SoABC` 直接复用了结构体名那个标识符,demangle 为 `-> __C.UICellConfigurationState`;`PencilKit.PKDrawing`(`$s9PencilKit9PKDrawingV19_bridgeToObjectiveCSoABCyF`)与 `UniformTypeIdentifiers.UTType` 的符号形状完全相同。 +2. **改名只在 SDK 里**。`UICellConfigurationState` 的改名来自 `MacOSX27.2.sdk/System/iOSSupport/.../UIKit.framework/Headers/UIKit.apinotes:275-276` 的 `SwiftPrivate: true`,头文件 `UICellConfigurationState.h:34` 没有宏;`PKDrawing` 来自 `PencilKit.apinotes:4-6` 的 `SwiftName: PKDrawingReference` + `SwiftBridge: PKDrawing`。 +3. **SDK 统计**(macOS 27.2 SDK 与 iOS SDK 的全部 `.tbd` 里导出了 `_bridgeToObjectiveC` 的类型,与 swiftinterface 逐个对照):同名又桥接的 22 个,其中 2 个在私有框架(`ASCredentialProvider`、`WFVariableString`,SDK 无资料);其余 20 个: + - `__X`(`SwiftPrivate`)6 个:UIKit 的 `UICellConfigurationState`、`UIViewConfigurationState`、`UIContentUnavailableConfigurationState`、`UIListSeparatorConfiguration`、`UIPointerEffect`、`UIPointerShape` + - `XReference`(`SwiftName` + `SwiftBridge`)14 个:PencilKit 8 个、`NSDiffableDataSource(Section)Snapshot`(UIKit / AppKit)、`UTType`、`INShortcut`、`INMediaDestination` + - 另有 15 个 `__` 类型与对应 Swift 类型不同名(如 Foundation 的 `NSMorphology` ↔ `Morphology`、`UIButtonConfiguration` ↔ `UIButton.Configuration`)。 +4. **Clang importer 的改名规则**(`swift/lib/ClangImporter/ImportName.cpp`):`importNameImpl` 遇到 `swift_name`(约 1659 行 `findSwiftNameAttr`)直接用它并在 1776 行 `return result`,**不再**加 `__`;只有没有 `swift_name` 时才走 2446 行「If this declaration has the swift_private attribute, prepend "__"」。API notes 的 `SwiftName:` / `SwiftPrivate:` 就是这两个属性。 +5. **现有实现的改名表跳过了这两种情况**:`Sources/Declaration/TypeIndexing/APINotesIndex.swift:117` 是 `guard let swiftName = entity.swiftName, entity.isSwiftPrivate != true else { continue }`——没有 `SwiftName` 的不进表,有 `SwiftName` 但标了 `SwiftPrivate` 的也不进表。测试 `Tests/TypeIndexingTests/APINotesIndexTests.swift:93` `swiftPrivateEntitiesAreAttributedButNotRenamed` 断言后一种不改名。追查来历:提案 0009 落地时(`1785a9e7`,2026-08-22)`Documentations/Internal/TypeIndexingPipeline.md:95` 写「改名表仍跳过 `SwiftPrivate`」,没有给理由,是沿用历史实现「只注册有 `SwiftName` 的实体」的保守做法;按上一条的编译器规则,这个保守做法是错的。 +6. **sourcekitd 路径**:`SourceKitManager.swift:62-63` 用 `xcode-select -p` 拼 `/Toolchains/XcodeDefault.xctoolchain/usr/lib/sourcekitd.framework/Versions/A/sourcekitd`。只装 Command Line Tools 时 `xcode-select -p` 是 `/Library/Developer/CommandLineTools`,sourcekitd 在 `usr/lib/sourcekitd.framework`(本机核对过,没有 `Toolchains/` 一层),拼出的路径不存在。Command Line Tools 自带 `SDKs/MacOSX.sdk`,其中有 `System/iOSSupport/.../UIKit.apinotes`,所以 macOS 与 Mac Catalyst 的 API notes 都在;iOS 等其他平台的 SDK 只有 Xcode 里有。 +7. **`TypeIndexing` 的耦合面**(`next` 上 `Sources/Declaration/TypeIndexing/` 12 个文件约 1300 行): + - 只依赖 Foundation / FoundationToolbox / SourceKitD / swift-apinotes、可以原样搬走的 9 个:`InterfaceDeclarationNode`、`InterfaceTypeNameExtractor`、`ModuleIndexCache`、`ModuleInterfaceIndexer`、`SDKIndexer`、`SDKPlatform`、`SourceKitManager`、`Subprocess`、`SupplementaryAPINotes`。 + - 要解耦的 2 个:`APINotesIndex.swift`(用了 SwiftPrinting 的 `CImportedTypeNameCategory`)与 `TypeDatabase.swift`(泛型 `TypeDatabase`,在 `indexObjCMetadata(of:)`(211-233 行)里用 `ObjCInterfaceIndexer(machO:imagePath:)` + `prepare()` + `classNames` / `protocolNames` / `structNames` / `unionNames`,以及 MachOKitExtensions 的 `imagePath`;同时用了 `CImportedTypeNameCategory`)。 + - 留在本仓库的 1 个:`SwiftInterfaceBuilderTypeNameProvider.swift`(依赖 `SwiftInterface`、`SwiftPrinting` 的角色协议、MachOKit 的 `Platform`)。 + - `CImportedTypeNameCategory` 声明在 `Sources/Output/SwiftPrinting/NodePrintables/TypeNameResolving.swift:8-26`,它的 `init(nodeKind:)` 依赖 Demangling,打印器本身也用它(`TypeNodePrintable.swift:240`),所以不能搬走,新包要有自己的分类枚举。 + - 缓存目录写死在 `ModuleIndexCache.swift:46-54`(`Application Support/MachOSwiftSection/SDKIndexer//`),`TypeDatabase.index` 内部直接构造它(`TypeDatabase.swift:72`),调用方无法指定。 + - 本组织里没有别的仓库依赖 `TypeIndexing` product;本仓库内的使用方只有 `SwiftSectionKit` 的 `InterfaceRequest.swift:245-297`(`--resolve-c-module-names`)与测试。 +8. **API notes 不需要 sourcekitd**:`SDKIndexer.discover` 只扫文件、解析 `.apinotes`(秒级);只有「从模块接口取类型名」这一层才要 sourcekitd(提案 0009 A 节)。所以「改名」与「ObjC 头文件的 Swift 命名标注」只要找得到 SDK 就能做,模块归属在没有 sourcekitd 时退化为「API notes 列出的实体 + ObjC 元数据」。 +9. **MachOObjCSection 现状**(`MachOObjCSection` 的 `next`): + - `Sources/ObjCDeclarationRendering/ObjCSwiftImportNotes.swift:25`,`Note` 只有 `isRefinedForSwift`,只能标成员,没有类型一级的标注;渲染在 72-84 行。 + - 只有按类打印的入口接收标注(`ObjCInterfaceBuilder.swift:116-131`、`149-163`),协议(336 / 354)、category(445 / 463)不接收。 + - 类型声明行由 `ObjCDeclarationHeader`(`ObjCDump+SemanticString.swift:109-153`)打印;演进视图把可用性宏单独打一行放在声明行上面(`Sources/ObjCInterface/Internal/ObjCEvolutionContainerLayout.swift:268-271`),是类型一级宏的现成写法。 + - 包支持 macOS 10.15,而 `TypeDatabase` 要求 macOS 13,接入处要加可用性判断。 + - 全仓库没有任何 `apinotes`、`SwiftName`、`moduleName` 相关代码。 +10. **RuntimeViewer 现状**(`next`): + - 打印:每个 Swift 镜像一个 `SwiftDeclarationPrinter`(`RuntimeSwiftSection.swift:68`、`:234`),Find 语料用另一个打印器(`:2313-2333`)。关掉「Synthesize Opaque Type」时调用 `printer.removeAllTypeNameResolvers()`(`:1937-1939`),会把所有解析器一起清掉。 + - ObjC:`RuntimeEngine.swift:956-962` 只给类传 `swiftSection.objcSwiftImportNotes(for:)`(`RuntimeSwiftSection.swift:516-531`),语料一侧同样(`RuntimeEngine+Search.swift:355-356`)。 + - 打印发生在服务进程:本机、Catalyst、文件、框架四个 XPC service(`ServicePluginEntry.swift`),以及独立运行的命令行 host;App 进程只转发。 + - 生成选项随每个请求发出(`InterfaceCommand.options`),用 MetaCodable 的 `@Default` 声明(`RuntimeObjectInterface+GenerationOptions.swift`),旧版对端缺字段时取默认值;界面入口是 Generation Options 面板(`GenerationOptionsViewController.swift`,`Synthesize Opaque Type` 等开关都在这里)。 + - 刷新:App 的接口缓存在 `engine.dataChangePublisher` 上清空(`RuntimeInterfaceCache.swift:121-139`),但内容区只在对象或选项变化时重新取(`ContentTextViewModel.swift:227-247`);`RuntimeDataChange` 只有 `fullReload` 与 `specializationAdded` 两个 case。 + - 后台工作与 Report:`RuntimeEngineBackgroundWork.swift:85-137`、`ReportNode.swift:9-64`(`ReportCategory` 现有 `backgroundIndexing`、`searchableInterfaces`、`crossReferences`、`manualLoading`)、`ReportTreeBuilder.swift`、`ReportViewModel.swift`;协调器模板是 `CrossReferencePreparationCoordinator.swift`。 + - 缓存位置:`RuntimeDerivedDataLocation.swift:36-68` 只在 `.app` 与 `Contents/XPCServices` 下给出 `~/Library/Caches//DerivedData`,独立命令行 host 与 Catalyst helper 得到 `nil`;删除走 `RuntimeDerivedDataMaintenance.swift:64-75`,App 侧 `RuntimeDerivedDataController.swift:50-93`。 + - Find 语料的 variant 是 `"\(transformer.derivedDataDigest)-ByCategory"`(`RuntimeInterfaceCorpusSnapshot.swift:29-31`),内存里只比 transformer(`RuntimeInterfaceCorpusStore.swift:357-369`)。 + - MCP(`MCPBridgeServer.swift:822-834`)、命令行(`CommandExecutor.swift:578`、`ApplicationOptionsReader.swift:49-55`)、导出(`RuntimeEngine+Export.swift:44`)都走同一个 `engine.interface(for:options:)`;命令行插件 `AgentPlugins/runtime-viewer/` 两个清单都是 `1.3.0`。 + - 依赖:`RuntimeViewerCore/Package.swift:139-158` 以 `branch: "next"` + 本地候选声明 MachOObjCSection 与本仓库;`Tuist.swift:100` 把本仓库的 `"TypeIndexing"` 列为源码依赖 target;SourceKitD 与 swift-apinotes 已经经本仓库进了三个 workspace 的 `Package.resolved`。 +11. **依赖包**:SourceKitD(`Mx-Iris/SourceKitD` 0.1.0,只声明 macOS 10.15);swift-apinotes(`MxIris-DeveloperTool-Forks/swift-apinotes` 0.1.0,依赖 MetaCodable 与 Yams,MetaCodable 是宏包,构建时要 swift-syntax)。两者现在都只是本仓库的普通 URL 依赖。 + +## 提议方案 + +四个仓库,依赖方向自下而上: + +```text +swift-type-indexing ← MachOObjCSection ← MachOSwiftSection ← RuntimeViewer +``` + +1. **新包 `swift-type-indexing`**(`MxIris-Reverse-Engineering/swift-type-indexing`,公开,MIT,模块与唯一 product 都叫 `TypeIndexing`)。内容是本仓库 `TypeIndexing` 的 11 个文件,外加: + - `TypeDatabase` 去泛型,ObjC 元数据那一层改为接收 `[any DeclaredTypeNameSource]`; + - 自己的 `ImportedTypeNameCategory`; + - 改名规则按 Clang importer 修正(有 `SwiftName` 用它;只有 `SwiftPrivate` 时 `__` + C 名); + - sourcekitd 定位同时认 Xcode 与 Command Line Tools;找不到 sourcekitd 时退化而不是失败(API notes 与 ObjC 元数据照常工作,只少了「模块接口」这一层归属); + - 缓存目录由调用方传入(不传就用 `Application Support/swift-type-indexing/…`); + - 可用性探测 `TypeIndexingAvailability`; + - ObjC 容器的 API notes 查询(类、协议及其方法与属性的 `SwiftName` / `SwiftPrivate`),给 MachOObjCSection 打标注用。 + - 所有类型 `public`,源码仍包在 `#if os(macOS)` 里、类型标 `@available(macOS 13.0, *)`,包的平台声明与现在本仓库一致,消费方按 `.when(platforms: [.macOS])` 依赖它。 +2. **MachOObjCSection**: + - 新 target 与 product `ObjCTypeIndexing`(只在 macOS 依赖新包),提供 `ObjCDeclaredTypeNames`(`DeclaredTypeNameSource` 的实现,包一层 `ObjCInterfaceIndexer`)与「API notes → `ObjCSwiftImportNotes`」的转换;`ObjCIndexing`、`ObjCDeclarationRendering` 本身不依赖新包。 + - `ObjCSwiftImportNotes` 加成员的 `swiftName` 与类型一级的标注;协议与 category 的打印入口也接收标注;类型一级的宏单独打一行放在 `@interface` / `@protocol` 上面,成员的宏放在 `;` 前,顺序是 `NS_SWIFT_NAME(...)` 在前、`NS_REFINED_FOR_SWIFT` 在后。 +3. **MachOSwiftSection(本仓库)**: + - 删除 `TypeIndexing` target、product 与 `TypeIndexingTests`(测试随代码搬进新包),不再直接依赖 SourceKitD 与 swift-apinotes。 + - 新 target 与 product `SwiftTypeNameResolution`(macOS 才依赖新包):`TypeDatabaseTypeNameResolver`(把一个 `TypeDatabase` 适配成打印器的 `ModuleNameResolving` + `CImportedNameResolving`,负责两种分类枚举的映射)与原来的 `SwiftInterfaceBuilderTypeNameProvider`(改为建立在前者之上)。 + - `swift-section interface --resolve-c-module-names` / `--supplementary-apinotes` 名字与行为不变(改名修正随之生效);`swift-section objc interface` 新增 `--mark-sdk-swift-names`,按 SDK 的 API notes 标出 Swift 命名。 +4. **RuntimeViewer**: + - Core 新增 `TypeNames/` 功能目录:每个服务进程每个 SDK 平台一个 `TypeDatabase`(`RuntimeTypeIndex`),engine 连上后后台预建它用到的模块;建好后广播新的 `RuntimeDataChange.typeNamesResolved`,各镜像的打印器注册解析器、清掉旧的接口缓存。 + - Swift:`SwiftGenerationOptions.resolvesImportedTypeNames`(默认开)。ObjC:`GenerationOptions.marksSwiftNamesFromAPINotes`(默认开;`objcHeaderOptions` 是 MachOObjCSection 的类型,这个开关只管 RuntimeViewer 传不传标注,所以放顶层),类、协议、category 都把 API notes 的标注并进现有的 `objcSwiftImportNotes`。两个开关放在 Generation Options 面板各自的分组里。 + - 界面请求不等索引(先显示 `__C.`,建好后刷新);MCP、命令行、导出、Find 语料构建等索引就绪(或确认不可用)再打印,保证输出稳定。 + - Report 新增「Imported Type Names」一类,显示每个平台的索引状态(建立中 / 就绪 / 不可用及原因)与缓存大小;工具栏活动显示建立进度。 + - 缓存放在 `~/Library/Caches//TypeIndex/`,所有进程共用(App 内嵌的命令行从可执行文件往上找到 `.app`;不在 App 里的命令行用 `~/Library/Caches/runtime-viewer-cli/TypeIndex/`);「Delete Derived Data」一起删除并计入大小。 + - Find 语料的 variant 带上「是否解析了类型名」与 SDK 版本。 + - 命令行插件的 skill 说明输出变化,两个插件清单抬到 `1.4.0`。 + +### 非目标 + +- **iOS 设备、注入的进程、Simulator payload 不解析**:那些进程里没有 SDK。它们照旧打印 `__C.`。 +- **ObjC 头文件不加 `@import` 行**,也不标 nullability、`NS_SWIFT_UNAVAILABLE` 等其余 API notes 属性——只标 Swift 命名。 +- **MachOObjCSection 自带的 `objc-section` 命令行不加开关**;只有 `swift-section objc` 加。 +- **不在纯二进制层面推断改名**(见动机最后一段);找不到 SDK 时如实显示 `__C.`。 +- **不保留 git 历史**:新仓库的首个提交注明来自本仓库哪个提交,不做 `filter-repo` 式的历史迁移。 +- **不保留过渡层**:本仓库不留转发旧 `TypeIndexing` product 的壳——组织里没有外部使用方。 +- **不改 Find 语料以外的 derived data**:类型索引的缓存是按 SDK 版本的独立目录,不是 `RuntimeDerivedDataKind`。 + +## 改动地图 + +步骤编号见「落地步骤」。 + +### swift-type-indexing(新仓库) + +| 文件 / 类型 | 动作 | 改什么 | 为什么 | 步骤 | +|---|---|---|---|---| +| `Package.swift` | 新增 | 包名 `swift-type-indexing`,product / target `TypeIndexing`,测试 target `TypeIndexingTests`;依赖 SourceKitD、swift-apinotes(`from: "0.3.0"`,本地候选 `../../../Fork/Library/swift-apinotes`)、FrameworkToolbox(后两者均 `.when(platforms: [.macOS])`);平台与本仓库一致(macOS 10.15 / iOS 13 / tvOS 13 / watchOS 6 / visionOS 1);打开 `ExistentialAny`、`MemberImportVisibility`、`InferIsolatedConformances` | 独立成包;平台声明不能高于 MachOObjCSection,否则 SwiftPM 拒绝解析 | 1 | +| `Sources/TypeIndexing/{InterfaceDeclarationNode,InterfaceTypeNameExtractor,ModuleIndexCache,ModuleInterfaceIndexer,SDKIndexer,SDKPlatform,SourceKitManager,Subprocess,SupplementaryAPINotes}.swift` | 移入 | 从本仓库原样搬入;`package` 改 `public`(只公开调用方需要的,其余 `internal`);`@Loggable` 子系统改为 `com.mxiris.type-indexing` | 搬家 | 1 | +| `Sources/TypeIndexing/APINotesIndex.swift` · `APINotesIndex` | 移入 + 修改 | 用 `ImportedTypeNameCategory`;改名规则:有 `SwiftName` 用它(不论 `SwiftPrivate`),只有 `SwiftPrivate` 时 `"__" + cName`;`cNamesBySwiftName` 同步登记;新增 ObjC 容器的方法、属性条目索引 | 修正改名;给 ObjC 标注提供数据 | 1、2、3 | +| `Sources/TypeIndexing/TypeDatabase.swift` · `TypeDatabase` | 移入 + 修改 | 去泛型;`index(dependencies:moduleFilter:)` 改收 `[any DeclaredTypeNameSource]`,可多次调用(第一次发现 SDK、登记 API notes,之后只补新模块与新依赖);API notes、模块接口、运行时元数据三张表在查询时按优先级查,不再靠写入顺序覆盖;`moduleName(forImagePath:)` 保持纯函数;构造器加 `cacheDirectory:`;没有 sourcekitd 时只读缓存;新增 `swiftImportAnnotations(forObjCClassNamed:)` / `forObjCProtocolNamed:` | 去掉对 MachOObjCSection 的依赖;RuntimeViewer 加载新镜像时要追加模块;缓存位置由调用方决定;给 ObjC 标注用 | 1、2、3 | +| `Sources/TypeIndexing/DeclaredTypeNameSource.swift` · `DeclaredTypeNameSource` | 新增 | 协议:`imagePath`、`declaredTypeNames() async throws -> [String]` | 取代直接调用 `ObjCInterfaceIndexer` | 1 | +| `Sources/TypeIndexing/ImportedTypeNameCategory.swift` · `ImportedTypeNameCategory` | 新增 | `objcClass` / `objcProtocol` / `valueType` / `other` | 取代 SwiftPrinting 的 `CImportedTypeNameCategory` | 1 | +| `Sources/TypeIndexing/SourceKitLocator.swift` · `SourceKitLocator` | 新增 | 依次试 `/Toolchains/XcodeDefault.xctoolchain/usr/lib/sourcekitd.framework/sourcekitd` 与 `/usr/lib/sourcekitd.framework/sourcekitd`;`SourceKitManager` 改用它 | 支持 Command Line Tools | 2 | +| `Sources/TypeIndexing/TypeIndexingAvailability.swift` · `TypeIndexingAvailability` | 新增 | `static func availability(for: SDKPlatform) -> TypeIndexingAvailability`:`sdkSettings`(含 SDK 路径与版本,供 RuntimeViewer 的语料 variant 用)、sourcekitd 路径、不可用原因 | 调用方决定开不开、在界面上说明原因 | 2 | +| `Sources/TypeIndexing/SDKPlatform.swift` · `SDKPlatform.macCatalyst`、`SDKSettings.macCatalystVersion`、`compilerArguments(for:)` | 修改 | 新 case `macCatalyst`:读 macOS SDK(`xcrunSDKName`),target `ios-macabi`,给 sourcekitd 显式补 `-Fsystem …/System/iOSSupport/System/Library/Frameworks`;`SDKIndexer` 的 Catalyst 搜索路径先 `System/iOSSupport/…` 再 macOS 的;缓存目录与 macOS 分开 | Mac Catalyst 的 UIKit 与其 API notes 只在 `iOSSupport` 里,原来按 `.macOS` 索引找不到 | 2、3 | +| `Sources/TypeIndexing/SwiftImportAnnotation.swift` · `SwiftImportAnnotation`、`ObjCContainerSwiftImportAnnotations`、`ObjCMemberKey` | 新增 | 单个声明与一个类 / 协议的 API notes 命名标注 | 给 MachOObjCSection 用 | 3 | +| `Tests/TypeIndexingTests/*` | 移入 + 修改 | 本仓库 `Tests/TypeIndexingTests/` 的 7 个文件搬入;`TypeDatabase` 改为用假的 `DeclaredTypeNameSource`;`swiftPrivateEntitiesAreAttributedButNotRenamed` 改写为新规则 | 搬家;规则修正 | 1、2 | +| `Tests/TypeIndexingTests/{DeclaredTypeNameSourceTests,SwiftNameRuleTests,SourceKitLocatorTests,TypeIndexingAvailabilityTests,CacheDirectoryTests,MacCatalystPlatformTests,ObjCSwiftImportAnnotationTests}.swift` | 新增 | 见各步骤的行为清单 | 回归测试 | 1、2、3 | +| `Tests/TypeIndexingTests/SDKIntegrationTests.swift` | 新增 | 对本机真实 SDK 的核对,默认关闭:`TYPE_INDEXING_SDK_TESTS=1`(只读 API notes,约 2 秒),再加 `TYPE_INDEXING_SOURCEKIT_TESTS=1` 经 sourcekitd 冷生成 Catalyst 的 UIKit 接口(实测 126 秒) | 单测覆盖不到 SDK 布局与 sourcekitd 参数 | 2、3 | +| `README.md`、`LICENSE`、`AGENTS.md` + `CLAUDE.md`(符号链接)、`Documentations/README.md`、`Documentations/Evolutions/README.md`(项目类型:库)、`Documentations/Internal/TypeIndexingPipeline.md`(从本仓库移入并更新) | 新增 / 移入 | 用法、三层数据源、改名规则、缓存布局、可用性 | 新仓库的文档 | 1、3 | +| `.github/workflows/macOS.yml` | 新增 | 照本仓库 `macOS.yml` 配 macOS 构建与测试 | CI | 1 | +| `Sources/TypeIndexing/SourceKitManager.swift` · `SourceKitManager`、`InterfaceDocumentService`、`SourceKitDInterfaceDocumentService` | 修改 | 每个打开的接口读完就用同一文档名 `editor.close`(生成失败也关);同时最多生成 2 个;请求经 `InterfaceDocumentService` 发出;发 `0.1.1` | 验收时 SourceKitService 涨到 80 GB(见决策日志) | 验收 | +| `Tests/TypeIndexingTests/SourceKitManagerTests.swift`、`Documentations/Internal/TypeIndexingPipeline.md` | 新增 / 修改 | 替身核对打开与关闭配对、并发上限(去掉任一即失败);文档记下原因与量法 | 回归,文档同批 | 验收 | + +### swift-apinotes(fork,实现中加入) + +| 文件 / 类型 | 动作 | 改什么 | 为什么 | 步骤 | +|---|---|---|---|---| +| `Sources/APINotes/TopLevelItems/ObjCContext.swift` · `ObjCContext.methods` / `properties` | 修改 | 标 `public`;打 tag `0.3.0` | 0.2.0 里是 internal,包外读不到类与协议的成员,ObjC 成员的标注没有来源 | 3 | +| `Tests/APINotesTests/ObjCContextMemberAccessTests.swift` | 新增 | 不带 `@testable` 读成员(修复前编译失败) | 回归 | 3 | + +### swift-semantic-string(验收中加入) + +| 文件 / 类型 | 动作 | 改什么 | 为什么 | 步骤 | +|---|---|---|---|---| +| `Sources/Semantic/SemanticType.swift` · `SemanticType.macro`、`Sources/Semantic/Components/Macro.swift` · `Macro` | 新增 | 宏这一语义类型与它的组件;冻结编码取 22(之前的读者把它当未知编码,显示成 `.other`);发 `0.7.0` | MachOObjCSection 打印的 `NS_SWIFT_NAME` / `NS_REFINED_FOR_SWIFT` 原先只能标成关键字 | 验收 | +| `Tests/SemanticTests/FrozenSemanticStringTests.swift`、`ReviewFindingsRegressionTests.swift`、`README.md`、`AGENTS.md` | 修改 | 类型清单与编码总数加一,冻结与两种 `Codable` 的往返;文档列出新类型 | 回归,文档同批 | 验收 | + +### MachOObjCSection + +| 文件 / 类型 | 动作 | 改什么 | 为什么 | 步骤 | +|---|---|---|---|---| +| `Package.swift` | 修改 | `.package(local: ../swift-type-indexing, remote: …swift-type-indexing, from: "0.1.0")`,带理由注释;新 target `ObjCTypeIndexing`(依赖 `ObjCIndexing`、`ObjCDeclarationRendering`、`TypeIndexing` 限 macOS)与同名 product;测试 target `ObjCTypeIndexingTests` | 接入新包,且只有新 target 依赖它 | 4 | +| `Sources/ObjCTypeIndexing/ObjCDeclaredTypeNames.swift` · `ObjCDeclaredTypeNames` | 新增 | 实现 `DeclaredTypeNameSource`:`ObjCInterfaceIndexer(machO:imagePath:)` → `prepare()` → 类、协议、struct、union 名 | 取代本仓库 `TypeDatabase.indexObjCMetadata(of:)` 的那段 | 4 | +| `Sources/ObjCTypeIndexing/ObjCSwiftImportNotes+TypeDatabase.swift` | 新增 | `ObjCSwiftImportNotes.init(apiNotesForClassNamed:in:)`、`init(apiNotesForProtocolNamed:in:)` | API notes → 标注 | 5 | +| `Sources/ObjCDeclarationRendering/ObjCSwiftImportNotes.swift` · `ObjCSwiftImportNotes`、`Note` | 修改 | `Note` 加 `swiftName: String?`;值上加 `declarationNote: Note?`;加 `merging(_:)`;渲染 `NS_SWIFT_NAME(name)`(在 `NS_REFINED_FOR_SWIFT` 前);新增类型一级的渲染函数 | 标 Swift 命名 | 5 | +| `Sources/ObjCDeclarationRendering/ObjCDump+SemanticString.swift` · `ObjCClassInfo` / `ObjCProtocolInfo` / `ObjCCategoryInfo` 的 `semanticString(using:)` | 修改 | 声明行之前打印类型一级的宏行;category 成员也读标注 | 类型一级宏 | 5 | +| `Sources/ObjCInterface/ObjCInterfaceBuilder.swift` · `protocolInterface` / `markedProtocolInterface` / `categoryInterface` / `markedCategoryInterface` | 修改 | 加 `swiftImportNotes:` 参数(默认空) | 协议与 category 也能标 | 5 | +| `Tests/ObjCInterfaceTests/SwiftImportNotesRenderingTests.swift` | 修改 | 加 `NS_SWIFT_NAME`、类型一级、协议、category 的用例 | 回归 | 5 | +| `Tests/ObjCTypeIndexingTests/*` | 新增 | `ObjCDeclaredTypeNames` 对 Foundation 镜像列出 `NSObject` 等;API notes 转换(临时 `.apinotes` 驱动) | 回归 | 4、5 | +| `Sources/ObjCDeclarationRendering/ObjCSwiftImportNotes.swift` | 修改 | 两个宏由 `Keyword` 改为 `Macro`;括号里的 Swift 名仍是普通文本 | 验收时发现它们与 `@interface` 同为关键字色,Xcode 用宏色(见决策日志) | 验收 | +| `Sources/objc-section/Utilities/SemanticString+Color.swift` | 修改 | `.macro` 用 Xcode Default 主题的宏色(浅色 `#643820`、深色 `#FD8F3F`) | 命令行配色同步 | 验收 | +| `Package.swift`(swift-semantic-string) | 修改 | 临时钉 `branch: "feature/swift-type-indexing-package"`(注明 TEMPORARY),收尾改为 `from: "0.7.0"` | 用到 `Macro` | 验收 | +| `Tests/ObjCInterfaceTests/SwiftImportNotesRenderingTests.swift` · `macrosAreMacroRuns` | 修改 | 两个宏是 `.macro`、Swift 名是 `.standard`(修复前失败) | 回归 | 验收 | +| `README.md`、`Documentations/Guides/ObjCSectionCommandLine.md`(库调用方一节)、`Documentations/Glossary.md:167-177`、`Documentations/Evolutions/README.md`(cross-repository 行) | 修改 | 新 target、新标注、指向本提案 | 文档同批 | 4、5 | + +### MachOSwiftSection(本仓库) + +| 文件 / 类型 | 动作 | 改什么 | 为什么 | 步骤 | +|---|---|---|---|---| +| `Package.swift` | 修改 | 删 `TypeIndexing` target(886-903)、product(1535)、`TypeIndexingTests`(1225-1231)、SourceKitD 与 swift-apinotes 两个依赖(105-108);加 swift-type-indexing 本地候选依赖;加 target / product `SwiftTypeNameResolution`(依赖 `SwiftPrinting`、`SwiftInterface`、`TypeIndexing` 与 `ObjCTypeIndexing` 限 macOS);`SwiftSectionKit`、`IntegrationTests` 改依赖它 | 搬家后的接线 | 6 | +| `Sources/Declaration/TypeIndexing/`(除适配器外 11 个文件) | 删除 | 已移入新包 | 搬家 | 6 | +| `Sources/Output/SwiftTypeNameResolution/TypeDatabaseTypeNameResolver.swift` · `TypeDatabaseTypeNameResolver` | 新增 | 包一个 `TypeDatabase`,实现 `ModuleNameResolving` + `CImportedNameResolving`,映射 `CImportedTypeNameCategory` → `ImportedTypeNameCategory` | 打印器与新包之间唯一的适配点,RuntimeViewer 也用它 | 6 | +| `Sources/Output/SwiftTypeNameResolution/SwiftInterfaceBuilderTypeNameProvider.swift` | 移动 + 修改 | 从 `Sources/Declaration/TypeIndexing/` 移来;依赖改为 `TypeDatabaseTypeNameResolver` 与 `ObjCDeclaredTypeNames`;`buildVersionCommand` 改用 MachOKitExtensions 的公开版本 | 名字不变以免动 CLI 调用方 | 6 | +| `Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift` | 修改 | `import TypeIndexing` 改为新模块;`APINotesFile(path:)` 预校验照旧 | 接线 | 6 | +| `Sources/Executables/swift-section/ObjC/Commands/ObjCInterfaceCommand.swift`、`Sources/Commands/SwiftSectionKit/ObjC/*` | 修改 | 新增 `--mark-sdk-swift-names`:按镜像平台建 `TypeDatabase`,把 API notes 标注交给 `ObjCInterfaceBuilder`;找不到 SDK 时警告并照常输出 | `swift-section objc` 的同类开关 | 7 | +| `Tests/TypeIndexingTests/` | 删除 | 已移入新包 | 搬家 | 6 | +| `Tests/IntegrationTests/TypeIndexing/TypeNameProviderTests.swift`、`Tests/SwiftSectionCommandTests/CommandRequestMappingTests.swift:137-144` | 修改 | import 改名;加 `--mark-sdk-swift-names` 的映射用例 | 接线 | 6、7 | +| `Tests/SwiftTypeNameResolutionTests/TypeDatabaseTypeNameResolverTests.swift` | 新增 | 分类映射、`__C` 解析经适配器到达打印器 | 回归 | 6 | +| `README.md`(:76 product 表、:445-451)、`Documentations/README.md`、`Documentations/SupplementaryTypeMappings.md`、`Documentations/Internal/{TypeIndexingPipeline.md(删,改为指向新包),ProjectMap.md,Modules/README.md}`、`Documentations/Glossary.md:445-448`、`Documentations/SwiftSectionKit{,_zh}.md`、`Documentations/ObjCCommandLine{,_zh}.md`、`AGENTS.md:69` / `CLAUDE.md:69`、`AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md`(:46、:216-217、§8 :352-357,加 objc 新开关)及其插件清单的 `version` | 修改 | 指向新包、新 target、新开关 | 文档同批 | 6、7 | +| `Documentations/Evolutions/README.md` | 修改 | 登记本提案 | 索引 | 0 | +| `Sources/Executables/swift-section/Output/StandardStreamOutput.swift` | 修改 | `.macro` 的配色与 objc-section 相同 | `objc interface --mark-sdk-swift-names` 的宏上色 | 验收 | +| `Package.swift`(swift-semantic-string) | 修改 | 临时钉功能分支,收尾改为 `from: "0.7.0"` | 与 MachOObjCSection 的钉法一致 | 验收 | + +### RuntimeViewer + +| 文件 / 类型 | 动作 | 改什么 | 为什么 | 步骤 | +|---|---|---|---|---| +| `RuntimeViewerCore/Package.swift` | 修改 | 加 swift-type-indexing(本地候选 `../../swift-type-indexing` + 远端,限 macOS);`RuntimeViewerCore` target 加 `TypeIndexing`、`ObjCTypeIndexing`、`SwiftTypeNameResolution` 三个 product(限 macOS)。**实现期间** MachOObjCSection 与 MachOSwiftSection 临时钉 `branch: "feature/swift-type-indexing-package"`,收尾时改回 `branch: "next"` | 接线 | 8 | +| `RuntimeViewer-Local.xcworkspace/contents.xcworkspacedata`、`.worktrees/swift-type-indexing` 链接、`Documentations/Guides/LocalDependencies.md:37-44` | 修改 | 加 `../swift-type-indexing` | 本地联调 | 8 | +| `Tuist.swift:49-110`、`TuistScript.sh:82` | 修改 | 删本仓库的 `"TypeIndexing"`,加 `"SwiftTypeNameResolution"`、MachOObjCSection 的 `"ObjCTypeIndexing"`;swift-type-indexing 加进 `SOURCE_DEPENDENCIES` 并列出它的 target | Tuist 描述同批 | 8 | +| `AGENTS.md`「Dependency floors」 | 修改 | 加 swift-type-indexing 的版本下限与理由 | 规则 | 8 | +| `RuntimeViewerCore/Sources/RuntimeViewerCore/TypeNames/RuntimeTypeIndex.swift` · `RuntimeTypeIndex` | 新增 | actor,每进程一个(`static let process`,不经 `@Dependency`,见决策日志);每个 `SDKPlatform` 一个 `TypeDatabase`;`request(_:)` 把一个镜像链接的模块和它自己的 ObjC 元数据排成一批,同平台的批次依次执行;每批完成把平台的 generation 加一并通知监听者;`resolution(for:)`、`swiftImportNotes(forClassNamed:/forProtocolNamed:platform:)`、`status()` | 进程级共享索引 | 9 | +| `.../TypeNames/RuntimeTypeNames.swift` · `RuntimeTypeNames` | 新增 | 进程开关 `enableInThisProcess()`(照 `RuntimeDerivedData.enableInThisProcess()`);`platformName(of:)` 取镜像第一个 `LC_BUILD_VERSION` 的平台 | 只有打印的服务进程建索引 | 9 | +| `.../TypeNames/RuntimeTypeIndexLocation.swift` | 新增 | 缓存目录:`.app` / `Contents/XPCServices` / `Contents/Applications` 往上找 `.app` → `~/Library/Caches//TypeIndex`;不在 App 里 → `~/Library/Caches/runtime-viewer-cli/TypeIndex`;测试用临时目录 | 所有进程共用缓存 | 9 | +| `.../TypeNames/RuntimeTypeIndexStatus.swift` | 新增 | 线上类型:每个平台 `building(progress)` / `ready` / `unavailable(reason)`、缓存字节数 | Report 与工具栏 | 9 | +| `.../TypeNames/RuntimeEngine+TypeNames.swift`、`Engine/RuntimeEngine+Commands.swift` · `TypeIndexStatusCommand` | 新增 | Core 自有命令 `typeIndexStatus`,路由 `.servingEngine`,加进 `SharedCacheRoutingDeclarationTests` 的清单;`typeIndexStatus()` 经新的 `dispatchToServingProcess(_:timeout:)` 发出、连接自带 2 秒超时,旧对端答 `.empty`;`startObservingTypeIndex()` 把批次完成转成广播;`RuntimeTypeNamesCorpusVariant` | 让 App 读状态 | 9 | +| `.../Engine/RuntimeDataChange.swift` | 修改 | 新 case `typeNamesResolved(platform: String)` | 通知 App 刷新 | 9 | +| `.../Sections/Swift/RuntimeSwiftSection.swift` | 修改 | 显示打印器与语料打印器都注册 `TypeDatabaseTypeNameResolver`;`updateConfiguration` 每次按开关重建解析器列表(不再被 `removeAllTypeNameResolvers()` 误删);收到索引就绪时清 `interfaceByObject` / `importedInterfaceByObject` | 打印解析后的名字 | 9 | +| `.../Sections/ObjC/RuntimeObjCSection.swift:146-236`、`RuntimeEngine.swift:956-962`、`Search/RuntimeEngine+Search.swift:355-356` | 修改 | 类、协议、category 都取 API notes 标注,与 `objcSwiftImportNotes(for:)` 合并后传入 | ObjC 标注 | 9 | +| `.../Interfaces/SwiftGenerationOptions.swift` | 修改 | `@Default(true) resolvesImportedTypeNames` | 开关 | 9 | +| `.../Interfaces/RuntimeObjectInterface+GenerationOptions.swift` · `GenerationOptions` | 修改 | `@Default(true) marksSwiftNamesFromAPINotes`(ObjC 头文件的开关,放顶层:`objcHeaderOptions` 是 MachOObjCSection 的 `ObjCGenerationOptions`,而这个开关只决定 RuntimeViewer 传不传标注);`@Default(false) waitsForTypeIndex` | 开关;非交互的调用方等索引 | 9 | +| `.../Search/Corpus/RuntimeInterfaceCorpusSnapshot.swift:29-31`、`RuntimeInterfaceCorpusStore.swift:357-369` | 修改 | variant 加 `-TypeNames` 或 `-UnresolvedTypeNames`;内存比较加同一条件;语料构建前等索引 | 语料与显示一致 | 9 | +| `ServicePluginEntry.swift`(本机、Catalyst、文件、框架四个 service 与 Catalyst helper 五个入口)、`CommandLineHostServer.start()`(只在独立 host) | 修改 | 进程启动时 `RuntimeTypeNames.enableInThisProcess()`;缓存位置由 `RuntimeTypeIndexLocation` 从 `Bundle.main` 推出,不用配置 | 每个打印的进程 | 9 | +| `RuntimeViewerAppCore/BackgroundWork/TypeIndex/TypeIndexCoordinator.swift` | 新增 | 照 `CrossReferencePreparationCoordinator`:读状态、`isWorkInProgress`、`close()` | Report 与 App Nap | 10 | +| `RuntimeEngineBackgroundWork.swift:85-137` | 修改 | 创建协调器,并入 `isWorkInProgress`、activity reporter、`close()` | 接入后台工作 | 10 | +| `Reports/ReportNode.swift`、`ReportTreeBuilder.swift`、`ReportViewModel.swift` | 修改 | 新 `ReportCategory.importedTypeNames` 及其节点;状态、原因、缓存大小 | Report 可见 | 10 | +| `Activity/RuntimeEngineActivityReporter.swift`、`Activity/ToolbarActivity.swift`、`Presentation/SystemSymbol.swift` | 修改 | 新活动种类(每个批次一项,文案 Indexing Imported Type Names)与 Report 图标 `shippingbox` | 工具栏进度 | 10 | +| `Content/ContentTextViewModel.swift` | 修改 | 收到 `.typeNamesResolved` 时先在主线程清文档的接口缓存,再重新取当前内容(`Base/ViewModel.swift` 不用改) | 建好后自动刷新 | 10 | +| `RuntimeViewerUsingAppKit/.../Generation Options/GenerationOptionsViewController.swift` | 修改 | Swift 组加「Resolve Imported Type Names」,ObjC 组加「Mark Swift Names From SDK」 | 开关 | 10 | +| `RuntimeViewerUsingAppKit/.../App/RuntimeDerivedDataController.swift:50-93`、`DerivedDataStorage/RuntimeDerivedDataMaintenance.swift` | 修改 | 量与删都包括 `TypeIndex` 目录;确认框文案提到它 | Delete Derived Data 一起删 | 10 | +| `RuntimeViewerMCPBridge/MCPBridgeServer.swift:822-834`、`RuntimeViewerCommandLineInterface/CommandExecutor.swift:444-450,578-596`、`Export/RuntimeEngine+Export.swift:44` | 修改 | 置 `waitsForTypeIndex = true` | 输出稳定 | 11 | +| `AgentPlugins/runtime-viewer/skills/runtime-viewer-cli/SKILL.md`、`.claude-plugin/plugin.json`、`.codex-plugin/plugin.json` | 修改 | 说明 `__C.` 解析与首次等待;版本 `1.3.0` → `1.4.0` | 插件规则 | 11 | +| `Documentations/DerivedData.md`、`Documentations/Guides/CommandLineInterface.md`、`Documentations/Evolutions/README.md`(cross-repository 行)、`Documentations/README.md` | 修改 | 新缓存目录、输出变化、索引 | 文档同批 | 8、11 | +| 测试(见各步骤的行为清单) | 新增 | `RuntimeViewerCoreTests` 与 `RuntimeViewerAppCoreTests` 中的对应套件 | 回归 | 9、10、11 | +| `RuntimeViewerCore/Package.swift`(swift-semantic-string) | 修改 | 也临时钉功能分支,收尾改回 `branch: "next"` | MachOObjCSection 的功能分支钉着它,两处不一致 SwiftPM 解析不了 | 验收 | +| `RuntimeViewerSettings/Settings+Theme.swift` · `Preset.macro`、`Style.xcodeMacro` | 修改 | 新颜色槽,`@Default` 是 Xcode 的宏色对、常规字重;之前存下的自定义主题照样解码 | 主题原本只有七种文字颜色,没有宏色 | 验收 | +| `RuntimeViewerSettingsUI/Components/ThemeSettingsView.swift` | 修改 | 编辑器加 Macro 一行,预览加一行 `NS_SWIFT_NAME`,列表的色块加一格 | 宏色可编辑 | 验收 | +| `RuntimeViewerAppUI/Theme/ThemePreset+ThemeProfile.swift` · `ResolvedTheme` | 修改 | `.macro` 取 `preset.macro` | `NSTextView` 面板的着色 | 验收 | +| `RuntimeViewerUsingAppKit/.../Content/SourceEditorThemeConversion.swift` | 修改 | `.macro` 标成 `xcode.syntax.identifier.macro.system`,`xcode.syntax.preprocessor` 也取宏色;`identifier.macro` 仍借给错误色 | SourceEditor 面板的着色,与 Xcode 的键一致 | 验收 | +| `RuntimeViewerCore/.../Search/RuntimeSemanticKind.swift` | 修改 | `.macro` 归入 `.keyword` | 这个枚举跨 engine 边界,加新 case 旧对端解码不了 | 验收 | +| `ThemePresetMacroSlotTests`、`ResolvedThemeTests`、`RuntimeSemanticKindTests`、`SemanticRetypingTests.anObjectiveCSDKMacroTakesTheSystemMacroTypeFromItsSemanticRun` | 新增 | 旧预设解码、主题映射(去掉映射即失败)、归并、SourceEditor 把宏重新标成系统宏 | 回归 | 验收 | +| 五个锁文件(Debug、Distribution workspace 与 Core、Packages、CommandLine 包) | 修改 | 三个功能分支的新提交,swift-semantic-string 改钉功能分支 | 钉版本同批 | 验收 | + +## 架构图 + +### 模块依赖(改了什么) + +```text +before after + +MachOSwiftSection + swift-type-indexing +├── TypeIndexing ─┬─> SourceKitD + └── TypeIndexing ──┬─> SourceKitD +│ ├─> swift-apinotes + ├─> swift-apinotes +│ ├─> ObjCIndexing (MOS) + └─> FrameworkToolbox +│ ├─> SwiftInterface +│ └─> SwiftPrinting MachOObjCSection +├── SwiftInterface ├── ObjCIndexing +├── SwiftPrinting ├── ObjCDeclarationRendering ~ notes: swiftName, type-level +└── SwiftSectionKit ──> TypeIndexing ├── ObjCInterface ~ protocol/category take notes + + └── ObjCTypeIndexing ─┬─> TypeIndexing +MachOObjCSection + ├─> ObjCIndexing +├── ObjCIndexing + └─> ObjCDeclarationRendering +├── ObjCDeclarationRendering +└── ObjCInterface MachOSwiftSection + - ├── TypeIndexing +RuntimeViewerCore + ├── SwiftTypeNameResolution ─┬─> TypeIndexing +├── SwiftInterface (MSS) + ├─> ObjCTypeIndexing (MOS) +├── SwiftPrinting (MSS) + └─> SwiftPrinting, SwiftInterface +└── ObjCInterface (MOS) └── SwiftSectionKit ──> SwiftTypeNameResolution + + RuntimeViewerCore + ├── SwiftInterface, SwiftPrinting (MSS) + ├── ObjCInterface (MOS) + + ├── SwiftTypeNameResolution (MSS) [macOS] + + ├── ObjCTypeIndexing (MOS) [macOS] + + └── TypeIndexing [macOS] +``` + +### 新包内部(改了什么) + +```text +TypeDatabase (actor, no longer generic) +├── SDKIndexer.discover() -> .swiftmodule list, .apinotes files (no sourcekitd) +├── ModuleInterfaceIndexer -> type names per module (sourcekitd; skipped when missing) +│ ├── SourceKitManager +│ │ + └── SourceKitLocator -> Xcode toolchain | Command Line Tools +│ └── ModuleIndexCache ~ directory injected by the caller +├── APINotesIndex ~ SwiftName wins; SwiftPrivate alone -> "__" + C name +│ + ObjC container entries (methods, properties) +- ├── ObjCInterfaceIndexer (MOS) ++ └── [any DeclaredTypeNameSource] -> lazy fallback, first image wins +``` + +### RuntimeViewer 的数据流(建立与刷新) + +```text +service process starts (local / Catalyst / file / framework service, Catalyst helper, standalone CLI host) + └─> RuntimeTypeNames.enableInThisProcess() + +RuntimeSwiftSection.updateConfiguration(for: options) an image is printed (resolvesImportedTypeNames on) + └─> RuntimeTypeIndex.process.request(platform of LC_BUILD_VERSION, + modules the image links, the image's own ObjC metadata) + ├─> TypeIndexingAvailability.availability(for:) unavailable -> status .unavailable(reason), no batch + └─> batch, after the platform's previous one Report row "Imported Type Names", toolbar activity + └─> TypeDatabase.index(dependencies:moduleFilter:) reads/writes ~/Library/Caches//TypeIndex + └─> generation += 1, listeners called + ├─> next print: section sees a new generation -> registers TypeDatabaseTypeNameResolver, + │ drops interfaceByObject / importedInterfaceByObject + └─> engine broadcasts RuntimeDataChange.typeNamesResolved(platformName:) + └─> app: ContentTextViewModel flushes RuntimeInterfaceCache, refetches + -> "UIKit.__UICellConfigurationState" + +interface request + ├─ UI (waitsForTypeIndex = false) -> prints now: "__C.X" until the image's batch is done + └─ MCP/CLI/export/Find corpus (waitsForTypeIndex = true) -> awaits the image's batch, then prints +``` + +## 详细设计 + +### 新包的公开 API + +```swift +#if os(macOS) +import Foundation + +/// One dependency image whose runtime metadata lists the types it declares. +/// `TypeDatabase` consults these, in order, only for names that neither the +/// SDK's module interfaces nor its API notes attribute; the first image that +/// declares a name wins. +public protocol DeclaredTypeNameSource: Sendable { + /// The image's install path; the module name is derived from it + /// (`TypeDatabase.moduleName(forImagePath:)`). + var imagePath: String { get } + + /// Every class, protocol, struct and union name the image's metadata declares. + func declaredTypeNames() async throws -> [String] +} + +/// The namespace a C-imported name lives in, as the printer asks about it. +public enum ImportedTypeNameCategory: Sendable, Hashable { + case objcClass + case objcProtocol + case valueType + case other +} + +/// Whether this Mac can index an SDK platform, and why not. +public struct TypeIndexingAvailability: Sendable, Hashable { + public enum UnavailabilityReason: Sendable, Hashable { + case noDeveloperDirectory + case sdkNotInstalled(SDKPlatform) + } + public let sdkSettings: SDKSettings? // path, version, build, Mac Catalyst version + /// `nil` when the developer directory has no sourcekitd: API notes and + /// runtime metadata still resolve names, module interfaces are skipped. + public let sourceKitPath: String? + public let unavailabilityReason: UnavailabilityReason? + public var isAvailable: Bool { unavailabilityReason == nil } + + public static func availability(for platform: SDKPlatform) -> TypeIndexingAvailability +} + +public enum SDKPlatform: String, CaseIterable, Hashable, Codable, Sendable { + case macOS = "macosx" + case macCatalyst = "maccatalyst" // the macOS SDK read through System/iOSSupport + case iOS = "iphoneos" + // tvOS, watchOS, visionOS, driverKit and the simulators, as before +} + +/// What an API notes file says about how Swift imports one declaration. +public struct SwiftImportAnnotation: Sendable, Hashable { + /// `SwiftName:`; when present, it is the Swift name as is. + public var swiftName: String? + /// `SwiftPrivate: true`; without a `SwiftName`, Swift prefixes `__`. + public var isSwiftPrivate: Bool +} + +/// The key API notes files use for an Objective-C member. +public enum ObjCMemberKey: Sendable, Hashable { + case method(selector: String, isClassMethod: Bool) + case property(name: String, isClassProperty: Bool) +} + +/// API notes for one Objective-C class or protocol and its members. +public struct ObjCContainerSwiftImportAnnotations: Sendable, Hashable { + public var declaration: SwiftImportAnnotation? + public var members: [ObjCMemberKey: SwiftImportAnnotation] +} + +@available(macOS 13.0, *) +public actor TypeDatabase { + public init( + platform: SDKPlatform, + cacheDirectory: URL? = nil, // nil: Application Support/swift-type-indexing + supplementaryAPINotesURLs: [URL] = [] + ) + + public func index( + dependencies: [any DeclaredTypeNameSource], + moduleFilter: @Sendable (String) -> Bool + ) async throws + + public func moduleName(forTypeName typeName: String) async -> String? + public func swiftName(forCName cName: String, category: ImportedTypeNameCategory) -> String? + public func swiftImportAnnotations(forObjCClassNamed className: String) -> ObjCContainerSwiftImportAnnotations? + public func swiftImportAnnotations(forObjCProtocolNamed protocolName: String) -> ObjCContainerSwiftImportAnnotations? + + public static func moduleName(forImagePath imagePath: String) -> String +} +#endif +``` + +- `SDKPlatform` 公开,并新增 `macCatalyst`(落地时发现,见决策日志);`SDKSettings`(`sdkPath`、`version`、`productBuildVersion`、`macCatalystVersion`、`cacheDirectoryComponent`)与 `APINotesFile(path:)` 一并公开——后者是 `swift-section` 预检 `--supplementary-apinotes` 路径用的。 +- `index(dependencies:moduleFilter:)` 可多次调用:第一次发现 SDK 并登记 API notes,之后只补新的模块与依赖镜像;因此 API notes 优先于模块接口改为查询时决定(三张表),不再靠写入顺序。 +- 搬家时保留的三个 `register(...)` 测试钩子(提案 0009「与提案的差异」一节)降为 `internal`,测试用 `@testable import`。 +- 命名照 `apple-style-api-design`:协议按「是什么」命名并沿用组织里 `ObjCMetadataSource` 的 `Source` 后缀;查询读成名词短语(`moduleName(forTypeName:)`);不给 MachOKit 的类型补遵循新包的协议(由 MachOObjCSection 的包装类型实现)。 + +### 改名规则 + +```swift +// APINotesIndex.registerEntities(_:declaredIn:into:) +for entity in entities { + let cName = entity.name + moduleNamesByCName[cName] = moduleName + let swiftName: String? = if let explicitSwiftName = entity.swiftName { + explicitSwiftName // swift_name wins, no "__" + } else if entity.isSwiftPrivate == true { + "__" + cName // swift_private alone + } else { + nil + } + guard let swiftName, swiftName != cName else { continue } + self[keyPath: renameTable][cName] = Name(moduleName: moduleName, name: swiftName) + cNamesBySwiftName[swiftName] = Name(moduleName: moduleName, name: cName) +} +``` + +ObjC 成员(`Methods:` 的 `Selector` + `MethodKind`,`Properties:` 的 `Name` + `PropertyKind`)按同样的两条规则记进 `ObjCContainerSwiftImportAnnotations`,但只记原始的两个属性(`swiftName` / `isSwiftPrivate`)——成员一级要打印的是宏,不是推导后的 Swift 名。 + +### 缓存目录 + +`ModuleIndexCache` 的目录改为 `///`;`cacheDirectory` 为 `nil` 时是 `Application Support/swift-type-indexing/SDKIndexer`。`currentGeneratorVersion` 不变(条目格式没变);目录名换了,旧的 `Application Support/MachOSwiftSection/SDKIndexer` 不再读,也不自动删(新包第一次运行重建,属一次性成本)。 + +### MachOObjCSection + +```swift +// ObjCTypeIndexing +#if os(macOS) +public struct ObjCDeclaredTypeNames: DeclaredTypeNameSource { + public init(machO: MachO, imagePath: String) + public var imagePath: String { get } + public func declaredTypeNames() async throws -> [String] +} + +extension ObjCSwiftImportNotes { + /// The notes the SDK's API notes give a class and its members. + @available(macOS 13.0, *) + public init(apiNotesForClassNamed className: String, in typeDatabase: TypeDatabase) async + @available(macOS 13.0, *) + public init(apiNotesForProtocolNamed protocolName: String, in typeDatabase: TypeDatabase) async +} +#endif + +// ObjCDeclarationRendering +extension ObjCSwiftImportNotes { + public struct Note: Sendable, Hashable { + public var isRefinedForSwift: Bool + public var swiftName: String? // + NS_SWIFT_NAME(swiftName) + } + public var declarationNote: Note? // + the type itself + public func merging(_ other: ObjCSwiftImportNotes) -> ObjCSwiftImportNotes // other wins per field +} +``` + +打印效果: + +```objc +NS_REFINED_FOR_SWIFT +@interface UICellConfigurationState : UIViewConfigurationState +@property (nonatomic, getter=isEditing) BOOL editing; +@end + +NS_SWIFT_NAME(PKDrawingReference) +@interface PKDrawing : NSObject +- (instancetype)initWithData:(NSData *)data error:(NSError **)error; +@end +``` + +`declarationNote` 两个字段都有时打成一行 `NS_SWIFT_NAME(X) NS_REFINED_FOR_SWIFT`。成员一级 `- (void)foo NS_SWIFT_NAME(bar()) NS_REFINED_FOR_SWIFT;`。标注不进可折叠区域(与现在的 `NS_REFINED_FOR_SWIFT` 一致:它是声明的一部分,不是注释)。 + +### MachOSwiftSection 的适配层 + +```swift +#if os(macOS) +@available(macOS 13.0, *) +public struct TypeDatabaseTypeNameResolver: ModuleNameResolving, CImportedNameResolving { + public init(typeDatabase: TypeDatabase) + public func moduleName(forTypeName typeName: String) async -> String? + public func swiftName(forCName cName: String, category: CImportedTypeNameCategory) async -> String? +} +#endif +``` + +`SwiftInterfaceBuilderTypeNameProvider` 保留公开名字与构造器签名,内部改为:按镜像平台建 `TypeDatabase`(`LC_BUILD_VERSION` 的 macCatalyst 映射到 `.macCatalyst`,原来映射到 `.macOS`,Catalyst 镜像因此读不到 UIKit 的 API notes),依赖镜像包成 `ObjCDeclaredTypeNames`,把查询转给一个 `TypeDatabaseTypeNameResolver`。 + +`swift-section objc interface --mark-sdk-swift-names`:按镜像 `LC_BUILD_VERSION` 的平台建 `TypeDatabase`(只读 API notes,`moduleFilter` 返回 `false`,所以不碰 sourcekitd),对每个类与协议取 `ObjCSwiftImportNotes(apiNotesFor…:in:)` 传给 `ObjCInterfaceBuilder`。找不到 SDK 时打印一条 warning,输出与不加开关时相同。 + +### RuntimeViewer + +**进程开关**。`RuntimeTypeNames.enableInThisProcess()` 照 `RuntimeDerivedData.enableInThisProcess()` 的样子:四个 XPC service、Catalyst helper 与独立的命令行 host(`CommandLineHostServer.start()`,`kind == .standalone` 时;App 当 host 时打印在 App 的 service 里)在入口处打开,其余进程——App 本身、注入的 payload、iOS 设备、测试——都不打开,照旧印 `__C.`,也从不读 SDK、不写缓存。忘了调用不会坏事,只是那个进程不解析。 + +**进程内的索引**。`RuntimeTypeIndex` 是每个打印进程一个的 actor(`static let process`)。它不经 `@Dependency`:`RuntimeViewerCore` 不依赖 swift-dependencies,能碰到它的只有 engine 与 section,和 `RuntimeDerivedData` 一样。按 `SDKPlatform` 各持一个 `TypeDatabase`: + +- 平台:一律取镜像第一个 `LC_BUILD_VERSION` 的平台(`RuntimeTypeNames.platformName(of:)`,`macCatalyst` 映射到 `.macCatalyst`),共享缓存镜像、磁盘文件与已加载镜像同一条规则。没有这个 load command 的旧镜像不解析。 +- 批次:`RuntimeSwiftSection.updateConfiguration` 第一次为一个镜像配置时(`resolvesImportedTypeNames` 开着)调 `request(_:)`,交出这个镜像链接的模块名(`machO.dependencies` 的 install name 推出模块名)和它自己的 `ObjCDeclaredTypeNames`。新模块、新镜像才排一批;平台的第一批同时读 API notes。同一平台的批次串起来依次执行,所以不会重复建。依赖镜像里的私有类型,要等那个依赖自己被打开(后台索引迟早会开)才算进来——不为打印一个镜像去打开它全部依赖的 ObjC 元数据。 +- 不可用:`TypeIndexingAvailability` 不可用时记下原因,不排批次,打印器不注册解析器,输出保持 `__C.`。 +- 内存:每个打印的服务进程各有一份(本机、Catalyst、每个文件、每个框架实例),落地时量一次 `malloc` 在用量写进提案(步骤 9)。 + +**打印**。每批完成把平台的 generation 加一。`RuntimeSwiftSection` 记着自己注册解析器时的 generation,下次配置时发现变了,就按当前选项重建完整的解析器列表(opaque 解析器 + 类型名解析器,互不误删),清掉 `interfaceByObject` / `importedInterfaceByObject`;语料打印器同样按 generation 重建。批次完成时 engine 把监听回调转成 `broadcast(.typeNamesResolved(platformName:))`(`startObservingTypeIndex()`,每个 engine 一次)。ObjC 头文件在 `marksSwiftNamesFromAPINotes` 开着时,把 `swiftImportNotes(forClassNamed:/forProtocolNamed:platform:)` 的结果与 `objcSwiftImportNotes(for:)` 合并;category 按它的类查。 + +**等待**。`GenerationOptions.waitsForTypeIndex` 为 `true` 时,`updateConfiguration` 等这个镜像那一批完成再打印;`false`(界面)时直接打印。MCP(`.mcp` 预设)、命令行(每种选项来源都置 `true`)、导出(`exportGenerationOptions`)等待;Find 语料打印前一律等待(`waitForTypeIndex(of:)`)。等待只在磁盘缓存冷、第一次生成某个 SDK 版本的模块接口时明显。 + +**兼容性**。三个新选项都用 `@Default`,旧版对端解码时取默认;`RuntimeDataChange` 新 case 只由新版 Mac 服务发出,旧对端不会收到也不会发出;`typeIndexStatus` 命令对旧对端没有处理器,XPC 上没有处理器的命令被丢弃而不是回错,所以 `typeIndexStatus()` 经 `dispatchToServingProcess(_:timeout:)` 用连接自带的 2 秒超时发出,超时或出错都答 `.empty`,Report 里不显示这一类。 + +**语料 variant**。`RuntimeInterfaceCorpusSnapshot` 的 variant 加一段 `RuntimeTypeNamesCorpusVariant.component`:开着索引、找得到 macOS SDK 时是 `TypeNames-`(共享缓存的 macOS 与 Mac Catalyst 镜像都对着 macOS SDK 读),否则 `UnresolvedTypeNames`。 + +**缓存位置**。`RuntimeTypeIndexLocation` 从进程的 `Bundle.main` 往上找第一个是 RuntimeViewer 的 `.app`(`RuntimeDerivedDataLocation.enclosingApplication`),用 `~/Library/Caches//TypeIndex`,与 `DerivedData` 并列;App、它的 XPC service 与内嵌的命令行工具因此共用一份。不在 App 里的命令行工具用 `~/Library/Caches/runtime-viewer-cli/TypeIndex`。Delete Derived Data 一并量它、删它(先改名再后台删)。 + +**界面**。Generation Options 面板:Swift 组「Resolve Imported Type Names」、ObjC 组「Mark Swift Names From SDK」,都默认勾选。Report 新类别「Imported Type Names」(排在 Cross References 之后),每个平台一行:建立中(第几批 / 共几批)、就绪(模块数)、不可用(没有开发者目录 / 没装这个平台的 SDK),类别行带缓存大小;没有平台时整类不显示,没有取消、推出、清除。`TypeIndexCoordinator` 照 `CrossReferencePreparationCoordinator`:启动时、每次 `.typeNamesResolved`、engine 换进程时问一次状态,建立中每 2 秒问一次;建立中算进 `isWorkInProgress`(防 App Nap),工具栏显示 Indexing Imported Type Names。内容区收到 `.typeNamesResolved` 先在主线程清文档的接口缓存再重新取,避免缓存自己的清空排在重新取之后。 + +## 替代方案考量 + +- **在二进制层面推断(同名 + `_ObjectiveCBridgeable` ⇒ `__X`)**:否。SDK 里 20 个同名桥接中 14 个是 `XReference`,在二进制里与 `__X` 无法区分;另有 15 个 `__` 类型不同名,规则碰不到。 +- **新包留在本仓库、只给 RuntimeViewer 用**:否。MachOObjCSection 需要同一份 API notes 数据,而它是本仓库的依赖,不能反向依赖本仓库的 target。 +- **新包继续依赖 MachOObjCSection 的 `ObjCIndexing`**:否。用户选择让 ObjC 头文件也接入,MachOObjCSection 依赖新包,两者互相依赖会成环;改为协议注入。 +- **ObjC 一侧另起提案**:用户否了,选择一并做。 +- **RuntimeViewer 默认关、手动开**:用户否了,选择找得到 SDK 就自动开。 +- **界面等索引建好再显示**:用户否了,选择先显示 `__C.`、后台预建、建好刷新。 +- **MCP / 命令行 / 导出保持 `__C.`**:用户否了,选择一起换。 +- **开关放进 Settings 的新分支**:否。Swift / ObjC 的打印开关都在 Generation Options 面板,它们随每个请求发出、进接口缓存的键、命令行也读同一份;放进 Settings 要另造一条把设置送到服务进程的通道。 +- **类型索引缓存作为 `RuntimeDerivedDataKind`**:否。derived data 按 dyld 共享缓存的系统身份分目录、只给共享缓存镜像用,而类型索引按 SDK 版本,与镜像无关;放成同级的独立目录,删除时一起删。 +- **保留 git 历史迁移到新仓库**:不做。路径在历史里变过(`Sources/TypeIndexing` → `Sources/Declaration/TypeIndexing`),迁移收益小;首个提交注明来源提交。 + +## 影响 + +### 源码兼容性(source compatibility) + +**有破坏**(本仓库): + +- `TypeIndexing` library product 删除。组织内没有外部使用方(逐个仓库的 `Package.swift` 查过)。改前 `.product(name: "TypeIndexing", package: "MachOSwiftSection")`,改后 `.product(name: "TypeIndexing", package: "swift-type-indexing")`,或改用 `SwiftTypeNameResolution`。 +- `SwiftInterfaceBuilderTypeNameProvider` 从 `TypeIndexing` 模块移到 `SwiftTypeNameResolution` 模块:调用方 `import TypeIndexing` 改为 `import SwiftTypeNameResolution`,签名不变。 +- `swift-section interface` 的输出变化:`SwiftPrivate` / `SwiftName` 改名开始生效(例如 `UIKit.UICellConfigurationState` → `UIKit.__UICellConfigurationState`、`PencilKit.PKDrawing` → `PencilKit.PKDrawingReference`),只在 `--resolve-c-module-names` 打开时。 + +MachOObjCSection 为纯新增:`Note` 加字段带默认值、`declarationNote` 默认 `nil`、新参数带默认值。 + +### ABI 兼容性(条件项) + +不适用 —— 四个仓库都以 SPM 源码分发,使用方每次重新编译。 + +### 下游影响 + +- 本仓库:`SwiftSectionKit`、`IntegrationTests`、`swift-section` 可执行产物。 +- MachOObjCSection:新 target `ObjCTypeIndexing`;`ObjCInterface` 的协议与 category 入口多一个带默认值的参数。 +- RuntimeViewer(经 `branch: "next"` 跟随两个库):用户可见的变化见下;依赖图多一个包(SourceKitD、swift-apinotes 早已在图里),`Tuist.swift` 的 target 清单要跟着改。 +- MachOKitUI、SymbolViewer 等其他下游:不受影响(不依赖 `TypeIndexing`)。 + +**RuntimeViewer 用户能看到的变化**: + +- Swift 接口里的 `__C.X` 变成真实模块与 Swift 名(`UIKit.UITraitCollection`、`UIKit.__UICellConfigurationState`、`PencilKit.PKDrawingReference`),macOS 与 Mac Catalyst 只要装了 Xcode 或 Command Line Tools;读 iOS 等其他平台的文件需要装了对应 SDK 的 Xcode。 +- ObjC 头文件的类、协议、category 与成员上出现 `NS_SWIFT_NAME(...)` / `NS_REFINED_FOR_SWIFT`。 +- 第一次在某个 SDK 版本上使用时,Report 里有一行「Imported Type Names」在建立,期间界面先显示 `__C.`,建好后自动刷新;命令行与 MCP 在这期间会等待。 +- Generation Options 面板多两个默认勾选的开关;Delete Derived Data 会同时删掉类型索引缓存。 + +### 文档与示例 + +见改动地图各仓库的文档行;新仓库的 README 写清三层数据源、改名规则、可用性与缓存位置。 + +## API 演进与废弃策略 + +- `TypeIndexing` product 在本仓库直接删除,不留 `@available(*, deprecated)` 的转发:没有外部使用方,转发壳会让本仓库继续依赖 SourceKitD 与 swift-apinotes。 +- 本仓库 semver:删除 product 属破坏性改动,按本仓库 0.x 惯例抬 minor 版本,在 changelog 写明迁移方式。 +- MachOObjCSection:纯新增,抬 patch 或 minor 按其惯例。 +- 新包从 `0.1.0` 起步;`DeclaredTypeNameSource` 的要求、`ImportedTypeNameCategory` 的 case 一经发布就是公开契约——后者落地前确认四个 case 够用(它与 `CImportedTypeNameCategory` 一一对应)。 + +## 落地步骤 + +0. **提案入库**——本仓库 `Documentations/Evolutions/README.md` 登记草案;批准后、开工前,在 MachOObjCSection 与 RuntimeViewer 的提案索引各加一行 cross-repository 链接。 + - 行为:无代码。 +1. ✅ **建新包并原样搬入**(2026-11-23 完成)——swift-type-indexing 改动地图的 Package.swift、移入的源码与测试、`DeclaredTypeNameSource`、`ImportedTypeNameCategory`、README / LICENSE / AGENTS.md / CI。 + - 行为:`existingTypeIndexingTestsPassAgainstNonGenericDatabase` + - 行为:`declaredTypeNameSourcesAreQueriedLazilyInDependencyOrder` + - 行为:`firstImageDeclaringANameWinsTheAttribution` + - 行为:`failingSourceIsDroppedAndNotRetried` +2. ✅ **改名规则、Command Line Tools 与 Mac Catalyst**(2026-11-23 完成)——`APINotesIndex` 改名规则、`SourceKitLocator`、`TypeIndexingAvailability`、缓存目录注入。先写测试并确认修复前失败。 + - 行为:`swiftPrivateWithoutSwiftNameResolvesToDoubleUnderscorePrefix` + - 行为:`swiftNameWinsOverSwiftPrivate` + - 行为:`plainEntityKeepsItsCName` + - 行为:`sourceKitIsFoundInCommandLineToolsLayout` + - 行为:`sourceKitIsFoundInXcodeToolchainLayout` + - 行为:`missingSourceKitSkipsModuleInterfacesButKeepsAPINotes` + - 行为:`availabilityReportsMissingSDK` + - 行为:`cacheEntriesAreWrittenUnderTheGivenDirectory` + - 行为:`macCatalystSearchesIOSSupportFirst`、`macCatalystTargetTripleIsMacABI`、`macCatalystInterfaceGenerationSeesIOSSupportFrameworks`、`macCatalystCachesApartFromMacOS` + - 实测(`SDKIntegrationTests`):Catalyst 下 `UICellConfigurationState` → `UIKit` / `__UICellConfigurationState`;macOS 下 `PKDrawing` → `PencilKit` / `PKDrawingReference`;sourcekitd 冷生成 Catalyst 的 UIKit 接口后 `UIStackView` → `UIKit` +3. ✅ **ObjC 容器的 API notes 查询**(2026-11-23 完成;用户批准后 fork 推送并打 `0.3.0`,新仓库 `swift-type-indexing` 公开、推送并打 `0.1.0`)——`SwiftImportAnnotation`、`ObjCContainerSwiftImportAnnotations`、`TypeDatabase.swiftImportAnnotations(…)`。 + - 行为:`classAnnotationCarriesSwiftNameAndSwiftPrivate` + - 行为:`methodAnnotationIsKeyedBySelectorAndKind` + - 行为:`propertyAnnotationIsKeyedByNameAndKind` + - 行为:`protocolAnnotationsAreSeparateFromClassAnnotations` + - 前置:swift-apinotes fork 把 `ObjCContext.methods` / `properties` 改成 `public`,打 `0.3.0`。 + - 新包打 `0.1.0` 并推送(公开仓库)。 +4. ✅ **MachOObjCSection 接入新包**(2026-11-23 完成)——`Package.swift`、`ObjCTypeIndexing`、`ObjCDeclaredTypeNames`。 + - 行为:`declaredTypeNamesListFoundationClassesProtocolsAndStructs` + - 行为:`typeDatabaseAttributesPrivateClassThroughObjCDeclaredTypeNames` +5. ✅ **ObjC 头文件的 Swift 命名标注**(2026-11-23 完成)——`ObjCSwiftImportNotes` 扩展、协议与 category 入口、类型一级宏、API notes 转换。 + - 行为:`memberSwiftNamePrintsBeforeRefinedForSwift` + - 行为:`classDeclarationNotePrintsOnItsOwnLineAboveInterface` + - 行为:`protocolInterfaceTakesNotes` + - 行为:`categoryMembersTakeNotes` + - 行为:`mergingKeepsBothSourcesAndTheArgumentWinsPerField` + - 行为:`apiNotesForClassBecomeNotes`(临时 `.apinotes` 驱动) + - 行为:`markedRenderingStillProjectsToPlainRendering` +6. ✅ **本仓库切换到新包**(2026-11-23 完成)——删 `TypeIndexing`、加 `SwiftTypeNameResolution`、CLI 接线、文档与 skill。 + - 行为:`resolverMapsEveryPrinterCategory` + - 行为:`resolverPrintsResolvedModuleAndSwiftName`(假的 `TypeDatabase` 数据驱动打印器) + - 行为:`resolveCModuleNamesFlagStillMapsToRequest` + - 端到端(维护者手动):`swift-section interface --resolve-c-module-names` 对 UIKitCore(Catalyst)输出 `UIKit.__UICellConfigurationState`、对 PencilKit 输出 `PencilKit.PKDrawingReference`。 +7. ✅ **`swift-section objc --mark-sdk-swift-names`**(2026-11-23 完成;`ObjCRequestTests` 按 CI 的步骤先用 Xcode 26.6 编出 `SymbolTestsCore` 夹具再跑,17 条全过)。 + - 行为:`markSDKSwiftNamesFlagMapsToRequest` + - 行为:`missingSDKWarnsAndPrintsUnmarkedOutput` + - 端到端(手动):PencilKit 的 `PKDrawing` 头文件出现 `NS_SWIFT_NAME(PKDrawingReference)`。 +8. ✅ **RuntimeViewer 依赖接线**(2026-11-23 完成;`Tuist.swift` 顺带补上 MachOSwiftSection 早已有的 `SwiftSectionTestingMacros`,`next` 上 `check` 本来就因它不过;`RuntimeViewerServer.xcodeproj` 自带的锁文件在 `next` 上已过时,重新解析会带进无关升级,没有动)——`RuntimeViewerCore/Package.swift`、Local workspace 与 `.worktrees` 链接、Tuist、`AGENTS.md` 依赖下限、三个 workspace 的锁文件(`UpdatePackagesScript.sh`)。 + - 行为:`./TuistScript.sh check` 通过;Debug workspace 能编过。 +9. ✅ **RuntimeViewer Core**(2026-11-23 完成;行为测试按实际做法落在 `RuntimeTypeNamesTests`、`SharedCacheRoutingDeclarationTests` 与 MachOSwiftSection、swift-type-indexing 的测试里;各服务进程多出的 `malloc` 在用量没有量,留作后续)——`TypeNames/` 目录、`RuntimeDataChange` 新 case、`typeIndexStatus` 命令、打印器接线、ObjC 标注合并、三个选项、语料 variant、四个服务与命令行 host 的入口配置。实测:Catalyst 镜像的 API notes 确实来自 `iOSSupport`;记录每个服务进程多出的 `malloc` 在用量。 + - 行为:`typeIndexBuildsOncePerPlatformAndMergesConcurrentRequests` + - 行为:`unavailableSDKLeavesImportedNamesUnresolved` + - 行为:`resolverSurvivesOpaqueTypeSwitchOff` + - 行为:`readyIndexClearsSectionInterfaceCaches` + - 行为:`readyIndexBroadcastsTypeNamesResolved` + - 行为:`waitingRequestPrintsResolvedNamesOnColdIndex` + - 行为:`nonWaitingRequestPrintsImportedPlaceholderOnColdIndex` + - 行为:`switchOffPrintsImportedPlaceholder` + - 行为:`objcHeaderMergesAPINotesWithRefinedMembers` + - 行为:`corpusVariantNamesTypeNameResolution` + - 行为:`typeIndexStatusCommandRoutesToServingProcess` + - 行为:`olderPeerDecodesOptionsWithDefaults` + - 行为:`cacheLocationWalksUpToEnclosingApp`(App、XPC service、内嵌命令行三种位置) +10. ✅ **RuntimeViewer App**(2026-11-23 完成;`contentRefetchesOnTypeNamesResolved` 即 `ContentTextPipelineTests` 的「a finished batch of the type index refetches the interface on screen」;Delete Derived Data 的两条没有单独的测试,App 一侧只是把同一个目录交给 `RuntimeTypeIndexLocation` 的量与删,后者有测试)——协调器、Report、工具栏活动、内容刷新、Generation Options 两个开关、Delete Derived Data。 + - 行为:`typeIndexCoordinatorReportsBuildingReadyAndUnavailable` + - 行为:`reportListsImportedTypeNamesPerPlatform` + - 行为:`contentRefetchesOnTypeNamesResolved` + - 行为:`deleteDerivedDataRemovesTypeIndexDirectory` + - 行为:`derivedDataSizeIncludesTypeIndexDirectory` +11. ✅ **MCP、命令行、导出与插件**(2026-11-23 完成;MCP 一条由 `RuntimeTypeNamesTests` 的「An interactive print does not wait…; MCP's does」覆盖)——`waitsForTypeIndex`、skill、两个插件清单 `1.4.0`、`CommandLineInterface.md`。 + - 行为:`mcpOptionsWaitForTypeIndex` + - 行为:`commandLineOptionsWaitForTypeIndex` + - 行为:`exportConfigurationWaitsForTypeIndex` + +**收尾时必须判断两件事**(判断结果写进决策日志,不允许沉默跳过): + +- **要不要配套专题文章**——新包的 `Documentations/Internal/TypeIndexingPipeline.md`(从本仓库移入)承担实现说明;RuntimeViewer 一侧预计要在 `Documentations/DerivedData.md` 加一节类型索引缓存,是否另写实现说明到时判断。 +- **有没有引入新术语**——预计有「类型索引(type index)」「Swift 命名标注」,登记进各仓库的 `Glossary.md`。 + +## 决策日志 + +| 日期 | 变更 | 说明 | +|------|------|------| +| 2026-11-23 | Created as Draft | RuntimeViewer 把 `UICellConfigurationState` 的桥接类型显示成 `__C.UICellConfigurationState`。查明二进制只记 ObjC 运行时名、改名只在 SDK 的 API notes 里,而本仓库已有的 `TypeIndexing` RuntimeViewer 用不上、且改名规则有误;用户决定把它抽成独立的包,三方接入 | +| 2026-11-23 | 否决二进制层面的推断 | 同名又桥接的 20 个 SDK 类型里 14 个是 `XReference`,与 `__X` 在二进制里无法区分 | +| 2026-11-23 | ObjC 一侧并入本提案 | 用户选择一并做,而不是另起提案;新包因此不能依赖 MachOObjCSection,ObjC 元数据一层改为协议注入 | +| 2026-11-23 | 新仓库名 `swift-type-indexing` | 用户选择;模块名仍是 `TypeIndexing` | +| 2026-11-23 | RuntimeViewer 找得到 SDK 就自动开 | 用户选择;可用条件从「装了 Xcode」改为「找得到该平台 SDK」,因为 Command Line Tools 也带 macOS SDK 与 sourcekitd(用户指出,本机核对) | +| 2026-11-23 | ObjC 只标 Swift 命名、不加 `@import` | 用户选择 | +| 2026-11-23 | 后台预建、先显示 `__C.` | 用户选择 | +| 2026-11-23 | 提案放在本仓库 | 用户选择;其余三个仓库的索引加 cross-repository 行 | +| 2026-11-23 | MCP、命令行、导出一起换 | 用户选择;为了输出稳定,这些非交互的调用方等索引就绪(agent 自定,可推翻) | +| 2026-11-23 | 开关放 Generation Options 面板 | agent 自定,可推翻:与现有打印开关同处,随请求发出、进缓存键、命令行也读同一份 | +| 2026-11-23 | 共识确认 | 用户确认以上决定,开始写提案 | +| 2026-11-23 | Accepted | 用户批准,开始实现 | +| 2026-11-23 | swift-apinotes fork 加入范围 | 它的 `ObjCContext.methods` / `properties` 在 0.2.0 是 internal,ObjC 成员的标注读不到。改为 `public` 并打 0.3.0(每个字段一行),比在新包里另写一套 YAML 解析更小;推送与打 tag 和新仓库一起经用户批准 | +| 2026-11-23 | 新增 `SDKPlatform.macCatalyst` | 提案原定 Catalyst 按 `.macOS` 索引并「落地时实测确认」:实测 `SDKIndexer` 不搜 `System/iOSSupport`,Catalyst UIKit 的 API notes 找不到;sourcekitd 按前端调用解析参数,macabi target 不会自动加 iOSSupport 框架路径(报 `Could not load module: UIKit`)。新 case 读 macOS SDK、先搜 iOSSupport、显式传 `-Fsystem` | +| 2026-11-23 | `index` 可多次调用、优先级改为查询时决定 | RuntimeViewer 加载新镜像时要追加模块;原先 API notes 靠写入顺序覆盖模块接口名,追加的接口名会把名字抢回去 | +| 2026-11-23 | 可用性返回 `sdkSettings` 而非 `sdkPath` | RuntimeViewer 的语料 variant 要 SDK 版本与 build,`SDKSettings` 一并给出 | +| 2026-11-23 | 加默认关闭的 `SDKIntegrationTests` | 单测覆盖不到真实 SDK 布局与 sourcekitd 参数,上面两个 Catalyst 问题都是实测才发现的;手动开启,不进 CI | +| 2026-11-23 | MachOObjCSection、MachOSwiftSection、RuntimeViewer 临时钉功能分支 | MachOObjCSection 0.8.209 要等收尾才发,实现期间 MachOSwiftSection 对它、RuntimeViewer 对两者都钉 `branch: "feature/swift-type-indexing-package"`(清单里注明 TEMPORARY);收尾时发 0.8.209,MachOSwiftSection 改回 `"0.8.209" ..< "0.9.0"`,RuntimeViewer 改回 `branch: "next"` | +| 2026-11-23 | RuntimeViewer 用进程开关,不配置缓存位置 | 原定在各入口「配置缓存位置」。改为 `RuntimeTypeNames.enableInThisProcess()`,照派生数据的开关:缓存位置能从 `Bundle.main` 推出,真正要控制的是哪些进程读 SDK、跑 sourcekitd——测试、注入的 payload、App 本身都不该。Catalyst helper 也打开(它跑的是 Catalyst 的 engine);命令行 host 只在独立运行时打开 | +| 2026-11-23 | `RuntimeTypeIndex` 不经 `@Dependency` | 原定 `@Dependency` + `fileprivate static let shared`。`RuntimeViewerCore` 不依赖 swift-dependencies,项目里 `RuntimeDerivedData` 也是同样的 `static` 单例 | +| 2026-11-23 | 平台一律取 `LC_BUILD_VERSION`,批次按镜像排 | 原定共享缓存镜像查分区、文件查 `RuntimeFile.platform`,engine 连上时预建。改为每个镜像第一次打印时排一批(它链接的模块 + 它自己的 ObjC 元数据):一条规则覆盖三种镜像;只为打开了的镜像建,不在连上时为整个共享缓存跑 sourcekitd。依赖镜像的私有类型等那个依赖被打开时才算入 | +| 2026-11-23 | 刷新靠 generation,等待放在 section 配置时 | 原定索引就绪时主动通知各 section 清缓存、在 `_interface(for:)` 里等待。改为 section 下次配置时比较平台的 generation,自己重建解析器、清缓存;`waitsForTypeIndex` 在 `updateConfiguration` 里等这个镜像那一批。少一条 actor 之间的回调,也不用记哪些 section 活着 | +| 2026-11-23 | 旧对端的状态答 `.empty`,不显示 | 原定把「无应答」当 `.unavailable`。旧对端(iOS 设备、注入的进程、旧版本)本来就没有索引,Report 里多一行「不可用」只是噪音;查询经连接自带的 2 秒超时发出,因为没有处理器的命令在 XPC 上被丢弃、不回错,靠任务取消收不了尾 | +| 2026-11-23 | 语料 variant 只带 macOS SDK 的版本 | 原定 `TypeNames-`。服务进程的共享缓存镜像——macOS 与 Mac Catalyst——都对着同一个 macOS SDK 读,一段就够 | +| 2026-11-23 | 内容区刷新前自己清一次接口缓存 | 文档的接口缓存在同一事件上清空,但它和内容区的订阅各自调度,先后没有保证;内容区先在主线程清再重新取,读不到批次之前的旧结果 | +| 2026-11-23 | 一条既有测试的夹具换类 | RuntimeViewerCore 现在经 swift-apinotes 静态链接 MetaCodable 的 `HelperCoders`,它让 `ISO8601DateFormatter` 遵循 `DateFormatConverter`;镜像把一个类的遵循列成一个条目,「只采纳私有 `@objc` 协议的 category 什么都不打印」那条测试的前提因此不成立。夹具改用没有任何依赖扩展的 `EnergyFormatter`,测试先断言该类只有一个遵循条目 | +| 2026-11-23 | 实现完成,待用户看过后收尾 | 新包 0.1.0 与 swift-apinotes 0.3.0 已发;MachOObjCSection、MachOSwiftSection、RuntimeViewer 的功能分支已推送并在本地合进各自的常驻检出(未推送)。验证:MachOSwiftSection 的相关测试与夹具测试通过;RuntimeViewer Core 与应用层的整套测试在 Ultra 上跑过,红的都是记忆中的基线红灯或满载超时,单独重跑通过(`TitleActivityIndicatorTests` 一条基线必红);`./TuistScript.sh check` 通过,Tuist workspace 编出整个 App。收尾时发 MachOObjCSection 0.8.209、把临时分支钉改回去 | +| 2026-11-23 | `NS_SWIFT_NAME` / `NS_REFINED_FOR_SWIFT` 改用宏色,swift-semantic-string 加入范围 | 用户验收时发现两个宏与 `@interface`、`@end` 同为关键字色:MachOObjCSection 把它们打成了 `Keyword`。查证 Xcode 27.2:Objective-C 的 grammar 从 SourceModel 的 `KnownMacros.plist` 认出两者(`NS_REFINED_FOR_SWIFT` 属普通宏、`NS_SWIFT_NAME` 属函数宏),但只为让解析跳过它们,词法上标成 `xcode.syntax.plain`;SDK 头文件里的宏色来自索引给的 `xcode.syntax.identifier.macro.system`(Default (Light) `#643820`、Default (Dark) `#FD8F3F`,与预处理语句同色,常规字重)。用户选定完整方案:swift-semantic-string 加 `SemanticType.macro` 与 `Macro`(冻结编码 22,之前的读者当普通文本),MachOObjCSection 改用它,RuntimeViewer 主题加可编辑的宏色槽(默认取 Xcode 色,之前存下的自定义主题照样解码),SourceEditor 面板把宏标成 `identifier.macro.system`,搜索的 `RuntimeSemanticKind` 把宏归入关键字、线上格式不变;两个命令行的配色同步。收尾因此多两步,排在发 MachOObjCSection 0.8.209 之前:先发 swift-semantic-string 0.7.0,MachOObjCSection 与本仓库把它改回 `from: "0.7.0"`;RuntimeViewer 对它改回 `branch: "next"` | +| 2026-11-23 | SourceKitService 不再涨到 80 GB:接口生成完就关闭,同时最多生成 2 个 | 用户验收时发现 RuntimeViewer 的两个服务进程各带一个 SourceKitService,各涨到 80 GB。复现:`swift-section interface --uses-system-dyld-shared-cache -n AppKit --resolve-c-module-names`(缓存清空),按秒采样新起的 SourceKitService,6 秒、27 个模块时到 27 GB,被设的上限掐断。原因在 SourceKit 源码里(`SwiftEditorInterfaceGen.cpp`、`SwiftEditor.cpp`):每次 `editor.open.interface` 留一个 `SwiftInterfaceGenContext`(两个 `CompilerInstance`,载入模块及其全部导入),只有同名的 `editor.close` 才从 `IFaceGenContexts` 里删掉;`SourceKitManager` 每个模块用一个新 UUID 打开、从不关闭,`TypeDatabase.index` 又把一个镜像的模块一次全提交。用户选了「关闭 + 限并发」:读完响应即关(生成失败也关),同时最多 2 个。同一条复现峰值 413 MB,33 个模块 70 秒全部生成完,名字照常解析。收尾多一步:swift-type-indexing 发 0.1.1,RuntimeViewer 的下限抬到 0.1.1 | +| 2026-11-24 | 收尾:发版,临时钉改回 | 用户看过、批准收尾,与叠在上面的 [0106](0106-c-imported-type-name-spelling.md) 一起落地。swift-semantic-string 发 0.7.0(`SemanticType.macro`,连同它 `next` 上已有的 Swift 6 upcoming features),MachOObjCSection 发 0.8.209。MachOObjCSection 与本仓库对 swift-semantic-string 改回 `from: "0.7.0"`,本仓库对 MachOObjCSection 改回 `"0.8.209" ..< "0.9.0"`,对 swift-type-indexing 的下限也抬到 0.1.1(复现那次膨胀用的就是 `swift-section interface --resolve-c-module-names`);RuntimeViewer 对三个库改回 `branch: "next"`,swift-type-indexing 的下限抬到 0.1.1,五个锁文件只改这几条。MachOObjCSection 自带的锁文件原本就落后于清单(MachOKitExtensions 还在 1.3.0),这次重解析一并对齐。RuntimeViewer 的这些改动提交在它的本地 `next`:那里还有别的功能先合进来、在等用户看,等它们收尾时一起推 | +| 2026-11-24 | 文档与术语判断 | 不另写专题文章:实现说明就是 swift-type-indexing 的 `TypeIndexingPipeline.md`,RuntimeViewer 的 `DerivedData.md` 已有类型索引缓存一段。术语:「类型索引(type index)」登记进本仓库与 RuntimeViewer 的术语表;「Swift 命名标注」就是 MachOObjCSection 术语表里已有的「Swift import notes(Swift 导入标注)」,只给它补了本提案的链接 | +| 2026-11-24 | 落地验证,取号 | 钉改回发布版本后的本仓库 `next`,在 Ultra 上构建并跑两份提案相关的测试(`CImportedTypeNameSpelling`、`TypeDatabaseTypeNameResolver`、`TypeNameProvider`、`ObjCRequest`、`CommandRequestMapping`、`ObjCSectionCommand`,5 个测试目标共 90 条),构建与测试的退出码都是 0。MachOObjCSection 0.8.209 的 GitHub CI 没分到 macOS runner,超时判为失败;同样的构建与测试在 Ultra 上用 Xcode 26.6 跑过,退出码都是 0,358 条全过。状态改为 Implemented,编号 0105,演进账本 §151 | diff --git a/Documentations/Evolutions/0106-c-imported-type-name-spelling.html b/Documentations/Evolutions/0106-c-imported-type-name-spelling.html new file mode 100644 index 000000000..778d1edf3 --- /dev/null +++ b/Documentations/Evolutions/0106-c-imported-type-name-spelling.html @@ -0,0 +1,593 @@ + + + + + + +0106 - C 导入类型的名字统一成 Swift 名,并能切换回 C 名 + + + + +
+ +
+

MachOSwiftSectionEvolutions0106

+

0106 C 导入类型的名字统一成 Swift 名,并能切换回 C 名

+
+
状态
Implemented
+
最后更新
2026-11-24
+
项目类型
库(跨仓库唯一提案,RuntimeViewer 参与)
+
原文
0106-c-imported-type-name-spelling.md
+
+
+ + + +
+ +
+

摘要

+

Swift interface 里,从 C 导入、被改了名的类型(NS_SWIFT_NAME、typedef、CF 的 Ref 去尾)现在声明行印 Swift 名、其余地方印 C 名:struct AnyWeakAttribute { var _details: __C.AGWeakAttribute.__Unnamed_struct__details },紧跟着 extension __C.AGWeakAttribute: Swift.Hashable {}。原因是声明行取类型描述符里的名字,而引用处取 mangled 名,Swift 给 Clang 声明做 mangling 时一律用 C 名。描述符的导入信息(import info)里两个名字本来都存着,不需要 SDK。

+

本提案让打印器多一个拼写选项 CImportedTypeNameSpelling:

+
    +
  • 默认 .swiftName:声明、成员类型、扩展头全部用 Swift 名。查不到所属模块时写裸名(extension AnyWeakAttribute: Swift.Hashable {}),查得到时照旧写成 模块.Swift名。
  • +
  • .cName:一律按 mangled 的样子印(声明 struct AGWeakAttribute,引用 __C.AGWeakAttribute)。
  • +
+

同时修掉扩展头不经类型名解析器的问题:SDK 类型的成员已经解析成 CoreFoundation.CGRect,扩展头却还是 __C.CGRect。

+

RuntimeViewer 把这个选项做成全局生成选项(Generation Options › Imported Type Names: Swift / C)。用 SourceEditor 显示时,改了名的 C 类型在声明行末尾带一个注释标签样式的胶囊(C name AGWeakAttribute),单击就切换。胶囊画在文本旁边,不进接口文本。

+
+ +
+

要你定

+
+

已定:单击行尾标签

+

最初按 Xcode 原生两步做了行尾标注(点横幅弹下拉框、按钮在下拉框里)。用户看过后不要这种像报错的横幅,改成标签:声明行末尾一个与注释标签同样的胶囊,单击即切换;悬停变深、手形指针、工具提示。标签写法(C name、放在行尾)是我们定的,目视后可调。

+
+
+ +
+

方案

+

MachOSwiftSection

+
    +
  1. 拼写选项:SwiftDeclarationPrintConfiguration.cImportedTypeNameSpelling,默认 .swiftName。
  2. +
  3. 本镜像的名字表:打印器第一次需要时,从本镜像所有 C 导入的类型描述符建一张表,以 mangled 身份为键、描述符的名字为值,只收可信的条目: +
      +
    • 有 ABI 名,且与描述符的名字不同;
    • +
    • 不是相关实体(__C_Synthesized 里的错误码结构体之类);
    • +
    • ABI 名不以描述符的名字结尾——导入成成员的类型(NSAttributedStringKey → Key)都长这样,描述符给的只是叶子,宁可不改名。代价是 NSDecimal → Decimal 这类顶层改名也被挡掉,照旧印 C 名,有 SDK 时由类型索引补上。
    • +
    +
  4. +
  5. .swiftName 下一个 __C 引用怎么印(按顺序取第一个成立的):解析器把模块解析出来了 → 照旧 模块.Swift拼写;名字表里有它 → 只写 Swift 名,不写模块(AnyWeakAttribute);都没有 → 照旧 __C.ABI名。嵌在 C 类型里的类型,父类型那一段按同样的规则印(AnyWeakAttribute.__Unnamed_struct__details)。
  6. +
  7. .cName:引用一律按 mangled 的样子印 __C.ABI名,打印时不问任何解析器——模块也不解析,因为 UIKit.UICellConfigurationState 会和同名的 Swift 结构体混淆。只有打开标注时,声明名会去问解析器要标注里的 Swift 名,打印的文字不变。
  8. +
  9. 声明行与引用走同一套规则:.cName 下是 ABI 名;.swiftName 下依次取解析器给的 Swift 拼写(可以带点号,struct NSAttributedString.Key)、名字表里的名字、ABI 名。不可信的条目因此从 struct Key 变成 struct NSAttributedStringKey。
  10. +
  11. 扩展头改走异步的类型打印路径:只改扩展类型根在 __C / __C_Synthesized 的扩展,仍包成同一种 TypeDeclaration。其余扩展一个字节都不变。
  12. +
  13. 标注:marksCImportedTypeNames(默认关)打开时,两种拼写不同的声明名外面包一个 AnnotationRegion,kind 里带着两个名字。文本不变,分离之后与不标注时逐字节相同。
  14. +
  15. swift-section interface --c-imported-type-name-spelling swift-name|c-name,默认 swift-name。
  16. +
+

RuntimeViewer

+
    +
  1. 生成选项:SwiftGenerationOptions.cImportedTypeNameSpelling(@Default(.swiftName))。面板的 Swift 一组加一行 Imported Type Names: Swift | C。它与「Resolve Imported Type Names」各管各的:后者在 C 名模式下不起作用,也不再为它建类型索引。
  2. +
  3. 内部标注开关:GenerationOptions.marksCImportedTypeNames,不出现在面板里,存下来的值永远是 false;内容区只在 SourceEditor 可用时打开,currentMergedGenerationOptions 照同样的规则合并。
  4. +
  5. 接口带回名字:RuntimeObjectInterface.cImportedTypeNames,每条是声明名的 UTF-8 范围和两个名字,与宏展开在同一处从标注区域里取出;注释结构不认这种 kind。
  6. +
  7. 行尾标签:bridge 新增 showLineEndTags(_:) 与一个代理回调。Swift 名模式写 C name AGWeakAttribute(提示 Show C Names),C 名模式写 Swift name AnyWeakAttribute(提示 Show Swift Names)。单击即翻转全局生成选项,所有内容区一起重新取接口。标签画在文本旁边,复制、查找、导出都不受影响。
  8. +
  9. 其余出口跟着选项走:MCP、App 充当 host 时的命令行、导出读的都是 appDefaults.options;独立运行的命令行 host 用默认的 Swift 名。Find 语料始终用 Swift 名打印。
  10. +
+

非目标

+
    +
  • 不推断导入成成员的类型的父路径:描述符只给叶子,没有 SDK 就保持 C 名。
  • +
  • 相关实体(__C_Synthesized)不改。
  • +
  • 只在声明行放提示,引用处不放。
  • +
  • 侧栏、路径栏、Find 结果里的对象名不跟着切换;Find 语料始终是 Swift 名,搜 C 名搜不到改了名的引用。
  • +
  • dump、diff、snapshot 的键不变(ABI diff 按 mangled 身份对比)。
  • +
  • NSTextView 显示路径与 iOS 版不放提示;命令行工具不加对应参数。
  • +
+
+ +
+

架构图

+
    +
  • 新增
  • +
  • 修改
  • +
  • 不变
  • +
+
+ + + MachOSwiftSection + CImportedTypeNameSpelling.swiftName (default) | .cName + CImportedTypeSwiftNameTablemangled identity -> trusted descriptor name + AnnotationRegion.Kind.cImportedTypeName(_:)both names, when marking is on + SwiftDeclarationPrintConfiguration+ cImportedTypeNameSpelling, + marksCImportedTypeNames + SwiftDeclarationPrintermemoized name table from typeContextDescriptors + TypeNodePrintable.printTypespelling rules for __C references + +Headers: declared name, extension headerssame rules; extension headers become async + swift-section interface--c-imported-type-name-spelling swift-name|c-name + swift-type-indexing resolvers (SDK) + + + RuntimeViewer + SwiftGenerationOptions+ cImportedTypeNameSpelling (@Default .swiftName) + GenerationOptions+ marksCImportedTypeNames (internal, stored false) + RuntimeInterfaceCImportedTypeNamedeclared name's UTF-8 range + both names + RuntimeObjectInterface+ cImportedTypeNames + SourceEditorBridgingLineEndTag, LineEndTagControllercapsule + text layer past the line's end; hover, click, pointing hand + SourceEditorBridging + delegate+ showLineEndTags(_:), + didClickLineEndTag + ContentInterface, ContentTextViewModel+ tags, + spelling toggle input + ContentSourceEditorViewControllerline-end tags, toggle relay + GenerationOptionsViewController: Imported Type Names + + + + +
+

实线:RuntimeViewer 的生成选项映射进打印配置。虚线:接口里的名字来自打印器标出的区域。SDK 解析器照旧注册在打印器上,没有改动。

+ +
+ + click the tag "C name AGWeakAttribute"LineEndTagController, an event consumer of SourceEditorView, takes the click + navigationDelegate.didClickLineEndTagContentSourceEditorViewController -> toggle relay + ContentTextViewModelappDefaults.options.swiftInterfaceOptions.cImportedTypeNameSpelling = .cName + appDefaults.$optionsevery content pane refetches + service: RuntimeSwiftSection.updateConfigurationprinter prints with .cName and marks declared names; cache cleared + separatingAnnotationRegions()RuntimeObjectInterface.cImportedTypeNames + setSource + showLineEndTagsstruct AGWeakAttribute { (Swift name AnyWeakAttribute) + + + + + + + +
+

单击行尾标签之后:改的是全局生成选项,所有内容区经同一条重新取接口的路径刷新。

+
+ +
+

改动地图

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
仓库 · 文件 / 类型动作改什么为什么步骤
MSS · SwiftPrinting/CImportedTypeNameSpelling.swift新增.swiftName / .cName拼写选项的类型1
MSS · SwiftDeclarationPrintConfiguration.swift修改加 cImportedTypeNameSpelling 与 marksCImportedTypeNames打印配置1
MSS · SwiftPrinting/CImportedTypeSwiftNameTable.swift新增「mangled 身份 → 描述符名字」的表与可信规则描述符里现成的 Swift 名1
MSS · SwiftDeclarationPrinter.swift修改按需建表并复用;回答名字表查询;扩展头调用改 await打印器持有名字表1、2
MSS · NodePrintables/TypeNodePrintable.swift · printType(_:)修改__C 引用按拼写规则印统一引用处2
MSS · NodePrintables/NodePrintable.swift · resolvedModuleName修改.cName 下不问解析器C 名等于 mangled 拼写2
MSS · 节点打印器的 delegate 协议修改按 mangled 身份取名字表里的 Swift 名名字表是打印器自带的2
MSS · SwiftDeclarationPrinter+Headers.swift修改声明名同一套规则;标注时包区域;根在 __C 的扩展头走异步类型打印声明、扩展与成员一致2、3
MSS · 扩展头的四个调用点修改await renderExtendedTypeName签名变成 async2
MSS · SwiftPrinting/AnnotationRegionKind+CImportedTypeName.swift新增CImportedTypeNames、kind 的构造与解析把两个名字交给宿主3
MSS · InterfaceRequest.swift、InterfaceCommand.swift修改--c-imported-type-name-spelling命令行能切回 C 名3
MSS · Tests/SwiftInterfaceTests/CImportedTypeNameSpellingTests.swift新增第 1–3 步的行为回归1–3
MSS · 受新默认拼写影响的快照测试修改只更新改了名的 C 类型那几行默认输出变了2
MSS · README.md、插件 skill、两份插件清单修改新参数与新默认拼写;0.27.0 → 0.28.0文档随代码3
MSS · Documentations/Evolutions/README.md修改登记本草案索引0
RV · Interfaces/SwiftGenerationOptions.swift修改拼写枚举与 cImportedTypeNameSpelling用户选项4
RV · Interfaces/RuntimeObjectInterface+GenerationOptions.swift修改marksCImportedTypeNames只有内容区要提示4
RV · Interfaces/SwiftDeclarationPrintConfiguration+GenerationOptions.swift修改拼写映射进打印配置;不进 applySwitches(of:)显示跟选项,语料不跟4
RV · Interfaces/RuntimeInterfaceCImportedTypeName.swift新增声明名的范围与两个名字提示所需的数据4
RV · RuntimeObjectInterface.swift 及两处 +AnnotationRegions修改可选字段;分离时取出;注释结构忽略照宏展开的路4
RV · RuntimeSwiftSection.swift · updateConfiguration修改设标注开关;.cName 下不请求类型索引C 名用不到索引4
RV · SourceEditorBridging.swift修改SourceEditorBridgingLineEndTag、showLineEndTags(_:)、代理回调bridge 接口5
RV · LineEndTagController.swift新增行尾画胶囊与文字层;悬停、工具提示、单击、手形光标画行尾标签、接点击5
RV · SourceEditorBridge.swift修改注册控制器;换数据源前清掉标签;外观交给两个控制器接上控制器5
RV · CommentDecorationController.swift · TagAppearance修改多存注释字体;按样式取字色;cgColor(_:in:) 模块内可见两种标签共用外观5
RV · RuntimeViewerSourceEditorBridgeTests/LineEndTagTests.swift新增第 5 步的行为回归5
RV · RuntimeViewerAppCore/Content/ContentInterface.swift修改标签的值(范围、标签名、另一个名字、工具提示)AppCore 描述、App 只画6
RV · RuntimeViewerAppCore/Content/ContentTextViewModel.swift修改合并标注开关;新输入翻转拼写切换即改全局选项6
RV · RuntimeViewerAppCore/Base/ViewModel.swift修改currentMergedGenerationOptions 同样合并缓存键对齐6
RV · Content/ContentSourceEditorViewController.swift修改setSource 之后放标签;回调进 relay接上 ViewModel6
RV · Generation Options/GenerationOptionsViewController.swift修改Imported Type Names: Swift | C面板入口6
RV · Core 与 AppCore 测试新增第 4、6 步的行为回归4、6
RV · 命令行插件 skill 与清单修改补上描述符的 Swift 名与 C 名选项;1.4.0 已发布就抬到 1.4.1输出变了7
RV · RuntimeViewerCore/Package.swift 与锁文件修改抬 MSS 的 pin取上游改动7
RV · Documentations/Evolutions/README.md修改cross-repository draft 一行索引0
+
+
+ +
+

详细设计

+
+ 一个 __C 引用怎么印 +
+
printType(reference rooted in __C)
+├─ spelling == .cName                       -> "__C." + ABI name       (no resolver asked)
+└─ spelling == .swiftName
+   ├─ a resolver resolves the module        -> Module + Swift spelling (existing path)
+   ├─ name table has a trusted entry        -> bare Swift name          AnyWeakAttribute
+   └─ otherwise                             -> "__C." + ABI name        __C.NSAttributedStringKey
+
+declared name of a C-imported descriptor
+├─ .cName                                   -> ABI name                 AGWeakAttribute
+└─ .swiftName                               -> resolver's spelling ?? trusted name ?? ABI name
+
+
+
+ MachOSwiftSection 的公开 API +
+
public enum CImportedTypeNameSpelling: String, Sendable, Hashable, CaseIterable {
+    case swiftName
+    case cName
+}
+
+// SwiftDeclarationPrintConfiguration
+public var cImportedTypeNameSpelling: CImportedTypeNameSpelling = .swiftName
+public var marksCImportedTypeNames: Bool = false
+
+public struct CImportedTypeNames: Sendable, Hashable {
+    public let swiftName: String
+    public let cName: String
+    public init(swiftName: String, cName: String)
+}
+
+extension AnnotationRegion.Kind {
+    public static func cImportedTypeName(_ names: CImportedTypeNames) -> Self
+    public var cImportedTypeNames: CImportedTypeNames? { get }
+}
+

kind 的编码是 "cImportedTypeName|" + swiftName + "|" + cName;| 不会出现在 Swift 或 C 的名字里,Swift 名里可以照常带点号。原设计用 U+001F,被 swift-semantic-string 拒绝(kind 里不许有控制字符),实现时改成了 |。

+
+
+
+ 名字表与可信规则(模块内部) +
+
struct CImportedTypeSwiftNameTable: Sendable {
+    init(typeContextDescriptors: [TypeContextDescriptorWrapper], in context: some ReadingContext)
+    func swiftName(forIdentity identity: Node) -> String?
+
+    static func trustsUserFacingName(_ userFacingName: String, importInfo: TypeImportInfo) -> Bool {
+        guard let abiName = importInfo.abiName, abiName != userFacingName, !importInfo.isRelatedEntity else { return false }
+        return !abiName.hasSuffix(userFacingName)
+    }
+}
+
    +
  • 键是 mangled 身份节点(SymbolicDemangler.demangleContext(for:in:))的结构,照 ExtensionName 的结构化 Hashable。
  • +
  • 只遍历 C 导入的描述符,读名字与 typeImportInfo(in:);第一次需要时才建,配置怎么变都不重建;读出错的条目跳过。
  • +
+
+
+
+ 打印规则的落点 +
+
    +
  • printType(_:):.cName 写原模块名与标识符;.swiftName 先走现有路径,模块没解析出来但名字表有答案时,不写模块与分隔符,把 Swift 名写成标识符(语义仍是这个类型的 printIdentifier 上下文,跳转不受影响)。嵌套类型的父段递归回 printType,套用同一规则。
  • +
  • printModuleSelector(ofNestedType:):父段是改了名的裸名时不写模块选择器。
  • +
  • renderTypeDeclarationHeader:C 导入的描述符按方案第 5 条取名;解析器那一路用 ABI 名去问,与引用处的查询相同,声明与引用必然一致。displayParentName == true 那条路不变。
  • +
  • renderExtendedTypeName 改成 async:根在 __C 时走 typeDemangleResolver.resolve(for:) 再 .replacingTypeNameOrOtherToTypeDeclaration();其余分支原样。
  • +
+
+
+
+ RuntimeViewer 的类型与 bridge 接口 +
+
// SwiftGenerationOptions
+public enum CImportedTypeNameSpelling: String, Codable, Sendable, Equatable, Hashable, CaseIterable { case swiftName, cName }
+@Default(CImportedTypeNameSpelling.swiftName)
+public var cImportedTypeNameSpelling: CImportedTypeNameSpelling
+
+// RuntimeObjectInterface.GenerationOptions
+@Default(false)
+public var marksCImportedTypeNames: Bool
+
+public struct RuntimeInterfaceCImportedTypeName: Codable, Sendable, Hashable {
+    public let nameUTF8Range: Range<Int>
+    public let swiftName: String
+    public let cName: String
+}
+// RuntimeObjectInterface
+public let cImportedTypeNames: [RuntimeInterfaceCImportedTypeName]?
+
+@objc(RuntimeViewerSourceEditorBridgingLineEndTag)
+public final class SourceEditorBridgingLineEndTag: NSObject {
+    public let characterRange: NSRange
+    public let label: String          // "C name"
+    public let value: String          // "AGWeakAttribute"
+    public let valueStyle: SourceEditorBridgingCommentRunStyle
+    public let toolTip: String?       // "Show C Names"
+    public let identifier: String
+}
+// SourceEditorBridging
+func showLineEndTags(_ tags: [SourceEditorBridgingLineEndTag])
+// SourceEditorBridgingNavigationDelegate
+func sourceEditorBridge(_ bridge: SourceEditorBridging, didClickLineEndTagWithIdentifier identifier: String)
+
    +
  • 线上兼容:旧版对端不认这两个选项,不带 cImportedTypeNames,内容区就没有提示;新版对端收到旧版请求时取默认值。
  • +
  • LineEndTagController 是布局可视化、事件消费者(.high)与光标矩形提供者,在 bridge 的 init 里注册一次。每次布局取「选中整行时会画的矩形」里最后一行最右的那个,胶囊左边离它一个空格宽,高度与注释标签一样;胶囊是 CAShapeLayer、文字是 CATextLayer,都在 underlayLayer,外观用注释标签那一份(多存了注释字体)。
  • +
  • 左键按下(不带 ⌘、⌃)落在胶囊里就回调并吃掉这次点击与随后的抬起;移动时悬停的胶囊填充不透明度翻倍、内容视图的 toolTip 换成标签的提示(照 gutter 的做法);每个胶囊一个手形光标矩形。setSource 换数据源前清掉标签。
  • +
  • AppCore 按当前拼写生成值:.swiftName 是 C name + C 名、提示 Show C Names,.cName 是 Swift name + Swift 名、提示 Show Swift Names;ViewModel 的新输入在主线程翻转 appDefaults.options 里的拼写。
  • +
+
+
+
+ +
+

调研

+
+ 12 条查证过的事实 +
+
    +
  1. 复现:swift-section 0.24.0 interface --show-c-imported-types 打 macOS 27.2 的 AttributeGraph,得到 struct AnyAttribute、struct AnyWeakAttribute { … var _details: __C.AGWeakAttribute.__Unnamed_struct__details } 与 struct WeakAttribute<A> { var base: __C.AGWeakAttribute }。
  2. +
  3. 两套名字从哪来:声明行取 descriptor.name(in:)(SwiftDeclarationPrinter+Headers.swift:47/56/73);引用来自 mangled 名,Swift 按 Clang 名 mangling(ASTMangler::tryAppendClangName),SymbolicDemangler.cImportedTypeIdentity(SymbolicDemangler.swift:982)是反方向的映射。
  4. +
  5. 描述符里存的是什么:IRGen computeIdentity(GenMeta.cpp:1568)写的是 Swift 名的叶子,名字不同时追加 N<ABI 名>。shared cache 实测:AnyAttribute/AGAttribute ×9、AnyWeakAttribute/AGWeakAttribute ×4、CGColor/CGColorRef ×142、Decimal/NSDecimal ×47、Key/NSAttributedStringKey ×158、Name/NSNotificationName ×68。导入成成员的类型只剩叶子。
  6. +
  7. 父上下文:getAddrOfParentContextDescriptor(GenDecl.cpp:885)把 Clang 导入的名义类型一律挂到 __C 下,父路径不在二进制里。
  8. +
  9. 现有改名的条件:printType(TypeNodePrintable.swift:170-262)只在模块解析成功后才改标识符。
  10. +
  11. 扩展头不经解析器(读代码得出,未实测):renderExtendedTypeName 调同步的 ExtensionName.print,四个调用点。
  12. +
  13. 可用的 API:machO.swift.typeContextDescriptors、isCImportedContextDescriptor(in:)、typeImportInfo(in:)、SymbolicDemangler.demangleContext(for:in:);打印器已有按需建一次的状态写法。
  14. +
  15. 标注区域只有 kind 和内容;名字编进 kind 有先例(attachedMacroTrackedProperty(_:named:))。
  16. +
  17. 命令行:InterfaceCommand.swift、InterfaceRequest.swift;插件 skill §8,清单 0.27.0。
  18. +
  19. RuntimeViewer:生成选项在 appDefaults.options,内容区随它重取;面板有 .enumOption;注释结构与宏展开都是「标区域 → 分离 → 接口带可选字段」;bridge 是 Objective-C 协议,从未用过行尾标注;命令行插件 1.4.0 尚未发布。
  20. +
  21. 复刻版 SourceEditor 的行尾标注(tag 27.2.0-alpha.2):insertLineAnnotation(_:) 等公开入口齐全;横幅本身不带按钮,点横幅弹下拉框(handleLeftMouseUpEvent),右键菜单只有 revealAction;交互代理没有「点了横幅」的回调。
  22. +
  23. 注释标签怎么画、能不能接点击(验收时查的):胶囊是 underlayLayer 里的 CAShapeLayer,位置取自 selectionRects,字是编辑器自己画的源码文字,所以离不开文本;SourceEditorView 把按下、抬起、移动、移出都先交给事件消费者,移动来自它自己的跟踪区域;光标矩形提供者在 I 形光标之后追加;gutter 悬停时改视图的 toolTip;positionFromInternalCharOffset、lineContentLengthForLine 都是公开的。
  24. +
+
+
+
+ +
+

替代方案

+
+ 7 条被否的路径 +
+
    +
  • 模块未知时写 __C.AnyWeakAttribute:与声明行仍不一致,且是打印器以前特意避开的半翻译写法;用户选了裸名。
  • +
  • 默认按 C 名统一:读的是 Swift interface,Swift 名更贴合;C 名作为可切换的拼写保留。
  • +
  • 按前缀推断成员导入的父类型:二进制里没有父路径,前缀切分会切出 NS.Decimal 这种错误结果。
  • +
  • 打印器多印一段注释,再按注释标签画:标签的字来自文本,复制、查找、导出都会带上,NSTextView 下还是普通注释;改由 bridge 在行尾自己画。
  • +
  • 复刻版的行尾标注(最初的实现):横幅像报错,切换要点两下;用户看过后改成单击的行尾标签。
  • +
  • 只切换当前编辑栏:要另存一份不进设置的状态,缓存键多一维;用户选了全局生成选项。
  • +
  • 拼写与 resolvesImportedTypeNames 合成三档:类型索引功能还在验收,合并就要改它的设置与测试;两个开关各管各的更简单。
  • +
+
+
+
+ +
+

影响

+

源码兼容性

+
    +
  • 纯新增:两个类型、两个配置属性、kind 的构造与解析。renderExtendedTypeName 是 package,改 async 只影响本包四处调用。
  • +
  • 输出有变化:改了名的 C 类型的引用与扩展头变成 Swift 名;不可信条目的声明行从叶子名变成 C 名(struct Key → struct NSAttributedStringKey、struct Decimal → struct NSDecimal);注册了解析器时 SDK 类型的扩展头变成 模块.名字。
  • +
+

ABI 兼容性

+

不适用 —— 本库以 SPM 源码分发,使用方每次重新编译。

+

下游影响

+
    +
  • 本仓库:SwiftInterfaceBuilder、diff --interface 的渲染、swift-section interface 的默认输出跟着变;ABI diff 的键不变。
  • +
  • MachOKitUI、SymbolViewer:输出变化同上,不需要改代码。
  • +
  • RuntimeViewer · 用户可见:SourceEditor 下改了名的声明行末尾多一个注释标签样式的胶囊,写着另一个名字,单击即切换;Generation Options 多一行;默认接口统一成 Swift 名;MCP、App 充当 host 时的命令行与导出跟着选项;Find 结果始终是 Swift 名。
  • +
  • RuntimeViewer · 兼容:旧设置取 .swiftName,标注开关存下来永远是 false,不需要迁移;提示只在 macOS 的 SourceEditor 路径;不涉及权限、公证与 Sparkle;Find 语料的旧文件因产出者身份改变自然失效,不必改 variant。
  • +
  • 顺序约束:两边都叠在 swift-type-indexing-package 上(它还在两个仓库的本地 next、没推送),要等它先收尾,或在它的功能分支之上开分支。
  • +
+

文档与示例

+
    +
  • 本仓库 README 与 swift-section 插件 skill(§4、§8、§9),插件清单抬到 0.28.0。
  • +
  • RuntimeViewer 命令行插件 skill 的「Imported types」一段。
  • +
  • 落地时判断要不要在两边术语表登记「C 导入类型名拼写」。
  • +
+

API 演进与废弃策略

+

没有被替代的旧 API。默认输出变化按 minor 版本发布并写进 release note;CImportedTypeNameSpelling 用 enum,因为只有两种拼写、调用方需要穷举。

+
+ +
+

落地步骤

+
    +
  1. ✅ 登记草案 —— 两边的提案索引;提案随两个功能分支的第一个提交走。
  2. +
  3. ✅ 名字表与可信规则 —— trustsUserFacingNameWhenABINameDiffers、refusesLeafNameOfTypeImportedAsMember、refusesRelatedEntityName、refusesNameWithoutABIName、nameTableReadsTheFixturesDescriptors(测试里现场编译的桥接头 fixture)。
  4. +
  5. ✅ 打印规则 —— swiftSpellingPrintsBareSwiftNameWhenModuleIsUnknown、untrustedDeclaredNamePrintsCName、swiftSpellingKeepsModuleThatResolverFinds、extensionHeaderSpellsLikeMemberTypes、cSpellingPrintsMangledNamesAndAsksNoResolver;扩展头逐字节不变与 diff 的键由全量测试覆盖。
  6. +
  7. ✅ 标注与命令行 —— markedDeclaredNameCarriesBothSpellings、markedCSpellingCarriesTheSameNames、sameSpellingsAreNotMarked、regionKindRoundTripsDottedSwiftName、interfaceCImportedTypeNameSpelling;README 与插件 skill(0.28.0)。
  8. +
  9. ✅ RuntimeViewer Core —— 对系统 AttributeGraph 的引擎测试 7 条与 changedSpellingReconfiguresOnce;类型索引那条在测试进程里无从观察,不写。
  10. +
  11. ✅ Bridge 的行尾标签(最初做成行尾标注,验收时改掉) —— tagSitsPastTheEndOfTheLineItsRangeStartsOn、tagAddsNothingToTheText、showingAgainReplaces、setSourceRemovesTags、clickingNotifiesDelegateWithIdentifier、tagTakesThePointingHand、hoveringDarkensTagAndShowsToolTip。
  12. +
  13. ✅ AppCore 与 App —— tagHoldsCNameUnderSwiftSpelling、tagHoldsSwiftNameUnderCSpelling、tagRangeIsInUTF16、noNamesNoTags、togglingFlipsStoredSpelling;界面目视交给用户。
  14. +
  15. ✅ 收尾的一部分 —— 五个锁文件钉到 MachOSwiftSection 功能分支的同一提交、命令行插件 skill;取号与 Implemented 留给正式收尾。
  16. +
+
+ +
+

决策日志

+
+ 24 条,最近一条:落地验证,取号 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
日期变更说明
2026-11-24Created as DraftRuntimeViewer 显示 AttributeGraph 的 AGWeakAttribute 时,声明行是 Swift 名,扩展头与成员类型是 C 名;用户要求统一,并在 SourceEditor 里给一个能点击切换的提示。
2026-11-24提示用 Xcode 式的行尾标注用户选了行尾标注,不选胶囊标签:不改接口文本,复制与导出不受影响。
2026-11-24模块未知时写裸名用户选了 AnyWeakAttribute,与声明行完全一致。
2026-11-24切换是全局生成选项用户选了全局:存进设置、所有窗口一起变、面板里有同名开关。
2026-11-24提案放在 MachOSwiftSection照 RuntimeViewer 索引里 cross-repository draft 的做法,由最底层的仓库维护唯一提案。
2026-11-24导入成成员的类型不用描述符的名字实测描述符只存叶子(Key、Name);ABI 名以描述符名字结尾的一律不信,代价是 NSDecimal → Decimal 也退回 C 名。
2026-11-24C 名模式等于 mangled 拼写不解析模块,避免与同名 Swift 结构体混淆。
2026-11-24扩展头一并修扩展头不经解析器,和本提案改的是同一条路径;只改根在 __C 的扩展。
2026-11-24两次点击待用户确认复刻版框架的横幅没有按钮;先按原生两步加右键菜单做,要一次点击就得改 Mx-Iris/SourceEditor。
2026-11-24Accepted用户批准,开始实现。
2026-11-24交互定为两次点击用户确认按 Xcode 原生的两步做(横幅 → 下拉里的按钮,右键菜单也有),不改复刻版框架。
2026-11-24两边都从远端的 feature/swift-type-indexing-package 切远端比两边本地 next 多了验收时的修复;提案随功能分支的第一个提交走。
2026-11-24In Progress第 1–4 步做完。
2026-11-24kind 的分隔符改成 |swift-semantic-string 不允许 kind 里出现控制字符。
2026-11-24C 名模式在标注时才问解析器打印的文字不受影响,C 名模式下的提示仍能写出 SDK 给的 Swift 名。
2026-11-24MSS 测试用现场编译的 fixture三种形状都能精确构造,不随系统版本变;RuntimeViewer 的引擎测试仍用系统的 AttributeGraph。
2026-11-24两条行为测试并入全量与别的测试其余两条在测试进程里无从观察,不写。
2026-11-24行尾标注的外观是我们自己的类别灰色、info.circle.fill、整行 8% 淡灰,交给用户目视验收时再调。
2026-11-24实现完成,待用户看过后收尾相关测试全过;MSS 全量只有读不到本机没有的文件的 36 处,与基线同类;整个 App 编译通过;两个功能分支已在本地合进常驻 next,没推送。
2026-11-24文档判断提案、MSS 的 README 与插件 skill、RV 的命令行插件 skill 已同步;其余不需要改。
2026-11-24提示改成行尾标签用户看过行尾标注后不要这种像报错的横幅,要标签。改为声明行末尾一个与注释标签同样的胶囊,单击即切换,悬停变深、手形指针、工具提示;由 bridge 自己画胶囊与文字层,接口文本、复制与查找都不变,打印器不动。标签写法与位置是我们定的,目视后可调。
2026-11-24收尾用户看过行尾标签,批准收尾。本提案叠在 0105 上,两份一起落地:本仓库的 next 推送;RuntimeViewer 对本仓库的钉从本功能分支改回 branch: "next",锁文件随 0105 一起重解析,提交在 RuntimeViewer 的本地 next,等那里先合进来的别的功能收尾时一起推
2026-11-24文档与术语判断不另写实现说明:可信规则(ABI 名以描述符名字结尾的不信)与「导入成成员的类型不改名」写进本仓库术语表的新条目「C-imported type name spelling(C 导入类型名拼写)」,指回本提案的详细设计;「可信的描述符名字」并入这一条,不单列。RuntimeViewer 的术语表登记同名条目,讲全局开关与行尾标签
2026-11-24落地验证,取号与 0105 同一次验证:钉改回发布版本后的本仓库 next,在 Ultra 上构建并跑两份提案相关的测试(5 个测试目标共 90 条,含 CImportedTypeNameSpelling),构建与测试的退出码都是 0。状态改为 Implemented,编号 0106,演进账本 §152
+
+
+
+
+ +
+
+ + diff --git a/Documentations/Evolutions/0106-c-imported-type-name-spelling.md b/Documentations/Evolutions/0106-c-imported-type-name-spelling.md new file mode 100644 index 000000000..4e013733e --- /dev/null +++ b/Documentations/Evolutions/0106-c-imported-type-name-spelling.md @@ -0,0 +1,546 @@ +# 0106 - C 导入类型的名字统一成 Swift 名,并能切换回 C 名 + +- **状态**: Implemented +- **作者**: JH +- **创建日期**: 2026-11-24 +- **最后更新**: 2026-11-24 +- **所属愿景**: 无 +- **关联提案**: [0105 swift-type-indexing-package](0105-swift-type-indexing-package.md)(`__C` 类型名按 SDK 解析,本提案叠在它上面);RuntimeViewer 的 0064(注释结构由打印器标出、引擎分离后随 interface 下发,本提案照这条路传名字) +- **实现分支 / PR**: 两个仓库都是 `feature/c-imported-type-name-spelling`(worktree `.worktrees/MachOSwiftSection-CImportedTypeNameSpelling`、`.worktrees/RuntimeViewer-CImportedTypeNameSpelling`),叠在 `feature/swift-type-indexing-package` 上 +- **配套文档**: 无单独文章;可信规则与「导入成成员的类型不改名」记在术语表的 [C-imported type name spelling](../Glossary.md) 条目,细节在本提案「详细设计」 +- **网页版**: 同目录同名的 `.html` +- **涉及仓库**: MachOSwiftSection(本仓库,打印器与 `swift-section`)、RuntimeViewer(生成选项、内容区的行尾标签)。这是跨仓库的唯一提案,RuntimeViewer 的提案索引登记为 cross-repository 0106 + +## 摘要 + +Swift interface 里,从 C 导入、被改了名的类型(`NS_SWIFT_NAME`、typedef、CF 的 `Ref` 去尾)现在**声明行印 Swift 名、其余地方印 C 名**:`struct AnyWeakAttribute { var _details: __C.AGWeakAttribute.__Unnamed_struct__details }`,紧跟着 `extension __C.AGWeakAttribute: Swift.Hashable {}`。原因是声明行取类型描述符里的名字,而引用处取 mangled 名,Swift 给 Clang 声明做 mangling 时一律用 C 名。描述符的导入信息(import info)里两个名字本来都存着,不需要 SDK。 + +本提案让打印器多一个拼写选项 `CImportedTypeNameSpelling`: + +- **默认 `.swiftName`**:声明、成员类型、扩展头全部用 Swift 名。查不到所属模块时写裸名(`extension AnyWeakAttribute: Swift.Hashable {}`),查得到时照旧写成 `模块.Swift名`。 +- **`.cName`**:一律按 mangled 的样子印(声明 `struct AGWeakAttribute`,引用 `__C.AGWeakAttribute`)。 + +同时修掉扩展头不经类型名解析器的问题:SDK 类型的成员已经解析成 `CoreFoundation.CGRect`,扩展头却还是 `__C.CGRect`。 + +RuntimeViewer 把这个选项做成全局生成选项(Generation Options › Imported Type Names: Swift / C)。用 SourceEditor 显示时,改了名的 C 类型在声明行末尾带一个注释标签样式的胶囊(`C name AGWeakAttribute`),单击就切换。胶囊画在文本旁边,不进接口文本。 + +## 动机 + +**现象**(RuntimeViewer 显示 AttributeGraph 的 `AGWeakAttribute`,2026-11-24): + +```swift +struct AnyWeakAttribute { + struct __Unnamed_struct__details { + var identifier: __C.AGAttribute + var seed: Swift.UInt32 + } + var _details: __C.AGWeakAttribute.__Unnamed_struct__details +} + +extension __C.AGWeakAttribute: Swift.Hashable {} +extension __C.AGWeakAttribute: Swift.CustomStringConvertible {} +extension __C.AGWeakAttribute: Swift.Equatable {} +``` + +同一个类型在一屏里有两个名字,扩展头看上去像是给另一个类型加的遵循。`swift-section 0.24.0 interface --show-c-imported-types` 打 AttributeGraph 得到的完全一样,还有 `struct AnyAttribute` 对 `__C.AGAttribute` 这一对(前期调研 1)。 + +**`swift-type-indexing-package` 解决不了这个**:它的改名只在模块解析成功时才生效(前期调研 5),而 AttributeGraph 这样的私有框架在 SDK 里没有模块,`__C.` 照旧。而且就算 SDK 类型解析成功了,扩展头也不经解析器(前期调研 6),`extension __C.CGRect` 与 `CoreFoundation.CGRect` 的成员并排出现。 + +**现在的声明行也会误导**:用 `NS_SWIFT_NAME(NSAttributedString.Key)` 导入成成员的 typedef,描述符里只存叶子名 `Key`(前期调研 3),于是声明行印成 `struct Key`,看不出是 `NSAttributedString.Key`。 + +用户还要能看 C 名:逆向时对照头文件、符号、IDA 里的名字都是 C 名。所以统一之后要能切回去,并且在界面上告诉读者这个类型有另一个名字。 + +## 前期调研 + +1. **复现**:本机(macOS 27.2)`swift-section 0.24.0 interface --uses-system-dyld-shared-cache --cache-image-name AttributeGraph --show-c-imported-types` 打出 `struct AnyAttribute { let rawValue: Swift.UInt32 }`、`struct AnyWeakAttribute { … var _details: __C.AGWeakAttribute.__Unnamed_struct__details }`,以及 `struct WeakAttribute { var base: __C.AGWeakAttribute }`。`dump` 则把声明也印成 `struct __C.AGWeakAttribute`(它按 mangled 身份打印)。 +2. **两套名字从哪来**: + - 声明行:`SwiftDeclarationPrinter+Headers.swift:47/56/73` 把 `descriptor.name(in:)` 交给 `renderUnboundTypeName`(`:118`),最终 `renderLeafName` 写 `TypeDeclaration(kind, bareName)`(`:137-146`)。 + - 引用处(成员类型、扩展头)来自 mangled 名。Swift 对 Clang 声明一律按 Clang 名 mangling(`swift/lib/AST/ASTMangler.cpp` 的 `tryAppendClangName`)。`SymbolicDemangler.cImportedTypeIdentity`(`Sources/Analysis/SwiftInspection/SymbolicDemangler.swift:982`)正是把描述符换算成这个 mangled 身份的反方向映射:名字取 ABI 名,C typedef 改成 `typeAlias`,相关实体(related entity)包一层。 +3. **描述符里存的是什么**:IRGen 的 `computeIdentity`(`swift/lib/IRGen/GenMeta.cpp:1568`)写 `UserFacingName = Type->getName()`,即 Swift 名的**叶子**;Clang 声明的名字不同时,在名字后面追加 `N`(`TypeImportInfo`,`Sources/ABI/MachOSwiftSection/Models/Type/TypeImportInfo.swift`;`abiName` 只在两者不同时存在)。扫描本机 shared cache 全部子文件里「名字\0N\0」的序列: + + | 描述符的名字 | ABI 名 | 份数 | 说明 | + |---|---|---|---| + | `AnyAttribute` | `AGAttribute` | 9 | `NS_SWIFT_NAME` 改名,顶层 | + | `AnyWeakAttribute` | `AGWeakAttribute` | 4 | 同上 | + | `CGColor` | `CGColorRef` | 142 | CF 类型去 `Ref` | + | `Decimal` | `NSDecimal` | 47 | 顶层改名 | + | `Key` | `NSAttributedStringKey` | 158 | 导入成 `NSAttributedString.Key`,**只剩叶子** | + | `Name` | `NSNotificationName` | 68 | 导入成 `NSNotification.Name`,只剩叶子 | + + 结论:对顶层改名,描述符的名字就是 Swift 名;对导入成成员的类型,描述符只给叶子,父类型丢了,而且从描述符本身分不出这两种情况。 +4. **父上下文**:`IRGenModule::getAddrOfParentContextDescriptor`(`swift/lib/IRGen/GenDecl.cpp:885`)对 Clang 导入的名义类型一律挂到 `__C`(`ClangImporterContext`)下,只有真正嵌在 C 结构体里的类型(`__Unnamed_struct__details`)才以结构体为父。这一条同样说明「导入成成员」的父路径不在二进制里。 +5. **现有改名的条件**:`TypeNodePrintable.printType`(`Sources/Output/SwiftPrinting/NodePrintables/TypeNodePrintable.swift:170-262`)只在 `resolvedModuleName(of:siblingIdentifier:)`(`NodePrintable.swift:179`)把 `__C` 解析成真实模块之后,才问 `CImportedNameResolving.swiftName(forCName:category:)` 改标识符。注释写明这样做是为了避免 `__C.CFString` 这种一半 C 一半 Swift 的写法。所以模块查不到时,标识符永远是 C 名。 +6. **扩展头不经解析器**(读代码得出,未实测):`renderExtendedTypeName`(`SwiftDeclarationPrinter+Headers.swift:743`)调用同步的 `ExtensionName.print(usesModuleSelectors:)`(`Sources/Declaration/SwiftDeclaration/Model/Names/ExtensionName.swift:15`),只用 `DemangleOptions` 拼字符串,不碰异步的类型名解析器。调用方有四处:`SwiftDeclarationPrinter.swift:688`、`+ObjCProtocols.swift:168`、`+ObjCImportedDefinitions.swift:101` 与 `:265`。所以即便 `swift-type-indexing` 解析成功,扩展头仍是 `__C.`。 +7. **可用的 API**:`machO.swift.typeContextDescriptors`(`Sources/ABI/MachOSwiftSection/MachOFile+Swift.swift:54`、`MachOImage+Swift.swift:54`)、`isCImportedContextDescriptor(in:)`(`ContextDescriptorProtocol.swift:47`)、`typeImportInfo(in:)`(`TypeContextDescriptorProtocol.swift:70`)、`SymbolicDemangler.demangleContext(for:in:)`(`SymbolicDemangler.swift:342`,产出 mangled 身份节点)。打印器已有按需建一次、之后复用的状态写法(`memoizedRawLayoutBuiltinStorage`,`SwiftDeclarationPrinter.swift:115`)。 +8. **标注区域只有 kind 和内容**:swift-semantic-string 的 `AnnotationRegion`(`Sources/Semantic/AnnotationRegions/AnnotationRegion.swift:37`)没有属性字段。本仓库已有把名字编进 kind 字符串的先例:`AnnotationRegion.Kind.attachedMacroTrackedProperty(_:named:)`(`Sources/Output/SwiftPrinting/AnnotationRegionKind+AttachedMacro.swift`)。 +9. **`swift-section` 的接口参数**:`Sources/Executables/swift-section/Commands/InterfaceCommand.swift`(`--resolve-c-module-names` 在 `:34`)与 `Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift`。插件 skill 在 `AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md`(§8 讲 `--resolve-c-module-names`),两份插件清单都是 `0.27.0`。 +10. **RuntimeViewer 现状**(`next`,含尚未推送的类型索引功能): + - 生成选项存在 `appDefaults.options`,内容区在 `appDefaults.$options` 变化时重新取接口(`RuntimeViewerAppCore/Content/ContentTextViewModel.swift`,`interfaceStream` 的 `combineLatest`);`ViewModel.currentMergedGenerationOptions`(`RuntimeViewerAppCore/Base/ViewModel.swift:51`)与它同样合并内部开关,让缓存键对齐。 + - `SwiftGenerationOptions.resolvesImportedTypeNames`(`RuntimeViewerCore/Interfaces/SwiftGenerationOptions.swift:98`,`@Default(true)`);面板的「Resolve Imported Type Names」在 `GenerationOptionsViewController.swift:64`;面板已有 `.enumOption`(`Member Sort Order` 就是),枚举写法照 `SwiftGenerationOptions.MemberSortOrder`。 + - 注释结构与宏展开都是「打印器标区域 → 引擎 `separatingAnnotationRegions()` → `RuntimeObjectInterface` 带一个可选字段」(`commentStructure`、`macroExpansions`,`RuntimeObjectInterface.swift:22/33`;`RuntimeObjectInterface+AnnotationRegions.swift`)。 + - `RuntimeSwiftSection.updateConfiguration(for:)`(`RuntimeSwiftSection.swift:1900`)在 `resolvesImportedTypeNames` 开着时请求类型索引,配置有变化就清掉接口缓存。 + - Bridge 是一个 Objective-C 协议 `SourceEditorBridging`(`RuntimeViewerSourceEditorBridge/SourceEditorBridging.swift`),点击回调走 `SourceEditorBridgingNavigationDelegate`;行内展开(`showInlineExpansion`)是「随 interface 传数据、由 bridge 放进编辑器」的先例。Bridge 从未用过行尾标注。 + - 命令行插件 skill `AgentPlugins/runtime-viewer/skills/runtime-viewer-cli/SKILL.md:165-172` 讲了 `__C.` 名的解析;插件版本 `1.4.0` 是类型索引功能抬的,还没发布。 +11. **复刻版 SourceEditor 的行尾标注**(`Mx-Iris/SourceEditor` tag `27.2.0-alpha.2`,RuntimeViewer 钉的版本): + - 公开入口 `SourceEditorView.insertLineAnnotation(_:)`、`removeAllLineAnnotations()`、`lineAnnotations`(`SourceEditor/macOS/SourceEditorView.swift:967-989`);`SourceEditorLineAnnotation.init(category:message:lineIdentifier:…:revealAction:…)`(`SourceEditor/Annotations/LineAnnotations/SourceEditorLineAnnotation.swift:134`);`SourceEditorLineAnnotationCategory`(同文件 `:7`);动作 `SourceEditorLineAnnotation.Action`(`SourceEditorLineAnnotationAction.swift`,`DisplayStyle` 有 `inline` / `lineItem` / `dropdown`)。 + - **横幅本身不带按钮**:点横幅时 `SourceEditorLineAnnotationManager.handleLeftMouseUpEvent`(`SourceEditorLineAnnotationManager.swift:960-977`)弹出 Xcode 那种下拉框,动作按钮在下拉框里;右键横幅弹出的菜单里只有 `revealAction` 这一项(`SourceEditorLineAnnotationView.swift:788-800`)。`SourceEditorLineAnnotationInteractionDelegate`(`SourceEditorLineAnnotationDropdownPresentation.swift:39`)没有「点了横幅」的回调。所以「点一下就切换」要么走两步(点横幅、再点下拉里的按钮),要么用右键菜单,要么去改复刻版框架。 +12. **RuntimeViewer 的注释标签怎么画、能不能接点击**(验收时用户要求把行尾标注改成标签后查的): + - 注释标签(`Field offset 0x0` 那种胶囊)由 bridge 的 `CommentDecorationController` 画:胶囊是 `CAShapeLayer`,放在内容视图的 `underlayLayer` 里,位置取自「选中这几列时会画的矩形」(`SourceEditorContentView.selectionRects(for:coalesceInteriorRects:includeLineSpacing:)`),每次布局在 `LayoutVisualization.didLayoutInContentView` 里重摆;胶囊里的字是编辑器自己画的源码文字,只改了颜色。所以标签离不开文本里的一段注释,行尾没有文字可画。 + - 鼠标:复刻版 `SourceEditorView` 把按下、抬起、移动、移出都先交给事件消费者(`SourceEditorView+EventHandling.swift`),移动来自它自己的跟踪区域(`SourceEditorView.swift:285`,`mouseMoved`、`inVisibleRect`、窗口为 key 时);消费者返回 `true` 就不再进选区跟踪。折叠三角就是这样接的点击。 + - 指针:`addCursorRectOverrideProvider(_:)` 的提供者在编辑器的 I 形光标之后追加光标矩形(`SourceEditorView.resetCursorRects`)。 + - 工具提示:复刻版自己只在 gutter 用,做法是悬停时改视图的 `toolTip`(`SourceEditorGutter.swift:501`)。 + - 行信息:`SourceEditorDataSource.positionFromInternalCharOffset(_:lineHint:)`、`lineContentLengthForLine(_:)`、`lineCount` 都是公开的。 + +## 提议方案 + +### MachOSwiftSection + +1. **拼写选项**:`SwiftDeclarationPrintConfiguration.cImportedTypeNameSpelling: CImportedTypeNameSpelling`,默认 `.swiftName`。 +2. **本镜像的名字表**:打印器第一次需要时,从本镜像所有 C 导入的类型描述符建一张表,以 mangled 身份为键、描述符的名字为值,**只收可信的条目**: + - 有 ABI 名,且与描述符的名字不同; + - 不是相关实体(`__C_Synthesized` 里的错误码结构体之类); + - ABI 名**不以**描述符的名字结尾——导入成成员的类型(`NSAttributedStringKey` → `Key`)都长这样,描述符给的只是叶子,宁可不改名。代价是 `NSDecimal` → `Decimal` 这类顶层改名也被挡掉(前期调研 3),它们照旧印 C 名,有 SDK 时由类型索引补上。 +3. **`.swiftName` 下一个 `__C` 引用怎么印**(按顺序取第一个成立的): + 1. 注册了的解析器把模块解析出来了 → 照旧写成 `模块.Swift拼写`(`swift-type-indexing-package` 的路径,不变); + 2. 名字表里有它 → **只写 Swift 名,不写模块**(`AnyWeakAttribute`,用户定的); + 3. 都没有 → 照旧 `__C.ABI名`。 + + 嵌在 C 类型里的类型,父类型那一段按同样的规则印(`AnyWeakAttribute.__Unnamed_struct__details`)。 +4. **`.cName`**:引用一律按 mangled 的样子印 `__C.ABI名`,**打印时不问任何解析器**——模块也不解析,因为 `UIKit.UICellConfigurationState` 会和同名的 Swift 结构体混淆,这正是 `swift-type-indexing-package` 起因里的例子。只有打开了标注(第 7 条)时,声明名会去问解析器要标注里那个 Swift 名,打印出来的文字不变。 +5. **声明行与引用走同一套规则**:C 导入类型的声明名,在 `.cName` 下是 ABI 名;在 `.swiftName` 下依次取解析器给的 Swift 拼写(可以带点号,`struct NSAttributedString.Key`)、名字表里的名字、ABI 名。不可信的条目因此从 `struct Key` 变成 `struct NSAttributedStringKey`。 +6. **扩展头改走异步的类型打印路径**:只改扩展类型根在 `__C` / `__C_Synthesized` 的扩展,用打印器同一套解析与拼写印出名字,仍包成同一种 `TypeDeclaration`。其余扩展一个字节都不变。 +7. **标注**:`SwiftDeclarationPrintConfiguration.marksCImportedTypeNames`(默认关)打开时,两种拼写不同的 C 导入类型的声明名外面包一个 `AnnotationRegion`,kind 里带着两个名字。文本不变,分离之后与不标注时逐字节相同。 +8. **`swift-section interface --c-imported-type-name-spelling swift-name|c-name`**,默认 `swift-name`。 + +### RuntimeViewer + +1. **生成选项**:`SwiftGenerationOptions.cImportedTypeNameSpelling`(`@Default(.swiftName)`,旧设置读出来是 Swift 名)。Generation Options 面板的 Swift 一组加一行 `Imported Type Names: Swift | C`。它与「Resolve Imported Type Names」各管各的:后者决定要不要用 SDK 解析模块,在 C 名模式下不起作用,也不再为它建类型索引。 +2. **内部标注开关**:`GenerationOptions.marksCImportedTypeNames`,不出现在面板里,存下来的值永远是默认的 false。内容区只在 SourceEditor 可用时把它打开,`currentMergedGenerationOptions` 照同样的规则合并。 +3. **接口带回名字**:`RuntimeObjectInterface.cImportedTypeNames: [RuntimeInterfaceCImportedTypeName]?`,每条是声明名在文本里的 UTF-8 范围和两个名字。从分离出的标注区域里取,与宏展开在同一处;注释结构不认这种 kind。 +4. **行尾标签**:bridge 新增 `showLineEndTags(_:)` 与一个代理回调。内容区每次 `setSource` 之后,给每个改了名的声明在行尾放一个标签,样子与注释标签一样(胶囊、标签字体与配色),写着文本没印的那个名字: + - Swift 名模式:`C name AGWeakAttribute`,提示 `Show C Names`; + - C 名模式:`Swift name AnyWeakAttribute`,提示 `Show Swift Names`。 + + 单击标签就切换:翻转全局的生成选项,所有内容区一起重新取接口。标签画在文本旁边,不进接口文本,复制、查找、导出都不受影响。 +5. **其余出口跟着选项走**:MCP、App 充当 host 时的命令行、导出读的都是 `appDefaults.options`,与其他生成选项一样;独立运行的命令行 host 用默认的 Swift 名。Find 语料始终用 Swift 名打印。 + +### 交互:单击行尾标签 + +最初按用户批准的 Xcode 原生两步做了行尾标注(点横幅弹下拉框,按钮在下拉框里)。用户看过之后不要这种像报错的横幅,改成标签:声明行末尾一个与注释标签同样的胶囊,单击即切换。悬停时胶囊变深、指针变成手形、显示工具提示(`Show C Names` / `Show Swift Names`)。注释标签离不开文本里的一段注释(前期调研 12),所以行尾标签由 bridge 自己画胶囊和文字,不往接口文本里加东西。不改 `Mx-Iris/SourceEditor`。 + +### 非目标 + +- **不推断导入成成员的类型的父路径**:描述符只给叶子(`Key`),没有 SDK 就保持 C 名,不按前缀去猜 `NSAttributedString.Key`。 +- **相关实体不改**:`__C_Synthesized` 里的类型(`CKError` 之类)照旧打印。 +- **只在声明行放提示**:引用处(`var base: AnyWeakAttribute`)不放,一屏里可能有几十个引用,提示会太吵。 +- **侧栏、路径栏、Find 结果里的对象名不跟着切换**:它们来自索引,不重新打印。Find 语料始终是 Swift 名,搜 C 名搜不到改了名的引用。 +- **`dump`、`diff`、`snapshot` 的键不变**:ABI diff 按 mangled 身份对比(`Sources/Output/SwiftDiffing/Keying.swift`),只有 `diff --interface` 的渲染会跟着新的默认拼写变。 +- **NSTextView 显示路径与 iOS 版不放提示**:两处都没有行尾标签;iOS 版也没有生成选项界面,只能用默认的 Swift 名。 +- **命令行工具不加对应参数**:它读 App 的生成选项,独立 host 用默认值。 + +## 改动地图 + +| 仓库 · 文件 / 类型 | 动作 | 改什么 | 为什么 | 步骤 | +|---|---|---|---|---| +| MSS · `Sources/Output/SwiftPrinting/CImportedTypeNameSpelling.swift` · `CImportedTypeNameSpelling` | 新增 | `.swiftName` / `.cName` 两种拼写 | 拼写选项的类型 | 1 | +| MSS · `Sources/Output/SwiftPrinting/SwiftDeclarationPrintConfiguration.swift` | 修改 | 加 `cImportedTypeNameSpelling`(默认 `.swiftName`)与 `marksCImportedTypeNames`(默认 false) | 打印配置 | 1 | +| MSS · `Sources/Output/SwiftPrinting/CImportedTypeSwiftNameTable.swift` · `CImportedTypeSwiftNameTable` | 新增 | 从 `typeContextDescriptors` 建「mangled 身份 → 描述符名字」的表,`trustsUserFacingName(_:importInfo:)` 是可信规则 | 描述符里现成的 Swift 名 | 1 | +| MSS · `Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift` | 修改 | 按需建一次名字表并复用(照 `memoizedRawLayoutBuiltinStorage`);回答节点打印器对名字表的查询;扩展头调用改成 `await` | 打印器持有名字表 | 1、2 | +| MSS · `Sources/Output/SwiftPrinting/NodePrintables/TypeNodePrintable.swift` · `printType(_:)` | 修改 | `__C` 引用按方案第 3、4 条的规则印 | 统一引用处的拼写 | 2 | +| MSS · `Sources/Output/SwiftPrinting/NodePrintables/NodePrintable.swift` · `resolvedModuleName(of:siblingIdentifier:)` | 修改 | `.cName` 下不问解析器 | C 名模式等于 mangled 拼写 | 2 | +| MSS · 节点打印器的 delegate 协议(与 `swiftName(forCName:category:)` 同处) | 修改 | 加一个内部查询:按 mangled 身份取名字表里的 Swift 名 | 名字表不是可注册的解析器,是打印器自带的 | 2 | +| MSS · `Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift` · `renderTypeDeclarationHeader`、`renderExtendedTypeName` | 修改 | 声明名按同一套规则取;标注开着时包区域;扩展头根在 `__C` 时走异步类型打印 | 声明、扩展与成员一致 | 2、3 | +| MSS · `SwiftDeclarationPrinter.swift:688`、`+ObjCProtocols.swift:168`、`+ObjCImportedDefinitions.swift:101/265` | 修改 | 调用 `await renderExtendedTypeName` | 签名变成 async | 2 | +| MSS · `Sources/Output/SwiftPrinting/AnnotationRegionKind+CImportedTypeName.swift` | 新增 | `CImportedTypeNames`(两个名字)、`AnnotationRegion.Kind.cImportedTypeName(_:)` 与解析回来的 `cImportedTypeNames` | 把两个名字交给宿主 | 3 | +| MSS · `Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift`、`Sources/Executables/swift-section/Commands/InterfaceCommand.swift` | 修改 | `--c-imported-type-name-spelling swift-name\|c-name` | 命令行能切回 C 名 | 3 | +| MSS · `Tests/SwiftInterfaceTests/CImportedTypeNameSpellingTests.swift` | 新增 | 第 1–3 步的行为 | 回归 | 1–3 | +| MSS · 受新默认拼写影响的快照 / baseline 测试 | 修改 | 只更新改了名的 C 类型那几行 | 默认输出变了 | 2 | +| MSS · `README.md` 的 swift-section 一节、`AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md`(§4 参数表、§8、§9)、两份插件清单 | 修改 | 新参数与新默认拼写;插件版本 `0.27.0` → `0.28.0` | 文档与插件随代码 | 3 | +| MSS · `Documentations/Evolutions/README.md` | 修改 | 登记本草案 | 索引 | 0 | +| RV · `RuntimeViewerCore/Sources/RuntimeViewerCore/Interfaces/SwiftGenerationOptions.swift` | 修改 | `CImportedTypeNameSpelling` 枚举与 `cImportedTypeNameSpelling`(`@Default(.swiftName)`) | 用户选项 | 4 | +| RV · `…/Interfaces/RuntimeObjectInterface+GenerationOptions.swift` | 修改 | `marksCImportedTypeNames`(`@Default(false)`) | 只有内容区要提示 | 4 | +| RV · `…/Interfaces/SwiftDeclarationPrintConfiguration+GenerationOptions.swift` | 修改 | 把拼写映射进打印配置;**不**进 `applySwitches(of:)`,Find 语料保持 Swift 名 | 显示跟着选项,语料不跟 | 4 | +| RV · `…/Interfaces/RuntimeInterfaceCImportedTypeName.swift` | 新增 | 声明名的 UTF-8 范围与两个名字 | 接口带回提示所需的数据 | 4 | +| RV · `…/Interfaces/RuntimeObjectInterface.swift`、`RuntimeObjectInterface+AnnotationRegions.swift`、`RuntimeInterfaceCommentStructure+AnnotationRegions.swift` | 修改 | 加可选字段 `cImportedTypeNames`;分离时取出;注释结构忽略这种 kind | 照宏展开的路 | 4 | +| RV · `…/Sections/Swift/RuntimeSwiftSection.swift` · `updateConfiguration` | 修改 | 设 `marksCImportedTypeNames`;`.cName` 下不请求类型索引 | C 名用不到索引 | 4 | +| RV · `RuntimeViewerUsingAppKit/RuntimeViewerSourceEditorBridge/SourceEditorBridging.swift` | 修改 | `SourceEditorBridgingLineEndTag`、`showLineEndTags(_:)`、代理的 `sourceEditorBridge(_:didClickLineEndTagWithIdentifier:)` | bridge 接口 | 5 | +| RV · `…/RuntimeViewerSourceEditorBridge/LineEndTagController.swift` · `LineEndTagController` | 新增 | 在行尾画胶囊与文字层;悬停变深、工具提示;单击回调;手形光标矩形 | 画行尾标签、接点击 | 5 | +| RV · `…/RuntimeViewerSourceEditorBridge/SourceEditorBridge.swift` | 修改 | 注册控制器;`setSource` 换数据源前清掉标签;标签外观同时交给两个控制器 | 接上控制器 | 5 | +| RV · `…/RuntimeViewerSourceEditorBridge/CommentDecorationController.swift` · `TagAppearance` | 修改 | 多存注释字体;按样式取字色的方法;`cgColor(_:in:)` 改成模块内可见 | 行尾标签与注释标签共用外观 | 5 | +| RV · `RuntimeViewerUsingAppKit/RuntimeViewerSourceEditorBridgeTests/LineEndTagTests.swift` | 新增 | 第 5 步的行为(`CommentDecorationTests` 的 `CursorRectRecorder` 改成测试目标内可见) | 回归 | 5 | +| RV · `RuntimeViewerPackages/Sources/RuntimeViewerAppCore/Content/ContentInterface.swift` | 修改 | 加标签的值(UTF-16 范围、标签名、另一个名字、工具提示),按当前拼写生成文字 | AppCore 描述、AppUI / App 只画 | 6 | +| RV · `…/RuntimeViewerAppCore/Content/ContentTextViewModel.swift` | 修改 | 合并 `marksCImportedTypeNames`;新输入 `cImportedTypeNameSpellingToggled`,翻转 `appDefaults.options` 里的拼写 | 切换即改全局选项 | 6 | +| RV · `…/RuntimeViewerAppCore/Base/ViewModel.swift` · `currentMergedGenerationOptions` | 修改 | 同样合并 `marksCImportedTypeNames` | 缓存键与内容区对齐 | 6 | +| RV · `RuntimeViewerUsingAppKit/RuntimeViewerUsingAppKit/Content/ContentSourceEditorViewController.swift` | 修改 | `setSource` 之后 `showLineEndTags`;代理回调进 relay | 接上 ViewModel | 6 | +| RV · `RuntimeViewerUsingAppKit/RuntimeViewerUsingAppKit/Generation Options/GenerationOptionsViewController.swift` | 修改 | `.enumOption(title: "Imported Type Names", labels: ["Swift", "C"], …)` | 面板入口 | 6 | +| RV · `RuntimeViewerCore/Tests/…`、`RuntimeViewerPackages/Tests/RuntimeViewerAppCoreTests/…` | 新增 | 第 4、6 步的行为 | 回归 | 4、6 | +| RV · `AgentPlugins/runtime-viewer/skills/runtime-viewer-cli/SKILL.md`、两份插件清单 | 修改 | 「Imported types」一段补上描述符的 Swift 名与 C 名选项;`1.4.0` 已发布就抬到 `1.4.1`,没发布就留在 `1.4.0` | 输出变了 | 7 | +| RV · `RuntimeViewerCore/Package.swift` 与锁文件 | 修改 | 抬 MSS 的 pin | 取上游的改动 | 7 | +| RV · `Documentations/Evolutions/README.md` | 修改 | cross-repository draft 一行 | 索引 | 0 | + +## 架构图 + +**改了什么**: + +```text +MachOSwiftSection + Sources/Output/SwiftPrinting/ ++ CImportedTypeNameSpelling .swiftName (default) | .cName ++ CImportedTypeSwiftNameTable mangled identity -> descriptor's Swift name (trusted entries only) ++ AnnotationRegion.Kind.cImportedTypeName(_:) carries both names when marking is on +~ SwiftDeclarationPrintConfiguration + cImportedTypeNameSpelling, + marksCImportedTypeNames +~ SwiftDeclarationPrinter + memoized name table (machO.swift.typeContextDescriptors) +~ TypeNodePrintable.printType spelling rules for __C references +~ NodePrintable.resolvedModuleName .cName asks no resolver +~ +Headers.renderTypeDeclarationHeader declared name by the same rules; region when marked +~ +Headers.renderExtendedTypeName async; C-imported extended types through the type printer + Sources/Executables/swift-section/ +~ interface --c-imported-type-name-spelling swift-name|c-name + +RuntimeViewer + RuntimeViewerCore/Interfaces/ +~ SwiftGenerationOptions + cImportedTypeNameSpelling (@Default .swiftName) +~ GenerationOptions + marksCImportedTypeNames (internal, stored false) ++ RuntimeInterfaceCImportedTypeName declared name's UTF-8 range + both names +~ RuntimeObjectInterface + cImportedTypeNames + RuntimeViewerSourceEditorBridge/ ++ SourceEditorBridgingLineEndTag ++ LineEndTagController capsule + text layer past the line's end; hover, click, pointing hand +~ SourceEditorBridging + showLineEndTags(_:) +~ SourceEditorBridgingNavigationDelegate + didClickLineEndTagWithIdentifier +~ CommentDecorationController.TagAppearance + commentFont, shared with the line-end tags + RuntimeViewerAppCore/Content/ +~ ContentInterface, ContentTextViewModel + tags, + spelling toggle input + RuntimeViewerUsingAppKit/ +~ ContentSourceEditorViewController line-end tags, toggle relay +~ GenerationOptionsViewController + "Imported Type Names: Swift | C" +``` + +**一个 `__C` 引用怎么印**: + +```text +printType(reference rooted in __C) +├─ spelling == .cName -> "__C." + ABI name (no resolver asked) +└─ spelling == .swiftName + ├─ a resolver resolves the module -> Module + Swift spelling (existing path) + ├─ name table has a trusted entry -> bare Swift name AnyWeakAttribute + └─ otherwise -> "__C." + ABI name __C.NSAttributedStringKey + +declared name of a C-imported descriptor +├─ .cName -> ABI name AGWeakAttribute +└─ .swiftName -> resolver's spelling ?? trusted name ?? ABI name +``` + +**单击行尾标签之后**: + +```text +click the tag "C name AGWeakAttribute" after `struct AnyWeakAttribute {` + -> SourceEditorView.mouseDown -> event consumers + -> LineEndTagController.handleMouseEvent consumes the click + -> navigationDelegate.sourceEditorBridge(_:didClickLineEndTagWithIdentifier:) + -> ContentSourceEditorViewController: cImportedTypeNameSpellingToggledRelay + -> ContentTextViewModel: appDefaults.options.swiftInterfaceOptions.cImportedTypeNameSpelling = .cName + -> appDefaults.$options: every content pane refetches + -> RuntimeEngine.interface(for:options:) (service process) + -> RuntimeSwiftSection.updateConfiguration printer config changed: cache cleared + -> SwiftDeclarationPrinter prints with .cName, marks declared names + -> separatingAnnotationRegions() -> RuntimeObjectInterface.cImportedTypeNames + -> ContentSourceEditorViewController.setSource + showLineEndTags + struct AGWeakAttribute { (Swift name AnyWeakAttribute) +``` + +## 详细设计 + +### MachOSwiftSection 的公开 API + +```swift +/// How a print spells the types a mangling places in the Clang importer's modules (`__C`, +/// `__C_Synthesized`): imported C structs, enums, typedefs, CF types and Objective-C classes. +public enum CImportedTypeNameSpelling: String, Sendable, Hashable, CaseIterable { + /// The name Swift code uses. A type whose module a registered resolver finds prints under + /// it (`CoreFoundation.CGRect`); a type the image's own descriptors rename prints under that + /// name alone (`AnyWeakAttribute`); any other keeps its mangled spelling (`__C.AGFoo`). + case swiftName + /// The C declaration's own name, exactly as the mangling spells it: `__C.AGWeakAttribute` + /// in a reference, `AGWeakAttribute` on its declaration. No resolver is asked. + case cName +} + +public struct SwiftDeclarationPrintConfiguration { + // … + /// How imported C and Objective-C type names are spelled. `.swiftName` by default. + public var cImportedTypeNameSpelling: CImportedTypeNameSpelling = .swiftName + + /// Marks the declared name of every C-imported type whose two spellings differ with a + /// `cImportedTypeName` annotation region carrying both. Off by default; separating the + /// regions gives exactly the print with it off. + public var marksCImportedTypeNames: Bool = false +} + +/// The two names of a C-imported type: what Swift code calls it and what its C declaration is called. +public struct CImportedTypeNames: Sendable, Hashable { + /// `AnyWeakAttribute`; dotted when a resolver spells a type imported as a member + /// (`NSAttributedString.Key`). + public let swiftName: String + /// `AGWeakAttribute`. + public let cName: String + + public init(swiftName: String, cName: String) +} + +extension AnnotationRegion.Kind { + /// The declared name of a C-imported type whose Swift and C names differ, marked when + /// `SwiftDeclarationPrintConfiguration.marksCImportedTypeNames` is on. The region's text is the + /// spelling printed; the kind carries both. Not a comment. + public static func cImportedTypeName(_ names: CImportedTypeNames) -> Self + + /// The names a `cImportedTypeName` kind carries; nil for any other kind. + public var cImportedTypeNames: CImportedTypeNames? { get } +} +``` + +kind 的编码是 `"cImportedTypeName|" + swiftName + "|" + cName`。`|` 不会出现在 Swift 或 C 的名字里,点号可以照常出现在 Swift 名里。解析只认这个前缀,并且要求恰好三段、两个名字都不为空。原先设计用 U+001F,实现时发现 swift-semantic-string 拒绝 kind 里的任何控制字符(它自己的标记就是控制字符,`AnnotationTag.validate`),改成了 `|`。 + +### 名字表(模块内部) + +```swift +/// The Swift names the image's own C-imported type descriptors give, keyed by the identity a +/// mangling spells — `SymbolicDemangler.demangleContext(for:in:)` of the descriptor. +struct CImportedTypeSwiftNameTable: Sendable { + static let empty = Self(entries: [:]) + + init(typeContextDescriptors: [TypeContextDescriptorWrapper], in context: some ReadingContext) + + /// The trusted Swift name of the C-imported type `identity` names, or nil. + func swiftName(forIdentity identity: Node) -> String? + + /// Whether a descriptor's user-facing name is the type's whole Swift name. A type imported as + /// a member (`NS_SWIFT_NAME(NSAttributedString.Key)`) keeps only its leaf (`Key`) in the + /// descriptor, and its ABI name ends with that leaf; such a name is not trusted. + static func trustsUserFacingName(_ userFacingName: String, importInfo: TypeImportInfo) -> Bool { + guard let abiName = importInfo.abiName, abiName != userFacingName, !importInfo.isRelatedEntity else { return false } + return !abiName.hasSuffix(userFacingName) + } +} +``` + +- 键是 mangled 身份节点的**结构**(照 `ExtensionName` 的结构化 `Hashable`),所以 C typedef 的 `typeAlias` 种类、嵌套 C 类型的父路径都对得上。 +- 只遍历 `isCImportedContextDescriptor(in:) == true` 的描述符,读名字和 `typeImportInfo(in:)`,不建声明模型。表放在打印器里,第一次打印 `__C` 引用或 C 导入声明时才建;打印配置怎么变都不重建,因为表只取决于镜像。 +- 读描述符出错的条目直接跳过(表少一条只会退回 C 名),不报 degradation。 + +### 打印规则的落点 + +- `printType(_:)`:`contextNode.kind == .module` 且模块是 `__C` / `__C_Synthesized` 时: + - `.cName`:写原模块名与标识符,不调 `resolvedModuleName` 的解析分支,也不问 `swiftName(forCName:category:)`。 + - `.swiftName`:先走现有路径;模块没解析出来、但名字表对整个 `name` 节点有答案时,**不写模块与分隔符**,把 Swift 名写成标识符(语义仍是这个类型的 `printIdentifier` 上下文,RuntimeViewer 的跳转不受影响)。 + - 嵌套类型的父段经 `printName(contextNode, asPrefixContext:)` 递归回到 `printType`,自然套用同一规则。 +- `printModuleSelector(ofNestedType:)`:父段是改了名的裸名时,不写模块选择器(与第 2 条的「不写模块」一致)。 +- `renderTypeDeclarationHeader`:描述符是 C 导入的(`isCImportedContextDescriptor`)时,按方案第 5 条算出名字,替换现在的 `descriptor.name(in:)`。解析器那一路用描述符的 ABI 名去问:`moduleName(forTypeName:)` 加 `swiftName(forCName:category:)`,分类取 `CImportedTypeNameCategory(nodeKind:)`,与引用处的查询相同,所以声明与引用必然一致。`displayParentName == true`(`dump` 风格)那条路不变。 +- `renderExtendedTypeName` 改成 `async`:`extensionName.node` 根在 `__C` / `__C_Synthesized` 时,打印走 `typeDemangleResolver.resolve(for:)`,再 `.replacingTypeNameOrOtherToTypeDeclaration()`(`renderUnboundTypeName` 现成的写法);位置命名的局部类型那条分支与其余扩展保持原样。 + +### RuntimeViewer 的类型 + +```swift +extension SwiftGenerationOptions { + public enum CImportedTypeNameSpelling: String, Codable, Sendable, Equatable, Hashable, CaseIterable { + case swiftName + case cName + } +} + +// SwiftGenerationOptions +/// How imported C and Objective-C types are spelled: under their Swift name (`AnyWeakAttribute`, +/// `UIKit.UITraitCollection`), or as the binary mangles them (`__C.AGWeakAttribute`). With `.cName`, +/// `resolvesImportedTypeNames` does nothing. Swift names in settings saved before it existed. +@Default(CImportedTypeNameSpelling.swiftName) +public var cImportedTypeNameSpelling: CImportedTypeNameSpelling + +// RuntimeObjectInterface.GenerationOptions +/// Asks the Swift printer to mark the declared names of renamed C-imported types, which the +/// interface then carries as `cImportedTypeNames`. Only the content pane sets it, and only where +/// SourceEditor runs; stored values are always the default. +@Default(false) +public var marksCImportedTypeNames: Bool + +/// A declared C-imported type whose Swift and C names differ. +public struct RuntimeInterfaceCImportedTypeName: Codable, Sendable, Hashable { + /// Where the declared name is in the interface's text, in UTF-8 offsets, as the comment + /// structure counts them. + public let nameUTF8Range: Range + public let swiftName: String + public let cName: String +} + +// RuntimeObjectInterface +/// The renamed C-imported types this interface declares, when the request marked them; nil +/// otherwise, and from a peer built before them. +public let cImportedTypeNames: [RuntimeInterfaceCImportedTypeName]? +``` + +线上兼容:旧版对端不认这两个选项,按自己的 MachOSwiftSection 打印,不带 `cImportedTypeNames`,内容区就没有提示;新版对端收到旧版请求时取默认值。 + +### Bridge + +```swift +/// A tag a space past the end of a line that the reader can click, drawn as a comment tag is: a +/// capsule in a note's fill holding a label in a note's label colour and a value after it, in the +/// comment font. A class, because `SourceEditorBridging` is an Objective-C protocol. +@objc(RuntimeViewerSourceEditorBridgingLineEndTag) +public final class SourceEditorBridgingLineEndTag: NSObject { + /// A UTF-16 range into the current source; the tag sits after the end of the line its start lies on. + public let characterRange: NSRange + public let label: String // "C name" + public let value: String // "AGWeakAttribute" + public let valueStyle: SourceEditorBridgingCommentRunStyle // .type + public let toolTip: String? // "Show C Names" + public let identifier: String + + public init(characterRange: NSRange, label: String, value: String, + valueStyle: SourceEditorBridgingCommentRunStyle, toolTip: String?, identifier: String) +} + +// SourceEditorBridging +/// Replaces the line-end tags shown on the current source. `setSource` removes them all, so call +/// this after it, with ranges of that source. Nothing is added to the text. +func showLineEndTags(_ tags: [SourceEditorBridgingLineEndTag]) + +// SourceEditorBridgingNavigationDelegate +/// The line-end tag shown under `identifier` was clicked. +func sourceEditorBridge(_ bridge: SourceEditorBridging, didClickLineEndTagWithIdentifier identifier: String) +``` + +- `LineEndTagController` 是一个布局可视化(`LayoutVisualization`)、事件消费者(优先级 `.high`,与注释标签相同)和光标矩形提供者,在 bridge 的 `init` 里注册一次(前期调研 12)。 +- **画法**:每次布局(以及 `show` 时),对每个标签取「选中整行时会画的矩形」里最后一行最右的那个,胶囊左边离它一个空格宽,高度与注释标签一样(文字高减上下各 1 点,行被抬高时按注释字体的文字高)。胶囊是 `CAShapeLayer`,文字是 `CATextLayer`(CoreText 属性:注释字体,标签取 note 的标签色,名字取类型色),都放在 `underlayLayer`,外观用注释标签的那一份(`TagAppearance`,多存了注释字体)。被折叠进上一行的行不画。 +- **鼠标**:左键按下(不带 ⌘、⌃)落在胶囊里就回调、吃掉这次点击,连同之后的抬起;移动时更新悬停的标签:胶囊填充的不透明度翻倍,内容视图的 `toolTip` 换成标签的提示(照 gutter 的做法),移出时还原。 +- **指针**:每个胶囊上一个手形光标矩形;胶囊位置变了或滚动时让编辑器重算光标矩形(照注释标签的三角)。 +- `setSource` 在换数据源之前清掉标签:标签记的是旧文本的行号。 +- 不用复刻版的行尾标注(`SourceEditorLineAnnotation`):横幅像报错、动作要两步,用户看过后否掉了(决策日志)。 + +### AppCore 与 App + +- `ContentInterface` 加 `cImportedTypeNameTags: [ContentTextViewModel.CImportedTypeNameTag]`,每条是 UTF-16 范围、标签名、另一个名字和工具提示,由 `ContentTextViewModel.cImportedTypeNameTags(of:)` 按取接口时的拼写生成(`FetchedInterface` 带着 `cImportedTypeNames` 与 `cImportedTypeNameSpelling`): + - `.swiftName`:`C name` + ``,提示 `Show C Names`; + - `.cName`:`Swift name` + ``,提示 `Show Swift Names`。 + + 文字放在 AppCore,因为它是「描述值」(RuntimeViewerPackages 的 `Sources/AGENTS.md`)。 +- 内部标注开关照 `marksAttachedMacros` 的写法:`Settings.Editor.showsCImportedTypeNameTags`(SourceEditor 可用即为真),`ContentTextViewModel` 取接口时与 `currentMergedGenerationOptions` 都合并进去。 +- `ContentTextViewModel.Input` 加 `cImportedTypeNameSpellingToggled: Signal`(`@Init(default: .empty())`,NSTextView 与 iOS 的调用点不用改),在主线程把 `appDefaults.options.swiftInterfaceOptions.cImportedTypeNameSpelling` 换成另一个值。之后所有内容区都经 `appDefaults.$options` 重新取接口,不需要单独通知。 +- `ContentSourceEditorViewController`:每次 `setSource` 之后 `bridge.showLineEndTags(...)`(名字用 `.type` 的颜色),identifier 用标签的序号;代理回调直接 `accept` 到 relay(不管是哪一个,都是同一个全局切换)。 +- 面板:`.enumOption(title: "Imported Type Names", labels: ["Swift", "C"], keyPath: \.swiftInterfaceOptions.cImportedTypeNameSpelling)`,放在「Resolve Imported Type Names」上面。 + +## 替代方案考量 + +- **模块未知时写 `__C.AnyWeakAttribute`**:保留「C 导入、模块未知」的信号,但与声明行 `struct AnyWeakAttribute` 仍不一致,而且是打印器以前特意避开的半翻译写法(前期调研 5)。用户选了裸名。 +- **按 C 名统一(声明行也印 `AGWeakAttribute`)作为默认**:与 mangled 一致,但读的是 Swift interface,Swift 名更贴合。C 名作为可切换的另一种拼写保留。 +- **按前缀推断成员导入的父类型**(`NSAttributedStringKey` → `NSAttributedString.Key`):二进制里没有父路径(前期调研 3、4),按前缀切分会把 `NSDecimal` 切成 `NS.Decimal` 这种错误结果。`swift-type-indexing-package` 已经否定过只靠二进制推断改名。 +- **提示做成打印器输出的一段注释,再按注释标签画**:标签的字要来自文本(前期调研 12),所以得让打印器多印一段注释,复制、查找与导出都会带上它,NSTextView 路径还会显示成普通注释。改由 bridge 在行尾自己画胶囊和文字,文本不变。 +- **复刻版的行尾标注**(最初的实现):横幅像报错,切换要先点横幅、再点下拉框里的按钮。用户看过后改成单击的行尾标签。 +- **只切换当前编辑栏**:要在 ViewModel 里另存一份不进设置的状态,接口缓存键也要多一维;用户选了全局生成选项。 +- **把拼写和 `resolvesImportedTypeNames` 合成一个三档枚举**:类型索引功能还在验收、设置项已经写好,合并就要改它的设置与测试;两个开关各管各的更简单,C 名模式下后者不起作用即可。 + +## 影响 + +### 源码兼容性(source compatibility) + +- **纯新增**:`CImportedTypeNameSpelling`、`CImportedTypeNames`、两个配置属性、`AnnotationRegion.Kind.cImportedTypeName(_:)` / `cImportedTypeNames`。 +- `renderExtendedTypeName` 是 `package`,改成 `async` 只影响本包的四个调用点。 +- **输出有变化**(不是编译期破坏):默认拼写下,改了名的 C 类型的引用与扩展头变成 Swift 名;不可信条目的声明行从叶子名变成 C 名(`struct Key` → `struct NSAttributedStringKey`、`struct Decimal` → `struct NSDecimal`);SDK 类型的扩展头在注册了解析器时变成 `模块.名字`。依赖输出文本的下游测试要更新期望值;要旧的 C 名可以设 `.cName`,但声明行会变成 C 名,与以前的「声明 Swift、引用 C」不完全相同——那种混合正是要去掉的。 + +### ABI 兼容性(条件项) + +不适用 —— 本库以 SPM 源码分发,使用方每次重新编译。 + +### 下游影响 + +- **本仓库**:`SwiftInterface`(`SwiftInterfaceBuilder` 用同一个打印器)、`SwiftDiffing` 的 `--interface` 渲染、`swift-section interface` 的默认输出跟着变;ABI diff 的键不变。 +- **MachOKitUI、SymbolViewer**:经打印器显示 Swift interface,输出变化同上,不需要改代码。 +- **RuntimeViewer**(本提案的另一半): + - **用户可见**:用 SourceEditor 显示时,改了名的 C 类型的声明行末尾多一个注释标签样式的胶囊,写着另一个名字,单击即切换;Generation Options 多一行 `Imported Type Names`;默认接口里这些类型统一成 Swift 名;MCP、App 充当 host 时的命令行与导出跟着选项;Find 结果始终是 Swift 名。 + - **可发现性**:提示默认就在(只要 SourceEditor 可用),面板里有同名开关;不加首次引导。 + - **数据与配置兼容**:`appDefaults.options` 里没有这个键时取 `.swiftName`;`marksCImportedTypeNames` 存下来永远是 false。不需要迁移。 + - **平台**:提示只在 macOS 的 SourceEditor 路径;NSTextView 路径与 iOS 版只有默认的 Swift 名。 + - **发布**:不涉及权限、entitlement、公证与 Sparkle。 + - **派生数据**:Find 语料的打印变了,但代码变化本身会改变产出者身份(`Documentations/DerivedData.md`),旧语料自然失效,不必改 variant。 +- **顺序约束**:两边都叠在 `swift-type-indexing-package` 上(它的改动还在两个仓库的本地 `next` 上、没推送)。本提案要等它先收尾,或者在它的功能分支之上开分支,落地时再变基。 + +### 文档与示例 + +- 本仓库 `README.md` 的 swift-section 一节与 `AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md`:§4 参数表加 `--c-imported-type-name-spelling`;§8 说明默认的 Swift 名不依赖 `--resolve-c-module-names`;§9「看起来像 bug 其实不是」加一条:导入成成员的类型没有 SDK 时保持 C 名。两份插件清单抬到 `0.28.0`。 +- RuntimeViewer 的命令行插件 skill(「Imported types print under their module and Swift name」那一段)补上描述符的 Swift 名与 C 名选项。 +- 术语:落地时判断要不要在两边的术语表登记「C 导入类型名拼写」。 + +## API 演进与废弃策略 + +- 没有被替代的旧 API,不需要废弃期。 +- 默认输出变化按 minor 版本发布,在 release note 里写明「C 导入类型默认按 Swift 名打印,要旧的 C 名请设 `.cName` / `--c-imported-type-name-spelling c-name`」。 +- `CImportedTypeNameSpelling` 用 enum:只有两种拼写,调用方需要穷举(RuntimeViewer 的映射、命令行参数)。以后真要加第三种,就是一次有意的源码破坏,到时再评估。 + +## 落地步骤 + +已完成的步骤标 ✅。测试名是实际写成的;MachOSwiftSection 的测试在 `Tests/SwiftInterfaceTests/CImportedTypeNameSpellingTests.swift`,用测试里现场编译的桥接头 fixture(`swift_name` 改名的结构体与 `swift_wrapper` typedef、匿名嵌套结构体、导入成成员的 `ProbeOwner.Key`),照 `CImportedTypeConformanceInterfaceTests` 的做法,不依赖系统镜像。 + +0. ✅ **登记草案** —— 两边的提案索引;提案随两个功能分支的第一个提交走。 +1. ✅ **名字表与可信规则** —— MSS 的 `CImportedTypeNameSpelling.swift`、配置两个属性、`CImportedTypeSwiftNameTable.swift`、打印器按需建表 + - 行为:`trustsUserFacingNameWhenABINameDiffers`(`AnyWeakAttribute` / `AGWeakAttribute`、`AnyAttribute` / `AGAttribute`、`CGColor` / `CGColorRef`、`__UIPointerShape` / `UIPointerShape`) + - 行为:`refusesLeafNameOfTypeImportedAsMember`(`Key` / `NSAttributedStringKey`、`Name` / `NSNotificationName`、`Decimal` / `NSDecimal`) + - 行为:`refusesRelatedEntityName`、`refusesNameWithoutABIName` + - 行为:`nameTableReadsTheFixturesDescriptors`(fixture 的 `AnyFooThing`、`AnyFooIdentifier` 各对一条,`Key` 与匿名结构体没有) +2. ✅ **打印规则** —— MSS 的 `printType`、`resolvedModuleName`、delegate 查询、声明头、扩展头与四个调用点 + - 行为:`swiftSpellingPrintsBareSwiftNameWhenModuleIsUnknown`(`var _details: AnyFooThing.__Unnamed_struct__details`、`extension AnyFooThing: … Swift.Equatable`,全文不出现 C 名) + - 行为:`untrustedDeclaredNamePrintsCName`(`struct ProbeOwnerKey`,没有 `struct Key`) + - 行为:`swiftSpellingKeepsModuleThatResolverFinds`(替身解析器:找到模块、没给 Swift 名时取描述符的名字 `ProbeModule.AnyFooThing`;给了 `ProbeOwner.Key` 时声明 `struct ProbeOwner.Key`、引用与扩展头 `ProbeModule.ProbeOwner.Key`) + - 行为:`extensionHeaderSpellsLikeMemberTypes` + - 行为:`cSpellingPrintsMangledNamesAndAsksNoResolver`(声明 `struct AGFooThing`、扩展 `extension __C.AGFooThing`,替身解析器被问 0 次) + - 原计划的 `nonCImportedExtensionHeadersAreByteIdentical` 与 `abiDiffKeysAreUnchanged` 不单独写:两者由 MachOSwiftSection 的全量测试覆盖(快照与 diff 测试照旧通过),见决策日志。 +3. ✅ **标注与命令行** —— MSS 的 `AnnotationRegionKind+CImportedTypeName.swift`、声明头包区域、`InterfaceRequest` 与 `InterfaceCommand`、README 与插件 skill(插件 `0.28.0`) + - 行为:`markedDeclaredNameCarriesBothSpellings`(分离后的文本与不标注时逐字节相同) + - 行为:`markedCSpellingCarriesTheSameNames` + - 行为:`sameSpellingsAreNotMarked` + - 行为:`regionKindRoundTripsDottedSwiftName` + - 行为:`interfaceCImportedTypeNameSpelling`(`SwiftSectionCommandTests`:默认 `swift-name`,`c-name` 映射到 `.cName`,拒绝 `cName` 这种拼法) + - MSS 功能分支已推送;RuntimeViewer 临时按分支钉(`RuntimeViewerCore/Package.swift` 的 TEMPORARY 注释)。 +4. ✅ **RuntimeViewer Core** —— 两个选项、`RuntimeInterfaceCImportedTypeName`、接口字段、分离、`updateConfiguration`、打印配置映射 + - 行为(`CImportedTypeNameSpellingEngineTests`,对系统的 AttributeGraph):`spellingDefaultsToSwiftNameInOlderPayload`、`spellingRawValuesAreStable`、`corpusPrintsSwiftNamesWhateverTheSpelling`、`swiftSpellingIsUniform`、`cSpellingIsUniform`、`interfaceCarriesCImportedTypeNamesWhenMarked`、`commentStructureIgnoresCImportedTypeNameRegions` + - 行为(`SwiftSectionPrinterConfigurationTests`):`changedSpellingReconfiguresOnce`(打印器只重配一次,接口缓存随之清掉) + - 原计划的 `cNameSpellingRequestsNoTypeIndex` 不写:测试进程不打开类型索引(`RuntimeTypeNames.enableInThisProcess()` 只在服务进程调用),无从观察,代码是 `updateConfiguration(for:)` 里一行条件。`marksCImportedTypeNamesIsNeverStoredTrue` 改由第 6 步的 `togglingFlipsStoredSpelling` 一并断言。 +5. ✅ **Bridge 的行尾标签** —— `SourceEditorBridging.swift`、`LineEndTagController.swift`、`SourceEditorBridge.swift`、`CommentDecorationController.swift`、`LineEndTagTests.swift`(最初做成行尾标注,验收时改掉,见决策日志) + - 行为:`tagSitsPastTheEndOfTheLineItsRangeStartsOn`、`tagAddsNothingToTheText`、`showingAgainReplaces`、`setSourceRemovesTags`、`clickingNotifiesDelegateWithIdentifier`、`tagTakesThePointingHand`、`hoveringDarkensTagAndShowsToolTip` +6. ✅ **AppCore 与 App** —— `ContentInterface`、`ContentTextViewModel`、`ViewModel.currentMergedGenerationOptions`、`ContentSourceEditorViewController`、面板 + - 行为(`CImportedTypeNameTagTests`):`tagHoldsCNameUnderSwiftSpelling`、`tagHoldsSwiftNameUnderCSpelling`、`tagRangeIsInUTF16`、`noNamesNoTags`、`togglingFlipsStoredSpelling` + - 原计划的 `mergedOptionsMarkCImportedTypeNamesWhereSourceEditorRuns` 不写:取决于 `SourceEditorFrameworks.availability`,包级测试里框架不在,写出来只是重复实现。 + - 编完用 SourceEditor 打开 AttributeGraph 的 `AnyWeakAttribute`,人工看一次标签与切换(交给用户目视)。 +7. ✅ **收尾** —— RuntimeViewer 插件 skill(版本 `1.4.0` 是类型索引功能抬的、还没发布,不再抬)、抬 MSS pin、重解析五个锁文件、两边索引与本提案状态 + +**收尾时必须判断两件事**(判断结果写进决策日志,不允许沉默跳过): + +- **要不要配套专题文章** —— 可信规则与「为什么导入成成员的类型不改名」是下次维护最容易踩的,倾向写进 `Documentations/Internal/` 的一篇实现说明,或并入现有的类型名解析说明。 +- **有没有引入新术语** —— 「C 导入类型名拼写」「可信的描述符名字」是否登记术语表。 + +## 决策日志 + +| 日期 | 变更 | 说明 | +|------|------|------| +| 2026-11-24 | Created as Draft | RuntimeViewer 显示 AttributeGraph 的 `AGWeakAttribute` 时,声明行是 Swift 名,扩展头与成员类型是 C 名;用户要求统一,并在 SourceEditor 里给一个能点击切换 Swift 名 / C 名的提示。 | +| 2026-11-24 | 提示用 Xcode 式的行尾标注 | 用户在「行尾标注」和「类型名后的胶囊标签」之间选了前者:不改接口文本,复制与导出不受影响。 | +| 2026-11-24 | 模块未知时写裸名 | 用户选了 `AnyWeakAttribute`,不选 `__C.AnyWeakAttribute`:与声明行完全一致。 | +| 2026-11-24 | 切换是全局生成选项 | 用户选了全局:存进设置、所有窗口一起变、面板里有同名开关,不做只管当前编辑栏的临时状态。 | +| 2026-11-24 | 提案放在 MachOSwiftSection | 照 RuntimeViewer 索引里两篇 cross-repository draft 的做法,跨仓库的唯一提案由最底层的仓库维护。 | +| 2026-11-24 | 导入成成员的类型不用描述符的名字 | 实测 shared cache:`NSAttributedStringKey` 的描述符只存 `Key`、`NSNotificationName` 只存 `Name`,二进制里没有父路径;ABI 名以描述符名字结尾的一律不信,代价是 `NSDecimal` → `Decimal` 这类也退回 C 名。 | +| 2026-11-24 | C 名模式等于 mangled 拼写 | 不解析模块:`UIKit.UICellConfigurationState` 会与同名 Swift 结构体混淆。 | +| 2026-11-24 | 扩展头一并修 | 扩展头不经解析器(读代码得出),和本提案改的是同一条路径;只改根在 `__C` 的扩展,其余逐字节不变。 | +| 2026-11-24 | 两次点击待用户确认 | 复刻版框架的横幅没有按钮,点横幅弹下拉框、按钮在下拉框里;先按原生两步加右键菜单做,要一次点击就得改 `Mx-Iris/SourceEditor`。 | +| 2026-11-24 | Accepted | 用户批准,开始实现。 | +| 2026-11-24 | 交互定为两次点击 | 用户确认按 Xcode 原生的两步做(横幅 → 下拉里的按钮,右键菜单也有),不改复刻版框架。 | +| 2026-11-24 | 两边都从远端的 `feature/swift-type-indexing-package` 切 | 远端比两边本地 `next` 多了验收时的修复(宏的配色、文档);提案随功能分支的第一个提交走,因为两边本地 `next` 都有未推送的合并,不往 `next` 上单独提交提案。 | +| 2026-11-24 | In Progress | 第 1–4 步做完:MachOSwiftSection 的打印器、命令行与文档,RuntimeViewer Core。 | +| 2026-11-24 | kind 的分隔符改成 `\|` | 原设计的 U+001F 被 swift-semantic-string 拒绝:它不允许 kind 里出现任何控制字符(`AnnotationTag.validate`),它自己的标记就是控制字符。 | +| 2026-11-24 | C 名模式在标注时才问解析器 | C 名模式的声明名原先也去问解析器(为了标注里的 Swift 名),`cSpellingPrintsMangledNamesAndAsksNoResolver` 抓到了。改为只在 `marksCImportedTypeNames` 打开时问,打印的文字不受影响,RuntimeViewer 在 C 名模式下的提示仍能写出 SDK 给的 Swift 名。 | +| 2026-11-24 | MSS 测试用现场编译的 fixture | 原计划读系统 shared cache 的 AttributeGraph 与 SwiftUICore;改用 `CImportedTypeConformanceInterfaceTests` 那种测试里现场编译的桥接头 dylib,三种形状(顶层改名、`swift_wrapper` typedef 改名、导入成成员)都能精确构造,也不随系统版本变。RuntimeViewer Core 的引擎测试仍用系统的 AttributeGraph,那是报告的现场。 | +| 2026-11-24 | 两条行为测试并入全量与别的测试 | `nonCImportedExtensionHeadersAreByteIdentical`、`abiDiffKeysAreUnchanged` 由 MachOSwiftSection 全量测试覆盖;`marksCImportedTypeNamesIsNeverStoredTrue` 并入 `togglingFlipsStoredSpelling`;`cNameSpellingRequestsNoTypeIndex` 与 `mergedOptionsMarkCImportedTypeNamesWhereSourceEditorRuns` 在测试进程里无从观察(类型索引只在服务进程打开,SourceEditor 框架只在 App 里),不写。 | +| 2026-11-24 | 行尾标注的外观是我们自己的类别 | Xcode 的 issue 与 note 类别在 IDESourceEditor 里,不在复刻范围;取灰色、`info.circle.fill`、整行 8% 的淡灰,交给用户目视验收时再调。 | +| 2026-11-24 | 实现完成,待用户看过后收尾 | 验证(都在 Ultra):MachOSwiftSection 相关测试 43 条全过;全量 22 个目标中只有 `IntegrationTests` 报 36 处,全是读不到本机没有的文件(`Xcode-26.3.0.app`、iOS 18.5 模拟器运行时),与基线同类。RuntimeViewer Core 相关 55 条、AppCore 14 条全过;整个 App 经 Tuist 工作区编译通过;bridge 测试 78 条中 `LineAnnotation` 5 条全过,失败的是两条既有的滚动条测试,外加一条高负载下偶发的 `SymbolOccurrence`(单独重跑两次都过)。五个锁文件把 MachOSwiftSection 钉到 `feature/c-imported-type-name-spelling` 的同一提交。两个功能分支已在本地合进各自的常驻 `next`,没推送。 | +| 2026-11-24 | 文档判断 | 已同步:本提案、MachOSwiftSection 的 README 与 swift-section 插件 skill(插件 `0.28.0`)、RuntimeViewer 的命令行插件 skill。RuntimeViewer 的 `AGENTS.md` 与使用指南没有讲到这两个开关的地方,不需要改。配套实现说明与术语登记留给正式收尾时判断。 | +| 2026-11-24 | 提示改成行尾标签 | 用户看过行尾标注后不要这种像报错的横幅,要标签。改为声明行末尾一个与注释标签同样的胶囊(`C name AGWeakAttribute` / `Swift name AnyWeakAttribute`),单击即切换,悬停变深、手形指针、工具提示。注释标签的字来自文本,行尾没有文字,所以由 bridge 自己画胶囊与文字层,接口文本、复制与查找都不变;打印器与 `marksCImportedTypeNames` 不动。标签写法(`C name`、放在行尾而不是紧跟类型名)是我们定的,用户目视后可调。 | +| 2026-11-24 | 收尾 | 用户看过行尾标签,批准收尾。本提案叠在 [0105](0105-swift-type-indexing-package.md) 上,两份一起落地:本仓库的 `next` 推送;RuntimeViewer 对本仓库的钉从本功能分支改回 `branch: "next"`,锁文件随 0105 一起重解析,提交在 RuntimeViewer 的本地 `next`,等那里先合进来的别的功能收尾时一起推 | +| 2026-11-24 | 文档与术语判断 | 不另写实现说明:可信规则(ABI 名以描述符名字结尾的不信)与「导入成成员的类型不改名」写进本仓库术语表的新条目「C-imported type name spelling(C 导入类型名拼写)」,指回本提案的详细设计;「可信的描述符名字」并入这一条,不单列。RuntimeViewer 的术语表登记同名条目,讲全局开关与行尾标签 | +| 2026-11-24 | 落地验证,取号 | 与 [0105](0105-swift-type-indexing-package.md) 同一次验证:钉改回发布版本后的本仓库 `next`,在 Ultra 上构建并跑两份提案相关的测试(5 个测试目标共 90 条,含 `CImportedTypeNameSpelling`),构建与测试的退出码都是 0。状态改为 Implemented,编号 0106,演进账本 §152 | diff --git a/Documentations/Evolutions/0107-moved-swift-type-modules.html b/Documentations/Evolutions/0107-moved-swift-type-modules.html new file mode 100644 index 000000000..50ab0ddab --- /dev/null +++ b/Documentations/Evolutions/0107-moved-swift-type-modules.html @@ -0,0 +1,505 @@ + + + + + + +0107 - 被 SDK 搬过家的 Swift 类型,按现在声明它的模块打印 + + + + +
+ +
+

MachOSwiftSectionEvolutions0107

+

0107 被 SDK 搬过家的 Swift 类型,按现在声明它的模块打印

+
+
状态
Implemented
+
最后更新
2026-11-25
+
项目类型
库(跨仓库:swift-type-indexing + MachOSwiftSection)
+
原文
0107-moved-swift-type-modules.md
+
+
+ +
+ +
+ +
+

摘要

+

Apple 把一些 Swift 类型从一个模块搬进另一个模块时,会给声明加上 @_originallyDefinedIn(module: "旧模块", 平台 版本)。这个属性让 mangled name 和运行时元数据继续使用旧模块名,老二进制不用重编,所以二进制里只能读到旧名字:CGFloat 现在由 CoreFoundation 声明,mangling 却还是 $s12CoreGraphics7CGFloatV;macOS 15 起 SwiftUI 的约 370 个类型搬进了 SwiftUICore,mangling 还是 7SwiftUI。swift-section interface 因此印出 CoreGraphics.CGFloat、SwiftUI.View,而 SDK 的 .swiftinterface 写的是 CoreFoundation::CGFloat(CoreGraphics 的接口)、SwiftUICore.View(SwiftUI 的接口,2182 处)。

+
    +
  • swift-type-indexing 在 TypeDatabase 第一次 index 时顺带扫描 SDK 里所有模块的文本 .swiftinterface,把每个顶层类型声明上的 @_originallyDefinedIn 记成「旧模块 + 类型名 → 现在声明它的模块,以及各平台的搬家版本」,新增查询 declaringModuleName(ofMovedTypeNamed:originallyDefinedIn:builtAgainst:)。扫描只读文本,不用 sourcekitd。
  • +
  • MachOSwiftSection 的打印器多一个解析器角色 MovedTypeModuleResolving。注册了它,原生 Swift 类型的模块名就先问它,嵌套类型跟随最外层类型。swift-section interface 新增开关 --resolve-moved-type-modules,默认关闭。
  • +
+

是否改写按二进制自己的 SDK 版本判断(LC_BUILD_VERSION 的 sdk):用 macOS 14 SDK 编出的 SwiftUI 镜像,View 那时还在 SwiftUI 里,照旧印 SwiftUI.View。

+
+ +
+

要你定

+
+

没有待定的事

+

已落地:swift-type-indexing 0.2.0 已发版,本库的版本下限已抬到 from: "0.2.0",实现合进 next。

+
+
+

已定(用户批准)

+
    +
  • 开关做成独立的 --resolve-moved-type-modules,默认关闭。
  • +
  • 按二进制的 LC_BUILD_VERSION sdk 判断,不看 minos。
  • +
  • dump、diff、snapshot、evolution 不改。
  • +
  • TypeDatabaseTypeNameResolver 不变,RuntimeViewer 升级后输出不变。
  • +
+
+
+ +
+

架构图

+
    +
  • 新增
  • +
  • 修改
  • +
  • 不变
  • +
+
+ + + swift-type-indexing + TypeDatabase (actor) + MovedTypeIndexscans every SDK module's .swiftinterface text + declaringModuleName(ofMovedTypeNamed:…)public query, gated by the image's SDK version + SDKPlatforminterface file suffix, Catalyst / visionOS fallback + moduleName(forTypeName:) · swiftName(forCName:…)__C only, unchanged + + + MachOSwiftSection + SwiftPrinting + MovedTypeModuleResolving + resolvedModuleName(of:…) + SwiftDeclarationPrinterregistry: movedTypeModuleResolvers + printModuleSelector(ofNestedType:)key: outermost type; extension headers too + + SwiftTypeNameResolution + TypeDatabaseMovedTypeModuleResolvertypeDatabase + sdkVersion + SwiftInterfaceBuilderTypeNameProviderresolutions: [.cImportedModules, .movedTypeModules] + TypeDatabaseTypeNameResolverunchanged (RuntimeViewer) + + SwiftSectionKit · swift-section + --resolve-moved-type-modulesswift-section interface + InterfaceRequestresolvesMovedTypeModules + + + + + + + +
+

打印器在 resolvedModuleName 处问新角色;provider 持有适配器,适配器带着镜像的 SDK 版本去查 TypeDatabase。CLI 开关 → 请求 → provider。

+

一次查询的数据流:

+
interface print of `x: CoreGraphics.CGFloat`
+  TypeNodePrintable (context node = module "CoreGraphics", identifier "CGFloat")
+    resolvedModuleName(of: module, siblingIdentifier: "CGFloat")
+      not __C / __ObjC
+      delegate.declaringModuleName(ofMovedTypeNamed: "CGFloat", originallyDefinedIn: "CoreGraphics")
+        SwiftDeclarationPrinter -> first non-nil of movedTypeModuleResolvers
+          SwiftInterfaceBuilderTypeNameProvider
+            TypeDatabaseMovedTypeModuleResolver(sdkVersion: LC_BUILD_VERSION.sdk)
+              TypeDatabase.declaringModuleName(ofMovedTypeNamed:originallyDefinedIn:builtAgainst:)
+                movedTypeDeclarationsByKey[CoreGraphics, CGFloat]
+                  -> declaringModule "CoreFoundation", moved macOS 10.0
+                  sdkVersion >= 10.0 -> "CoreFoundation"
+    writes "CoreFoundation" + "." (or "::")
+
+ +
+

改动地图

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
文件 / 类型动作改什么为什么步骤
swift-type-indexing Sources/TypeIndexing/MovedTypeIndex.swift · MovedTypeIndex、MovedTypeDeclaration、MovedTypeKey新增文本扫描器(纯函数)与表的键值类型搬家记录只在文本接口里1
swift-type-indexing Sources/TypeIndexing/SDKPlatform.swift · SDKPlatform修改内部属性:文本接口的文件名后缀,取哪个平台的搬家版本(含 Catalyst / visionOS 回退到 iOS)挑文件、选版本都按平台1
swift-type-indexing Sources/TypeIndexing/TypeDatabase.swift · TypeDatabase修改discoverSDK() 扫描并登记;新增 declaringModuleName(ofMovedTypeNamed:originallyDefinedIn:builtAgainst:);内部 register(movedTypeDeclarations:)对外唯一入口2
swift-type-indexing Tests/TypeIndexingTests/MovedTypeIndexTests.swift新增扫描器单元测试(手写接口文本)规则可脱离 SDK 验证1
swift-type-indexing Tests/TypeIndexingTests/TypeDatabaseMovedTypeTests.swift新增版本判断与平台回退查询语义2
swift-type-indexing Tests/TypeIndexingTests/SDKIntegrationTests.swift修改加 CGFloat 与 SwiftUI.View 两条,照旧默认关闭对真实 SDK 的核对2
swift-type-indexing TypeIndexingPipeline.md、README.md、Evolutions/README.md修改「搬家记录」一节、查询用法、cross-repository 一行文档同批2
SwiftPrinting/NodePrintables/TypeNameResolving.swift · MovedTypeModuleResolving新增角色协议打印器侧入口3
SwiftPrinting/NodePrintables/NodePrintableDelegate.swift修改加 declaringModuleName(ofMovedTypeNamed:originallyDefinedIn:)节点打印器经委托提问3
SwiftPrinting/SwiftDeclarationPrinter.swift · TypeNameResolverRegistry修改新角色的注册与分发与其他角色同一套机制3
SwiftPrinting/NodePrintables/NodePrintable.swift · resolvedModuleName(of:siblingIdentifier:)修改非 __C 模块问新角色模块名输出的唯一出口3
SwiftPrinting/NodePrintables/TypeNodePrintable.swift · printModuleSelector(ofNestedType:)修改模块节点来自根时,用最外层类型的标识符作键嵌套类型跟随外层(编译器同样如此)3
SwiftPrinting/SwiftDeclarationPrinter+Headers.swift · renderExtendedTypeName(_:)、isMovedTypeReference(_:)修改最外层类型被认作搬家时,扩展头改走类型打印器扩展头原本照 mangling 印,不经模块名出口(实现时发现)3
Tests/SwiftInterfaceTests/MovedTypeModuleTests.swift新增FixtureCompiler 现编引用 CGFloat 的小库,配记录型替身解析器打印器行为不依赖 SDK3
SwiftTypeNameResolution/TypeDatabaseMovedTypeModuleResolver.swift新增包 TypeDatabase + SDK 版本的适配器版本按镜像固定4
SwiftTypeNameResolution/SwiftInterfaceBuilderTypeNameProvider.swift修改顶层选项集合 SDKTypeNameResolutions 与 resolutions: 参数;遵循新角色;只开搬家时不生成模块接口两个开关共用一个数据库4
Tests/SwiftTypeNameResolutionTests/TypeDatabaseMovedTypeModuleResolverTests.swift新增适配器的版本判断适配层契约4
SwiftSectionKit/Swift/InterfaceRequest.swift修改resolvesMovedTypeModules 字段、provider 接线与警告子命令逻辑在请求里5
swift-section/Commands/InterfaceCommand.swift修改--resolve-moved-type-modules 与 makeRequest() 一行CLI 只是外壳5
Tests/SwiftSectionKitTests/…、CommandRequestMappingTests.swift修改请求两侧各一条新开关两侧各一测5
Package.swift修改两个测试目标加依赖;swift-type-indexing 版本下限抬到 0.2.0测试要现编小库;用上新 API4
AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md修改新开关的说明与陷阱CLI 改动同批改 skill5
Modules/SwiftInterface.md、Modules/SwiftSectionKit.md、Glossary.md、ProjectEvolutionLog.md、CLAUDE.md修改新角色、新开关、术语 moved type、账本一节文档同批6
+
+
+ +
+

详细设计

+
+ 扫描器:只认第 0 列的属性组与紧跟的类型声明 +
+
struct MovedTypeKey: Hashable, Sendable {
+    let originalModuleName: String
+    let typeName: String
+}
+
+struct MovedTypeDeclaration: Hashable, Sendable {
+    let typeName: String
+    /// The module the mangling names: the part before a `;`.
+    let originalModuleName: String
+    /// The module whose interface declares the type now.
+    let declaringModuleName: String
+    let movedVersionsByPlatformName: [String: OperatingSystemVersion]
+}
+
+enum MovedTypeIndex {
+    static func movedTypeDeclarations(inInterfaceText interfaceText: String, moduleName: String) -> [MovedTypeDeclaration]
+}
+
    +
  • 属性组是连续的、从第 0 列开始的 @ 行;一个属性写多个平台时逐个拆开。
  • +
  • 组后第一行去掉属性与修饰词(public、open、final、indirect、nonisolated),关键字是 struct / class / enum / protocol / actor / typealias 才记,名字到 <、:、空格、=、{ 截止,反引号去掉。
  • +
  • OSX 视同 macOS,*ApplicationExtension 视同基础平台。
  • +
  • module: 有分号取前半段;等于本模块(Swift;CompatibilitySpan)就丢弃。
  • +
  • 接口文件:.swiftmodule 目录下 <架构>-apple-<平台后缀>.swiftinterface,排除 .private / .package,按文件名排序取第一个;没有文本接口的模块跳过,读失败记日志跳过。
  • +
+
+
+
+ 查询与版本判断:按二进制的 SDK 版本 +
+
extension TypeDatabase {
+    public func declaringModuleName(ofMovedTypeNamed typeName: String, originallyDefinedIn originalModuleName: String, builtAgainst sdkVersion: OperatingSystemVersion) -> String?
+}
+
    +
  • 平台条目:macOS → macOS;Catalyst → macCatalyst,没有就 iOS;iOS / 模拟器 → iOS;tvOS、watchOS 同名;visionOS → visionOS,没有就 iOS 并换算(17.x → 1.x,18.x → 2.x,26 起相同,17 以前视为早已搬家);driverKit 同名。
  • +
  • 找不到适用条目:属性在该平台不生效,mangling 本来就是新模块,返回 nil。
  • +
  • sdkVersion 不低于搬家版本才返回新模块;未 index 过返回 nil。
  • +
  • 用 sdk 不用 minos:mangling 与部署目标无关,interface 要还原的是编译所用 SDK 里的写法;系统镜像的 sdk 就是它所属的系统版本。
  • +
+
+

已知偏差

+

属性写的版本不一定是源码真正搬家的时间:CGFloat 写 macOS 10.0,运行时 macOS 13 才搬进 libswiftCoreFoundation。用 macOS 12 SDK 编的二进制也会印 CoreFoundation.CGFloat。这里信属性,不另做修正表。

+
+
+
+
+ 打印器:新角色与嵌套类型的键 +
+
public protocol MovedTypeModuleResolving: TypeNameResolving {
+    func declaringModuleName(ofMovedTypeNamed typeName: String, originallyDefinedIn originalModuleName: String) async -> String?
+}
+
+// resolvedModuleName(of:siblingIdentifier:)
+if moduleName != objcModule, moduleName != cModule,
+   let identifier = siblingIdentifier, !identifier.isEmpty,
+   let delegate,
+   let declaringModuleName = await delegate.declaringModuleName(ofMovedTypeNamed: identifier, originallyDefinedIn: moduleName) {
+    return (declaringModuleName, false)
+}
+
    +
  • 返回的 isResolvedCImportedModule 仍是 false,不触发 C 名改写;与 cImportedTypeNameSpelling 无关。
  • +
  • declaringModuleForModuleSelector 同时带回模块节点的来源:来自根时带回最外层类型的标识符作键;来自 extension 时不查询。
  • +
  • 扩展头:renderExtendedTypeName(_:) 原本对非 C 类型直接照 mangling 印。新增 isMovedTypeReference(_:),最外层类型被解析器认作搬家时改走类型打印器;没搬家的照旧,输出逐字节不变。
  • +
+
+
+
+ 适配层、请求与 CLI +
+
public struct TypeDatabaseMovedTypeModuleResolver: MovedTypeModuleResolving {
+    public let typeDatabase: TypeDatabase
+    public let sdkVersion: OperatingSystemVersion
+    public init(typeDatabase: TypeDatabase, sdkVersion: OperatingSystemVersion)
+}
+
+public struct SDKTypeNameResolutions: OptionSet, Hashable, Sendable {
+    public static let cImportedModules: SDKTypeNameResolutions
+    public static let movedTypeModules: SDKTypeNameResolutions
+}
+
+public init?(machO: MachO, dependencies: SwiftInterfaceBuilderDependencies<MachO>, resolutions: SDKTypeNameResolutions = .cImportedModules, supplementaryAPINotesURLs: [URL] = [])
+
    +
  • MachOKit.Version → OperatingSystemVersion 的转换放在适配层(swift-type-indexing 不依赖 MachOKit)。
  • +
  • 未开 .cImportedModules:两个 C 角色方法返回 nil,setup() 用 moduleFilter: { _ in false } 调一次 index;未开 .movedTypeModules:新角色返回 nil。
  • +
  • InterfaceRequest.resolvesMovedTypeModules: Bool = false;任一开关打开就构造 provider,警告措辞换成实际打开的开关名。
  • +
  • CLI:--resolve-moved-type-modules,帮助文字写明只读 SDK 的 .swiftinterface,需要 Xcode 或 Command Line Tools,不需要 sourcekitd,仅 macOS。
  • +
+
+
+
+ +
+

调研

+
+ 编译器、SDK、现状代码与成本 +
+
    +
  1. 编译器:Attr.h:2486 的 OriginallyDefinedInAttr 存 ManglingModuleName 与 LinkerModuleName("Swift;CompatibilitySpan" 分号前是 mangling 用的模块)。Decl.cpp:1155 的 getAlternateModuleName() 自己没有就沿 DeclContext 往上找,嵌套类型跟随外层。Attr.cpp:2561 的 isActivePlatform 只看平台不看版本。PlatformKindUtils.cpp:131:iOS 条目对 Catalyst 与 visionOS 同样生效。
  2. +
  3. SDK:libswiftCoreFoundation.tbd 的 $ld$previous 显示 CGFloat 在 macOS 10.15–13.0 位于 libswiftCoreGraphics.dylib,属性却写 macOS 10.0。SwiftUICore 的搬家版本有 15.0、15.2、26.0、27.0 等批次;跟在属性后的声明有 266 struct、23 class、33 enum、40 protocol、5 typealias,另有 994 extension、17 func、185 var、16 let。
  4. +
  5. 现状代码:NodePrintable.swift:186 的 resolvedModuleName 只对 __C / __ObjC 提问,三个调用点 NodePrintable.swift:176、TypeNodePrintable.swift:197、TypeNodePrintable.swift:310。InterfaceRequest.swift:224 只在 cModuleNameResolution 打开时挂 provider;dump、diff、snapshot、evolution 不挂解析器。import 行来自 SwiftInterfaceBuilder.swift:357 的 collectModules()。
  6. +
  7. swift-type-indexing(0.1.1):只回答 __C;sourcekitd 一层不留属性,文档说明不读文本接口。SDKIndexer 已列出每个 .swiftmodule 的路径。
  8. +
  9. 成本:macOS 27.2 SDK 有 368 个 .swiftmodule、266 份 arm64e-apple-macos.swiftinterface,grep 扫完用时 0.38 秒;Swift 逐行解析的实测落地时补上。
  10. +
  11. 现在的输出能编过:SE-0491 让 Module::Name 也能找到被该模块重新导出的声明;CoreGraphics 重新导出 CoreFoundation,SwiftUI 的接口第 19 行 @_exported import SwiftUICore。
  12. +
  13. 使用方:RuntimeViewer 经 TypeDatabaseTypeNameResolver(typeDatabase:) 注册(RuntimeTypeIndex.swift:145),本提案不改它。
  14. +
+
+
+
+ +
+

替代方案

+
+ 七条被否的路径 +
+
    +
  • 并进 --resolve-c-module-names:那个开关首次要经 sourcekitd 生成接口(UIKit 冷生成 126 秒),名字也说的是 __C。否,两者都开时共用数据库。
  • +
  • 从 $ld$previous 推导:给的是库路径不是模块名,还要逐符号归并。否。
  • +
  • 经 sourcekitd 接口读属性:只覆盖依赖命中的模块、不留属性,而搬家后的模块常不是直接依赖。否。
  • +
  • 不判断版本:macOS 14 的 SwiftUI 会印出当时不存在的 SwiftUICore。否。
  • +
  • 按定义是否在被打印镜像里判断:SwiftUICore 镜像会被反着判。否。
  • +
  • 打印器协议带版本:版本是镜像的固定属性,构造适配器时给一次即可。否。
  • +
  • 给 TypeDatabaseTypeNameResolver 直接加角色:RuntimeViewer 升级后会悄悄改变输出,且拿不到每个镜像的 SDK 版本。否。
  • +
+
+
+
+ +
+

影响

+
+ 纯新增;swift-type-indexing 要先发 0.2.0 +
+
    +
  • 源码兼容:纯新增。SwiftInterfaceBuilderTypeNameProvider.init 与 InterfaceRequest 加的参数都有保持现状的默认值;NodePrintableDelegate 是内部协议。
  • +
  • ABI:不适用,两个库都以 SPM 源码分发。
  • +
  • 下游:swift-type-indexing 0.1.x → 0.2.0 先发版;RuntimeViewer 与 MachOObjCSection 的 ObjCTypeIndexing 不受影响。
  • +
  • 非目标:dump;diff / snapshot / evolution 与查找键;import 行;声明在搬过家的 extension 里的嵌套类型;函数与变量的搬家;默认开启;RuntimeViewer 接入。
  • +
+
+
+
+ +
+

落地步骤

+
+ 六步:扫描器 → 数据库 → 打印器 → 适配层 → 请求与 CLI → 文档 +
+
    +
  1. 扫描器:structMovedFromAnotherModuleIsRecorded、protocolClassEnumActorAndTypealiasAreRecorded、extensionsFunctionsAndVariablesAreNotRecorded、declarationModifiersAndAttributesBeforeTheKeywordAreSkipped、severalPlatformsInOneAttributeAreSplit、manglingModuleIsThePartBeforeTheSemicolon、moveWithinTheSameModuleIsNotRecorded、indentedAttributesAreIgnored、interfaceFileMatchingThePlatformIsChosen
  2. +
  3. 数据库与查询(之后发 swift-type-indexing 0.2.0):answersTheDeclaringModuleWhenTheSDKIsNotOlderThanTheMove、answersNothingForAnSDKOlderThanTheMove、answersNothingForATypeThatNeverMoved、answersNothingBeforeIndexing、macCatalystFallsBackToTheIOSVersion、visionOSMapsTheIOSVersion、firstDiscoveredModuleWinsATiedKey;SDK 集成(默认关闭)cgFloatMovedFromCoreGraphicsToCoreFoundation、swiftUIViewMovedToSwiftUICoreInMacOS15
  4. +
  5. 打印器:movedTopLevelTypePrintsUnderItsDeclaringModule、nestedTypeFollowsItsOutermostType、moduleSelectorsSpellTheDeclaringModuleOnNestedTypes、extensionHeaderOfAMovedProtocolUsesTheDeclaringModule、cImportedModulesAreNeverAskedAboutMoves、withoutAResolverTheManglingModuleIsKept、importLinesKeepTheManglingModules
  6. +
  7. 适配层:resolverAnswersForTheImagesSDKVersion、providerWithOnlyMovedTypesAnswersNoCImportedQuestion、providerDefaultKeepsTodaysResolutions(providerWithBothResolutionsSharesOneDatabase 未写,见决策日志)
  8. +
  9. 请求与 CLI:interfaceRequestResolvesMovedTypeModulesOnlyWhenAsked、resolveMovedTypeModulesFlagMapsOntoTheRequest、bothResolutionFlagsCombine;核对 skill 点到的开关都还存在
  10. +
  11. 文档与收尾:打宿主 27.2 与 14.6 归档 cache 的 TipKit、DeveloperToolsSupport,前者 SwiftUI.View → SwiftUICore.View、后者照旧;默认关闭时输出逐字节不变,不需要渲染 A/B
  12. +
+
+
+
+ +
+

决策日志

+
+ 14 条,最近一条:swift-type-indexing 0.2.0 发版 +
+
+ + + + + + + + + + + + + + + + + + +
日期变更说明
2026-11-25Created as Draft用户发现 CGFloat 在 SDK 里由 CoreFoundation 声明、二进制里却叫 CoreGraphics,问 swift-type-indexing 能否让输出与 SDK 一致;调研确认能做,用户要求写提案。
2026-11-25方案取舍独立开关、默认关闭;按二进制的 SDK 版本判断是否改写;dump 与 diff 类命令不改;RuntimeViewer 不随升级改变行为。用户确认开关做成独立的 --resolve-moved-type-modules。
2026-11-25Accepted用户批准,开始实现。
2026-11-25第 1–2 步完成(swift-type-indexing)扫描器与查询落地;单元测试 103 个、SDK 集成测试 7 个通过。另认 #if 指令与限定名属性;swift-type-indexing 0.2.0 未发版,本库经本地兄弟依赖构建。
2026-11-25第 3 步:扩展头也要改扩展头原本照 mangling 印(extension CoreGraphics.CGFloat),改为最外层类型被认作搬家时走类型打印器;修复前测试红、修复后绿。
2026-11-25第 4 步:选项集合放顶层嵌套在泛型 provider 里会逼调用方写泛型参数,改为顶层 SDKTypeNameResolutions。
2026-11-25第 4 步:两条测试的取舍共用数据库那条要跑 sourcekitd、写真实缓存,没写;另一条改名为 providerWithOnlyMovedTypesAnswersNoCImportedQuestion。
2026-11-25第 5 步:警告措辞只开搬家时不解析依赖镜像,警告按实际打开的开关写。
2026-11-25第 6 步:真机核对27.2 的 TipKit:SwiftUI.View 全变 SwiftUICore.View(14 处);14.6 的 TipKit 只差 6 行 CGFloat,SwiftUI.View 原样。DeveloperToolsSupport 的 PreviewLayout 改回它自己的模块(14.0 搬家)。插件校验通过。
2026-11-25全量验证Ultra(Xcode 26.6)2969 个测试、560 个套件全过,退出码 0。
2026-11-25收尾判断不另写专题文章;新术语 moved type 已登记。
2026-11-25实现完成,待用户看过后收尾两边功能分支已推送;当时 next 按远端版本下限用 swift-type-indexing 0.1.1,先不合。
2026-11-25swift-type-indexing 0.2.0 发版用户同意发版;Xcode 26.6 测试与 CI 通过后打 tag,本库下限抬到 from: "0.2.0"。
2026-11-25Implemented取号 0107、账本第 153 节;验证沿用全量 2969 个测试与按 0.2.0 重编后的 58 个相关测试;不另写专题文章。本地 next 上还叠着未收尾的 private-cf-type-modules,next 等它收尾时一起推。
+
+
+
+
+ +
+
+ + diff --git a/Documentations/Evolutions/0107-moved-swift-type-modules.md b/Documentations/Evolutions/0107-moved-swift-type-modules.md new file mode 100644 index 000000000..42aea2f65 --- /dev/null +++ b/Documentations/Evolutions/0107-moved-swift-type-modules.md @@ -0,0 +1,417 @@ +# 0107 - 被 SDK 搬过家的 Swift 类型,按现在声明它的模块打印 + +- **状态**: Implemented +- **作者**: JH +- **创建日期**: 2026-11-25 +- **最后更新**: 2026-11-25 +- **所属愿景**: 无 +- **关联提案**: [0105 swift-type-indexing-package](0105-swift-type-indexing-package.md)(`TypeDatabase` 搬进独立包,本提案给它加一类数据);[0106 c-imported-type-name-spelling](0106-c-imported-type-name-spelling.md)(`__C` 类型按 SDK 拼写,本提案把同样的思路推到原生 Swift 类型);[0082 image-group-evolution](0082-image-group-evolution.md)(evolution 把 SwiftUI 与 SwiftUICore 当一组比较,同样源于 `@_originallyDefinedIn`);[0064 module-selectors](0064-module-selectors.md)(`Module::Name` 写法) +- **实现分支 / PR**: 两个仓库都是 `feature/moved-swift-type-modules`;swift-type-indexing 一侧合进 `main` 并发 0.2.0,本仓库一侧合进 `next` +- **配套文档**: 不另写专题文章。调用方契约在 swift-type-indexing 的 `README.md` 与 `Documentations/Internal/TypeIndexingPipeline.md`「搬家记录」一节;打印器一侧在 [Modules/SwiftInterface.md](../Internal/Modules/SwiftInterface.md);术语见 [Glossary.md](../Glossary.md)「moved type」 +- **网页版**: 同目录同名的 `.html` +- **涉及仓库**: swift-type-indexing(从 SDK 读出搬家记录、提供查询)、MachOSwiftSection(本仓库:打印器、`SwiftTypeNameResolution` 适配层、`SwiftSectionKit` 请求、`swift-section interface` 开关)。这是跨仓库的唯一提案,swift-type-indexing 的提案索引登记为 cross-repository MachOSwiftSection 0107 + +## 摘要 + +Apple 把一些 Swift 类型从一个模块搬进另一个模块时,会给声明加上 `@_originallyDefinedIn(module: "旧模块", 平台 版本)`。这个属性让 mangled name 和运行时元数据继续使用旧模块名,老二进制不用重编,所以二进制里只能读到旧名字:`CGFloat` 现在由 CoreFoundation 声明,mangling 却还是 `$s12CoreGraphics7CGFloatV`;macOS 15 起 SwiftUI 的约 370 个类型搬进了 SwiftUICore,mangling 还是 `7SwiftUI`。`swift-section interface` 因此印出 `CoreGraphics.CGFloat`、`SwiftUI.View`,而 SDK 的 `.swiftinterface` 写的是 `CoreFoundation::CGFloat`(CoreGraphics 的接口)、`SwiftUICore.View`(SwiftUI 的接口,2182 处)。 + +本提案做两件事: + +- **swift-type-indexing** 在 `TypeDatabase` 第一次 `index` 时顺带扫描 SDK 里所有模块的文本 `.swiftinterface`,把每个顶层类型声明上的 `@_originallyDefinedIn` 记成「旧模块 + 类型名 → 现在声明它的模块,以及各平台的搬家版本」。新增一个查询 `declaringModuleName(ofMovedTypeNamed:originallyDefinedIn:builtAgainst:)`。扫描只读文本,不用 sourcekitd。 +- **MachOSwiftSection** 的打印器多一个解析器角色 `MovedTypeModuleResolving`。注册了它,原生 Swift 类型的模块名就先问它(`CoreGraphics.CGFloat` → `CoreFoundation.CGFloat`,嵌套类型跟随最外层类型)。`swift-section interface` 新增开关 `--resolve-moved-type-modules`,默认关闭。 + +是否改写按二进制自己的 SDK 版本判断(`LC_BUILD_VERSION` 的 `sdk`):用 macOS 14 SDK 编出的 SwiftUI 镜像,`View` 那时还在 SwiftUI 里,照旧印 `SwiftUI.View`。 + +## 动机 + +**现象**(本机 macOS 27.2,Xcode 27.2 的 MacOSX27.2 SDK): + +- SDK 的 `usr/lib/swift/CoreFoundation.swiftmodule/arm64e-apple-macos.swiftinterface` 第 10–16 行: + + ```swift + @available(macOS 10.0, macCatalyst 13.0, iOS 2.0, watchOS 1.0, tvOS 9.0, *) + @_originallyDefinedIn(module: "CoreGraphics", macOS 10.0) + @_originallyDefinedIn(module: "CoreGraphics", macCatalyst 13.0) + @_originallyDefinedIn(module: "CoreGraphics", iOS 2.0) + @_originallyDefinedIn(module: "CoreGraphics", watchOS 1.0) + @_originallyDefinedIn(module: "CoreGraphics", tvOS 9.0) + @frozen public struct CGFloat : Swift::Sendable { + ``` + + CoreGraphics 自己的接口里引用它时写的是 `CoreFoundation::CGFloat`(例如 `public func CGContextMoveToPoint(_ c: CoreGraphics::CGContext?, _ x: CoreFoundation::CGFloat, _ y: CoreFoundation::CGFloat)`)。 +- 二进制里:运行时 `libswiftCoreFoundation.dylib` 导出 `_$s12CoreGraphics7CGFloatVMn`(类型描述符)与 `_$s12CoreGraphics7CGFloatVN`(类型元数据),模块名仍是 CoreGraphics。 +- 因此任何引用 `CGFloat` 的二进制,`swift-section interface` 都印 `CoreGraphics.CGFloat`;SwiftUI 相关的二进制满屏是 `SwiftUI.View`、`SwiftUI.Text`,而 SDK 和 Xcode 的生成接口写的是 SwiftUICore。 + +用户在对照 SDK 阅读输出时会困惑「这个类型到底声明在哪」。现在的输出能编译过(见前期调研 6),所以问题出在跟 SDK 不一致:它照实反映了 ABI,却和源码对不上。已有的 `--resolve-c-module-names` 只处理 `__C` 类型(前期调研 3),管不到这类原生 Swift 类型。 + +**范围不只 CGFloat**(前期调研 5):macOS 27.2 SDK 里带 `@_originallyDefinedIn` 的模块有 SwiftUICore(旧模块 SwiftUI,约 370 个类型)、RealityFoundation(RealityKit)、CoreFoundation(CoreGraphics)、AVFAudio(AVFoundation)、RelevanceKit(AppIntents)、DeveloperToolsSupport 与 CoreTransferable(SwiftUI)、Foundation(`_System_Foundation`)等。一张表就能把它们全部修好。 + +## 前期调研 + +1. **编译器怎么用这个属性**(`/Volumes/SwiftProjects/swift-project/swift`): + - `include/swift/AST/Attr.h:2486` 的 `OriginallyDefinedInAttr` 存两个模块名:`ManglingModuleName`(mangling 用)与 `LinkerModuleName`(链接指令用)。源码里写成 `"Swift;CompatibilitySpan"` 时,分号前是 mangling 用的模块,分号后是链接用的库。 + - `lib/AST/Decl.cpp:1155` 的 `Decl::getAlternateModuleName()`:声明自己带有在当前平台生效的属性就用它的 `ManglingModuleName`,否则沿 `DeclContext` 往上找,所以**嵌套类型跟随外层类型的旧模块名**。`lib/AST/ASTMangler.cpp:205/970/2642/4484` 都经它取模块名。 + - 生效与否只看平台、**不看版本**:`lib/AST/Attr.cpp:2561` 的 `isActivePlatform` 只调 `isPlatformActive`。所以同一平台上,任何部署目标编出的 mangling 都用旧模块名;版本只影响链接指令(`$ld$previous`)。 + - 平台继承(`lib/AST/PlatformKindUtils.cpp:131`):`iOS` 条目在 Mac Catalyst(`ios-macabi` 三元组也是 iOS)和 visionOS(编译期)上同样生效;`macCatalyst` 条目只对 Catalyst 生效。 +2. **SDK 里的搬家记录**: + - `$ld$previous` 记录了运行时位置的变化:`libswiftCoreFoundation.tbd` 有 `$ld$previous$/usr/lib/swift/libswiftCoreGraphics.dylib$$1$10.15$13.0$_$s12CoreGraphics7CGFloatVMn$`,即部署目标在 macOS 10.15–13.0 之间时,这个符号链接到 `libswiftCoreGraphics.dylib`;Catalyst 是 13.0–16.0。现在的 `libswiftCoreGraphics.tbd` 只重新导出 CoreGraphics.framework。**属性写的是 macOS 10.0,运行时真正搬家是 macOS 13**:属性的版本不一定等于源码搬家的时间,见「已知偏差」。 + - SwiftUICore 的版本分布(`grep -o '^@_originallyDefinedIn(module: "SwiftUI", …)'`):macOS 15.0 共 1442 行,另有 15.2、26.0、27.0 等批次。**同一模块里不同声明的搬家版本不同**,表里必须逐个声明存版本。 + - `@_originallyDefinedIn` 只出现在顶层声明上,并且总是单独占一行、从第 0 列开始。SwiftUICore 里跟在它后面的声明:266 个 struct、23 个 class、33 个 enum、40 个 protocol、5 个 typealias,另有 994 个 extension、17 个 func、185 个 var、16 个 let。 +3. **现状代码怎么走**: + - 打印器只在模块名是 `__C` / `__ObjC` 时才去问解析器:`Sources/Output/SwiftPrinting/NodePrintables/NodePrintable.swift:186` 的 `resolvedModuleName(of:siblingIdentifier:)`。它是全部模块名输出的唯一出口,有三个调用点:`NodePrintable.swift:176`(`printModule`)、`TypeNodePrintable.swift:197`(顶层类型的限定名,`siblingIdentifier` 是该顶层类型的标识符)、`TypeNodePrintable.swift:310`(`printModuleSelector(ofNestedType:)`,嵌套类型自己的模块选择器,`siblingIdentifier` 是嵌套类型自己的标识符)。 + - 嵌套类型的模块选择器取自 `TypeNodePrintable.swift:635` 的 `declaringModuleForModuleSelector`:沿上下文链找到根上的 `module` 节点,或最近一层 `extension` 的模块。 + - 解析器角色协议在 `Sources/Output/SwiftPrinting/NodePrintables/TypeNameResolving.swift`(`ModuleNameResolving`、`CImportedNameResolving`、`OpaqueTypeResolving`,刻意不给默认实现);注册在 `SwiftDeclarationPrinter.swift:240` 的 `addTypeNameResolver(_:)`,按角色分发在 `SwiftDeclarationPrinter.swift:1296` 起的 `NodePrintableDelegate` 实现里。 + - 适配层:`Sources/Output/SwiftTypeNameResolution/TypeDatabaseTypeNameResolver.swift`(无状态,包一个 `TypeDatabase`)与 `SwiftInterfaceBuilderTypeNameProvider.swift`(extra-data provider,`init?` 从 `machO.loadCommands.buildVersionCommand` 取平台,`setup()` 按依赖过滤索引)。 + - `SwiftSectionKit` 的 `InterfaceRequest`(`Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift:224`)只在 `cModuleNameResolution == .enabled` 时挂上 provider;`dump`、`diff`、`snapshot`、`evolution` 都不挂任何类型名解析器。 + - interface 头部的 `import` 行来自符号里出现的 mangling 模块名(`SwiftInterfaceBuilder.swift:357` 的 `collectModules()`),本提案不改它。 +4. **swift-type-indexing 的现状**(`../swift-type-indexing`,0.1.1):`TypeDatabase` 只回答 `__C` 类型的归属(`moduleName(forTypeName:)`)与 C 名 → Swift 名(`swiftName(forCName:category:)`)。模块接口一层经 sourcekitd `editor.open.interface` 生成,`InterfaceDeclarationNode` 只留种类、名字与嵌套,不留属性;`Documentations/Internal/TypeIndexingPipeline.md` 明确说不读文本 `.swiftinterface`,因为它只含 Swift 声明,而那一层要的是 ObjC 导入类型。本提案要的恰好是 Swift 声明。`SDKIndexer.discover` 已经列出每个 `.swiftmodule` 目录(`SwiftModuleDescriptor.path`)。第一次 `index` 在 `discoverSDK()` 里登记 API notes;只要 ObjC 标注的调用方用一个不选任何模块的 `moduleFilter` 调一次 `index`,这个用法已有先例。 +5. **成本**:macOS 27.2 SDK 有 368 个 `.swiftmodule`,`arm64e-apple-macos.swiftinterface` 共 266 份(另有 `arm64e.x1-apple-macos` 12 份、`x86_64` 与 `ios-macabi` 各一套)。`grep -A12 '^@_originallyDefinedIn'` 扫完全部 macOS 份用时 0.38 秒。实现后实测:带上扫描,一次只读 API notes 的 macOS 索引(`moduleFilter` 不选任何模块:发现 SDK、解析 API notes、扫描搬家记录)在公司那台 10 核 Mac Studio 上单独跑约 1.7 秒(`SDKIntegrationTests.cgFloatMovedFromCoreGraphicsToCoreFoundation`,两次 1.67 / 1.73 秒)。 +6. **现在的输出能编过**:SE-0491(模块选择器)第 421 行规定 `Module::Name` 的候选包括「声明在该模块或被该模块重新导出的」声明;点号限定的写法同样会查到重新导出的声明。CoreGraphics 的接口头部有 `@_exported public import CoreFoundation`,SwiftUI 的接口第 19 行有 `@_exported import SwiftUICore`,所以 `CoreGraphics.CGFloat`、`SwiftUI.View` 都合法。本提案改的只是写法与 SDK 是否一致,不是正确性。 +7. **使用方**:RuntimeViewer 按平台共用一个 `TypeDatabase`,经 `TypeDatabaseTypeNameResolver(typeDatabase:)` 注册(`RuntimeViewerCore/Sources/RuntimeViewerCore/TypeNames/RuntimeTypeIndex.swift:145`)。本提案不改这个类型的行为,RuntimeViewer 的输出不会因为升级而悄悄改变。 + +## 提议方案 + +### swift-type-indexing + +1. 新增内部类型 `MovedTypeIndex`:输入一份 `.swiftinterface` 的文本和它所属的模块名,逐行扫描第 0 列的属性组。遇到 `@_originallyDefinedIn(module: "<名>", <平台> <版本>)` 就收集;属性组之后的第一行声明是 `struct` / `class` / `enum` / `protocol` / `actor` / `typealias`(前面可以有 `public`、`final`、`@frozen` 之类的修饰)时,记一条 `MovedTypeDeclaration`(类型名、mangling 旧模块、按平台的搬家版本)。是 extension、func、var 之类的就丢掉这组属性。模块名有分号时取分号前的部分;取出来等于本模块(例如 `Swift;CompatibilitySpan` 在 Swift 模块里)就不记。 +2. `TypeDatabase.discoverSDK()` 在登记 API notes 之后,对发现的每个模块挑一份与平台匹配的文本接口(选法见详细设计)交给 `MovedTypeIndex`,结果并进一张 `[MovedTypeKey: MovedTypeDeclaration]` 表,键是「旧模块 + 类型名」。同一个键在两个模块里都出现时,按发现顺序先到先得,并记一条日志。 +3. 新增公开查询: + + ```swift + public func declaringModuleName(ofMovedTypeNamed typeName: String, originallyDefinedIn originalModuleName: String, builtAgainst sdkVersion: OperatingSystemVersion) -> String? + ``` + + 当 SDK 把 `originalModuleName.typeName` 搬进了另一个模块、并且搬家版本不晚于 `sdkVersion`(数据库自身平台的版本)时,返回现在声明它的模块,否则返回 `nil`。 + +### MachOSwiftSection + +4. `SwiftPrinting` 新增角色协议 `MovedTypeModuleResolving`。`resolvedModuleName(of:siblingIdentifier:)` 在模块不是 `__C` / `__ObjC`、标识符不为空时问它;问到就印新模块,`isResolvedCImportedModule` 仍是 `false`,不触发 C 名改写。 +5. 嵌套类型的模块选择器(`printModuleSelector(ofNestedType:)`)改为按「它所在的顶层声明」查:模块节点来自上下文链的根时,键用最外层类型的标识符,`SwiftUI::Text.SwiftUI::Storage` 就整体变成 `SwiftUICore::Text.SwiftUICore::Storage`;来自某个 `extension` 时不查(非目标)。 +6. `SwiftTypeNameResolution` 新增 `TypeDatabaseMovedTypeModuleResolver`(`typeDatabase` + `sdkVersion`)。`SwiftInterfaceBuilderTypeNameProvider` 增加一个 `resolutions` 参数(选项集合:`.cImportedModules`、`.movedTypeModules`,默认只有前者,与现在一致);它从 `LC_BUILD_VERSION` 取 `sdk` 版本,开了 `.movedTypeModules` 就同时遵循新角色。只开 `.movedTypeModules` 时,`setup()` 用不选任何模块的 `moduleFilter` 调一次 `index`:不生成任何模块接口,不需要 sourcekitd。 +7. `InterfaceRequest` 新增 `resolvesMovedTypeModules: Bool = false`;`swift-section interface` 新增 `--resolve-moved-type-modules`。两个开关可以同时开,共用一个 provider 和一个数据库。 + +### 非目标 + +- **`dump`**:`dump` 按 mangled 身份打印,从不读 SDK,`__C` 类型在 dump 里也不解析(0106 前期调研 1)。搬家记录来自 SDK 而不是二进制,同样不进 dump。 +- **`diff`、`snapshot`、`evolution` 与一切查找键**:它们按 mangled 名比较,必须保持旧模块名。0082 已经用 image 分组处理了 SwiftUI → SwiftUICore 的搬家。 +- **interface 头部的 `import` 行**:旧模块总会重新导出新模块(例如 CoreGraphics 重新导出 CoreFoundation),`import CoreGraphics` 足以让 `CoreFoundation.CGFloat` 编过,不补 `import CoreFoundation`。 +- **声明在搬过家的 extension 里的嵌套类型**:SwiftUICore 有 994 个带 `@_originallyDefinedIn` 的 extension,声明在其中的嵌套类型,它自己的模块选择器仍印旧模块。这种情况很少,而且照样能编过。 +- **函数、全局变量与 extension 成员的搬家**:interface 引用它们时不带模块名。 +- **默认开启**:输出会随宿主机的 SDK 变化,同一份二进制在两台机器上印得不一样,渲染 A/B 与快照测试也会跟着漂移。 +- **RuntimeViewer 接入**:留给 RuntimeViewer 自己的后续改动,它要为每个镜像传入正确的 SDK 版本。 + +## 改动地图 + +| 文件 / 类型 | 动作 | 改什么 | 为什么 | 步骤 | +|---|---|---|---|---| +| swift-type-indexing `Sources/TypeIndexing/MovedTypeIndex.swift` · `MovedTypeIndex`、`MovedTypeDeclaration`、`MovedTypeKey` | 新增 | 文本扫描器(纯函数)与表的键值类型 | 搬家记录只在文本接口里 | 1 | +| swift-type-indexing `Sources/TypeIndexing/SDKPlatform.swift` · `SDKPlatform` | 修改 | 新增内部属性:本平台文本接口的文件名后缀(`-apple-macos`、`-apple-ios-macabi`、`-apple-ios-simulator`…),以及取哪个平台的搬家版本(含 Catalyst / visionOS 回退到 iOS) | 挑文件、选版本都要按平台来 | 1 | +| swift-type-indexing `Sources/TypeIndexing/TypeDatabase.swift` · `TypeDatabase` | 修改 | `discoverSDK()` 扫描并登记搬家表;新增 `declaringModuleName(ofMovedTypeNamed:originallyDefinedIn:builtAgainst:)`;内部的 `register(movedTypeDeclarations:)` 供测试直接驱动 | 对外的唯一入口 | 2 | +| swift-type-indexing `Tests/TypeIndexingTests/MovedTypeIndexTests.swift` | 新增 | 扫描器的单元测试(手写的接口文本) | 解析规则可脱离 SDK 验证 | 1 | +| swift-type-indexing `Tests/TypeIndexingTests/TypeDatabaseMovedTypeTests.swift` | 新增 | 版本判断与平台回退 | 查询语义 | 2 | +| swift-type-indexing `Tests/TypeIndexingTests/SDKIntegrationTests.swift` | 修改 | 加 `CGFloat` 与 `SwiftUI.View` 两条,照旧默认关闭 | 对真实 SDK 的核对 | 2 | +| swift-type-indexing `Documentations/Internal/TypeIndexingPipeline.md`、`README.md`、`Documentations/Evolutions/README.md` | 修改 | 新增「搬家记录」一节;README 写查询用法;提案索引登记 cross-repository 一行 | 文档同批 | 2 | +| `Sources/Output/SwiftPrinting/NodePrintables/TypeNameResolving.swift` · `MovedTypeModuleResolving` | 新增 | 角色协议 | 打印器侧的入口 | 3 | +| `Sources/Output/SwiftPrinting/NodePrintables/NodePrintableDelegate.swift` · `NodePrintableDelegate` | 修改 | 加 `declaringModuleName(ofMovedTypeNamed:originallyDefinedIn:)` | 节点打印器经委托提问 | 3 | +| `Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift` · `TypeNameResolverRegistry`、`addTypeNameResolver(_:)`、委托实现 | 修改 | 新角色的注册与分发 | 与其他角色同一套机制 | 3 | +| `Sources/Output/SwiftPrinting/NodePrintables/NodePrintable.swift` · `resolvedModuleName(of:siblingIdentifier:)` | 修改 | 非 `__C` 模块问新角色 | 唯一出口 | 3 | +| `Sources/Output/SwiftPrinting/NodePrintables/TypeNodePrintable.swift` · `printModuleSelector(ofNestedType:)`、`declaringModuleForModuleSelector` | 修改 | 模块节点来自根时,带回最外层类型的标识符作键 | 嵌套类型跟随外层(编译器同样如此) | 3 | +| `Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift` · `renderExtendedTypeName(_:)`、`isMovedTypeReference(_:)` | 修改 | 被扩展类型的最外层类型被解析器认作搬家时,扩展头改走类型打印器 | 扩展头原本直接照 mangling 印,不经模块名出口(实现时发现,见决策日志) | 3 | +| `Tests/SwiftInterfaceTests/MovedTypeModuleTests.swift` | 新增 | 用 `FixtureCompiler` 现编一个引用 `CGFloat` 的小库,配记录型替身解析器 | 打印器行为不依赖 SDK | 3 | +| `Sources/Output/SwiftTypeNameResolution/TypeDatabaseMovedTypeModuleResolver.swift` · `TypeDatabaseMovedTypeModuleResolver` | 新增 | 包 `TypeDatabase` + SDK 版本的适配器 | 版本按镜像固定,打印器协议不带版本 | 4 | +| `Sources/Output/SwiftTypeNameResolution/SwiftInterfaceBuilderTypeNameProvider.swift` · `SwiftInterfaceBuilderTypeNameProvider` | 修改 | 加顶层选项集合 `SDKTypeNameResolutions` 与 `resolutions:` 参数;遵循新角色;只开搬家时不生成模块接口 | 两个开关共用一个数据库 | 4 | +| `Tests/SwiftTypeNameResolutionTests/TypeDatabaseMovedTypeModuleResolverTests.swift` | 新增 | 适配器的版本判断,经 `@testable` 驱动 `register` | 适配层契约 | 4 | +| `Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift` · `InterfaceRequest` | 修改 | `resolvesMovedTypeModules` 字段与 provider 接线、非 macOS 与无 build version 的警告 | 子命令逻辑在请求里 | 5 | +| `Sources/Executables/swift-section/Commands/InterfaceCommand.swift` · `InterfaceCommand` | 修改 | `--resolve-moved-type-modules` 及 `makeRequest()` 一行 | CLI 只是外壳 | 5 | +| `Tests/SwiftSectionKitTests/…`、`Tests/SwiftSectionCommandTests/CommandRequestMappingTests.swift` | 修改 | 请求两侧各一条 | 新开关两侧各一测(CLAUDE.md) | 5 | +| `Package.swift` | 修改 | 测试目标依赖:`SwiftTypeNameResolutionTests` 加 `SwiftInterface` 与 `SwiftSectionFixtureSupport`,`SwiftSectionKitTests` 加 `SwiftSectionFixtureSupport`;swift-type-indexing 的版本下限抬到 `from: "0.2.0"` | 测试要现编小库;用上新 API | 4 | +| `AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md` | 修改 | 第 8 节旁加新开关的说明与陷阱(版本判断、默认关闭) | CLI 改动同批改 skill | 5 | +| `Documentations/Internal/Modules/SwiftInterface.md`、`Documentations/Internal/Modules/SwiftSectionKit.md`、`Documentations/Glossary.md`、`Documentations/Internal/ProjectEvolutionLog.md`、`CLAUDE.md` 的 SwiftTypeNameResolution 条 | 修改 | 新角色、新开关、术语「moved type」、账本一节 | 文档同批 | 6 | + +## 架构图 + +改了什么: + +```text +swift-type-indexing + TypeDatabase (actor) + discoverSDK() + APINotesIndex(files:) (kept) + + MovedTypeIndex.scan(interfaceText:moduleName:) for every SDK module + + movedTypeDeclarationsByKey: [MovedTypeKey: MovedTypeDeclaration] + moduleName(forTypeName:) (kept, __C only) + swiftName(forCName:category:) (kept, __C only) + + declaringModuleName(ofMovedTypeNamed:originallyDefinedIn:builtAgainst:) + +MachOSwiftSection + SwiftPrinting + TypeNameResolving + ModuleNameResolving / CImportedNameResolving / OpaqueTypeResolving (kept) + + MovedTypeModuleResolving + SwiftDeclarationPrinter.typeNameResolverRegistry + + movedTypeModuleResolvers + NodePrintable.resolvedModuleName(of:siblingIdentifier:) + __C / __ObjC -> ModuleNameResolving (kept) + + other module -> MovedTypeModuleResolving + TypeNodePrintable.printModuleSelector(ofNestedType:) + ~ key: outermost type's identifier when the module is the context root + SwiftTypeNameResolution + TypeDatabaseTypeNameResolver (kept, unchanged) + + TypeDatabaseMovedTypeModuleResolver(typeDatabase:sdkVersion:) + SwiftInterfaceBuilderTypeNameProvider + ~ resolutions: [.cImportedModules, .movedTypeModules] + SwiftSectionKit.InterfaceRequest + + resolvesMovedTypeModules + swift-section interface + + --resolve-moved-type-modules +``` + +一次查询的数据流: + +```text +interface print of `x: CoreGraphics.CGFloat` + TypeNodePrintable (context node = module "CoreGraphics", identifier "CGFloat") + resolvedModuleName(of: module, siblingIdentifier: "CGFloat") + not __C / __ObjC + delegate.declaringModuleName(ofMovedTypeNamed: "CGFloat", originallyDefinedIn: "CoreGraphics") + SwiftDeclarationPrinter -> first non-nil of movedTypeModuleResolvers + SwiftInterfaceBuilderTypeNameProvider + TypeDatabaseMovedTypeModuleResolver(sdkVersion: LC_BUILD_VERSION.sdk) + TypeDatabase.declaringModuleName(ofMovedTypeNamed:originallyDefinedIn:builtAgainst:) + movedTypeDeclarationsByKey[CoreGraphics, CGFloat] + -> declaringModule "CoreFoundation", moved macOS 10.0 + sdkVersion >= 10.0 -> "CoreFoundation" + writes "CoreFoundation" + "." (or "::") +``` + +## 详细设计 + +### 扫描器 + +```swift +struct MovedTypeKey: Hashable, Sendable { + let originalModuleName: String + let typeName: String +} + +struct MovedTypeDeclaration: Hashable, Sendable { + let typeName: String + /// The module the mangling names: the part of the attribute's module + /// argument before a `;`. + let originalModuleName: String + /// The module whose interface declares the type now. + let declaringModuleName: String + /// The version the attribute names per platform keyword (`macOS`, + /// `macCatalyst`, `iOS`, `tvOS`, `watchOS`, `visionOS`, `driverKit`). + let movedVersionsByPlatformName: [String: OperatingSystemVersion] +} + +enum MovedTypeIndex { + /// The type declarations `interfaceText` (a textual `.swiftinterface` + /// of `moduleName`) marks `@_originallyDefinedIn` another module. + static func movedTypeDeclarations(inInterfaceText interfaceText: String, moduleName: String) -> [MovedTypeDeclaration] +} +``` + +规则: + +- 只看从第 0 列开始的行。一个属性组是连续的以 `@` 开头的行;组里收集所有 `@_originallyDefinedIn(module: "M", P V)`,同一个属性写多个平台(`macOS 15.0, iOS 18.0`)时逐个拆开。 +- 属性组结束后的那一行是声明。去掉行首的属性(`@frozen`、`@MainActor`、`@preconcurrency` 等,含括号参数)和修饰词(`public`、`open`、`final`、`indirect`、`nonisolated`),第一个关键字是 `struct` / `class` / `enum` / `protocol` / `actor` / `typealias` 时取紧跟的标识符为类型名(遇到 `<`、`:`、空格、`=`、`{` 截止;反引号去掉)。其他关键字一律丢弃。 +- 平台关键字的拼写取 Swift 源码的写法:`macOS`、`macCatalyst`、`iOS`、`tvOS`、`watchOS`、`visionOS`、`driverKit`;`OSX` 视同 `macOS`,`*ApplicationExtension` 视同其基础平台。 +- `module:` 的值有 `;` 时取前半段。前半段等于 `moduleName` 时整条丢弃。 + +### 挑哪份接口文件 + +`SwiftModuleDescriptor.path` 是 `.swiftmodule` 目录。在它下面找文件名形如 `<架构>-apple-<平台后缀>.swiftinterface` 的文件,排除 `.private.swiftinterface` 与 `.package.swiftinterface`;平台后缀取自 `SDKPlatform`(`macos`、`ios-macabi`、`ios`、`ios-simulator`、`tvos`、`tvos-simulator`、`watchos`、`watchos-simulator`、`xros`、`xros-simulator`、`driverkit`)。同一模块有几种架构时按文件名排序取第一个(`arm64-` < `arm64e-` < `arm64e.x1-` < `x86_64-`,结果确定)。属性对每个平台都写全,所以选哪个架构不影响结果。目录里没有文本接口的模块(只有二进制 `.swiftmodule`)直接跳过。读文件失败记日志后跳过,不影响别的模块。 + +### 版本判断 + +```swift +extension TypeDatabase { + /// The module that declares the Swift type the mangling names + /// `originalModuleName.typeName`, when the SDK moved it there + /// (`@_originallyDefinedIn`) no later than `sdkVersion` of the database's + /// platform; nil when it never moved, or moved after that version. + public func declaringModuleName(ofMovedTypeNamed typeName: String, originallyDefinedIn originalModuleName: String, builtAgainst sdkVersion: OperatingSystemVersion) -> String? +} +``` + +- 用哪个平台的条目:`macOS` → `macOS`;`macCatalyst` → `macCatalyst`,没有就用 `iOS`(Catalyst 的版本号与 iOS 一致);`iOS` / `iOSSimulator` → `iOS`;`tvOS*` → `tvOS`;`watchOS*` → `watchOS`;`visionOS*` → `visionOS`,没有就用 `iOS` 并换算(iOS 17.x → visionOS 1.x,18.x → 2.x,26 起版本号相同,17 以前视为 visionOS 出现之前就已搬家);`driverKit` → `driverKit`。 +- 找不到适用条目:属性在该平台不生效,mangling 本来就是新模块,返回 `nil`。 +- `sdkVersion` 大于或等于搬家版本时返回 `declaringModuleName`。 +- 调用前没有 `index` 过:返回 `nil`(与 `moduleName(forTypeName:)` 一致)。 + +为什么用 `LC_BUILD_VERSION` 的 `sdk` 而不是 `minos`:mangling 与部署目标无关(前期调研 1),interface 想还原的是作者写代码时 SDK 里的样子,这由编译所用的 SDK 决定。系统镜像的 `sdk` 就是它所属的系统版本,所以 macOS 14 cache 里的 SwiftUI 不会被改写成 SwiftUICore。 + +**已知偏差**:属性写的版本不一定是源码真正搬家的时间。`CGFloat` 写的是 macOS 10.0,运行时却是 macOS 13 才搬进 `libswiftCoreFoundation`(前期调研 2)。用 macOS 12 SDK 编的二进制也会印成 `CoreFoundation.CGFloat`:它在当前 SDK 下成立,但不一定是当年 SDK 的写法。这里信属性,不另做修正表。 + +### 打印器 + +```swift +/// Resolves the module that declares a Swift type today when its mangling +/// names the module the type was originally defined in +/// (`@_originallyDefinedIn`): `CoreGraphics.CGFloat` → `CoreFoundation`. +public protocol MovedTypeModuleResolving: TypeNameResolving { + func declaringModuleName(ofMovedTypeNamed typeName: String, originallyDefinedIn originalModuleName: String) async -> String? +} +``` + +`resolvedModuleName(of:siblingIdentifier:)` 的新分支: + +```swift +if moduleName != objcModule, moduleName != cModule, + let identifier = siblingIdentifier, !identifier.isEmpty, + let delegate, + let declaringModuleName = await delegate.declaringModuleName(ofMovedTypeNamed: identifier, originallyDefinedIn: moduleName) { + return (declaringModuleName, false) +} +``` + +它与 `cImportedTypeNameSpelling` 无关:`.cName` 只管 C 导入类型。`printModuleSelector(ofNestedType:)` 改为让 `declaringModuleForModuleSelector` 同时带回「模块节点的来源」:来自根时,带回最外层类型节点的标识符(根模块节点的兄弟)作为查询键;来自 `extension` 时不带,不查询。C 导入模块照旧按嵌套类型自己的名字问 `__C` 解析器,行为不变。 + +扩展头另有一条路:`SwiftDeclarationPrinter+Headers.swift` 的 `renderExtendedTypeName(_:)` 原本对非 C 类型直接 `extensionName.print(usesModuleSelectors:)`,不经模块名出口。新增 `isMovedTypeReference(_:)`:剥掉 `type` 包装、沿上下文找到根模块,模块不是 `__C` / `__ObjC` 且解析器对最外层类型回答了搬家,才改走类型打印器(与 C 导入类型的扩展头同一条路);没搬家的类型照旧,输出逐字节不变。 + +### 适配层与请求 + +```swift +@available(macOS 13.0, *) +public struct TypeDatabaseMovedTypeModuleResolver: MovedTypeModuleResolving { + public let typeDatabase: TypeDatabase + /// The SDK version of the image being printed (`LC_BUILD_VERSION`'s `sdk`). + public let sdkVersion: OperatingSystemVersion + public init(typeDatabase: TypeDatabase, sdkVersion: OperatingSystemVersion) +} + +/// What a `SwiftInterfaceBuilderTypeNameProvider` resolves through the SDK. +public struct SDKTypeNameResolutions: OptionSet, Hashable, Sendable { + public static let cImportedModules: SDKTypeNameResolutions + public static let movedTypeModules: SDKTypeNameResolutions +} + +public init?(machO: MachO, dependencies: SwiftInterfaceBuilderDependencies, resolutions: SDKTypeNameResolutions = .cImportedModules, supplementaryAPINotesURLs: [URL] = []) +``` + +- `MachOKit.Version` → `OperatingSystemVersion` 的转换放在适配层(swift-type-indexing 不依赖 MachOKit)。 +- provider 未开 `.cImportedModules` 时,`moduleName(forTypeName:)` 与 `swiftName(forCName:category:)` 返回 `nil`,`setup()` 用 `moduleFilter: { _ in false }` 调一次 `index`,不传依赖;未开 `.movedTypeModules` 时,新角色的方法返回 `nil`。 +- `InterfaceRequest`:任一开关打开就构造 provider,`resolutions` 按两个开关组合。只开搬家时,现有警告的措辞里把 `--resolve-c-module-names` 换成实际打开的开关名。 + +### CLI + +```text +--resolve-moved-type-modules + Print a Swift type the SDK moved to another module (@_originallyDefinedIn) + under the module that declares it now (CoreGraphics.CGFloat -> + CoreFoundation.CGFloat, SwiftUI.View -> SwiftUICore.View), when the binary + was built against an SDK that had already moved it. Reads the SDK's + .swiftinterface files; needs Xcode or the Command Line Tools, not + sourcekitd. macOS only. +``` + +## 替代方案考量 + +- **并进 `--resolve-c-module-names`**:用户只需要记一个「按 SDK 解析」的开关,但那个开关第一次运行要经 sourcekitd 生成模块接口(UIKit 冷生成 126 秒),只想要搬家改写的人不该为它付这笔钱;它的名字和帮助文字也说的是 `__C`。否:用独立开关,两个都开时共用数据库。 +- **从 `$ld$previous` 推导**:tbd 里有符号的旧安装路径与版本区间,但给的是库路径而不是模块名,还要逐个符号去重归并成类型;属性才是编译器自己的依据。否。 +- **经 sourcekitd 生成的接口读属性**:那一层只有依赖过滤命中的模块才生成,而且 `InterfaceDeclarationNode` 不留属性。搬家后的模块常常不是二进制的直接依赖(引用 `SwiftUI.View` 的二进制未必直接链接 SwiftUICore)。否。 +- **不做版本判断、一律按宿主 SDK 改写**:macOS 14 的 SwiftUI 镜像会印出当时还不存在的 SwiftUICore,而 `View` 恰好就声明在被打印的这个镜像里。否。 +- **按「类型定义是否在被打印的镜像里」判断**:SwiftUICore 镜像(macOS 15 起)里的定义正应改写成 SwiftUICore,这条规则会反着判。否。 +- **打印器协议带版本参数**:版本是被打印镜像的固定属性,放进适配器构造时一次给定,打印器不必知道 Mach-O。否。 +- **给 `TypeDatabaseTypeNameResolver` 直接加新角色**:RuntimeViewer 升级后输出会悄悄改变,而且它拿不到每个镜像的 SDK 版本。否:另起一个适配器。 +- **默认开启**:见非目标。 + +## 影响 + +### 源码兼容性(source compatibility) + +纯新增: + +- swift-type-indexing:`TypeDatabase` 多一个公开方法。 +- MachOSwiftSection:`SwiftPrinting` 多一个公开协议;`SwiftTypeNameResolution` 多一个公开类型;`SwiftInterfaceBuilderTypeNameProvider.init` 多一个带默认值的参数(默认值保持现有行为);`InterfaceRequest` 多一个带默认值的字段;CLI 多一个开关。`NodePrintableDelegate` 是内部协议,加要求不影响外部。 + +### ABI 兼容性(条件项) + +不适用 —— 两个库都以 SPM 源码分发,使用方每次重新编译。 + +### 下游影响 + +- 本仓库:`SwiftPrinting`、`SwiftTypeNameResolution`、`SwiftSectionKit`、`swift-section`。 +- swift-type-indexing 要先发新版本(0.2.0,新增公开 API),本库才能用上。 +- RuntimeViewer:不受影响(`TypeDatabaseTypeNameResolver` 不变);以后想要这项改写,要为每个镜像构造 `TypeDatabaseMovedTypeModuleResolver` 并传入 SDK 版本。MachOObjCSection 的 `ObjCTypeIndexing` 不受影响。 + +### 文档与示例 + +- swift-type-indexing:`TypeIndexingPipeline.md` 新增一节,README 写查询用法。 +- 本仓库:`Documentations/Internal/Modules/SwiftInterface.md`、`Documentations/Internal/Modules/SwiftSectionKit.md`、`CLAUDE.md` 的 SwiftTypeNameResolution 一条、agent 插件 skill(`AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md`)、`Documentations/Glossary.md`(术语 moved type)、`ProjectEvolutionLog.md`。 + +## API 演进与废弃策略 + +- 不替代任何旧 API。 +- `SDKTypeNameResolutions` 用 `OptionSet`:以后再加别的 SDK 解析能力时只是加一个成员。 +- swift-type-indexing 0.1.x → 0.2.0;MachOSwiftSection 跟随下一个版本发布,不需要大版本跃迁。 + +## 落地步骤 + +1. ✅ **扫描器** —— 改动地图 swift-type-indexing 的 `MovedTypeIndex.swift`、`SDKPlatform.swift`、`MovedTypeIndexTests.swift` + - 行为:`structMovedFromAnotherModuleIsRecorded` + - 行为:`protocolClassEnumActorAndTypealiasAreRecorded` + - 行为:`extensionsFunctionsAndVariablesAreNotRecorded` + - 行为:`declarationModifiersAndAttributesBeforeTheKeywordAreSkipped` + - 行为:`severalPlatformsInOneAttributeAreSplit` + - 行为:`manglingModuleIsThePartBeforeTheSemicolon` + - 行为:`moveWithinTheSameModuleIsNotRecorded` + - 行为:`indentedAttributesAreIgnored` + - 行为:`interfaceFileMatchingThePlatformIsChosen` +2. ✅ **数据库与查询** —— 改动地图 swift-type-indexing 的 `TypeDatabase.swift`、`TypeDatabaseMovedTypeTests.swift`、`SDKIntegrationTests.swift` 与文档三行;完成后发 swift-type-indexing 0.2.0 + - 行为:`answersTheDeclaringModuleWhenTheSDKIsNotOlderThanTheMove` + - 行为:`answersNothingForAnSDKOlderThanTheMove` + - 行为:`answersNothingForATypeThatNeverMoved` + - 行为:`answersNothingBeforeIndexing` + - 行为:`macCatalystFallsBackToTheIOSVersion` + - 行为:`visionOSMapsTheIOSVersion` + - 行为:`firstDiscoveredModuleWinsATiedKey` + - 行为(SDK 集成,默认关闭):`cgFloatMovedFromCoreGraphicsToCoreFoundation`、`swiftUIViewMovedToSwiftUICoreInMacOS15` + - 落地时把扫描全部 SDK 模块的实测耗时写进前期调研 5(已写入)。 +3. ✅ **打印器** —— 改动地图 `TypeNameResolving.swift`、`NodePrintableDelegate.swift`、`SwiftDeclarationPrinter.swift`、`NodePrintable.swift`、`TypeNodePrintable.swift`、`SwiftDeclarationPrinter+Headers.swift`、`MovedTypeModuleTests.swift` + - 行为:`movedTopLevelTypePrintsUnderItsDeclaringModule` + - 行为:`nestedTypeFollowsItsOutermostType` + - 行为:`moduleSelectorsSpellTheDeclaringModuleOnNestedTypes` + - 行为:`extensionHeaderOfAMovedProtocolUsesTheDeclaringModule` + - 行为:`cImportedModulesAreNeverAskedAboutMoves` + - 行为:`withoutAResolverTheManglingModuleIsKept` + - 行为:`importLinesKeepTheManglingModules` +4. ✅ **适配层** —— 改动地图 `TypeDatabaseMovedTypeModuleResolver.swift`、`SwiftInterfaceBuilderTypeNameProvider.swift`、`TypeDatabaseMovedTypeModuleResolverTests.swift`、`Package.swift` + - 行为:`resolverAnswersForTheImagesSDKVersion` + - 行为:`providerWithOnlyMovedTypesAnswersNoCImportedQuestion`(原计划名 `providerWithOnlyMovedTypesGeneratesNoModuleInterface`) + - 行为:`providerDefaultKeepsTodaysResolutions` + - 原计划的 `providerWithBothResolutionsSharesOneDatabase` 未写,见决策日志。 +5. ✅ **请求与 CLI** —— 改动地图 `InterfaceRequest.swift`、`InterfaceCommand.swift`、两侧测试、agent 插件 skill + - 行为:`interfaceRequestResolvesMovedTypeModulesOnlyWhenAsked` + - 行为:`resolveMovedTypeModulesFlagMapsOntoTheRequest` + - 行为:`bothResolutionFlagsCombine` + - 核对 skill 里点到的每个开关都还存在(CLAUDE.md 的 `grep -ohE` 命令)。 +6. ✅ **文档与收尾** —— 改动地图最后一行 + - 用 `swift-section interface --resolve-moved-type-modules` 打一次宿主 macOS 27.2 cache 与 14.6 归档 cache 里的 DeveloperToolsSupport,确认前者印 SwiftUICore、后者照旧印 SwiftUI,结果写进决策日志。(原计划用 15.5 的 SwiftUI:15.5 已在搬家之后,验证不了「照旧」;换成体量小的 DeveloperToolsSupport,同样引用大量 SwiftUI 类型。) + - 新开关默认关闭,不开时输出逐字节不变;按 CLAUDE.md,这一改动不属于需要渲染 A/B 的大重构,以 `withoutAResolverTheManglingModuleIsKept` 与现有快照测试为准。 + +**收尾时必须判断两件事**(判断结果写进决策日志,不允许沉默跳过): + +- **要不要配套专题文章** —— 预计不单独写:调用方契约在 swift-type-indexing 的 README 与 `TypeIndexingPipeline.md` 里,打印器一侧在 `Modules/SwiftInterface.md`。 +- **有没有引入新术语** —— 有:「moved type」(被 `@_originallyDefinedIn` 搬过家的类型),登记进 `Documentations/Glossary.md`。 + +## 决策日志 + +| 日期 | 变更 | 说明 | +|------|------|------| +| 2026-11-25 | Created as Draft | 用户发现 `CGFloat` 在 SDK 里由 CoreFoundation 声明、二进制里却叫 CoreGraphics,问 swift-type-indexing 能否让输出与 SDK 一致;调研确认能做,用户要求写提案。 | +| 2026-11-25 | 方案取舍 | 独立开关、默认关闭;按二进制的 SDK 版本判断是否改写;`dump` 与 diff 类命令不改;RuntimeViewer 不随升级改变行为。用户确认开关做成独立的 `--resolve-moved-type-modules`。 | +| 2026-11-25 | Accepted | 用户批准,开始实现。 | +| 2026-11-25 | 第 1–2 步完成(swift-type-indexing) | 扫描器与查询落在 swift-type-indexing 的 `feature/moved-swift-type-modules`;单元测试 103 个、SDK 集成测试 7 个全部通过(公司那台本机,swift-type-indexing 不在远程编译清单里)。版本比较用内部类型 `PlatformVersion`(按数值比较、补零),公开 API 仍收 `OperatingSystemVersion`。扫描器另认 `#if` / `#else` / `#endif` 让属性组作废、限定名属性(`@_Concurrency.MainActor`)算一个属性,测试 `conditionalCompilationDirectivesEndTheAttributes`、`versionsCompareNumerically`、`answersNothingOnAPlatformTheAttributeDoesNotName` 是在提案清单之外加的。swift-type-indexing 0.2.0 尚未发版:发版不在本次授权内,本库在此之前经本地兄弟依赖构建。 | +| 2026-11-25 | 第 3 步:扩展头也要改 | 改动地图原先只列了模块名出口 `resolvedModuleName`。第一轮测试 `extensionHeaderOfAMovedProtocolUsesTheDeclaringModule` 红了:扩展头 `renderExtendedTypeName(_:)` 对非 C 类型直接照 mangling 印,印出 `extension CoreGraphics.CGFloat`,而成员里已是 `CoreFoundation.CGFloat`。改为最外层类型被解析器认作搬家时走类型打印器,与 0106 给 C 导入类型扩展头开的路相同;没搬家的类型照旧。修复前这条测试在 Ultra 上红、修复后绿。 | +| 2026-11-25 | 第 4 步:选项集合放顶层 | 提案写的是嵌套在 `SwiftInterfaceBuilderTypeNameProvider` 里的 `Resolutions`;provider 是泛型类,嵌套类型会让调用方(`InterfaceRequest`)写出泛型参数,改为顶层的 `SDKTypeNameResolutions`。 | +| 2026-11-25 | 第 4 步:两条测试的取舍 | `providerWithBothResolutionsSharesOneDatabase` 没写:要观察共用,就得在测试里开 `__C` 解析并跑 `setup()`,那会经 sourcekitd 生成模块接口、写进真实缓存目录;共用由构造器里只建一个 `TypeDatabase` 保证。`providerWithOnlyMovedTypesGeneratesNoModuleInterface` 改名为 `providerWithOnlyMovedTypesAnswersNoCImportedQuestion`,断言它能答搬家、不答 `__C`。MachOKit 的 `Version` 没有公开构造器,`MachOKit.Version` → `OperatingSystemVersion` 的转换不单测,由 provider 测试覆盖。测试要现编小库,`SwiftTypeNameResolutionTests` 加 `SwiftInterface` 与 `SwiftSectionFixtureSupport` 依赖,`SwiftSectionKitTests` 加 `SwiftSectionFixtureSupport`;都是包内目标,`Tuist/Package.swift` 不用改。 | +| 2026-11-25 | 第 5 步:警告措辞 | 只开 `--resolve-moved-type-modules` 时不解析依赖镜像(只有 `__C` 解析用得到),警告里的开关名按实际打开的那一个或两个写。 | +| 2026-11-25 | 第 6 步:真机核对 | 在 Ultra 上用沙盒编出的 debug CLI 核对。宿主 macOS 27.2 cache 的 TipKit:开关打开后 `SwiftUI.View` 0 处、`SwiftUICore.View` 14 处(`SwiftUICore.` 共 326 处,剩下 45 处 `SwiftUI.` 是没搬家的类型)。14.6 归档 cache 的 TipKit:开关前后只差 6 行,全是 `CoreGraphics.CGFloat` → `CoreFoundation.CGFloat`,`SwiftUI.View` 15 处原样不动——版本判断生效。DeveloperToolsSupport(27.2 与 14.6):`SwiftUI.PreviewLayout` 改成 `DeveloperToolsSupport.PreviewLayout`(SDK 里它是 `@_originallyDefinedIn(module: "SwiftUI", macOS 14.0)`,14.6 在其后),`CGFloat` 同上。原计划拿 15.5 的 SwiftUI 验证「照旧」,可 15.5 已在搬家之后,换成 14.6。插件 skill 新开关已在 `--help` 里;`claude plugin validate`(经 `claude-isolated`)插件与 marketplace 都通过。 | +| 2026-11-25 | 全量验证 | Ultra(macOS 27.2,Xcode 26.6),沙盒里本仓库功能分支加 swift-type-indexing 功能分支的拷贝、`USING_LOCAL_DEPENDENCIES=1`、现成的 Xcode 26.6 ad-hoc fixture:`swift test --skip IntegrationTests` 2969 个测试、560 个套件全部通过,退出码 0,用时 1112 秒。swift-type-indexing 在公司那台本机:单元测试 103 个、SDK 集成测试 7 个通过。 | +| 2026-11-25 | 收尾判断 | 不另写专题文章:调用方契约在 swift-type-indexing 的 README 与 `TypeIndexingPipeline.md`「搬家记录」一节,打印器一侧在 `Modules/SwiftInterface.md`。新术语 moved type 已登记进 `Documentations/Glossary.md`,「type index」条目补了一句。`Modules/SwiftSectionKit.md` 与 `Documentations/SwiftSectionKit.md` 不列请求字段,不用改。 | +| 2026-11-25 | 实现完成,待用户看过后收尾 | 两个仓库的功能分支都已推送。没有在本地合进 `next`:`next` 按远端版本下限用 swift-type-indexing 0.1.1,合进去后常驻检出编不过;等 swift-type-indexing 发 0.2.0、本库把下限抬到 `from: "0.2.0"` 后再合。 | +| 2026-11-25 | swift-type-indexing 0.2.0 发版 | 用户同意发版。swift-type-indexing 用 Xcode 26.6 跑过测试(103 个全过),功能分支以合并提交 `Merge branch 'feature/moved-swift-type-modules'` 快进推上 `main`,CI(Xcode 26.6)通过后在合并提交上打注释 tag 0.2.0。本库 `Package.swift` 的下限抬到 `from: "0.2.0"`。 | +| 2026-11-25 | Implemented | 用户看过本地合并后要求收尾。落地时取号 0107,演进账本对应第 153 节。验证沿用最终代码上的两次结果:Ultra(Xcode 26.6)全量 2969 个测试全过;抬到 swift-type-indexing 0.2.0 后按远端依赖重编,相关 58 个测试全过;此后只改文档。核心能力全部实现,没有遗留的后续项。文档判断:不另写专题文章,配套文档字段登记了现有的三处;新术语 moved type 已在术语表。本地 `next` 上紧接着还合进了 private-cf-type-modules(叠在本次合并之上,尚未收尾),所以 `next` 暂不推送,等那个提案收尾时一起推。 | diff --git a/Documentations/Evolutions/0108-private-cf-type-modules.html b/Documentations/Evolutions/0108-private-cf-type-modules.html new file mode 100644 index 000000000..772a4293a --- /dev/null +++ b/Documentations/Evolutions/0108-private-cf-type-modules.html @@ -0,0 +1,462 @@ + + + + + + +0108 - 私有 CF 类型按导出 GetTypeID 的镜像解析所属模块 + + + + +
+ +
+

MachOSwiftSectionEvolutions0108

+

0108 私有 CF 类型按导出 GetTypeID 的镜像解析所属模块

+
+
状态
Implemented
+
最后更新
2026-11-25
+
项目类型
库
+
原文
0108-private-cf-type-modules.md
+
+
+ + + +
+ +
+

摘要

+

swift-section interface --resolve-c-module-names 能把公开的 C 导入类型写到真实模块下(__C.CGColorRef → CoreGraphics.CGColor),私有的 CF 类型却查不到模块:SDK 里没有它们的头文件,依赖镜像的 Objective-C 元数据也不列 CF 类型,于是按 0106 的规则只印描述符给的裸名(CGSVGDocument)。

+

本提案在 SwiftTypeNameResolution 里新增 CFDeclaredTypeNames:从镜像的导出表里找出每个 …GetTypeID 函数,列出它定义的 CF 类型(_CGSVGDocumentGetTypeID → CGSVGDocumentRef)。provider 为根镜像登记它;每个直接依赖改登记新的 ImageDeclaredTypeNames,把这个镜像的 Objective-C 名字和 CF 类型合成一个来源,因为 TypeDatabase 每个镜像路径只收一个来源。GetTypeID 只负责定位:一个名字是不是 CF 类型,由根镜像自己的 foreign class 描述符决定。之后 CGSVGDocumentRef 归到 CoreSVG,引用印成 CoreSVG.CGSVGDocument。打印器、swift-type-indexing 和 CLI 参数都不改。

+
+ +
+

要你定

+
+

没有悬而未决的事

+

已落地:2026-11-25 合进 next,编号 0108。后续项:RuntimeViewer 接入、模块名与类型同名时用模块选择器、跟着重新导出找子框架、运行时来源放宽到间接依赖。

+
+
+ +
+

架构图

+
    +
  • 新增
  • +
  • 修改
  • +
  • 不变
  • +
+

改了什么

+
+ + + SwiftTypeNameResolution/ + SwiftInterfaceBuilderTypeNameProvider.setup()gate: cfTypedefNames(referencedBy: root)registers CF(root), then ImageDeclaredTypeNames per dependency + ImageDeclaredTypeNames<MachO>one source per image: ObjC names + CF typedef names + CFDeclaredTypeNames<MachO>exportedSymbols: _<Name>GetTypeID -> "<Name>Ref"only names the root's descriptors confirm (internal gate) + + MachOObjCSection + ObjCDeclaredTypeNames<MachO> + + swift-type-indexing 0.2.0 + TypeDatabase.moduleName(forTypeName:)SDK first, then sources; one per image path + protocol DeclaredTypeNameSourceimagePath, declaredTypeNames() + + SwiftPrinting + TypeNodePrintable.printType: module + descriptor name + + + + + + asks via provider + +
+

实线:调用;虚线:遵循协议或被组合。swift-type-indexing 与打印器都不改。

+ +

一个引用怎么印出来

+
+ + printType(__C.CGSVGDocumentRef) in SwiftUICore + swiftNameFromDescriptor -> "CGSVGDocument" (0106 name table) + TypeDatabase.moduleName("CGSVGDocumentRef"): SDK tables miss + CF(SwiftUICore) miss · Image(AttributeGraph) miss · … + ImageDeclaredTypeNames(CoreSVG): "CGSVGDocumentRef" (root descriptor confirms) -> "CoreSVG" + swiftName(forCName:) -> nil (no API notes, not SDK-indexed) + writes CoreSVG.CGSVGDocument (was: CGSVGDocument) + + +
+
+ +
+

改动地图

+
+ + + + + + + + + + + + + + + +
文件 / 类型动作改什么为什么步骤
Sources/Output/SwiftTypeNameResolution/CFDeclaredTypeNames.swift新增DeclaredTypeNameSource:读导出表,…GetTypeID → typedef 名;internal 的带闸门构造器私有 CF 类型的模块证据1
Tests/SwiftTypeNameResolutionTests/CFDeclaredTypeNamesTests.swift新增现场编译的 C 库经两种读法读出的名字;本机 cache 的 CoreSVG规则与两种读法1
Sources/Output/SwiftTypeNameResolution/ImageDeclaredTypeNames.swift新增一个镜像的 ObjC 名字与 CF 类型合成一个来源TypeDatabase 每个镜像路径只收一个来源2
Tests/SwiftTypeNameResolutionTests/ImageDeclaredTypeNamesTests.swift新增IOSurface 同时列出 IOSurface 与 IOSurfaceRef合成来源两种名字都在2
Sources/Output/SwiftTypeNameResolution/SwiftInterfaceBuilderTypeNameProvider.swift · setup()修改来源改为「根的 CF,然后每个依赖一个 ImageDeclaredTypeNames」;cfTypedefNames(referencedBy:) 从根镜像的 foreign 描述符收集闸门集合登记新来源,判定靠描述符2
Tests/SwiftTypeNameResolutionTests/PrivateCFTypeModuleTests.swift新增端到端:依赖定义的、根镜像定义的、不导出 GetTypeID 的、诱饵 swift_wrapper、不挂 provider 的端到端证明2
Sources/Executables/swift-section/Commands/InterfaceCommand.swift修改--resolve-c-module-names 的帮助文字--help 就是文档3
AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md 第 8 节修改私有 CF 类型的归属、哪些情况仍不解析CLI 行为变了3
CLAUDE.md(AGENTS.md)修改模块清单列出两个新类型、闸门与去重的坑模块清单与代码同步3
Documentations/Evolutions/README.md、Documentations/README.md修改登记本提案;落地时改编号与状态文档索引0、3
Documentations/Internal/ProjectEvolutionLog.md修改落地时追加一节演进账本3
+
+
+ +
+

提议方案

+
    +
  1. CFDeclaredTypeNames:每个 _<名字>GetTypeID 导出给出 <名字>Ref;以下划线开头的私有函数(__LSASNGetTypeID)同时给出去掉前导下划线的拼写。
  2. +
  3. ImageDeclaredTypeNames:一个镜像的 ObjC 名字在前、CF 名字在后,合成一个来源。分开登记的话,后登记的那个永远读不到。
  4. +
  5. provider 登记它们:根镜像的 CFDeclaredTypeNames,然后每个直接依赖一个 ImageDeclaredTypeNames。GetTypeID 只负责定位,「是不是 CF 类型」由 foreign 描述符决定:CF 来源只给出根镜像的 foreign class 描述符证实的名字。
  6. +
  7. 打印器、swift-type-indexing、CLI 参数都不改,只补帮助文字和 skill 说明。
  8. +
+

非目标

+
    +
  • 跟着重新导出找子框架(LSASNRef → CoreServices),与 ObjC 来源一起另开提案。
  • +
  • 间接依赖(CFPhoneNumberRef):放宽到传递闭包会让 SourceKit 接口生成回到几百个模块。
  • +
  • 没有 GetTypeID 导出的类型;自己定义、不导出 GetTypeID 的 CF 桥接类型印裸名(测试里的 ProbeLonelyRef)。
  • +
  • 本镜像没有描述符的引用:闸门挡在外面,仍印 __C.XRef。
  • +
  • 根镜像自己的 ObjC 类、dump、RuntimeViewer 接入(发版后把 ObjCDeclaredTypeNames 换成 ImageDeclaredTypeNames)。
  • +
  • 模块名与它里面的类型同名时(IOSurface.IOSurface 编不过)改用模块选择器 IOSurface::…:打印器的通用拼写问题,另做。
  • +
+
+ +
+

详细设计

+
+ API +
+
public struct CFDeclaredTypeNames<MachO: MachORepresentable & Sendable>: DeclaredTypeNameSource {
+    public let imagePath: String
+    public init(machO: MachO, imagePath: String)
+    init(machO: MachO, imagePath: String, restrictedTo admittedTypedefNames: Set<String>?)   // internal
+    public func declaredTypeNames() async -> [String]
+}
+
+public struct ImageDeclaredTypeNames<MachO: ObjCMetadataSource>: DeclaredTypeNameSource {
+    public let imagePath: String
+    public init(machO: MachO, imagePath: String)
+    init(machO: MachO, imagePath: String, restrictingCFTypesTo admittedTypedefNames: Set<String>?)   // internal
+    public func declaredTypeNames() async throws -> [String]
+}
+
+extension SwiftInterfaceBuilderTypeNameProvider {
+    static func declaredTypeNameSources(root: MachO, dependencies: [MachO]) -> [any DeclaredTypeNameSource]
+    static func cfTypedefNames(referencedBy image: MachO) -> Set<String>
+}
+

判定 CF 类只看描述符:种类是 class、isCImportedContextDescriptor 为真、import info 的 isCTypedef 为真且不是相关实体。只有 CF 类型会被升格成 class 而又来自 C typedef。名字取 ABI 名,ClangImporter 保留了 C 拼写时(IOSurfaceRef)取描述符自己的名字。带闸门的构造器是 internal,公开接口不变。

+
+
+
+ 命名规则 +
+
    +
  1. 导出名以一个 _ 开头,去掉它得到 C 函数名。
  2. +
  3. C 函数名以 GetTypeID 结尾,去掉后缀的部分是合法 C 标识符且不全是下划线,记为 base。
  4. +
  5. 给出 base + "Ref";base 以下划线开头时再给出去掉前导下划线的拼写。
  6. +
  7. 规则会产生 CFRef 这类非类型名字;provider 登记的来源都带闸门,只留根镜像证实的名字。
  8. +
+
+
+
+ 性能 +
+

Ultra 上 SwiftUICore 热缓存下 17.22 → 17.28 秒,测不出差别,不改成遍历导出 trie。

+
+
+
+ +
+

动机

+

macOS 27.2 的 cache 里,被 Swift 用到的 CF 类一共 66 个,其中 20 个不在公开 SDK 的头文件里:

+
+ + + + + + + + + + + + +
私有 CF 类型Swift 名导出 GetTypeID 的镜像用到它的 Swift 镜像
CGSVGDocumentRefCGSVGDocumentCoreSVGSwiftUICore
CGColorTransformRef、CGContextDelegateRef去掉 RefCoreGraphicsAppKit
AGGraphRef、AGSubgraphRefGraph、SubgraphAttributeGraphSwiftUICore、AttributeGraph
RIOPxrSdfLayerRef 等 9 个去掉 RefCoreRealityIORealityIO
CAXUIElementRefCAXUIElementCoreAccessibilityCoreAccessibility(自己)
CFPhoneNumberRefCFPhoneNumberCorePhoneNumbersIDSFoundation
LSASNRefLSASNLaunchServicesGamePolicyFoundation
CFXGPUDeviceRef、LXEntryRef、RTIImportOperation_t…找不到VFX 等
+
+
+ +
+

调研

+
+ 十条查证过的事实 +
+
    +
  1. CF 类导入成 ForeignKind::CFType 的类并合成 _CFObject;描述符种类 class,import info 写着 N<typedef 名> 与 St。
  2. +
  3. 模块不在二进制里;Swift 取顶层 Clang 模块。
  4. +
  5. GetTypeID 的镜像就是模块:46 个公开 CF 类全部一致。
  6. +
  7. 打印器在模块解析出来以后已经会用描述符的名字。
  8. +
  9. swift-type-indexing 已有 DeclaredTypeNameSource 注册表;TypeDatabase 按镜像路径去重,同一路径的第二个来源被丢掉(实现时由端到端测试发现)。
  10. +
  11. 去 Ref 规则只认 SDK 里有的名字,私有类型走描述符名(AGGraphRef → Graph)。
  12. +
  13. provider 只读直接依赖;RuntimeViewer 自己给每个镜像登记来源。
  14. +
  15. 按设计 20 个里覆盖 15 个;实测覆盖更多(有描述符但没有一致性记录的也算上)。
  16. +
  17. 带 Ref 的拼写在 Swift 里不能用;IOSurfaceRef 因为和 ObjC 类 IOSurface 重名而保留 Ref。
  18. +
  19. IOSurfaceRef 疑似问题未复现:TextRecognition 印 CoreGraphics.IOSurfaceRef,能编过;IOSurface.IOSurfaceRef 因模块名被同名类遮住编不过,要写 IOSurface::IOSurfaceRef。
  20. +
+
+
+
+ +
+

替代方案

+
+ 七条被否或推迟的方向 +
+
    +
  1. 打印器上另注册一个 ModuleNameResolving:否,注册表已经在 swift-type-indexing。
  2. +
  3. 让 swift-type-indexing 自己读导出表:否,那个包按设计不读 Mach-O。
  4. +
  5. 从 CF 运行时类注册取名字:否,要反汇编调用点,结果与导出表等价。
  6. +
  7. 用一致性符号里的模块:否,那是声明一致性的模块。
  8. +
  9. 让去 Ref 规则也认运行时名表:否,会改错 IOSurfaceRef 与 Graph。
  10. +
  11. 跟着重新导出算进伞框架:推迟。
  12. +
  13. 让 swift-type-indexing 允许一个镜像路径登记多个来源:否,本提案不改那个包。
  14. +
+
+
+
+ +
+

影响

+
    +
  • 源码兼容性:纯新增两个公开类型,provider 的公开接口不变;--resolve-c-module-names 下私有 CF 类型带上模块。
  • +
  • ABI:不适用,SPM 源码分发。
  • +
  • 下游:InterfaceRequest 自动受益;RuntimeViewer 发版后把 ObjCDeclaredTypeNames 换成 ImageDeclaredTypeNames 才受益。
  • +
  • API 演进:没有被替代的旧 API,按 minor 版本发布。
  • +
+
+ +
+

落地步骤

+
    +
  1. 提案落盘、登记索引 ✅
  2. +
  3. CFDeclaredTypeNames 与测试 ✅:fileNamesTheTypedefOfEveryExportedTypeIDFunction、loadedImageNamesTheSameTypedefs、coreSVGDeclaresItsPrivateDocumentType
  4. +
  5. 合成来源、provider 登记、端到端验证 ✅:listsTheObjectiveCClassAndTheCFTypeOfOneImage、aPrivateCFTypePrintsUnderTheImageExportingItsTypeID、aCFTypeTheRootDefinesPrintsUnderTheRootsModule、aBridgedTypeWithoutATypeIDFunctionKeepsItsBareSwiftName、aGetTypeIDExportDoesNotClaimATypedefThatIsNoCFClass、withoutTheProviderAPrivateCFTypeKeepsItsBareSwiftName
  6. +
  7. 文档与系统镜像验证 ✅:
  8. +
+
+ + + + + + + + +
镜像改动前后不同的行新增的模块限定改动后耗时
SwiftUICore300AttributeGraph.Subgraph 134、AttributeGraph.Graph 13、CoreSVG.CGSVGDocument 717.28 秒(改动前 17.22)
AppKit16CoreGraphics.CGColorTransform 4、CGContextDelegate 3、CGDisplayList 18.17 秒
RealityIO976CoreRealityIO.RIOPxrUsdObject 等二十多种2.24 秒
TextRecognition0无2.62 秒
+
+
+ +
+

决策日志

+
+ 11 条,最近一条:Implemented,落地编号 0108 +
+
+ + + + + + + + + + + + + + + +
日期变更说明
2026-11-25Created as DraftSwift 名 0106 已从描述符取得,缺的是模块;GetTypeID 定位模块,46 个公开类型验证全对。
2026-11-25形式是 DeclaredTypeNameSource用户设想的开放注册表已经存在;用户确认。
2026-11-25IOSurfaceRef 疑似问题先复现用户定:先复现,不并入本提案。
2026-11-25用户批准,开始实现功能分支从本地 next 切。
2026-11-25测试都放在公开 seam 上命名规则与来源顺序都经公开接口测。
2026-11-25新增 ImageDeclaredTypeNames偏离原方案:TypeDatabase 按镜像路径去重,分开登记的 CF 来源被丢掉。
2026-11-25加 foreign 描述符闸门用户指出判断 CF 类型要靠 foreign metadata;诱饵测试加闸前红、加闸后绿。
2026-11-25不导出 GetTypeID 的桥接类型印裸名应用户要求实测并写成测试。
2026-11-25IOSurfaceRef 疑似问题未复现印 CoreGraphics.IOSurfaceRef,能编过;模块选择器问题记为后续项。
2026-11-25不改成遍历导出 trie耗时测不出差别。
2026-11-25Implemented,落地编号 0108合进 next 并推送;演进账本第 154 节;后续项见「要你定」。
+
+
+
+
+ +
+
+ + diff --git a/Documentations/Evolutions/0108-private-cf-type-modules.md b/Documentations/Evolutions/0108-private-cf-type-modules.md new file mode 100644 index 000000000..20a804ebf --- /dev/null +++ b/Documentations/Evolutions/0108-private-cf-type-modules.md @@ -0,0 +1,331 @@ +# 0108 - 私有 CF 类型按导出 `GetTypeID` 的镜像解析所属模块 + +- **状态**: Implemented +- **作者**: JH +- **创建日期**: 2026-11-25 +- **最后更新**: 2026-11-25 +- **所属愿景**: 无 +- **关联提案**: [0105 swift-type-indexing-package](0105-swift-type-indexing-package.md)(`__C` 类型按 SDK 解析模块,`DeclaredTypeNameSource` 就是它定下的接口);[0106 c-imported-type-name-spelling](0106-c-imported-type-name-spelling.md)(引用处改用描述符给的 Swift 名,本提案补上它缺的模块) +- **实现分支 / PR**: `feature/private-cf-type-modules`,2026-11-25 合进 `next`(worktree 与分支已删)。开工时叠在本地 `next` 上:那里有 `feature/moved-swift-type-modules` 的本地合并、尚未推到 `origin/next`,它同样改了 `SwiftInterfaceBuilderTypeNameProvider.swift` +- **配套文档**: 待定 —— 落地时登记实现说明 / 使用指南的链接 +- **网页版**: 同目录同名的 `.html` +- **涉及仓库**: 只有 MachOSwiftSection。RuntimeViewer 自己登记类型名来源,要它也受益需要一行后续改动(见「非目标」) + +## 摘要 + +`swift-section interface --resolve-c-module-names` 能把公开的 C 导入类型写到真实模块下(`__C.CGColorRef` → `CoreGraphics.CGColor`),私有的 CF 类型却查不到模块:SDK 里没有它们的头文件,依赖镜像的 Objective-C 元数据也不列 CF 类型,于是按 0106 的规则只印描述符给的裸名(`CGSVGDocument`)。本提案在 `SwiftTypeNameResolution` 里新增 `CFDeclaredTypeNames`,它是 swift-type-indexing 的 `DeclaredTypeNameSource` 的又一个实现:从镜像的导出表里找出每个 `…GetTypeID` 函数,列出它定义的 CF 类型(`_CGSVGDocumentGetTypeID` → `CGSVGDocumentRef`)。`SwiftInterfaceBuilderTypeNameProvider` 为根镜像登记它;每个直接依赖改登记新的 `ImageDeclaredTypeNames`,把这个镜像的 Objective-C 名字和 CF 类型合成一个来源,因为 `TypeDatabase` 每个镜像路径只收一个来源。`GetTypeID` 只负责定位:一个名字是不是 CF 类型,由根镜像自己的 foreign class 描述符决定,CF 来源只给出被它证实的名字。之后 `CGSVGDocumentRef` 归到 CoreSVG,引用印成 `CoreSVG.CGSVGDocument`。打印器、swift-type-indexing 和 CLI 参数都不改。 + +## 动机 + +**现象**(按代码推断,没有实跑 CLI):macOS 27.2 的 SwiftUICore 用到私有的 `CGSVGDocumentRef`。0106 之后,`interface --resolve-c-module-names` 把它的引用印成 `CGSVGDocument`,没有模块;公开的 `CGImageRef` 则印成 `CoreGraphics.CGImage`。同一份接口里,读者分不出 `CGSVGDocument` 来自哪个框架,也无从知道它和另一个镜像里同名的类型是不是同一个。 + +**规模**:macOS 27.2 的 dyld shared cache 里,被 Swift 代码用到的 CF 类一共 66 个,其中 20 个不在公开 SDK 的头文件里(测法见「前期调研」第 1 条): + +| 私有 CF 类型(typedef 名) | 描述符里的 Swift 名 | 导出 `GetTypeID` 的镜像 | 用到它的 Swift 镜像 | +|---|---|---|---| +| `CGSVGDocumentRef` | `CGSVGDocument` | CoreSVG | SwiftUICore | +| `CGColorTransformRef`、`CGContextDelegateRef` | 去掉 `Ref` | CoreGraphics | AppKit | +| `AGGraphRef`、`AGSubgraphRef` | `Graph`、`Subgraph` | AttributeGraph | SwiftUICore、AttributeGraph | +| `RIOPxrSdfLayerRef` 等 9 个 `RIO…Ref` | 去掉 `Ref` | CoreRealityIO | RealityIO | +| `CAXUIElementRef` | `CAXUIElement` | CoreAccessibility | CoreAccessibility(自己) | +| `CFPhoneNumberRef` | `CFPhoneNumber` | CorePhoneNumbers | IDSFoundation | +| `LSASNRef` | `LSASN` | LaunchServices(导出名 `__LSASNGetTypeID`) | GamePolicyFoundation | +| `CFXGPUDeviceRef`、`LXEntryRef`、`RTIImportOperation_t` | `CFXGPUDevice`、`LXEntry`、`ImportOperation` | 找不到 | VFX、ImageGenerationServices、_USDKit_RealityKit | + +这些类型的 Swift 名 0106 已经能从描述符里读出来,缺的只有模块。模块不在二进制里(第 2 条),但定义 CF 类型的框架几乎都会导出一个 `<名字>GetTypeID` 函数,用公开类型验证,这个对应关系 46 个全对(第 3 条)。 + +## 前期调研 + +1. **哪些是 CF 类,怎么枚举。** ClangImporter 把指向带 `objc_bridge` / `objc_bridge_mutable` / `objc_bridge_related` 的 struct 的指针 typedef 当作 CF 类型(`swift/lib/ClangImporter/CFTypeInfo.cpp:75-78`),导入成 `ForeignKind::CFType` 的类,并合成一条 `_CFObject` 一致性(`swift/lib/ClangImporter/ImportDecl.cpp` 的 `importCFClassType`,`addSynthesizedProtocolAttrs(theClass, {KnownProtocolKind::CFObject})`)。它的类型描述符种类是 class,名字后的 import info 写着 `N` 和 `St`(来自 C typedef,`swift/include/swift/ABI/TypeIdentity.h:41-55`、`swift/lib/IRGen/GenMeta.cpp:1585-1608`)。dyld 在 cache 里预存了所有 `__C` 类型一致性的表,`ipsw dyld swift --foreign ` 能导出,键是「typedef 名 + `St`」;按协议 `_$s14CoreFoundation9_CFObjectMp` 筛出的就是被 Swift 用过的全部 CF 类。macOS 27.2:66 个,20 个私有(「动机」那张表),46 个公开。 +2. **模块不在二进制里。** CF 类的描述符挂在 `__C` 模块下,`_CFObject` 等合成的一致性在 `__C_Synthesized`(mangling 里的 `SC`),都不带真实模块。Swift 给一个 Clang 声明定模块时取的是**顶层** Clang 模块(`swift/lib/ClangImporter/ClangImporter.cpp:3143-3154`,注释写明 submodule 没有自己的 `ClangModuleUnit`),所以 LaunchServices 里的类型在 Swift 里属于 CoreServices(SDK 的 `CoreServices.framework/Modules/module.modulemap:43` 把 LaunchServices 声明成 CoreServices 的 submodule)。 +3. **`GetTypeID` 的镜像就是模块。** 对 46 个公开 CF 类逐个查 `_<去掉 Ref 的名字>GetTypeID` 由 cache 里哪个镜像导出(`ipsw dyld symaddr`),再和 SDK 里声明它的框架比,46 个全部一致;其中 `IOSurfaceRef` 在 CoreGraphics 的头文件里有一份前向声明,真正的声明在 IOSurface,导出镜像也是 IOSurface。私有的 20 个里有 17 个能这样找到镜像,`CFXGPUDeviceRef`、`LXEntryRef`、`RTIImportOperation_t` 找不到对应的导出。Core* 框架一共导出约 190 个公开 SDK 里没有的 `…GetTypeID`(CoreMedia 75、CoreRealityIO 41、CoreGraphics 23、CoreSVG 16、CoreFoundation 12),并不是每个都对应 Swift 用到的类型。 +4. **打印器在模块解析出来以后已经会用描述符的名字。** 引用处 `TypeNodePrintable.printType`(`Sources/Output/SwiftPrinting/NodePrintables/TypeNodePrintable.swift:186-268`):模块经 `resolvedModuleName(of:siblingIdentifier:)`(`NodePrintable.swift:186-196`,先按 C 名查,再按去掉 `Ref` 的名字查)解析;标识符依次取解析器的 `swiftName(forCName:category:)`、0106 名字表里描述符给的名字、C 名。声明行 `declaredTypeName(of:)`(`SwiftDeclarationPrinter+Headers.swift:153-183`)同样在解析器给不出 Swift 名时退回描述符的名字。所以只要模块查得到,私有 CF 类型就会印成 `CoreSVG.CGSVGDocument`,打印器不用改。 +5. **swift-type-indexing 已有开放的注册表。** 0.2.0 的 `DeclaredTypeNameSource`(`Sources/TypeIndexing/DeclaredTypeNameSource.swift`):一个依赖镜像报出它声明的类型名,`TypeDatabase.moduleName(forTypeName:)` 只在模块接口和 API notes 都没有这个名字时,才按登记顺序一个个读这些来源,第一个声明了它的镜像胜出,模块名取自 `TypeDatabase.moduleName(forImagePath:)`(镜像文件名去掉扩展名与 `libswift` 前缀)。文档写明这个包自己不读 Mach-O。MachOObjCSection 0.8.209 的 `ObjCDeclaredTypeNames`(`Sources/ObjCTypeIndexing/ObjCDeclaredTypeNames.swift`)是现在唯一的实现,报出类、协议、struct 和 union 名,不含 CF 类型。`TypeDatabase.register(dependencies:)` 按镜像路径去重(`Sources/TypeIndexing/TypeDatabase.swift:237-243`):同一路径的第二个来源直接丢掉,所以一个镜像的几种名字必须放进同一个来源。这一条是实现时由端到端测试发现的,见决策日志。 +6. **TypeDatabase 的 CF 去 `Ref` 规则只认 SDK 里有的名字。** `TypeDatabase.swiftName(forCName:category:)` 在 API notes 没有改名时,只有去掉 `Ref` 的名字出现在模块接口或 API notes 的归属表里才返回它,运行时登记的名字不算。私有 CF 类型因此拿不到解析器给的 Swift 名,走第 4 条里描述符那一档,`AGGraphRef` 正确地印成 `Graph` 而不是 `AGGraph`。 +7. **现在谁被登记。** `SwiftInterfaceBuilderTypeNameProvider.setup()`(`Sources/Output/SwiftTypeNameResolution/SwiftInterfaceBuilderTypeNameProvider.swift:81-98`)只给每个**直接**依赖登记一个 `ObjCDeclaredTypeNames`,根镜像自己不登记。只取直接依赖是有意的(`Sources/Output/SwiftInterface/SwiftInterfaceBuilderDependencies.swift:9-19`:每个依赖模块都要生成一份 SourceKit 接口,传递闭包有几百个镜像)。CLI 里只有 `interface --resolve-c-module-names` 会接上它(`Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift:273-320`),依赖按本机 dyld cache 解析。RuntimeViewer 不经这个 provider,它在 `RuntimeViewerCore/Sources/RuntimeViewerCore/Sections/Swift/RuntimeSwiftSection.swift:2013` 给自己打开的每个镜像登记一个 `ObjCDeclaredTypeNames`。 +8. **按这个设计能覆盖多少。** 对「动机」表里的 20 个查使用方的直接依赖(`dyld_info -dependents`):CoreSVG、CoreGraphics、AttributeGraph、CoreRealityIO 都是使用方的直接依赖,覆盖 14 个;`CAXUIElementRef` 由使用方自己定义,登记根镜像后覆盖,共 15 个。剩下 5 个:`LSASNRef` 的导出在 LaunchServices,使用方只直接链接重新导出它的 CoreServices;`CFPhoneNumberRef` 的 CorePhoneNumbers 不是 IDSFoundation 的直接依赖;另外 3 个没有对应的导出。 +9. **带 `Ref` 的名字在 Swift 里不能用。** ClangImporter 只在 Swift 3 及以后的名字里去掉 `Ref`(`swift/lib/ClangImporter/ImportName.cpp:2269-2277` 的 `swift3OrLaterName`),带 `Ref` 的拼写只剩一个改名用的兼容别名。所以一个私有 CF 类型如果在本镜像里没有描述符(只出现在符号签名里),即使模块解析出来,也只能印成 `CoreSVG.CGSVGDocumentRef`,能读懂,但不是能编译的写法;加了 foreign 描述符闸门以后(提议方案第 3 条),这种引用不再认领模块,保持 `__C.CGSVGDocumentRef`。去掉 `Ref` 时还要避开重名:`IOSurfaceRef` 的描述符名字就是 `IOSurfaceRef`,因为 IOSurface 里已有同名的 Objective-C 类 `IOSurface`(`hasNamingConflict`)。 +10. **顺带怀疑过、复现后没有出现**:曾推测第 6 条的去 `Ref` 规则不看重名,会把 `__C.IOSurfaceRef` 印成 `IOSurface.IOSurface`。在 Ultra 上对直接链接 IOSurface、用到 `IOSurfaceRef` 的 TextRecognition 跑 `interface --resolve-c-module-names`,改动前后都印成 `CoreGraphics.IOSurfaceRef`(9 处),名字没被改。模块落在 CoreGraphics,是因为 CoreGraphics 的头文件里也有一份 `IOSurfaceRef` 的 typedef;swiftc 6.4.2 探针确认 `CoreGraphics.IOSurfaceRef` 能编过。同一探针还确认 `IOSurface.IOSurfaceRef` 与 `IOSurface.IOSurface` 都编不过(模块名 `IOSurface` 被同名的 Objective-C 类遮住,报 `'IOSurfaceRef' is not a member type of class 'IOSurface.IOSurface'`),要写成模块选择器 `IOSurface::IOSurfaceRef`、`IOSurface::IOSurface`;`--module-selectors` 下 TextRecognition 印成 `CoreGraphics::IOSurfaceRef`。后者是打印器在「模块名与它里面的类型同名」时的通用问题,不属于本提案。 + +## 提议方案 + +1. **新增 `CFDeclaredTypeNames`**(`Sources/Output/SwiftTypeNameResolution/`),实现 `DeclaredTypeNameSource`,与 `ObjCDeclaredTypeNames` 同形:`init(machO:imagePath:)`,`declaredTypeNames()` 读 `machO.exportedSymbols`,每个名为 `_<名字>GetTypeID` 的导出给出 `<名字>Ref`;`<名字>` 以下划线开头的私有函数(`__LSASNGetTypeID`)同时给出去掉前导下划线的拼写(`LSASNRef`)。 +2. **新增 `ImageDeclaredTypeNames`**(同一目录),也实现 `DeclaredTypeNameSource`:一个镜像的 `ObjCDeclaredTypeNames` 名字在前、`CFDeclaredTypeNames` 名字在后,合成一个来源。`TypeDatabase` 每个镜像路径只收第一个来源(调研第 5 条),把两种来源分开登记,后登记的那个永远读不到。 +3. **provider 登记它们**:`setup()` 交给 `TypeDatabase.index(dependencies:moduleFilter:)` 的来源变成「根镜像的 `CFDeclaredTypeNames`,然后每个直接依赖一个 `ImageDeclaredTypeNames`」,取代原来每个依赖一个 `ObjCDeclaredTypeNames`。根镜像排第一,因为它自己定义的类型由它自己说了算;根镜像不进 `moduleFilter`,不触发 SourceKit 接口生成,它的 Objective-C 名字照旧不登记。来源的排列抽成一个内部静态函数。**`GetTypeID` 只负责定位,「是不是 CF 类型」由 foreign 描述符决定**:provider 先从根镜像收集 C 导入、从 C typedef 升格来的 class 描述符(ClangImporter 给 CF 类型生成的 foreign class)的 typedef 名,所有 CF 来源只给出这个集合里的名字。这样 `CFGetTypeID` 给出的 `CFRef` 这类非类型名字,以及恰好与某个导出同名的 `swift_wrapper` typedef,都不会被认领。 +4. **打印器、swift-type-indexing、CLI 参数都不改**。效果全部经现有路径体现:`moduleName(forTypeName:)` 多答出一些名字,打印器按调研第 4 条的规则写成 `模块.描述符名`。`--resolve-c-module-names` 的帮助文字和 swift-section skill 的说明补一句来源。 + +### 非目标 + +- **跟着重新导出找子框架**(`LSASNRef` → CoreServices):`ObjCDeclaredTypeNames` 同样不跟重新导出,两种来源应该一起做;MachOKitExtensions 3.3.0 的 `DependencyTraversal` 也只有 `direct` / `transitive`(`DependencyClosure.swift:6-11`)。另开提案。 +- **间接依赖**(`CFPhoneNumberRef`):放宽到传递闭包会让 SourceKit 接口生成回到几百个模块(调研第 7 条)。要做也应该只给运行时来源放宽、不动 `moduleFilter`,另开提案。 +- **没有 `GetTypeID` 导出的类型**(`CFXGPUDeviceRef` 等 3 个),以及非 CF 的私有 C 类型(struct、enum、`swift_wrapper` typedef,如 `AGTreeElement`):二进制里没有可靠的模块证据。 +- **本镜像没有描述符的引用**:foreign 描述符闸门把它挡在外面,仍印 `__C.XRef`(调研第 9 条)。要在没有描述符时也给出模块和 Swift 名,就得让 TypeDatabase 的去 `Ref` 规则认运行时名表,会碰上重名与 `swift_name` 改名(见「替代方案」第 5 条)。 +- **自己定义、却没导出 `GetTypeID` 的 CF 桥接类型**:foreign 描述符能证实它是 CF 类,但没有任何二进制证据说明它属于哪个模块(桥接到哪个类不进二进制),印描述符给的裸名。端到端测试里的 `ProbeLonelyRef` 钉住了这一点。 +- **根镜像自己的 Objective-C 类**:现在也没登记,是另一个问题,本提案不顺手改,免得 ObjC 输出跟着变。 +- **`dump`**:`dump` 不做 `__C` 模块解析,本提案不引入。 +- **RuntimeViewer 接入**:本库发版后,把 `RuntimeSwiftSection.swift:2013` 的 `metadataSources` 里的 `ObjCDeclaredTypeNames` 换成 `ImageDeclaredTypeNames`,属于 RuntimeViewer 的改动。不能另加一个 `CFDeclaredTypeNames`:同一路径的第二个来源会被丢掉。 +- **调研第 10 条的 `IOSurfaceRef` 疑似问题**:先复现,另行修复。 + +## 改动地图 + +| 文件 / 类型 | 动作 | 改什么 | 为什么 | 步骤 | +|---|---|---|---|---| +| `Sources/Output/SwiftTypeNameResolution/CFDeclaredTypeNames.swift` · `CFDeclaredTypeNames` | 新增 | `DeclaredTypeNameSource` 的实现:读导出表,`…GetTypeID` → typedef 名;内部静态函数 `typedefNames(forExportedSymbolName:)` 承载命名规则 | 私有 CF 类型的模块证据 | 1 | +| `Tests/SwiftTypeNameResolutionTests/CFDeclaredTypeNamesTests.swift` | 新增 | 现场编译的 C 动态库经 `MachOFile` 与 `MachOImage` 两种读法读出的名字(覆盖命名规则的各种写法);本机 cache 的 CoreSVG | 规则与两种读法 | 1 | +| `Sources/Output/SwiftTypeNameResolution/ImageDeclaredTypeNames.swift` · `ImageDeclaredTypeNames` | 新增 | 一个镜像的 ObjC 名字与 CF 类型合成一个 `DeclaredTypeNameSource` | `TypeDatabase` 每个镜像路径只收一个来源 | 2 | +| `Tests/SwiftTypeNameResolutionTests/ImageDeclaredTypeNamesTests.swift` | 新增 | IOSurface 一个镜像里同时列出 ObjC 类 `IOSurface` 与 CF 类型 `IOSurfaceRef` | 合成来源两种名字都在 | 2 | +| `Sources/Output/SwiftTypeNameResolution/SwiftInterfaceBuilderTypeNameProvider.swift:81-113` · `setup()` | 修改 | 来源改为「根的 `CFDeclaredTypeNames`,然后每个依赖一个 `ImageDeclaredTypeNames`」;排列抽成 `static func declaredTypeNameSources(root:dependencies:)`(internal) | 登记新来源 | 2 | +| `Tests/SwiftTypeNameResolutionTests/PrivateCFTypeModuleTests.swift` | 新增 | 用现场编译的 C 库与 Swift 库验证接口里的拼写:依赖定义的、根镜像定义的、不挂 provider 时的 | 端到端证明 | 2 | +| `Sources/Executables/swift-section/Commands/InterfaceCommand.swift:33` · `resolveCModuleNames` 的 `help` | 修改 | 来源列表补上「依赖导出的 `…GetTypeID`(CF 类型)」 | `--help` 就是文档 | 3 | +| `AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md` 第 8 节 | 修改 | 「没有 sourcekitd 时由 API notes 与 Objective-C 元数据归属」补上导出的 `GetTypeID`;加一句私有 CF 类型的效果与第 9 条的 `XRef` 退路 | CLI 行为变了,skill 同批更新 | 3 | +| `CLAUDE.md` · SwiftTypeNameResolution 一条 | 修改 | 列出 `CFDeclaredTypeNames` 与 `ImageDeclaredTypeNames` | 模块清单与代码同步 | 3 | +| `Documentations/Evolutions/README.md`、`Documentations/README.md` | 修改 | 登记本提案;落地时改编号与状态 | 文档索引 | 0、3 | +| `Documentations/Internal/ProjectEvolutionLog.md` | 修改 | 落地时追加一节 | 演进账本 | 3 | + +## 架构图 + +改了什么: + +```text +SwiftTypeNameResolution/ ++ CFDeclaredTypeNames DeclaredTypeNameSource ++ declaredTypeNames() machO.exportedSymbols: _GetTypeID -> "Ref" ++ ImageDeclaredTypeNames DeclaredTypeNameSource, one per image ++ declaredTypeNames() ObjCDeclaredTypeNames names + CFDeclaredTypeNames names +~ SwiftInterfaceBuilderTypeNameProvider.setup() ++ cfTypedefNames(referencedBy: root) root's foreign class descriptors -> the CF typedef names it uses ++ every CF source below gives only these names +~ TypeDatabase.index(dependencies: ++ [CFDeclaredTypeNames(root), +- ObjCDeclaredTypeNames(dependency1), ++ ImageDeclaredTypeNames(dependency1), +- ObjCDeclaredTypeNames(dependency2), ++ ImageDeclaredTypeNames(dependency2), ...], + moduleFilter: dependency module names) unchanged: root never generates an interface + +swift-type-indexing 0.2.0 (unchanged) + TypeDatabase.register(dependencies:) keeps the first source per image path + TypeDatabase.moduleName(forTypeName:) + 1. module interfaces, API notes + 2. runtime declared names, folded source by source in registration order + +SwiftPrinting (unchanged) + TypeNodePrintable.printType + module <- moduleName(forTypeName: C name, then Ref-stripped) + identifier <- swiftName(forCName:) ?? descriptor name (0106) ?? C name +``` + +一个引用怎么印出来(SwiftUICore 里的 `__C.CGSVGDocumentRef`): + +```text +printType(__C.CGSVGDocumentRef) +├─ swiftNameFromDescriptor -> "CGSVGDocument" (0106 name table) +├─ resolvedModuleName(__C, "CGSVGDocumentRef") +│ └─ SwiftInterfaceBuilderTypeNameProvider.moduleName +│ └─ TypeDatabase.moduleName +│ ├─ SDK tables miss +│ ├─ CFDeclaredTypeNames(SwiftUICore) miss (+) +│ ├─ ImageDeclaredTypeNames(AttributeGraph) miss (~ was ObjC only) +│ ├─ ... +│ └─ ImageDeclaredTypeNames(CoreSVG): "CGSVGDocumentRef" -> "CoreSVG" (~) +├─ swiftName(forCName: "CGSVGDocumentRef") -> nil (no API notes, not SDK-indexed) +└─ writes CoreSVG . CGSVGDocument +``` + +## 详细设计 + +### API + +```swift +#if os(macOS) + +import MachOKit +import TypeIndexing + +/// The Core Foundation types an image defines, as swift-type-indexing's `TypeDatabase` reads +/// them: one for every `…GetTypeID` function the image exports. +/// +/// A CF type's Swift metadata names the type but never its module — the descriptor sits in +/// `__C` — while the framework defining it exports the type's `GetTypeID` function. This +/// attributes a private CF type such as `CGSVGDocumentRef` to the image exporting +/// `CGSVGDocumentGetTypeID` (`CoreSVG`). `TypeDatabase` consults it only for names neither the +/// SDK's module interfaces nor its API notes attribute, and reads the image's exports only on +/// such a miss. +/// +/// `TypeDatabase` keeps one source per image path, so an image whose Objective-C names are +/// registered too goes in as one `ImageDeclaredTypeNames`, which reads both; this alone is for +/// an image read for its CF types only. +public struct CFDeclaredTypeNames: DeclaredTypeNameSource { + public let imagePath: String + + private let machO: MachO + + /// - Parameters: + /// - machO: The image, in this process or in a file. + /// - imagePath: Its install path, which names the module its types are attributed to + /// (`…/CoreSVG.framework/Versions/A/CoreSVG` → `CoreSVG`). + public init(machO: MachO, imagePath: String) { + self.machO = machO + self.imagePath = imagePath + } + + /// The typedef name of every CF type the image exports a `GetTypeID` function for. + public func declaredTypeNames() async -> [String] { + machO.exportedSymbols.flatMap { exportedSymbol in + Self.typedefNames(forExportedSymbolName: exportedSymbol.name) + } + } + + /// The typedef names an exported symbol implies: `_CGSVGDocumentGetTypeID` → + /// `["CGSVGDocumentRef"]`, the private `__LSASNGetTypeID` → `["_LSASNRef", "LSASNRef"]`, + /// any other symbol → `[]`. + static func typedefNames(forExportedSymbolName symbolName: String) -> [String] +} + +/// Every type an image declares, as one swift-type-indexing source: the classes, protocols, +/// structs and unions its Objective-C metadata names (`ObjCDeclaredTypeNames`), then the CF +/// types it exports a `GetTypeID` function for (`CFDeclaredTypeNames`). +public struct ImageDeclaredTypeNames: DeclaredTypeNameSource { + public let imagePath: String + + public init(machO: MachO, imagePath: String) + + /// The Objective-C names, then the CF typedef names. Throws when the Objective-C metadata + /// cannot be read, as `ObjCDeclaredTypeNames` does on its own: `TypeDatabase` then logs + /// the image and skips it whole. + public func declaredTypeNames() async throws -> [String] +} + +#endif +``` + +`ImageDeclaredTypeNames` 只要 `ObjCMetadataSource` 一个约束:它经 `MachORepresentableWithCache` 继承 `MachORepresentable` 与 `Sendable`,正好满足两种来源。Objective-C 元数据读不出来时整个来源抛错,与只登记 `ObjCDeclaredTypeNames` 时一样,由 `TypeDatabase` 记日志并跳过这个镜像;不为保住 CF 名字而吞掉这个错误。 + +形状照 `ObjCDeclaredTypeNames` 抄:同样的 `init(machO:imagePath:)`、同样的 `imagePath` 属性、同样放在 `#if os(macOS)` 里,名字按「来源 + `DeclaredTypeNames`」对称。泛型约束只要 `MachORepresentable & Sendable`:`exportedSymbols` 是 MachOKit `MachORepresentable` 的要求(`Sources/MachOKit/Protocol/MachORepresentable.swift:124-129`),`MachOFile`、`MachOImage` 和包装类型都有,不需要判断读取器种类。provider 的 `MachO` 约束经 `MachOSwiftSectionRepresentableWithCache: MachORepresentableWithCache: MachORepresentable, Sendable` 满足它。协议要求是 `async throws`,实现不会失败,所以写成不抛错的 `async`。 + +### 命名规则 + +1. 导出名必须以一个 `_` 开头(C 符号的 Mach-O 前缀),去掉它得到 C 函数名;Swift 符号(`_$s…`)和 Objective-C 符号(`_OBJC_…`)因为不以 `GetTypeID` 结尾自然落选。 +2. C 函数名以 `GetTypeID` 结尾,去掉后缀的部分非空、由字母数字和下划线组成、不以数字开头,记为 `base`。 +3. 给出 `base + "Ref"`;`base` 以下划线开头时,再给出去掉全部前导下划线后的 `+ "Ref"`(非空才给)。 +4. 规则本身会产生一些不是类型的名字,例如 `CFGetTypeID` 给出 `CFRef`。provider 登记的来源都带 foreign 描述符闸门(下一节),只给出根镜像证实是 CF 类的名字;公开的 `init(machO:imagePath:)` 不带闸门,给需要全部名字的调用方(RuntimeViewer 那种为整个进程登记镜像、没有单一根镜像的场合)。 + +### 来源的排列 + +```swift +extension SwiftInterfaceBuilderTypeNameProvider { + /// The declared-type-name sources `setup()` registers, in the order `TypeDatabase` folds + /// them: the root's CF types first — a type the root defines is its own — then each direct + /// dependency's Objective-C names and CF types, one `ImageDeclaredTypeNames` per image, in + /// dependency order. + static func declaredTypeNameSources(root: MachO, dependencies: [MachO]) -> [any DeclaredTypeNameSource] + + /// The typedef names of the CF types `image`'s Swift metadata refers to: its C-imported + /// class descriptors promoted from a C typedef — the foreign class ClangImporter makes of a + /// CF type. Named by the ABI name, or by the descriptor's own name when ClangImporter kept + /// the C spelling (`IOSurfaceRef`). + static func cfTypedefNames(referencedBy image: MachO) -> Set +} + +extension CFDeclaredTypeNames { + /// A source giving only the names in `admittedTypedefNames`. + init(machO: MachO, imagePath: String, restrictedTo admittedTypedefNames: Set?) +} + +extension ImageDeclaredTypeNames { + /// A source whose CF part gives only the names in `admittedTypedefNames`. + init(machO: MachO, imagePath: String, restrictingCFTypesTo admittedTypedefNames: Set?) +} +``` + +`setup()` 只把 `dependencies:` 参数换成这个函数的结果,`moduleFilter` 不变。带闸门的两个构造器是 internal:闸门的集合取决于一个根镜像,只有 provider 这种「为一个根镜像登记依赖」的调用方有它;公开接口因此不变。判定只看描述符:种类是 class、`isCImportedContextDescriptor` 为真、import info 的 `isCTypedef` 为真且不是相关实体。只有 CF 类型会被升格成 class 而又来自 C typedef(`swift_wrapper` 给的是 struct / enum,C++ 的 foreign reference type 来自 tag namespace),所以这四条合起来就是「ClangImporter 给 CF 类型生成的 foreign class」。 + +### 性能 + +`TypeDatabase` 只在一个名字查不到时才按顺序读下一个来源,读过的来源不再读。根镜像排第一,所以第一次未命中就会读一遍根镜像的导出表:SwiftUICore 这样的大镜像有数十万个导出,`exportedSymbols` 要建一个同样大的数组。第 3 步在 Ultra 上量了 `interface --resolve-c-module-names` 的耗时:SwiftUICore 热缓存下 17.22 → 17.28 秒,测不出差别,所以不改成直接遍历导出 trie。 + +## 替代方案考量 + +1. **在打印器上新注册一个 `ModuleNameResolving` 解析器**(讨论时最先选的方向,仍在本仓库):否。swift-type-indexing 已经有 `DeclaredTypeNameSource` 这个注册表,「SDK 优先、按依赖顺序折叠、第一个声明者胜出、镜像路径换模块名」都在那里。另写一个解析器要么把这些规则抄一遍,要么和 `TypeDatabase` 对同一个名字给出不同答案,谁胜出取决于注册顺序。RuntimeViewer 也是经 `DeclaredTypeNameSource` 接入的,走同一个接口它只需加一行。 +2. **让 swift-type-indexing 自己读导出表**:否。那个包按设计不读 Mach-O(`DeclaredTypeNameSource.swift` 的文档),读二进制的部分都由实现方提供。 +3. **从 CF 运行时类注册取类型名**(`_CFRuntimeRegisterClass` 的 `CFRuntimeClass.className`):否。要反汇编调用点才能找到参数,得到的仍然只是「哪个镜像定义了它」,和导出表等价;而且 `className` 是 `"CGSVGDocument"` 这样的显示名,不是 mangling 用的 typedef 名。 +4. **用一致性符号里的模块**(`_$sSo10AGGraphRefaSQ14AttributeGraphMc`):否。那是声明这条一致性的模块,不是类型的模块;合成的一致性在 `__C_Synthesized`;cache 里的这类本地符号大多被剥掉了。 +5. **让 TypeDatabase 的去 `Ref` 规则也认运行时名表**,好在没有描述符时也给出 Swift 名:否。它不知道重名,会把 `IOSurfaceRef` 改成 `IOSurface`(调研第 9 条);而打印器先问解析器、后用描述符,它还会把 `swift_name` 改过的 `AGGraphRef` 从 `Graph` 改坏成 `AGGraph`。 +6. **跟着 `LC_REEXPORT_DYLIB` 把子框架的导出算进伞框架**:推迟,见「非目标」第一条。 +7. **让 swift-type-indexing 允许一个镜像路径登记多个来源**(不合成 `ImageDeclaredTypeNames`):否。「一个来源代表一个镜像」是那个包按镜像路径去重时的模型,改它要动 swift-type-indexing 并发版,而本提案定下不改那个包;在本仓库合成一个来源就够了。 + +## 影响 + +### 源码兼容性(source compatibility) + +纯新增:多两个公开类型 `CFDeclaredTypeNames` 与 `ImageDeclaredTypeNames`,`SwiftInterfaceBuilderTypeNameProvider` 的公开接口不变。行为上,`--resolve-c-module-names` 下原本没有模块的私有 CF 类型会带上模块。 + +### ABI 兼容性(条件项) + +不适用 —— 本库以 SPM 源码分发,使用方每次重新编译。 + +### 下游影响 + +- 本仓库:`SwiftSectionKit` 的 `InterfaceRequest` 经 provider 自动受益,不用改代码。没有基线或快照测试开着 `__C` 模块解析(它要 SDK),渲染 A/B 校验不受影响。 +- RuntimeViewer:它不经 provider,自己在 `RuntimeSwiftSection.swift:2013` 登记来源,本提案落地不改变它的输出。要受益,等本库发版后把那里的 `ObjCDeclaredTypeNames` 换成 `ImageDeclaredTypeNames`(见「非目标」)。 +- MachOKitUI、SymbolViewer:不用 `SwiftTypeNameResolution`,不受影响。 + +### 文档与示例 + +`swift-section interface --help` 里 `--resolve-c-module-names` 的说明、swift-section skill 第 8 节、`CLAUDE.md` 的模块清单,都在第 3 步同批更新。 + +## API 演进与废弃策略 + +- 没有被替代的旧 API,不需要废弃期。 +- 纯新增,按 minor 版本发布。 + +## 落地步骤 + +0. **提案落盘、登记索引**(本次)—— 改动地图最后两行中的索引部分 +1. ✅ **`CFDeclaredTypeNames` 与它的测试** —— 改动地图第 1、2 行(`Tests/SwiftTypeNameResolutionTests/CFDeclaredTypeNamesTests.swift`;Ultra,Xcode 26.6,3 个测试通过) + - 行为:`fileNamesTheTypedefOfEveryExportedTypeIDFunction`(`FixtureCompiler` 现场编译的 C 库导出 `ProbeWidgetGetTypeID`、`_ProbeSecretGetTypeID`、`ProbeWidgetCreate`、`GetTypeID`、`__GetTypeID`,经 `MachOFile` 读出的名字恰好是 `ProbeWidgetRef`、`_ProbeSecretRef`、`ProbeSecretRef`) + - 行为:`loadedImageNamesTheSameTypedefs`(同一个库 `dlopen` 后经 `MachOImage` 读出同样的名字) + - 行为:`coreSVGDeclaresItsPrivateDocumentType`(本机 cache 里的 CoreSVG,文件与进程内两种读法都给出 `CGSVGDocumentRef`) +2. ✅ **合成来源、provider 登记新来源,端到端验证** —— 改动地图第 3–6 行(`ImageDeclaredTypeNamesTests.swift`、`PrivateCFTypeModuleTests.swift`;Ultra,Xcode 26.6,`SwiftTypeNameResolutionTests` 13 个测试通过。`aPrivateCFTypePrintsUnderTheImageExportingItsTypeID` 在合成来源之前是红的,见决策日志) + - 行为:`listsTheObjectiveCClassAndTheCFTypeOfOneImage`(本机 cache 的 IOSurface 一个来源里同时有 ObjC 类 `IOSurface` 与 CF 类型 `IOSurfaceRef`) + - 夹具:C 库 `ProbeCF` 导出 `ProbeWidgetGetTypeID`;Swift 库 `ProbeKit` 用桥接头声明两个 `CF_BRIDGED_TYPE(id)` 的 typedef,链接 `ProbeCF`,并用 `@_cdecl` 自己导出 `ProbeGadgetGetTypeID`。`FixtureCompiler` 把 install name 固定成 `@rpath/lib<名字>.dylib`,所以模块名是 `libProbeCF`、`libProbeKit` + - 行为:`aPrivateCFTypePrintsUnderTheImageExportingItsTypeID`(字段类型印成 `libProbeCF.ProbeWidget`) + - 行为:`aCFTypeTheRootDefinesPrintsUnderTheRootsModule`(根镜像自己定义的印成 `libProbeKit.ProbeGadget`) + - 行为:`aBridgedTypeWithoutATypeIDFunctionKeepsItsBareSwiftName`(`ProbeLonelyRef` 只有 `CF_BRIDGED_TYPE(id)`、没有任何镜像导出它的 `GetTypeID`,印裸名 `ProbeLonely`) + - 行为:`aGetTypeIDExportDoesNotClaimATypedefThatIsNoCFClass`(`ProbeCF` 导出 `ProbeDecoyGetTypeID`,`ProbeKit` 的 `ProbeDecoyRef` 却是 `swift_wrapper` 结构体,不被印成 `libProbeCF.ProbeDecoyRef`;加 foreign 描述符闸门之前它是红的) + - 行为:`withoutTheProviderAPrivateCFTypeKeepsItsBareSwiftName`(不挂 provider 时仍是 0106 的 `ProbeWidget`) +3. ✅ **文档与系统镜像验证** —— 改动地图第 7–11 行 + - 在 Ultra(macOS 27.2 26B131,Xcode 26.6 release 构建)上,对本机 cache 的四个镜像各跑一遍 `interface --resolve-c-module-names`,改动前用第 1 步那个提交(provider 还没改)编出的 `swift-section`,改动后用最终提交编出的: + + | 镜像 | 改动前后不同的行 | 新增的模块限定(出现次数) | 改动后耗时 | + |---|---|---|---| + | SwiftUICore | 300 | `AttributeGraph.Subgraph` 134、`AttributeGraph.Graph` 13、`CoreSVG.CGSVGDocument` 7 | 17.28 秒(改动前热缓存 17.22 秒) | + | AppKit | 16 | `CoreGraphics.CGColorTransform` 4、`CoreGraphics.CGContextDelegate` 3、`CoreGraphics.CGDisplayList` 1 | 8.17 秒 | + | RealityIO | 976 | `CoreRealityIO.RIOPxrUsdObject`、`RIOPxrVtValue`、`RIOBuilder…` 等二十多种 | 2.24 秒 | + | TextRecognition | 0 | 无(只用公开的 CF 类型) | 2.62 秒 | + + - 所有变化都是原本没有模块的私有 CF 类型带上了定义它的模块,没有归错的;实际覆盖比「动机」里按一致性表估计的多(AppKit 的 `CGDisplayList`、RealityIO 的 `RIOBuilder…` 一批不在那张表里,它们有描述符但没有一致性记录)。加 foreign 描述符闸门前后,这四个镜像的输出逐字节相同。耗时看 SwiftUICore 的热缓存对比,没有可测出的变化,所以「性能」一节说的「改成遍历导出 trie」不做 + - 测试一律在 Ultra 上跑(公司那台不跑本库的测试),`--filter` 同时带 `--skip IntegrationTests` + +**收尾时必须判断两件事**(判断结果写进决策日志,不允许沉默跳过): + +- **要不要配套专题文章** —— 预计不需要:调用方契约都在 `CFDeclaredTypeNames` 的文档注释里,维护要知道的「为什么只取直接依赖、为什么不认运行时名表去 `Ref`」在本提案里。 +- **有没有引入新术语** —— 预计没有。 + +## 决策日志 + +| 日期 | 变更 | 说明 | +|------|------|------| +| 2026-11-25 | Created as Draft | 起因是想知道 Swift 用到的私有 CF 类能否还原原名(`__C.CGSVGDocumentRef` → `CoreSVG.CGSVGDocument`)。调研发现 Swift 名 0106 已经从描述符取得,缺的是模块;定义 CF 类型的框架都导出 `GetTypeID`,46 个公开类型验证全对。 | +| 2026-11-25 | 实现放在本仓库,形式是 `DeclaredTypeNameSource` | 用户选定放在本仓库、不改 swift-type-indexing。调研发现用户设想的「类型索引开放注册表、各库注册自己的内容」已经以 `DeclaredTypeNameSource` 存在,ObjC 侧就是这样接入的,因此不再另写打印器解析器(替代方案第 1 条)。用户确认这个形式。 | +| 2026-11-25 | `IOSurfaceRef` 疑似问题先复现 | 用户定:先在 Ultra 上复现调研第 10 条,确认是真的再按 bug 修复另走一批,不并入本提案。 | +| 2026-11-25 | 用户批准,开始实现 | 轻量档,用户看过简报后批准。功能分支从本地 `next` 切,因为 moved-swift-type-modules 的本地合并也改了 provider 的 `setup()`,从 `origin/next` 切会在合回时冲突。 | +| 2026-11-25 | 测试都放在公开 seam 上 | 命名规则不单独测内部静态函数,改由现场编译的 C 库的导出覆盖各种写法;来源顺序不单独测内部函数,改由端到端测试证明根镜像与依赖各自归属。`declaredTypeNameSources(root:dependencies:)` 仍按设计抽成内部静态函数。 | +| 2026-11-25 | 新增 `ImageDeclaredTypeNames`,一个依赖只登记一个来源 | 偏离原方案。端到端测试发现依赖定义的私有 CF 类型仍印裸名:`TypeDatabase.register(dependencies:)` 按镜像路径去重,同一依赖先登记的 `ObjCDeclaredTypeNames` 占了位置,随后的 `CFDeclaredTypeNames` 被丢掉;根镜像只有一个来源,所以那条通过了。改为每个依赖登记一个合成两种名字的 `ImageDeclaredTypeNames`,方案方向不变,多一个纯新增的公开类型;RuntimeViewer 的后续接入也要用它。 | +| 2026-11-25 | 加 foreign 描述符闸门 | 用户指出判断「是不是 CF 类型」要靠 foreign metadata 才可靠。改为:`GetTypeID` 只负责定位,provider 先从根镜像的 foreign class 描述符(C 导入、从 C typedef 升格来的 class)收集 CF typedef 名,CF 来源只给出这些名字。诱饵测试 `aGetTypeIDExportDoesNotClaimATypedefThatIsNoCFClass` 加闸前红、加闸后绿。代价是本镜像没有描述符的引用不再认领模块,保持 `__C.XRef`(原来会印成不能编译的 `模块.XRef`)。带闸门的构造器是 internal,公开接口不变。 | +| 2026-11-25 | 自己定义、不导出 `GetTypeID` 的 CF 桥接类型印裸名 | 应用户要求实测:`ProbeLonelyRef` 只有 `CF_BRIDGED_TYPE(id)`,foreign 描述符证实它是 CF 类,但没有模块证据,印 `ProbeLonely`。写成测试钉住,列入非目标。 | +| 2026-11-25 | `IOSurfaceRef` 疑似问题未复现 | TextRecognition 改动前后都印 `CoreGraphics.IOSurfaceRef`,能编过;没有被改成 `IOSurface`。复现中确认的另一件事——`IOSurface.IOSurfaceRef` / `IOSurface.IOSurface` 因模块名被同名类遮住而编不过、要用 `IOSurface::…`——是打印器的通用拼写问题,记为后续项。 | +| 2026-11-25 | 不改成遍历导出 trie | 第 3 步实测 SwiftUICore 热缓存下耗时 17.22 → 17.28 秒,`exportedSymbols` 的开销测不出来。 | +| 2026-11-25 | 全量测试通过 | Ultra(macOS 27.2,Xcode 26.6),`swift test --skip IntegrationTests`:2978 个测试、563 个套件全部通过,退出码 0。 | +| 2026-11-25 | 实现完成,待用户看过后收尾 | 文档判断:CLI 帮助文字、swift-section skill、`CLAUDE.md` 模块清单、两处索引已同批更新;不写单独的使用指南或实现说明,调用方契约在两个类型的文档注释里,「为什么一个镜像只登记一个来源、为什么判定靠 foreign 描述符」记在本提案;没有新术语。演进账本一节留到正式收尾。 | +| 2026-11-25 | Implemented,落地编号 0108 | 合进 `next` 并推送(同一次推送带上了先在本地收尾的 0107);演进账本第 154 节。后续项:RuntimeViewer 接入(发版后把 `ObjCDeclaredTypeNames` 换成 `ImageDeclaredTypeNames`)、模块名与它里面的类型同名时改用模块选择器(`IOSurface::IOSurfaceRef`)、跟着重新导出找子框架、给运行时来源放宽到间接依赖。 | diff --git a/Documentations/Evolutions/0109-consistent-c-imported-type-spelling.html b/Documentations/Evolutions/0109-consistent-c-imported-type-spelling.html new file mode 100644 index 000000000..b656bc627 --- /dev/null +++ b/Documentations/Evolutions/0109-consistent-c-imported-type-spelling.html @@ -0,0 +1,422 @@ + + + + + + +0109 - C 导入类型的拼写补齐:同名类型去掉 __C,布局注释跟着打印器的拼写 + + + + +
+ +
+

MachOSwiftSectionEvolutions0109

+

0109 C 导入类型的拼写补齐:同名类型去掉 __C,布局注释跟着打印器的拼写

+
+
状态
Implemented
+
最后更新
2026-11-26
+
项目类型
库
+
原文
0109-consistent-c-imported-type-spelling.md
+
+
+ + + +
+ +
+

摘要

+

0106 让改了名的 C 导入类型在声明、成员类型和扩展头里一律写 Swift 名,但还剩两处混用。第一处:镜像里有 descriptor、Swift 名与 C 名相同的类型,声明行写裸名 struct AGDescriptionOption,引用和扩展头却写 __C::AGDescriptionOption。第二处:字段布局注释(展开的嵌套字段偏移树)用固定的 .default 选项印类型名,var base: AnyWeakAttribute 下面的注释写着 identifier (__C.AGAttribute),也不带模块选择器和 any。

+

本提案让名字表把「没有 ABI 名」的 descriptor 也收进来——编译器只在两个名字不同时才写 ABI 名,所以这样的 descriptor 证明了 Swift 名就是 C 名——引用处因此写裸名;再让 interface 路径的布局注释经打印器自己的类型拼写印类型名,离线(MachOFile)与进程内(MachOImage)两条后端一起改,dump 不变。镜像里没有 descriptor 的类型照旧写 __C::,跨镜像查找另开提案。

+
+

动机里的复现

+

用户打 macOS 27.2 的 AttributeGraph(显示 C 导入类型、注册 SwiftInterfaceBuilderTypeNameProvider、模块选择器、展开字段偏移),同一个类型出现两种写法:struct AGDescriptionOption { 的扩展头是 extension __C::AGDescriptionOption: @retroactive Swift::RawRepresentable;var base: AnyWeakAttribute 下面的注释写 identifier (__C.AGAttribute)、rawValue (Swift.UInt32),而整份输出开着模块选择器。用户确认只做二进制能证明的部分。

+
+
+ +
+

架构图

+
    +
  • 新增
  • +
  • 修改
  • +
  • 不变
  • +
+
+ + + SwiftPrinting + CImportedTypeSwiftNameTable+ knownSwiftName(ofDescriptorNamed:…)no ABI name, directly in __C → descriptor name + SwiftDeclarationPrinter.modelFieldBlock + TypeNodePrintable.printType / typeDemangleResolver + + + SwiftDeclarationRendering + DeclarationRenderConfiguration+ spellsFieldLayoutTypeNamesThroughResolver+ fieldLayoutTypeName(printedName:typeNode:) async + StaticFieldLayoutBackendtree rendering sync → async + RuntimeFieldLayoutBackend+ nestedTypeNode, walk sync → async + NestedFieldOffsetLevel rows+ typeNode: Node? (process-wide memo) + + + SwiftLayout + NestedFieldOffsettypeName (.default, cycle key) + typeNode: Node? + + + + + interface printer: renderConfiguration.demangleResolver = typeDemangleResolver; spellingFieldLayoutTypeNamesThroughResolver(true) + each row: await fieldLayoutTypeName(printedName: row.typeName, typeNode: row.typeNode) + flag on and node present → resolver spelling (AnyAttribute, Swift::UInt32); otherwise → printedName (dump: __C.AGAttribute) + +
+

名字表多收同名条目;布局注释的两条后端经同一个入口按打印器的拼写取每一行的类型名。

+
+ +
+

改动地图

+
+ + + + + + + + + + + + + + + + + +
文件 / 类型动作改什么为什么步骤
SwiftPrinting/CImportedTypeSwiftNameTable.swift修改init 求每个 C 导入 descriptor 的已知 Swift 名;新增 knownSwiftName(…);trustsUserFacingName 语义不变同名类型进表,引用写裸名1
SwiftPrinting/CImportedTypeNameSpelling.swift、TypeNodePrintable.swift修改文档与注释跟上行为1
swift-section/Commands/InterfaceCommand.swift修改--c-imported-type-name-spelling 帮助补同名类型与布局注释CLI 帮助即文档1、3
AgentPlugins/…/swift-section-cli/SKILL.md修改第 8 节:同名类型、何时保留 __C.、布局注释与 dump 的区别CLI 输出变了1、3
Tests/SwiftInterfaceTests/CImportedTypeNameSpellingTests.swift修改fixture 加 ProbePlainValue、ProbeOption、PlainBox;三步的行为测试回归1–3
CImportedTypeConformanceInterfaceTests.swift、interface 快照修改__C.ProbeMode → ProbeMode;快照 __C.CMTime → CMTime同名类型不再带 __C.1
SwiftLayout/NestedFieldOffsetTree.swift · NestedFieldOffset修改新增 public let typeNode: Node?渲染层拿节点按打印器拼写2
DeclarationRenderConfiguration.swift修改开关、修饰方法、fieldLayoutTypeName(printedName:typeNode:)两条后端共用入口2
StaticFieldLayoutBackend.swift修改树渲染改 async,每行经入口取名字离线路径2
SwiftDeclarationPrinter+Headers.swift · modelFieldBlock修改打开开关interface 用自己的拼写2
NestedFieldOffsetLevel.swift、RuntimeFieldLayoutBackend.swift修改缓存行带节点;nestedTypeNode;遍历改 async进程内路径,与离线逐行一致3
NestedFieldOffsetMemoizationTests.swift、SpecializedRuntimeTypeNameTests.swift修改开关打开的冷热缓存对照;注释期望改成声明拼写回归3
术语表、SwiftLayout 模块文档、FieldLayoutRendererReaderSpecialization.md、演进账本、ReviewAdjudications.md(A86–A91)、提案索引修改同批文档文档与代码同批0、4
+
+
+ +
+

提议方案

+

1. 名字表收「没有 ABI 名」的条目

+
    +
  • 不是相关实体、没有 ABI 名(含完全没有 import info)、且直接位于 __C / __C_Synthesized 下 → descriptor 的名字就是 Swift 名,收进表;
  • +
  • 有 ABI 名 → 照旧,trustsUserFacingName 采信才收;相关实体不收;import info 读不出来不收。
  • +
  • printType 不用改;声明行与 marksCImportedTypeNames 标注都不变;嵌在 C 类型里的类型不收。
  • +
+

2. 布局注释经打印器的拼写印类型名

+
    +
  • NestedFieldOffset 与进程内缓存的行多存 typeNode;typeName 保持 .default,仍是防环键与 dump 的拼写。
  • +
  • 渲染配置加包级开关 spellsFieldLayoutTypeNamesThroughResolver 与异步方法 fieldLayoutTypeName(printedName:typeNode:);interface 打印器打开,dump 不开。
  • +
  • 两条后端渲染树改成异步;树的形状、isLast、防环与深度判断、#log 告警不动。
  • +
+

于是注释的类型名与声明写法一致:.swiftName 下是 AnyAttribute,.cName 下是 __C.AGAttribute;开了模块选择器写 Swift::UInt32;存在类型带 any;语法糖(Swift.Int?);私有类型不带判别符、局部类型只写名字——都和声明一样。

+
+

没有询问就采用的假设

+
    +
  • 范围取字面最小:只补 0106 留下的两处,改名但不可信的类型不碰。
  • +
  • 「没有 ABI 名 = Swift 名就是 C 名」依据 IRGen 的 computeIdentity;唯一会错的是 C 名不带前缀、又被导入成成员的类型,没见过实例。
  • +
  • dump 不跟着改;进程内缓存存节点;开关放在渲染配置里,不按 DemangleResolver 的 case 判断。
  • +
+
+

非目标

+
    +
  • 镜像里没有 descriptor 的类型(AGValueOptions、AGSubgraphRef)保留 __C::;跨镜像查找另开提案。
  • +
  • 改名但不可信的条目(TreeValue、Signature、ValueFlags);@retroactive;dump 的任何输出与 diff / snapshot / evolution 的键;枚举布局等其它注释。
  • +
+
+ +
+

详细设计

+
+ 名字表与渲染配置的签名 +
+
static func knownSwiftName(ofDescriptorNamed userFacingName: String, importInfo: TypeImportInfo?, isDirectlyInImportedModule: Bool) -> String?
+
+@Init(.ignore)
+package var spellsFieldLayoutTypeNamesThroughResolver: Bool = false
+package func spellingFieldLayoutTypeNamesThroughResolver(_ spellsThroughResolver: Bool) -> Self
+package func fieldLayoutTypeName(printedName: String, typeNode: Node?) async -> String
+
+public let typeNode: Node?   // NestedFieldOffset, NestedFieldOffsetLevel rows
+

解析失败或得到空串时退回 printedName,一行注释不会因此消失。名字表先按 import info 排除相关实体与不可信改名,再 demangle 进表的条目。

+
+
+
+ 两条后端 +
+

离线:expandedFieldOffsets(for:baseOffset:) 与 renderNestedFieldOffsetTree(_:ancestors:) 改成 async,每行先 await configuration.fieldLayoutTypeName(…),再套进 async 版 commentRegion 递归子行。

+

进程内:walkNestedExpandedFieldOffsets 改成 async;建层时 nestedTypeNode(for:parentMetadata:) 求一次节点,存进行里,typeName 由同一个节点 .default 印出,与改前派生相同。

+
+
+
+ +
+

调研

+
+ 9 条前期调研 +
+
    +
  1. 名字表原先只收改了名、可信的条目;printType 只在表里有答案、模块没解析出来时写裸名。
  2. +
  3. 声明行本来就用 descriptor 的名字,同名类型的声明是裸名;扩展头经 typeDemangleResolver。
  4. +
  5. IRGen computeIdentity 只在 Swift 名与 Clang 名不同时写 ABI 名。
  6. +
  7. AttributeGraph:AGDescriptionOption 没有 ABI 名;AGTreeValue → TreeValue、AGTypeSignature → Signature 不可信;16 个只在签名里出现的类型在 AG 里没有 descriptor。
  8. +
  9. 布局注释的类型名在离线与进程内都用 .default 印,也是防环键与 transformer 模板的输入。
  10. +
  11. interface 路径的渲染配置拿着打印器的 typeDemangleResolver,这是唯一的构造点;打印器的节点身份缓存每次 printRoot 一份。
  12. +
  13. OfflineSpecializationParityTests 要求两条路径逐字节相同,所以一起改。
  14. +
  15. 进程内缓存存节点而不是渲染时重算:0067 去掉的正是重复 demangle。
  16. +
  17. dump 的配置是 .options(…),按 mangled 身份打印,不受影响。
  18. +
+
+
+
+ +
+

替代方案

+
+ 5 条被否的路径 +
+
    +
  • 按 DemangleResolver 的 case 决定:.builder 不等于 interface 打印器。
  • +
  • dump 的注释也走它自己的解析器:会改 dump 快照,dump 没有拼写开关;记为后续项。
  • +
  • typeName 直接改成打印器拼写:SwiftLayout 拿不到打印器,且它是防环键。
  • +
  • 进程内渲染时重新 demangle:把 0067 去掉的成本带回来。
  • +
  • 同名类型也写 __C:::声明行不能带模块,二进制已经证明了 Swift 名。
  • +
+
+
+
+ +
+

影响

+
    +
  • 源码兼容性:纯新增。NestedFieldOffset 多一个公开属性,init 多一个带默认值的参数;渲染配置的新成员是 package。ABI 兼容性不适用(SPM 源码分发)。
  • +
  • 输出:同名 C 类型的引用与扩展头少了 __C.(没开 --resolve-c-module-names 时 CGRect、CGPoint、RBColor 也是);interface 的布局注释与声明同拼写。dump、diff 键、snapshot 不变。
  • +
  • 开销:SwiftUICore 打开展开字段偏移的 interface 从 7.10 秒到 7.39 秒(+4%);进程内缓存 SwiftUICore 全部展开后多占约 2.1 MB(A91)。
  • +
  • RuntimeViewer:内容区文本跟着变,Imported Type Names 切到 C 名时注释也写 C 名;transformer 模板收到打印器拼写;不需要改代码。
  • +
+
+ +
+

落地步骤

+
    +
  1. 名字表收同名条目(已完成):同名 C 类型的引用与扩展头写裸名;解析器找到模块时写 模块.名字;C 名模式照旧;不可信改名照旧;不收嵌套的匿名结构;声明名不带标注。
  2. +
  3. 离线路径的布局注释经打印器拼写(已完成):改名与同名的 C 类型写声明用的名字;C 名模式写 C 名;模块选择器写 ::;dump 仍是 .default。
  4. +
  5. 进程内路径的布局注释经打印器拼写(已完成):进程内同样写 Swift 名与模块选择器;对非泛型字段两条路径逐行相同;带缓存与不带缓存逐字相同(开关关着与开着)。
  6. +
  7. 文档(已完成)。
  8. +
+
+ +
+

后续项

+
    +
  • 跨镜像查找 C 类型的 Swift 名(AGSubgraphRef → Subgraph),另开提案。
  • +
  • dump 的布局注释是否也走 dump 自己的解析器;@retroactive 按 mangling 的 __C 判定。
  • +
  • OpaqueReferenceSpelling 同样用 .default 印类型名;opaque 类型的注释行与声明仍不一致。
  • +
  • 0106 的疑似遗留:NS_ERROR_ENUM 的 Code 枚举被当成可信的顶层改名(未实测)。
  • +
  • pack、整数泛型参数、关联类型成员的嵌套行两条路径对照未覆盖;位置命名的局部类型两条路径地址不同。
  • +
  • 符号索引的建索引死锁(next 上就有):同一镜像 15 个以上调用方并发建索引时占满 16 个大栈线程,持锁者的 DemanglingWave 分不到线程。
  • +
  • 顶层 C++ 类模板特化的引用从 __C.Box<CInt> 变成 Box<CInt>,留给 C++ interop 的提案。
  • +
+
+ +
+

决策日志

+
+ 17 条,最近一条:Implemented,取号 0109 +
+
+ + + + + + + + + + + + + + + + + + + + + +
日期变更说明
2026-11-25Created as Draft同名 C 类型的声明写裸名、扩展头写 __C::,布局注释用 C 名且不带模块选择器;补齐 0106 留下的这两处
2026-11-25范围用户选定只做二进制能证明的部分;跨镜像查找另开提案
2026-11-25批准用户调用 implement-feature 即批准,提案由 agent 起草、用户事前未审阅
2026-11-25开始实现功能分支 feature/consistent-c-imported-type-spelling,从 next 切出
2026-11-25调研更正AGTreeValue、AGTypeSignature 实际改了名但不可信,照旧 __C::
2026-11-25两条后端一起改对照测试要求两条路径逐字节一致
2026-11-25进程内缓存存节点渲染时重算会带回 0067 去掉的成本
2026-11-25第 1 步审查修正文档里「只有没有 descriptor 的保留 __C.」;锁内 demangle 归入 A61;索引缺登记是误报
2026-11-25第 2 步审查补强两条测试;注释行不带判别符、带语法糖是有意的一致
2026-11-25进程内测试改在渲染器接缝上进程内建索引撞上 next 上的符号索引死锁;对照后来改为逐行相同
2026-11-25第 3 步审查补三条测试;改 SpecializedRuntimeTypeNameTests 的期望;几种嵌套形状记为后续项
2026-11-26自审9 条:耗时与内存实测后不修(A91);被排除的描述符先判定、不 demangle(A86);A87–A90 登记;skill 补布局注释与 dump 的区别
2026-11-26真实镜像对照AttributeGraph 的 __C 从 73 处降到 60 处,剩下的都是没有 descriptor 或改名不可信的类型
2026-11-26全量验证2997 个测试只有一条已知的负载超时,单独重跑全过;第一次的 SIGSEGV 是加存储属性后的旧目标文件,clean 后消失
2026-11-26收尾判断不另写使用指南或实现说明;没有新术语,更新了既有词条
2026-11-26实现完成,待用户看过后收尾在本地合进 next 的常驻检出,不推送
2026-11-26Implemented,取号 0109用户验收后与 IntegrationTests 的演进套件合并一起落地、推送 next;它先进入 next,取 0109
+
+
+
+
+ +
+
+ + diff --git a/Documentations/Evolutions/0109-consistent-c-imported-type-spelling.md b/Documentations/Evolutions/0109-consistent-c-imported-type-spelling.md new file mode 100644 index 000000000..46621835d --- /dev/null +++ b/Documentations/Evolutions/0109-consistent-c-imported-type-spelling.md @@ -0,0 +1,362 @@ +# 0109 - C 导入类型的拼写补齐:同名类型去掉 `__C`,布局注释跟着打印器的拼写 + +- **状态**: Implemented +- **作者**: JH +- **创建日期**: 2026-11-25 +- **最后更新**: 2026-11-26 +- **所属愿景**: 无 +- **关联提案**: [0106-c-imported-type-name-spelling](0106-c-imported-type-name-spelling.md)(本提案补齐它留下的两处:没改名的 C 类型、字段布局注释);[0067-nested-field-offset-memoization](0067-nested-field-offset-memoization.md)(进程内每层展开的缓存,本提案往缓存的行里多存一个类型节点);[0064-module-selectors](0064-module-selectors.md)、[0092-existential-any](0092-existential-any.md)(布局注释由此也带上模块选择器与 `any`) +- **实现分支 / PR**: `feature/consistent-c-imported-type-spelling`(worktree `.worktrees/MachOSwiftSection-ConsistentCImportedTypeSpelling`) +- **配套文档**: 无单独文档(见决策日志「收尾判断」);规则在 [术语表](../Glossary.md)「C-imported type name spelling」,裁决在 [ReviewAdjudications](../Internal/ReviewAdjudications.md) A86–A91 +- **网页版**: 同目录同名的 `.html` + +## 摘要 + +0106 让改了名的 C 导入类型在声明、成员类型和扩展头里一律写 Swift 名,但还剩两处混用。第一处:镜像里有 descriptor、Swift 名与 C 名相同的类型,声明行写裸名 `struct AGDescriptionOption`,引用和扩展头却写 `__C::AGDescriptionOption`。第二处:字段布局注释(展开的嵌套字段偏移树)用固定的 `.default` 选项印类型名,`var base: AnyWeakAttribute` 下面的注释写着 `identifier (__C.AGAttribute)`,也不带模块选择器和 `any`。本提案让名字表把「没有 ABI 名」的 descriptor 也收进来——编译器只在两个名字不同时才写 ABI 名,所以这样的 descriptor 证明了 Swift 名就是 C 名——引用处因此写裸名;再让 interface 路径的布局注释经打印器自己的类型拼写印类型名,离线(`MachOFile`)与进程内(`MachOImage`)两条后端一起改,dump 不变。镜像里没有 descriptor 的类型照旧写 `__C::`,跨镜像查找另开提案。 + +## 动机 + +用户用 `SwiftInterfaceBuilderTestSuite.DyldCacheTests.buildFile` 打 macOS 27.2 的 AttributeGraph(开 `showCImportedTypes`、注册 `SwiftInterfaceBuilderTypeNameProvider`、模块选择器、展开字段偏移),输出 `macOS-27.2.0-AttributeGraph-FileDump.swiftinterface` 里同一个类型出现两种写法: + +```swift +struct AGDescriptionOption { // 声明:裸名 +... +extension __C::AGDescriptionOption: @retroactive Swift::RawRepresentable { // 扩展头:__C:: +``` + +```swift +struct WeakAttribute { + // Field offset: 0x0 + // └── _details (__C.AGWeakAttribute.__Unnamed_struct__details): 0x0 + // ├── identifier (__C.AGAttribute): 0x0 + // │ └── rawValue (Swift.UInt32): 0x0 + var base: AnyWeakAttribute +``` + +第一段是同一个类型的声明与扩展头拼写不一致,读起来像是给另一个类型加的遵循。第二段的注释用 C 名 `__C.AGAttribute`,紧挨着的声明却写 `AnyWeakAttribute`;而且整份输出开着模块选择器(`Swift::UInt32`),注释里仍是 `Swift.UInt32`,违反项目「模块限定名必须经类型打印器或调用方的 `DemangleResolver` 印出」的规则(CLAUDE.md 声明模型一节)。RuntimeViewer 用同一个打印器,它的 Imported Type Names 开关切到 Swift 名时,这两处照样混用。 + +用户确认只做「二进制能证明的」部分:镜像里没有 descriptor 的类型(`AGValueOptions`、`AGSubgraphRef` 等)二进制里查不到 Swift 名,保留 `__C::`;从依赖它的其它镜像的 descriptor 找名字(`AGSubgraphRef` 在 SwiftUICore 里记作 `Subgraph`)另开提案。 + +## 前期调研 + +1. **名字表只收改了名的条目**。`CImportedTypeSwiftNameTable.init(typeContextDescriptors:in:)`(`Sources/Output/SwiftPrinting/CImportedTypeSwiftNameTable.swift:34`)要求 `descriptor.hasImportInfo`,再经 `trustsUserFacingName(_:importInfo:)`(同文件 `:74`)要求有 ABI 名、与 descriptor 的名字不同、不是相关实体、ABI 名不以 descriptor 的名字结尾。`TypeNodePrintable.printType`(`Sources/Output/SwiftPrinting/NodePrintables/TypeNodePrintable.swift:170-280`)只在模块没解析出来、名字表又有答案时省掉模块写裸名(`:202`),表里没有就写 `__C::` 加标识符。 + +2. **声明行用 descriptor 的名字**。`declaredTypeName(of:)`(`Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift:153`)对没有 ABI 名的 C 导入 descriptor 直接返回 descriptor 的名字、不带标注(`cImportedTypeNames: nil`),所以同名类型的声明本来就是裸名。扩展头经 `renderExtendedTypeName`(同文件 `:832`)走 `typeDemangleResolver`,即 `printType`。 + +3. **编译器什么时候写 ABI 名**。IRGen `computeIdentity`(`/Volumes/SwiftProjects/swift-project/swift/lib/IRGen/GenMeta.cpp:1567-1609`):`UserFacingName = Type->getName()`(Swift 声明的基名),ABI 名取 Clang 声明的限定名,**只有两者不同才写进 import info**;typedef 提升的类型另写符号命名空间 `St`。所以一个没有 ABI 名的 C 导入 descriptor,它的名字既是 Swift 名也是 C 名。不带任何 import info 的 descriptor(普通 C struct、`NS_ENUM`)同理。唯一的例外形态:一个 C 名不带前缀的类型被 `swift_name` 导入成另一个类型的成员(C 名 `Foo`、Swift 名 `Owner.Foo`),基名与 C 名相同、不写 ABI 名,但 Swift 拼写是 `Owner.Foo`。Apple SDK 的 C 名都带前缀,没有见过这种类型,作为假设记在方案里。 + +4. **AttributeGraph 里哪些是同名的**(macOS 27.2 系统 cache,`ipsw dyld str` / `ipsw dyld dump` 读 `__TEXT.__const`): + - `AGDescriptionOption`:AG 与 SwiftUICore 的 descriptor 的名字都是 `AGDescriptionOption`,后面只有 `St`,没有 ABI 名——同名,本提案让它的引用写裸名。 + - `AGTreeValue` → `TreeValue`、`AGTypeSignature` → `Signature`:有 ABI 名、但 ABI 名以 descriptor 的名字结尾,0106 的规则不采信(可能是导入成成员),照旧写 `__C::`,不在本提案范围。 + - `AGValueOptions`、`AGComparisonMode` 等 16 个只出现在签名里的类型:AG 里没有它们的 descriptor(C 导入类型的 metadata 由用到它的镜像各自按需生成,`lib/IRGen/GenDecl.cpp:1609` 的 `canBeLazy`),保留 `__C::`。 + +5. **布局注释的类型名从哪来**。 + - 离线:`StaticLayoutCalculator.nestedFieldOffsetTree`(`Sources/Analysis/SwiftLayout/NestedFieldOffsetTree.swift:49`、`:73`)与 `makeNode`(`:247`)用 `node.print(using: .default)` 印成字符串,存进公开的 `NestedFieldOffset.typeName`,同一个字符串还当防环的键(`enclosingTypeNames`)。`StaticFieldLayoutBackend.renderNestedFieldOffsetTree`(`Sources/Output/SwiftDeclarationRendering/StaticFieldLayoutBackend.swift:194`)原样交给 `expandedFieldOffsetComment`。 + - 进程内:`RuntimeFieldLayoutBackend.nestedTypeName(for:parentMetadata:)`(`Sources/Output/SwiftDeclarationRendering/RuntimeFieldLayoutBackend.swift:395`)同样 `.default`,结果存进 0067 的全进程缓存 `NestedFieldOffsetLevel`(`NestedFieldOffsetLevel.swift:27-49`),按 metatype 一份,所有打印器共用。 + - 两边最后都进 `DeclarationRenderConfiguration.expandedFieldOffsetComment(fieldName:typeName:…)`(`DeclarationRenderConfiguration.swift:305`),`typeName` 是字符串,也交给 `ExpandedFieldOffsetTransformer` 模板(RuntimeViewer 的设置界面)。 + - `.default` 不带 `useModuleSelectors`、`useExistentialAny`(CLAUDE.md:固定预设两者都不带),也不认识名字表,所以 C 名、点号限定、裸存在类型都由此而来。 + +6. **interface 路径手里有打印器的拼写**。`modelFieldBlock`(`SwiftDeclarationPrinter+Headers.swift:521`)构造渲染配置时把 `typeDemangleResolver` 传成 `demangleResolver`;它是 `.builder`,每次新建一个 `SemanticTypeNodePrinter` 印节点(`SwiftDeclarationPrinter.swift:199`)。这是渲染配置唯一的构造点。打印器按节点身份记忆片段的缓存是每个 `printRoot` 一份(`InterfaceNodePrintable.swift:18-28`),节点只要活过那一次调用就安全。 + +7. **两条后端必须一起改**。`OfflineSpecializationParityTests`(`Tests/SwiftSpecializationTests/OfflineSpecializationParityTests.swift`)要求进程内与离线两条路径在开着展开字段偏移时逐字节相同;只改一边,开了 `any` 或模块选择器的场景就会对不上。 + +8. **进程内缓存为什么存节点而不是渲染时重算**。0067 做这个缓存,是因为 RuntimeViewer 建搜索语料时 61% 的时间耗在逐层重读 metadata,且每个 struct 字段节点要 demangle 约三次(`demangleTypeUncached`)。渲染时重新 demangle 会把这部分成本带回来;而节点在建层时本来就算出来了(`nestedTypeName` 先得节点再印),存下它不增加 CPU,只增加每个唯一 metatype 一份的内存。 + +9. **dump 不受影响的理由**。dump 的渲染配置是 `.options(...)`(测试里是 `.options(.test)`,`Sources/TestSupport/SwiftSectionFixtureSupport/DumpableTests.swift:32`),声明按 mangled 身份打印(0106 前期调研 1),它没有 C 名 / Swift 名开关。本提案不改 dump 的任何输出。 + +## 提议方案 + +### 1. 名字表收「没有 ABI 名」的条目 + +`CImportedTypeSwiftNameTable` 对每个 C 导入(父模块是 `__C` / `__C_Synthesized`)的 descriptor 求「已知的 Swift 名」: + +- 不是相关实体、没有 ABI 名(含完全没有 import info)、且直接位于 `__C` / `__C_Synthesized` 模块下 → descriptor 的名字就是 Swift 名,收进表; +- 有 ABI 名 → 照旧,`trustsUserFacingName` 采信才收; +- 相关实体 → 不收; +- 有 import info 却读不出来 → 不收(读失败不当作没有)。 + +`printType` 不用改:表里有答案、模块没解析出来就写裸名,解析器找到模块照旧写 `模块::名字`。声明行不变(本来就是裸名),标注(`marksCImportedTypeNames`)不变(两种拼写相同的不标)。嵌在 C 类型里的类型(`__Unnamed_struct__details`)不收:它的引用由父类型那一段决定写法,表里不需要它。 + +### 2. 布局注释经打印器的拼写印类型名 + +- `NestedFieldOffset` 多存一个公开的 `typeNode: Node?`(字段类型的节点,替换过泛型参数),`typeName` 保持 `.default` 字符串——它仍是防环键和 dump 的拼写。 +- 进程内缓存的行(`NestedFieldOffsetLevel.StructField` / `EnumPayload`)同样多存 `typeNode`。 +- `DeclarationRenderConfiguration` 加一个包级开关 `spellsFieldLayoutTypeNamesThroughResolver`(默认关,`@Init(.ignore)`,照 `marksCommentStructure` 用修饰方法设置)和一个异步方法 `fieldLayoutTypeName(printedName:typeNode:)`:开关开着、有节点时经 `demangleResolver` 印节点取纯文本,否则返回 `printedName`。 +- 两条后端渲染树时改成异步:每一行先 `await` 取类型名,再递归渲染子行,最后套进 `commentRegion`(已有 async 版本)。树的形状、`isLast`、防环与深度判断、`#log` 告警都不动。 +- interface 打印器构造渲染配置时打开这个开关。dump 不开,输出逐字节不变。 + +于是 interface 里注释的类型名与声明写法一致:`.swiftName` 下是 `AnyAttribute`,`.cName` 下是 `__C.AGAttribute`;开了模块选择器写 `Swift::UInt32`;存在类型带 `any`;`Optional`、`Array`、`Dictionary` 写成语法糖(`Swift.Int?`);私有类型不带判别符(`M.Foo`,`.default` 写 `M.(Foo in _ABC…)`),局部类型只写自己的名字——都和声明一样。`ExpandedFieldOffsetTransformer` 模板收到的也是这个拼写。注释行因此和声明一样分不清同名的私有类型;要分清,看声明上方 `--emit-private-source-files` 印的源文件注释。 + +### 没有询问就采用的假设 + +- **范围取字面最小的理解**:只补 0106 留下的两处;`AGTreeValue` 这类「改了名但不可信」的类型不碰,照旧 `__C::`。 +- **「没有 ABI 名 = Swift 名就是 C 名」**:依据 IRGen 的 `computeIdentity`。唯一会错的形态是 C 名不带前缀、又被导入成成员的类型(前期调研 3),没有见过实例,接受这个风险。 +- **dump 不跟着改**:dump 没有拼写开关、按 mangled 身份打印,注释维持 `.default`。要不要让 dump 的注释也走它自己的 `demangleResolver`,记为后续项。 +- **进程内缓存存节点**:用内存换掉渲染时的重复 demangle(前期调研 8)。 +- **开关放在渲染配置而不是按 `DemangleResolver` 的 case 判断**:`.builder` 不等于「interface 打印器」,显式的开关不把语义绑在枚举 case 上。 + +### 非目标 + +- 镜像里没有 descriptor 的 C 类型(`AGValueOptions`、`AGSubgraphRef`):保留 `__C::`;从依赖它的镜像(SwiftUICore 记着 `Subgraph`)查名字另开提案。 +- 「改了名但不可信」的条目(`TreeValue`、`Signature`、`ValueFlags`):0106 的成员导入保护不放松。 +- `@retroactive`:它按 mangling 里的 `__C` 判定,模块解析出来后也照印,与本提案无关,记为后续项。 +- dump 的任何输出;diff / snapshot / evolution 的键(仍按 mangled 身份比较)。 +- 其它注释里的类型名(枚举布局等):本提案只管展开的字段偏移树;同类排查结果写进后续项。 + +## 改动地图 + +| 文件 / 类型 | 动作 | 改什么 | 为什么 | 步骤 | +|---|---|---|---|---| +| `Sources/Output/SwiftPrinting/CImportedTypeSwiftNameTable.swift` · `CImportedTypeSwiftNameTable` | 修改 | `init` 改为对每个 C 导入 descriptor 求已知 Swift 名;新增 `knownSwiftName(ofDescriptorNamed:importInfo:isDirectlyInImportedModule:)`;`trustsUserFacingName` 语义不变 | 同名类型进表,引用写裸名 | 1 | +| `Sources/Output/SwiftPrinting/CImportedTypeNameSpelling.swift` · `CImportedTypeNameSpelling.swiftName` | 修改 | 文档:「本镜像 descriptor 给出名字的类型(改名与否)写裸名」 | 文档跟上行为 | 1 | +| `Sources/Output/SwiftPrinting/NodePrintables/TypeNodePrintable.swift` · `swiftNameFromDescriptor(ofCImportedType:)` | 修改 | 只改注释 | 同上 | 1 | +| `Sources/Executables/swift-section/Commands/InterfaceCommand.swift` · `cImportedTypeNameSpelling` | 修改 | `--c-imported-type-name-spelling` 的帮助文字补上同名类型与布局注释 | CLI 帮助即文档 | 1、3 | +| `AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md` | 修改 | 「Swift names come first」一段补上同名类型、没有 descriptor 的保留 `__C.`、布局注释同拼写 | CLI 输出变了,skill 同批更新 | 1、3 | +| `Tests/SwiftInterfaceTests/CImportedTypeNameSpellingTests.swift` | 修改 | fixture 加两个同名 C 类型(普通 struct `ProbePlainValue`、`swift_wrapper` 的 `ProbeOption`),加第 1、2、3 步的行为测试 | 回归 | 1、2、3 | +| `Tests/SwiftInterfaceTests/CImportedTypeConformanceInterfaceTests.swift` | 修改 | 定位扩展块用的类型名从 `__C.ProbeMode` 改成 `ProbeMode` | 同名类型的扩展头不再带 `__C.` | 1 | +| `Tests/SwiftInterfaceTests/Snapshots/__Snapshots__/SymbolTestsCoreInterfaceSnapshotTests/interfaceSnapshot.1.txt` | 重录 | `__C.CMTime` → `CMTime` | fixture 镜像里有 `CMTime` 的 descriptor | 1 | +| `Sources/Analysis/SwiftLayout/NestedFieldOffsetTree.swift` · `NestedFieldOffset` | 修改 | 新增 `public let typeNode: Node?`,`init` 加 `typeNode: Node? = nil`;`makeNode` 填上 | 渲染层要拿节点按打印器拼写 | 2 | +| `Sources/Output/SwiftDeclarationRendering/DeclarationRenderConfiguration.swift` · `DeclarationRenderConfiguration` | 修改 | 新增 `spellsFieldLayoutTypeNamesThroughResolver`、`spellingFieldLayoutTypeNamesThroughResolver(_:)`、`fieldLayoutTypeName(printedName:typeNode:)` | 两条后端共用的拼写入口 | 2 | +| `Sources/Output/SwiftDeclarationRendering/StaticFieldLayoutBackend.swift` · `StaticFieldLayoutBackend` | 修改 | `expandedFieldOffsets(for:baseOffset:)`、`renderNestedFieldOffsetTree(_:ancestors:)` 改成 async,每行经 `fieldLayoutTypeName` 取名字 | 离线路径的注释跟拼写 | 2 | +| `Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift` · `modelFieldBlock` | 修改 | 渲染配置加 `.spellingFieldLayoutTypeNamesThroughResolver(true)` | interface 打开开关 | 2 | +| `Sources/Output/SwiftDeclarationRendering/NestedFieldOffsetLevel.swift` · `StructField` / `EnumPayload` | 修改 | 新增 `typeNode: Node?` | 进程内缓存带节点 | 3 | +| `Sources/Output/SwiftDeclarationRendering/RuntimeFieldLayoutBackend.swift` · `RuntimeFieldLayoutBackend` | 修改 | `nestedTypeName` 拆出 `nestedTypeNode`;建层时存节点;`expandedFieldOffsets(of:…)` 与 `walkNestedExpandedFieldOffsets` 改成 async,每行经 `fieldLayoutTypeName` 取名字 | 进程内路径的注释跟拼写,与离线逐字节一致 | 3 | +| `Tests/SwiftDeclarationRenderingTests/NestedFieldOffsetMemoizationTests.swift` | 修改 | 加一轮开关打开、用 `.interface` 拼写的「带缓存与不带缓存逐字相同」 | 缓存里存的节点也要证明冷热一致 | 3 | +| `Tests/SwiftSpecializationTests/SpecializedRuntimeTypeNameTests.swift` | 修改 | 布局注释的期望从 `(RuntimeNamedPrivateArgument in _…)` 改成和字段声明一样的 `SwiftSpecializationTests.RuntimeNamedPrivateArgument` | 注释行跟着声明拼写 | 3 | +| `Documentations/Glossary.md` · C-imported type name spelling | 修改 | 补同名类型、布局注释 | 术语表跟上行为 | 4 | +| `Documentations/Internal/Modules/SwiftLayout.md` | 修改 | 关键契约补一条:`typeName` 与 `typeNode` 两份,本模块不换拼写 | 模块参考 | 4 | +| `Documentations/Internal/FieldLayoutRendererReaderSpecialization.md` | 修改 | 两条后端经同一个入口取行的类型名 | 渲染分叉的说明(`SwiftDeclarationRendering`、`SwiftPrinting` 没有单独的模块文档) | 4 | +| `Documentations/Internal/ProjectEvolutionLog.md` | 修改 | 新增一节(落地前标题写日期,节号落地时取) | 演进账本 | 4 | +| `Documentations/Internal/ReviewAdjudications.md` | 修改 | 登记 A86–A91(审查与自审判为不修、误报或有意的发现) | 「不修」与「误报」的裁决留档 | 4 | +| `Documentations/Evolutions/README.md` | 修改 | 登记本提案(编号 `draft`);`Documentations/README.md` 照项目惯例在落地取号时登记(进行中的 draft 都不在那里) | 索引 | 0 | + +## 架构图 + +改了什么: + +```text +SwiftPrinting + CImportedTypeSwiftNameTable +~ init: entry when the descriptor's name is a known Swift name ++ knownSwiftName(ofDescriptorNamed:importInfo:isDirectlyInImportedModule:) ++ no ABI name, directly in __C -> descriptor name (Swift name == C name) + ABI name, trustsUserFacingName -> descriptor name (unchanged) + related entity / unreadable -> nil + SwiftDeclarationPrinter.modelFieldBlock +~ DeclarationRenderConfiguration(...).spellingFieldLayoutTypeNamesThroughResolver(true) + +SwiftLayout + NestedFieldOffset + typeName: String (.default spelling; cycle key, dump spelling) ++ typeNode: Node? + +SwiftDeclarationRendering + DeclarationRenderConfiguration ++ spellsFieldLayoutTypeNamesThroughResolver: Bool (package, default false) ++ fieldLayoutTypeName(printedName:typeNode:) async -> String + StaticFieldLayoutBackend +~ expandedFieldOffsets / renderNestedFieldOffsetTree sync -> async + NestedFieldOffsetLevel.StructField / EnumPayload ++ typeNode: Node? + RuntimeFieldLayoutBackend ++ nestedTypeNode(for:parentMetadata:) +~ nestedTypeName -> prints nestedTypeNode with .default +~ expandedFieldOffsets / walkNestedExpandedFieldOffsets sync -> async +``` + +一行布局注释的类型名怎么来: + +```text +interface print (SwiftDeclarationPrinter) + modelFieldBlock + renderConfiguration.demangleResolver = typeDemangleResolver (.builder: SemanticTypeNodePrinter) + renderConfiguration.spellsFieldLayoutTypeNamesThroughResolver = true + FieldLayoutRenderer.storedFieldComments + MachOFile -> StaticFieldLayoutBackend + provider.nestedFieldOffsetTree -> [NestedFieldOffset(typeName, typeNode)] + for row: await configuration.fieldLayoutTypeName(printedName: row.typeName, typeNode: row.typeNode) + MachOImage -> RuntimeFieldLayoutBackend + NestedFieldOffsetLevelMemo.level(for: metatype) -> rows(typeName, typeNode) + for row: await configuration.fieldLayoutTypeName(printedName: row.typeName, typeNode: row.typeNode) + fieldLayoutTypeName + flag on, node present -> (try? await demangleResolver.resolve(for: node))?.string e.g. AnyAttribute, Swift::UInt32 + otherwise -> printedName e.g. __C.AGAttribute (dump) + expandedFieldOffsetComment(fieldName:typeName:offset:...) +``` + +## 详细设计 + +### 名字表 + +```swift +struct CImportedTypeSwiftNameTable: Sendable { + init(typeContextDescriptors: [TypeContextDescriptorWrapper], in context: some ReadingContext) { + var swiftNamesByIdentity: [Node: String] = [:] + for descriptorWrapper in typeContextDescriptors { + let descriptor = descriptorWrapper.typeContextDescriptor + guard (try? descriptor.isCImportedContextDescriptor(in: context)) == true, + let userFacingName = try? descriptorWrapper.namedContextDescriptor.name(in: context), + let identity = try? SymbolicDemangler.demangleContext(for: descriptorWrapper.asContextDescriptorWrapper, in: context) + else { continue } + let importInfo: TypeImportInfo? + if descriptor.hasImportInfo { + // An import info that cannot be read is not an absent one. + guard let readImportInfo = try? descriptor.typeImportInfo(in: context) else { continue } + importInfo = readImportInfo + } else { + importInfo = nil + } + let key = Self.key(for: identity) + guard let swiftName = Self.knownSwiftName(ofDescriptorNamed: userFacingName, importInfo: importInfo, isDirectlyInImportedModule: key.children.first?.kind == .module) else { continue } + swiftNamesByIdentity[key] = swiftName + } + self.swiftNamesByIdentity = swiftNamesByIdentity + } + + /// The Swift name a C-imported descriptor's name is known to be, or nil. + static func knownSwiftName(ofDescriptorNamed userFacingName: String, importInfo: TypeImportInfo?, isDirectlyInImportedModule: Bool) -> String? { + if let importInfo, importInfo.isRelatedEntity { return nil } + guard let abiName = importInfo?.abiName, abiName != userFacingName else { + return isDirectlyInImportedModule ? userFacingName : nil + } + return trustsUserFacingName(userFacingName, importInfo: importInfo!) ? userFacingName : nil + } +} +``` + +(实现时去掉强制解包,写法以代码为准。)`trustsUserFacingName` 不改:`declaredTypeName(of:)` 仍用它决定改名,`refusesNameWithoutABIName` 测试的语义(「没有 ABI 名不算可信的改名」)保持。 + +### 渲染配置 + +```swift +extension DeclarationRenderConfiguration { + /// Set by a printer that spells its declarations' types through + /// `demangleResolver`: a field layout tree row then spells its type the + /// same way. The dump never sets it. + @Init(.ignore) + package var spellsFieldLayoutTypeNamesThroughResolver: Bool = false // stored property in the struct + + package func spellingFieldLayoutTypeNamesThroughResolver(_ spellsThroughResolver: Bool) -> Self + + /// The type name a field layout tree row prints: `typeNode` spelled + /// through `demangleResolver` when the printer asks for it, else + /// `printedName`, the `.default` spelling the tree was built with. + package func fieldLayoutTypeName(printedName: String, typeNode: Node?) async -> String +} +``` + +解析失败或得到空串时退回 `printedName`,一行注释不会因此消失。 + +### 两条后端 + +离线: + +```swift +@SemanticStringBuilder +private func expandedFieldOffsets(for mangledTypeName: MangledName, baseOffset: Int) async -> SemanticString + +@SemanticStringBuilder +private func renderNestedFieldOffsetTree(_ nodes: [NestedFieldOffset], ancestors: [Bool]) async -> SemanticString { + for (index, node) in nodes.enumerated() { + let isLast = index == nodes.count - 1 + let typeName = await configuration.fieldLayoutTypeName(printedName: node.typeName, typeNode: node.typeNode) + await configuration.commentRegion(.fieldLayoutNode) { + configuration.expandedFieldOffsetComment(fieldName: node.fieldName, typeName: typeName, offset: node.offset, baseIndentation: configuration.indentation, ancestors: ancestors, isLast: isLast) + await renderNestedFieldOffsetTree(node.children, ancestors: ancestors + [isLast]) + } + } +} +``` + +`storedFieldComments` 里 `configuration.optionalContent(.printFieldOffset) { configuration.commentRegion(.fieldOffset) { … } }` 换成 async 版本。 + +进程内:`walkNestedExpandedFieldOffsets` 同样改成 async,环与深度判断、两个 `#log` 告警原样;`nestedStructFields` / `nestedEnumPayloads` 建行时调 `nestedTypeNode(for:parentMetadata:)` 一次,存节点,`typeName` 由同一个节点 `.default` 印出(与改前相同的派生)。 + +## 替代方案考量 + +- **按 `DemangleResolver` 的 case 决定**(`.builder` 就经它印):dump 不会受影响,但「是 `.builder`」不等于「是 interface 打印器」,宿主自己传 `.builder` 时行为会悄悄变。否。 +- **dump 的注释也经它自己的 `demangleResolver`**:dump 测试用 `.options(.test)`,会改 dump 快照;dump 按 mangled 身份打印,没有拼写开关。超出范围,记为后续项。 +- **`NestedFieldOffset.typeName` 直接改成打印器拼写**:SwiftLayout 在 SwiftPrinting 之下,拿不到打印器;而且 `typeName` 还是防环键,必须是与打印无关的稳定拼写。否。 +- **进程内渲染时重新 demangle 取节点**:不占缓存内存,但把 0067 去掉的 demangle 成本带回来(前期调研 8)。否。 +- **同名类型也写 `__C::`,只把声明行改成 `__C::`**:声明行不能带模块;而且同名类型的 Swift 名二进制已经证明了,与改了名的类型一样写裸名才一致。否。 + +## 影响 + +### 源码兼容性(source compatibility) + +纯新增。`NestedFieldOffset` 多一个公开属性,`init` 多一个带默认值的参数,原有调用点不变。渲染配置的新成员是 `package`。 + +### ABI 兼容性(条件项) + +不适用 —— 本库以 SPM 源码分发,使用方每次重新编译。 + +### 下游影响 + +- 本仓库:`SwiftPrinting`、`SwiftDeclarationRendering`、`SwiftLayout`;interface 输出变化:同名 C 类型的引用与扩展头少了 `__C.`;开了展开字段偏移时注释的类型名与声明写法一致(C 类型 Swift 名、模块选择器、`any`、语法糖、私有类型不带判别符、局部类型只写名字)。每一行多一次经打印器的异步打印:SwiftUICore 打开展开字段偏移的 interface 从 7.10 秒到 7.39 秒(+4%);进程内缓存每行多存一个节点,SwiftUICore 全部展开后多占约 2.1 MB(实测见 [A91](../Internal/ReviewAdjudications.md))。没开 `--resolve-c-module-names` 时,镜像里有描述符的 SDK 类型(`CGRect`、`CGPoint`、RenderBox 的 `RBColor`)也从 `__C::CGRect` 变成裸的 `CGRect`。dump、diff 键、snapshot 不变。 +- RuntimeViewer:用同一个打印器,内容区的接口文本跟着变;Imported Type Names 切到 C 名时注释也写 C 名。它的 `ExpandedFieldOffsetTransformer` 模板收到的 `typeName` 变成打印器拼写。不需要改 RuntimeViewer 代码。 + +### 文档与示例 + +`swift-section interface --help`(`--c-imported-type-name-spelling`)、agent 插件 skill、术语表、模块参考、演进账本。 + +## API 演进与废弃策略 + +无废弃。新增的 `NestedFieldOffset.typeNode` 是可选值,没有它的旧构造点照旧印 `typeName`。 + +## 落地步骤 + +1. **名字表收同名条目**(已完成:行为测试先红后绿;两个审查 agent 各一轮,修了文档说法;SymbolTestsCore 的 interface 快照重录,只变了 `__C.CMTime` → `CMTime` 两行;`CImportedTypeConformanceInterfaceTests` 按新拼写改了定位用的类型名) —— 改动地图第 1–6 行 + - 行为:同名 C 类型的引用写裸名(`var plain: ProbePlainValue`) + - 行为:同名 C 类型的扩展头写裸名(`extension ProbePlainValue: Swift.Equatable`) + - 行为:解析器找到模块时同名类型写成 `模块.名字` + - 行为:C 名模式下同名类型的引用照旧写 `__C.ProbePlainValue` + - 行为:不可信的改名(`ProbeOwnerKey`)照旧写 `__C.ProbeOwnerKey` + - 行为:名字表收同名类型、不收嵌在 C 类型里的匿名结构 + - 行为:同名类型的声明名不带 C 名标注 +2. **离线路径的布局注释经打印器拼写**(已完成:行为测试先红后绿;两个审查 agent 各一轮,修了两条测试——dump 守护测试原先用 `.default` 解析器、证明不了开关,C 名测试原先在旧代码上也会过;受波及的六个测试目标 1082 个测试全过,离线与进程内的对照测试在这一步仍是绿的,因为它的嵌套行只有标准库类型与 builtin) —— 改动地图第 7–10、12 行 + - 行为:离线路径的布局注释里,改了名的 C 类型写声明用的 Swift 名(`identifier (AnyFooIdentifier)`) + - 行为:离线路径的布局注释里,同名 C 类型写裸名 + - 行为:C 名模式下布局注释写 mangled 的 C 名(`__C.AGFooIdentifier`) + - 行为:开了模块选择器时布局注释写 `Swift::UInt32` + - 行为:dump 的布局注释仍是 `.default` 拼写 +3. **进程内路径的布局注释经打印器拼写**(已完成:行为测试先红后绿;两个审查 agent 各一轮,补了三条测试——打印器提前释放会让对照测试两边都退回 `.default` 而假绿,现在保住它的生命周期并要求行里出现 `::`;对照从子集改成逐行相同;缓存测试补上开关打开的一轮;受波及的六个测试目标 1086 个测试全过) —— 改动地图第 11、13、14 行 + - 行为:进程内路径的布局注释同样写 Swift 名与模块选择器 + - 行为:进程内与离线两条路径对非泛型字段的布局注释逐行相同(且进程内的行里必须出现只有打印器才写的 `::`,防止两边都退回 `.default` 时空过) + - 行为:带缓存与不带缓存的进程内展开逐字相同,开关关着(既有测试)与开着、用另一种拼写(新增)都一样 +4. **文档**(已完成:术语表、插件 skill 第 8 节、`--c-imported-type-name-spelling` 帮助、SwiftLayout 模块文档、`FieldLayoutRendererReaderSpecialization.md`、演进账本、已裁决清单 A86–A91) —— 改动地图第 15–19 行,以及第 4、5 行在第 3 步之后的补全 + +**收尾时必须判断两件事**:要不要配套专题文章;有没有引入新术语。结论写进决策日志。 + +## 后续项 + +- 跨镜像查找 C 类型的 Swift 名:dyld cache 里扫依赖目标镜像的镜像,取它们 descriptor 的名字(`AGSubgraphRef` → `Subgraph`)。另开提案。 +- dump 的布局注释是否也走 dump 自己的 `demangleResolver`。 +- `@retroactive` 按 mangling 的 `__C` 判定,模块解析出来后(`extension AttributeGraph::Graph: @retroactive …`)仍印。 +- 同类排查:渲染层里另一处用 `.default` 印类型名进 interface 文本的是 `OpaqueReferenceSpelling`(`Sources/Output/SwiftDeclarationRendering/OpaqueReferenceSpelling.swift:142`、`:145`,没展开的 opaque 引用的泛型实参与所属声明的注释),同样不带模块选择器、`any` 与名字表。它走的是另一套拼写(`textualInterface`),单独处理。 +- 0106 的疑似遗留(第 1 步审查按编译器源码推断,未实测;若属实,`next` 上就有):`NS_ERROR_ENUM` 生成的 `Code` 枚举 descriptor 的名字是 `Code`、ABI 名是错误类型自己的 C 名(如 `MTLLibraryError`),不以 `Code` 结尾,于是被当成可信的顶层改名,引用印成裸的 `Code`,而 Swift 的拼写是 `MTLLibraryError.Code`。要另修 `trustsUserFacingName`。 +- 嵌套字段是 opaque 类型的行:经打印器后写成没展开的 `textualInterface` 拼写,而那个类型自己的声明是 `OpaqueTypeRewriter` 展开过的,两者仍不一致(改前的 `.default` 也不一致)。打印器给注释行印类型时没有 `targetNode`,展开不了。 +- 两条路径的对照还没覆盖的嵌套行形状:variadic 泛型的 pack 实参、整数泛型参数(`InlineArray<3, UInt8>`)、按层里自己的 metadata 绑定的关联类型成员(进程内可能印 `[Int].Element`,离线投影成 `Int`);位置命名的局部类型(`(Visitor in $<地址>)`)进程内与离线的地址不同。都是改前就有的差别,本提案没有让它变好或变坏。 +- **符号索引的建索引死锁**(第 3 步写测试时撞上,`next` 上就有;栈里没有本分支改过的代码):`SwiftSymbolIndexStore.Storage.demangledIndex(reportingProgressTo:)`(`Sources/Symbols/SwiftSymbols/SwiftSymbolIndexStore.swift:265`)先切到大栈线程、再取这个镜像的建索引锁;持锁的那个线程在 `DemanglingWave.waitUntilDemangled()`(`:1771`)等一批 demangle,而每一批也要先切到大栈线程(`:1760`)。同一 QoS 的大栈池只有 16 个线程,当 15 个以上的调用方同时为同一个镜像建索引、都切到大栈后在锁上排队时,池子被占满,持锁者的那批 demangle 永远分不到线程。观测到的触发方式:同一个测试进程里两个测试各自对 dlopen 进来的 fixture 做进程内的 `SwiftInterfaceBuilder.prepare()`(`prepareWithProgress` 从 `DispatchQueue.global(qos: .userInitiated)` 并发进入,共 20 个线程),同时还有别的套件在跑。修法方向:等锁不占大栈线程(先取锁、或把等待者挡在切大栈之前),或者让 wave 的批次不走同一个池子。当时的线程采样只留在 agent 的日志目录,没进仓库;要修时先照上面的触发方式造一条能卡住的测试(带看门狗)。本分支的进程内测试因此改在渲染器接缝上测,不建索引。 +- C++ 类模板特化(顶层、无命名空间)的 descriptor 的名字带尖括号(`Box`),按 IRGen 的规则不写 ABI 名,本提案后它的引用从 `__C.Box` 变成 `Box`。两种写法都不是可声明的 Swift 拼写,没有变坏;要不要单独处理留给 C++ interop 的提案。 + +## 决策日志 + +| 日期 | 变更 | 说明 | +|------|------|------| +| 2026-11-25 | Created as Draft | AttributeGraph 的 interface 里,同名 C 类型的声明写裸名、扩展头写 `__C::`,布局注释用 C 名且不带模块选择器;补齐 0106 留下的这两处 | +| 2026-11-25 | 范围 | 用户选定只做二进制能证明的部分:同名类型写裸名、布局注释跟开关;镜像里没有 descriptor 的类型保留 `__C::`,跨镜像查找另开提案 | +| 2026-11-25 | 批准 | 用户调用 `implement-feature` 即批准,提案由 agent 起草、用户事前未审阅 | +| 2026-11-25 | 开始实现 | 功能分支 `feature/consistent-c-imported-type-spelling`,从 `next` 切出 | +| 2026-11-25 | 调研更正 | 对话里曾把 `AGTreeValue`、`AGTypeSignature` 归为「有 descriptor、没改名」;读 cache 字节后确认它们改了名(`TreeValue`、`Signature`)但不可信,照旧写 `__C::`,不在本提案范围 | +| 2026-11-25 | 两条后端一起改 | `OfflineSpecializationParityTests` 要求两条路径逐字节一致 | +| 2026-11-25 | 进程内缓存存节点 | 渲染时重算会带回 0067 去掉的 demangle 成本 | +| 2026-11-25 | 第 1 步审查(两个审查 agent) | 文档里「只有没有 descriptor 的保留 `__C.`」说错了:改名不可信的(`ProbeOwnerKey`、`AGTreeValue`)也保留,CLI 帮助、插件 skill 与 `CImportedTypeNameSpelling` 的注释已改。名字表在锁内 demangle:A61 第一处已裁决「打印器的一次性建表不改锁」,理由(入口已切到大栈)对 0106 的名字表同样成立,不改,第 5 步登记。`Code` 枚举与 C++ 模板特化记为后续项。`Documentations/README.md` 缺登记是误报:项目惯例是 draft 落地时才登记 | +| 2026-11-25 | 第 2 步审查(两个审查 agent) | 两条测试证明不了它声称的:dump 守护测试改成用一个把所有类型都印成固定字样的解析器,开关关着不生效、开着才生效;C 名测试加开模块选择器。注释行跟着声明不带私有判别符、带语法糖,是这次有意的一致,写进「提议方案」与「影响」;opaque 行记为后续项。每行一次异步打印的开销,交付前在大框架上实测 | +| 2026-11-25 | 进程内测试改在渲染器接缝上 | 最初用进程内 `SwiftInterfaceBuilder` 打 dlopen 进来的 fixture,撞上符号索引的建索引死锁(后续项有详情,是 `next` 上的旧问题)。改为用打印器自己的 `typeDemangleResolver` 直接驱动 `FieldLayoutRenderer`,与打印器构造渲染配置的方式相同、但不建索引。离线与进程内的对照起初按「进程内的行是离线行的子集」比,第 3 步审查后改为逐行相同 | +| 2026-11-25 | 第 3 步审查(两个审查 agent) | 测试有三处证明力不够,已补(见落地步骤 3)。`SpecializedRuntimeTypeNameTests` 改了期望:注释行和字段声明一样写 `SwiftSpecializationTests.RuntimeNamedPrivateArgument`,测试要证明的「保留模块」不变;运行时名字里判别符的恢复另有 `RuntimeTypeNamePrivateDiscriminatorTests` 守着,不另加 dump 侧的孪生测试。pack、整数泛型参数、关联类型成员这几种嵌套行的两条路径对照、位置命名的局部类型在两条路径地址不同,都是改前就没覆盖的,记为后续项。进程内缓存多存节点的内存成本,交付前实测 | +| 2026-11-26 | 自审(`code-review` medium,整条分支) | 9 条:耗时与内存实测后不修(+4%、+2.1 MB,A91);名字表在锁内 demangle 归入 A61,锁不改,但被 import info 排除的描述符改为先判定、不 demangle(A86);同名 C 类型与同名 Swift 类型混淆是误报(A87);注释行不带私有判别符是有意的(A88);解析失败静默退回 `.default` 不修(A89);依赖镜像的 C 类型按根镜像的名字表拼是已知限制,插件 skill 写明(A90);插件 skill 补上布局注释与 dump 的区别;网页版随交付生成 | +| 2026-11-26 | 真实镜像对照 | macOS 27.2 的 AttributeGraph(显示 C 导入类型、模块选择器、展开字段偏移、`--resolve-c-module-names`):`__C` 从 73 处降到 60 处,`AGDescriptionOption` 的 6 个扩展头去掉 `__C::`,注释行改为 `AnyWeakAttribute.__Unnamed_struct__details`、`AnyAttribute`、`Swift::UInt32`。剩下的 60 处都是镜像里没有描述符的类型,或改名不可信的 `AGTreeElement`、`AGTreeValue`、`AGTypeSignature` | +| 2026-11-26 | 全量验证 | JHs-Mac-Studio-Ultra,Xcode 26.6,`swift test --skip IntegrationTests`:2997 个测试只有 `BoundedConcurrentMapTests.cancellationStopsSubmittingPendingElements` 超时(全量时线程池满载的已知偶发),单独重跑该套件 9 个全过。第一次全量在 `DumpRequest` 里复制 `DeclarationRenderConfiguration` 时 SIGSEGV:给这个结构体加了存储属性后增量构建链接了旧目标文件,`swift package clean` 后重编即消失 | +| 2026-11-26 | 收尾判断 | 不另写使用指南或实现说明:拼写规则写在术语表「C-imported type name spelling」,两份类型名的契约写在 SwiftLayout 模块文档,渲染入口写在 `FieldLayoutRendererReaderSpecialization.md`。没有新术语,更新了既有词条 | +| 2026-11-26 | 实现完成,待用户看过后收尾 | 三步与文档都已提交到功能分支;在本地合进 `next` 的常驻检出,不推送 | +| 2026-11-26 | Implemented,取号 0109 | 用户验收后与 IntegrationTests 的演进套件合并一起落地、推送 `next`;它先进入 `next`,取 0109。 | diff --git a/Documentations/Evolutions/0110-unify-evolution-integration-suites.html b/Documentations/Evolutions/0110-unify-evolution-integration-suites.html new file mode 100644 index 000000000..2d85ee837 --- /dev/null +++ b/Documentations/Evolutions/0110-unify-evolution-integration-suites.html @@ -0,0 +1,672 @@ + + + + + + +0110 - IntegrationTests 的演进套件合并:Swift 与 ObjC 共用一套版本轴 + + + + +
+ +
+

MachOSwiftSectionEvolutions0110

+

0110 IntegrationTests 的演进套件合并:Swift 与 ObjC 共用一套版本轴

+
+
状态
Implemented
+
最后更新
2026-11-26
+
项目类型
库
+
原文
0110-unify-evolution-integration-suites.md
+
+
+ +
+ +
+ +
+

摘要

+

Tests/IntegrationTests/ 里有四套演进(evolution)的维护者手检套件:Swift 的时间线报告、Swift 带标注的联合接口、ObjC 的时间线报告、ObjC 带标注的联合头文件,分在三个文件里,一共 21 个套件类、43 个测试。它们读的是同几条版本轴(哪几份 dyld cache、哪几个镜像),却各自把轴再定义一遍、互相引用对方的类属性,四条管线各自又把「单镜像」与「镜像组」写成两条几乎一样的路径。

+

本提案把它们合成一套:新目录 Tests/IntegrationTests/Evolution/ 下,版本轴只定义一次(一个轴一个套件类,共 10 个),轴按管线读的元数据(__swift5_* 或 __objc_*)各自筛出版本;四条管线收进一个协议,每条只写一遍,镜像组与单镜像在管线里用一个开关分开。每种输出在轴上仍是一对显式的一行测试(写文件 / 打到控制台),原有的 43 个「轴 × 输出」组合一个不增不减,输出文件名不变,只改测试名。只动 IntegrationTests,不碰库代码。

+
+ +
+

要你定

+
+

已批准并落地。以下是没问用户就采用的假设:

+
    +
  1. 默认三版本轴上 Swift 一侧沿用实际读的 SwiftUI、ObjC 一侧沿用 AppKit,拆成两个轴套件,不借合并之机统一成 AppKit;过时的「AppKit」注释改正。
  2. +
  3. 只保留现有的「轴 × 输出」组合,不顺手给轴补别的管线;要补时只是在套件里加一对一行测试。
  4. +
  5. 测试名改变(例如 ABIEvolutionTestSuite.DyldCacheTests/evolutionFile() → EvolutionTestSuite.SwiftUIDyldCacheTests/swiftReportFile()),旧名字不留别名——没有脚本按名字调用它们(已 grep 过 Scripts/ 与 .github/)。
  6. +
+
+
+ +
+

架构图

+
    +
  • 新增
  • +
  • 修改
  • +
  • 删除
  • +
  • 不变
  • +
+ +

改了什么:文件与类型

+
+ + + Tests/IntegrationTests/ (before) + + SwiftDiffing/ABIEvolutionTests.swift + protocol ABIEvolutionDumpTests — report, single + group paths + class MultiVersionDyldCacheImageTests — isOnAxis = __swift5_* + enum ABIEvolutionTestSuite — 4 suites + snapshot code written twice; indexConfiguration + + SwiftInterface/SwiftEvolutionInterfaceBuilderTests.swift + protocol SwiftEvolutionInterfaceDumpTests — single + group paths + enum SwiftEvolutionInterfaceBuilderTestSuite — 5 suites + ArchivedDyldCacheTests owns the 51 cache versions + + ObjCDiffing/ObjCAPIEvolutionTests.swift + protocol ObjCAPIEvolutionDumpTests — single + group paths + subclass MultiVersionDyldCacheImageTests: isOnAxis = __objc_* + enum ObjCAPIEvolutionTestSuite — 6 suites + protocol ObjCEvolutionInterfaceDumpTests — single + group + enum ObjCEvolutionInterfaceTestSuite — 6 suites + + 21 suites · 43 tests · 16 entry points + + + Tests/IntegrationTests/ (after) + + Evolution/EvolutionAxis.swift + EvolutionMetadataLanguage: swift (__swift5_*) | objc (__objc_*) + EvolutionAvailabilityPlatform: macOS → "macOS" | "macos" + EvolutionImage · EvolutionVersion · EvolutionAxis + class MultiVersionDyldCacheImageTests — one axis per language + + Evolution/EvolutionDumpTests.swift + protocol EvolutionDumpTests — requires evolutionAxis(for:) + EvolutionDumpKind: swift/objc × report/interface + dump(_:to:) → one private pipeline per kind + + Evolution/EvolutionTests.swift + enum EvolutionTestSuite — 10 axis suites + 43 one-line tests, same axis × output pairs + + SwiftInterface/SwiftInterfaceTestSupport.swift + write(_:forImageGroup:) takes [EvolutionImage] + write(_:for:), measuringPreparation, printResult unchanged + + + + + + + + +
+

三个旧文件的内容按职责拆进三个新文件:版本轴、管线、轴套件。

+ +

套件之间的引用

+
+ + + before + + ObjCEvolutionInterfaceTestSuite.* + + ObjCAPIEvolutionTestSuite.* + + ABIEvolutionTestSuite.MultiVersion… + + ABIEvolutionTestSuite.*Archived… + + SwiftEvolution… + .ArchivedDyldCache… + .cachePaths + + + + + borrows axes + + + after + + EvolutionTestSuite.*Tests + + MultiVersionDyldCacheImageTests + static defaultMacOSCachePaths + static archivedMacOSCachePaths + + SwiftUICoreSimulator… + + CrossVersion + MachOFileTests + diff suite, unchanged + + + +
+

改前 ObjC 两组和 Swift 报告组都去借 Swift 接口套件的版本清单;改后每个轴套件只认基类。

+ +

一次测试的调用链

+
+ + + @Test swiftReportFile() + + dump(.swiftReport, to: .file) + EvolutionDumpTests + + evolutionAxis(for: .swift) + stored per language at init + + swiftReport(over: axis) + + measuringPreparation { swiftSnapshotDocument(of:label:) } + every image of every version + + comparesImageGroups ? evolution(ofImageGroups:versions:) + : evolution(of: documents) + + ABIDiffer cross-check when N == 2, single image + + .file → write(text / json, forImageGroup:) + named after the newest version's images + + .console → printResult(text) + + + + + + + + +
+
+ +
+

改动地图

+
+ + + + + + + + + + + + + + + + + + +
文件 / 类型动作改什么为什么步骤
Evolution/EvolutionAxis.swift · EvolutionMetadataLanguage新增swift / objc,isCarried(by:) 判 __swift5_* / __objc_* 节取代 isOnAxis(_:) 覆写,两种语言的唯一差别收在一处1
同上 · EvolutionAvailabilityPlatform新增macOS,swiftSpelling / objcSpelling两条接口管线拼法不同,轴只声明「标 macOS」1
同上 · EvolutionImage / EvolutionVersion / EvolutionAxis新增镜像、版本、轴三个 Sendable 值类型取代嵌套元组,管线只认一种输入1
同上 · MultiVersionDyldCacheImageTests移动自 ABIEvolutionTests.swift:174-218 挪来:打开 cache、收镜像、按语言算两条轴;defaultMacOSCachePaths / archivedMacOSCachePaths;availabilityPlatform 类属性轴只定义一次,版本清单不再挂在某个套件上1
Evolution/EvolutionDumpTests.swift · EvolutionDumpTests新增协议要求 evolutionAxis(for:);扩展里 dump(_:to:)、四条 private 管线、两个快照函数、preparedObjCIndexer(of:)、indexConfiguration取代四个 dump 协议的 16 个入口与 8 个准备函数1
同上 · EvolutionDumpKind / EvolutionDumpDestination / EvolutionDumpOutput新增四种输出、两种去处、一次输出的内容测试体缩成一行1
SwiftInterface/SwiftInterfaceTestSupport.swift · write(_:forImageGroup:suffix:fileExtension:)修改第 1 步加一个收 [EvolutionImage] 的重载,第 2 步删掉收元组的旧重载镜像组命名改用新值类型;分两步保证每步都能编1、2
Evolution/EvolutionTests.swift · EvolutionTestSuite新增十个轴套件,43 个一行测试,沿用旧套件里仍成立的注释合并后的套件2
SwiftDiffing/ABIEvolutionTests.swift删除整个文件(SwiftDiffing/ 目录随之为空、删除)被合并2
SwiftInterface/SwiftEvolutionInterfaceBuilderTests.swift删除整个文件被合并2
ObjCDiffing/ObjCAPIEvolutionTests.swift删除整个文件(ObjCDiffing/ 目录随之为空、删除)被合并2
Documentations/Internal/ABIEvolutionDesign.md:235-243修改集成套件的路径与套件名改成新的这段是现行说明,引用了被删的文件3
Documentations/Internal/ProjectEvolutionLog.md修改落地时追加一节(节号落地时取)账本规则3
Documentations/Evolutions/README.md、Documentations/README.md修改登记本提案(现在 draft,落地时换编号)索引3
+
+

表中的 Evolution/、SwiftDiffing/ 等路径都在 Tests/IntegrationTests/ 下。

+
+ +
+

提议方案

+

在 Tests/IntegrationTests/Evolution/ 下用三个文件取代现在的三个演进文件:

+
    +
  1. EvolutionAxis.swift:版本轴只定义一次。EvolutionMetadataLanguage 判镜像带不带管线要读的元数据;EvolutionAvailabilityPlatform 记要标的平台,两种语言各有拼法;EvolutionImage / EvolutionVersion / EvolutionAxis 取代嵌套元组。基类 MultiVersionDyldCacheImageTests 挪到这里:每份 cache 打开一次,把套件列出的镜像里 cache 有的都收下,只要有主镜像就保留这份 cache;再为两种语言各算一条轴存下——主镜像被筛掉的版本不上这条轴。默认三版本 cache 与 51 份归档 cache 的清单作为基类的两个 static 属性。
  2. +
  3. EvolutionDumpTests.swift:四条管线各写一遍。协议只要求 evolutionAxis(for:);dump(_:to:) 是唯一入口,跑管线得到 EvolutionDumpOutput,再打到控制台或写文件,文件一律按最新版本的镜像组命名。每条管线内部按 axis.comparesImageGroups 选单镜像或镜像组的构建器入口。
  4. +
  5. EvolutionTests.swift:十个轴套件,挂在 enum EvolutionTestSuite 下,每种输出一对一行测试(<种类>File / <种类>String)。
  6. +
  7. SwiftInterfaceTestSupport.swift:write(_:forImageGroup:) 改收 [EvolutionImage]。
  8. +
+
+ + + + + + + + + + + + + + +
套件轴测试取代
SwiftUIDyldCacheTestsSwiftUI × 默认三版Swift 报告、Swift 接口、pack facadeABI DyldCacheTests、Swift 接口 DyldCacheTests
SwiftUICoreDyldCacheTestsSwiftUICore × 默认三版Swift 接口Swift 接口 SwiftUICoreDyldCacheTests
AppKitDyldCacheTestsAppKit × 默认三版ObjC 报告、ObjC 头文件ObjC 两组的 DyldCacheTests
SwiftUIArchivedDyldCacheTestsSwiftUI × 51 份归档,标 macOS 可用性Swift 接口Swift 接口 ArchivedDyldCacheTests
AppKitArchivedDyldCacheTestsAppKit × 51 份归档,标 macOS 可用性ObjC 报告、ObjC 头文件ObjC 两组的 ArchivedDyldCacheTests
SwiftUIImageGroupDyldCacheTestsSwiftUI + SwiftUICore × 默认三版四种全有四组各自的同名套件
SwiftUIImageGroupArchivedDyldCacheTestsSwiftUI + SwiftUICore × 51 份归档,标可用性四种全有四组各自的同名套件
AppKitImageGroupDyldCacheTestsAppKit + UIFoundation + CollectionViewCore + CoreAutoLayout × 默认三版ObjC 报告、ObjC 头文件ObjC 两组的同名套件
AppKitImageGroupArchivedDyldCacheTests同一组 × 51 份归档,标可用性ObjC 报告、ObjC 头文件ObjC 两组的同名套件
SwiftUICoreSimulatorTestsSwiftUICore 两个模拟器 runtime 文件(18.5 → 26.5)Swift 报告ABI SwiftUICoreTests
+
+

测试数:5 + 2 + 4 + 2 + 4 + 8 + 8 + 4 + 4 + 2 = 43,与现状相同。可用性平台只影响两种「接口」输出;报告输出和现状一样从不标。

+

非目标

+
    +
  • 不合并 diff 套件(SwiftDiffableInterfaceBuilderTestSuite)的两版本基类,也不改它读 cache 的方式;SwiftUICoreSimulatorTests 继续借用它的 CrossVersionMachOFileTests。
  • +
  • 不动 SwiftInterfaceBuilderTests.swift(单镜像接口套件;工作区里有维护者未提交的改动)、MachOSymbols 里的重复,以及其它不属于演进的 IntegrationTests。
  • +
  • 不改任何库代码、不改 CLI,也不新增 Package.swift 依赖。
  • +
  • 不运行 IntegrationTests;输出比对由维护者手动做。
  • +
+
+ +
+

详细设计

+
+ EvolutionAxis.swift +
+
enum EvolutionMetadataLanguage: Sendable {
+    case swift   // __swift5_* sections
+    case objc    // __objc_* sections
+
+    func isCarried(by machOFile: MachOFile) -> Bool
+}
+
+enum EvolutionAvailabilityPlatform: Sendable {
+    case macOS
+    var swiftSpelling: String { "macOS" }   // @available(macOS, …)
+    var objcSpelling: String { "macos" }    // API_AVAILABLE(macos(…))
+}
+
+struct EvolutionImage: Sendable { let imageName: String; let machOFile: MachOFile }
+
+struct EvolutionVersion: Sendable {
+    let label: String
+    let images: [EvolutionImage]            // the primary image first
+    var primaryImage: EvolutionImage { images[0] }
+}
+
+struct EvolutionAxis: Sendable {
+    let versions: [EvolutionVersion]
+    let comparesImageGroups: Bool
+    let availabilityPlatform: EvolutionAvailabilityPlatform?
+}
+
+@TestActor
+class MultiVersionDyldCacheImageTests: Sendable {
+    let caches: [FullDyldCache]
+    private let axesByLanguage: [EvolutionMetadataLanguage: EvolutionAxis]
+
+    class var cachePaths: [DyldSharedCachePath] { defaultMacOSCachePaths }
+    class var cacheImageName: MachOImageName { .SwiftUI }
+    class var cacheImageNames: [MachOImageName] { [cacheImageName] }
+    class var availabilityPlatform: EvolutionAvailabilityPlatform? { nil }
+
+    static var defaultMacOSCachePaths: [DyldSharedCachePath] { [.macOS_15_5, .macOS_26_5_2, .macOS_27_0] }
+    static var archivedMacOSCachePaths: [DyldSharedCachePath] { /* 51 versions, 11.0.1 → 11.0, 12.0.1 → 12.0 */ }
+
+    init() async throws
+    nonisolated func evolutionAxis(for language: EvolutionMetadataLanguage) -> EvolutionAxis
+}
+

axesByLanguage 在 init 里算好、以 let 存下:类属性是 @TestActor 隔离的,nonisolated 的协议实现读不到它们,读一个 Sendable 的 let 则可以。实现时若字典的强制解包不合适,改成两个 let 加一个 switch。

+
+
+
+ EvolutionDumpTests.swift +
+
enum EvolutionDumpKind: Sendable {
+    case swiftReport      // swift-section evolution: -Evolution.txt / .json
+    case swiftInterface   // evolution --interface: -EvolutionInterface.swiftinterface
+    case objcReport       // objc evolution: -ObjCEvolution.txt / .json
+    case objcInterface    // objc evolution --interface: -ObjCEvolutionInterface.h
+    var language: EvolutionMetadataLanguage
+}
+
+enum EvolutionDumpDestination: Sendable { case console, file }
+
+struct EvolutionDumpOutput {
+    let suffix: String
+    let text: String
+    let textFileExtension: String
+    let json: String?     // nil for an interface
+}
+
+protocol EvolutionDumpTests: SwiftInterfaceDumpTests {
+    func evolutionAxis(for language: EvolutionMetadataLanguage) -> EvolutionAxis
+}
+
+@available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *)
+extension EvolutionDumpTests {
+    var indexConfiguration: SwiftDeclarationIndexConfiguration { .init(showCImportedTypes: false) }
+
+    func dump(_ kind: EvolutionDumpKind, to destination: EvolutionDumpDestination) async throws
+
+    private func swiftReport(over axis: EvolutionAxis) async throws -> EvolutionDumpOutput
+    private func swiftInterface(over axis: EvolutionAxis) async throws -> EvolutionDumpOutput
+    private func objcReport(over axis: EvolutionAxis) async throws -> EvolutionDumpOutput
+    private func objcInterface(over axis: EvolutionAxis) async throws -> EvolutionDumpOutput
+
+    private func swiftSnapshotDocument(of image: EvolutionImage, label: String) async throws -> ABISnapshotDocument
+    private func objcSnapshotDocument(of image: EvolutionImage, label: String) async throws -> ObjCAPISnapshotDocument
+}
+
    +
  • swiftReport:measuringPreparation 里对每个版本的每个镜像取快照;镜像组配成 ABIImageSnapshot 交给 evolution(ofImageGroups:versions:),单镜像交给 evolution(of:),两版本时追加 ABIDiffer 对照行;JSON 用同一个 ABIEvolution 编码。
  • +
  • swiftInterface:按开关选 AnySwiftEvolutionInterfaceBuilder 的 imageGroups: 或 versions: 构造器,平台传 swiftSpelling;正文末尾加 // ABI-breaking on this axis: 行。
  • +
  • objcReport:同 swiftReport,换成 ObjC 的快照、构建器、differ 与 JSON 编码器;对照行写 API-breaking。
  • +
  • objcInterface:逐版本 addVersion(images:version:) 或 addVersion(indexer:machO:version:),build(availabilityPlatform:) 传 objcSpelling;正文末尾加 // API-breaking on this axis: 行。
  • +
+
+
+
+ EvolutionTests.swift:一个套件的样子 +
+
enum EvolutionTestSuite {
+    final class SwiftUIImageGroupArchivedDyldCacheTests: MultiVersionDyldCacheImageTests, nonisolated EvolutionDumpTests, @unchecked Sendable {
+        override class var cachePaths: [DyldSharedCachePath] { archivedMacOSCachePaths }
+        override class var cacheImageNames: [MachOImageName] { [.SwiftUI, .SwiftUICore] }
+        override class var availabilityPlatform: EvolutionAvailabilityPlatform? { .macOS }
+
+        @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *)
+        @Test func swiftReportFile() async throws { try await dump(.swiftReport, to: .file) }
+
+        @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *)
+        @Test func swiftReportString() async throws { try await dump(.swiftReport, to: .console) }
+
+        // swiftInterface / objcReport / objcInterface: one pair each
+    }
+
+    final class SwiftUICoreSimulatorTests: SwiftDiffableInterfaceBuilderTestSuite.CrossVersionMachOFileTests, nonisolated EvolutionDumpTests, @unchecked Sendable {
+        nonisolated func evolutionAxis(for language: EvolutionMetadataLanguage) -> EvolutionAxis {
+            // "18.5" → oldMachOFile, "26.5" → newMachOFile, one image each
+        }
+        // swiftReportFile / swiftReportString
+    }
+}
+

SwiftUIDyldCacheTests 另保留 swiftInterfaceStringViaPackFacade(@available(macOS 14.0, …)),从 Swift 轴取三个主镜像交给 SwiftEvolutionInterfaceBuilder,照旧不包 measuringPreparation(@TestActor 上的测试把隔离的闭包交出去会触发 region isolation 检查)。

+
+
+
+ 与现状的行为差异 +
+
    +
  • 测试名全部改变,套件从四个 enum 合到 EvolutionTestSuite 一个下。
  • +
  • 空轴:现状的 file 入口在轴上一个版本都没有时静默返回,string 入口抛 fewerThanTwoVersions;合并后两种都抛。只在 cache 卷没挂载、镜像全不在时出现。
  • +
  • 保留的 cache:现状只留「主镜像在这条语言的轴上」的 cache,合并后留「有主镜像」的 cache。在这十条轴上结果相同。
  • +
  • 输出内容与文件名不变;JSON 里的 createdAt 每次运行本来就不同。
  • +
+
+
+
+ +
+

动机

+
+ 五处具体的重复 +
+
    +
  1. 同一条轴定义了四次。SwiftUI 加 SwiftUICore 在默认三版本 cache 上的轴,在 ABIEvolutionTests.swift:239、SwiftEvolutionInterfaceBuilderTests.swift:286、ObjCAPIEvolutionTests.swift:244 与 :460 各写一次;51 份归档 cache 上同样四次。AppKit 组的两条轴、AppKit 单镜像的两条轴在 ObjC 两组里各写两次。
  2. +
  3. 轴靠互相引用来对齐。51 份归档 cache 的版本列表只在 SwiftEvolutionInterfaceBuilderTestSuite.ArchivedDyldCacheTests.cacheVersions 里,ObjC 两组和 Swift 报告那组都去引用这个 Swift 接口套件的类属性。
  4. +
  5. ObjC 的轴是继承 Swift 的轴再改一处。ObjCAPIEvolutionTestSuite.MultiVersionDyldCacheImageTests 只为覆写 isOnAxis(_:),把 __swift5_* 换成 __objc_*。
  6. +
  7. 每条管线把单镜像与镜像组写成两遍,四条管线合计 16 个入口、8 个准备函数;indexConfiguration 在两个协议扩展里各写一份。
  8. +
  9. 注释已经和代码对不上。两个 Swift 侧的 DyldCacheTests 注释写着读 AppKit,实际继承基类默认的 .SwiftUI;ObjC 的同名套件确实读 AppKit。
  10. +
+
+
+
+ +
+

调研

+
+ 八条查证过的事实 +
+
    +
  1. 四条管线的输入与差异:Swift 报告与 ObjC 报告都是「每个镜像索引 → 冻结成快照 → 经 JSON 往返 → 时间线」,单镜像两版本时与 differ 对照;Swift 接口用 AnySwiftEvolutionInterfaceBuilder,ObjC 头文件用 ObjCEvolutionInterfaceBuilder,末尾各加一行结论。
  2. +
  3. 单镜像与镜像组的输出不同,不能一律走镜像组:ABIEvolutionBuilder.evolution(ofImageGroups:versions:)(Sources/Output/SwiftDiffing/ABIEvolutionBuilder.swift:51-62)给版本描述写 imageNames,evolution(of:)(:16-27)带 provenance;AnySwiftEvolutionInterfaceBuilder.prepare(:189-194)与 ObjCEvolutionInterfaceBuilder.swift:269-275 也按版本形态二选一。
  4. +
  5. 文件命名在单镜像时两种写法相同(SwiftInterfaceTestSupport.swift:43-71),合并后一律用镜像组的写法。
  6. +
  7. 可用性平台两种语言拼法不同:Swift 传 "macOS",ObjC 传 "macos";只有归档轴的两种「接口」管线传平台。
  8. +
  9. Swift Testing 不继承测试:每个轴套件仍要自己声明测试,能省的是测试体和轴的重复定义。
  10. +
  11. 为什么不用参数化测试:一点就跑完全部参数,51 版归档轴要几个小时。
  12. +
  13. IntegrationTests 不让 agent 运行,只能验证编译;CI 的 swift test 会编译 IntegrationTests,且用 Xcode 26.6,所以 26.6 也要编一遍。
  14. +
  15. 目录无需登记:目标用默认路径 Tests/IntegrationTests,新子目录自动收进来;Tuist 按目标名映射。
  16. +
+
+
+
+ +
+

替代方案

+
+ 五条被否的路径 +
+
    +
  • 参数化测试:一点就跑全部管线,没法在跑之前单独挑一种输出。用户选了显式测试。
  • +
  • 所有轴都走镜像组路径:版本描述与 JSON 会变,和 CLI 单镜像的输出也不一致。
  • +
  • 把默认三版本轴统一成 AppKit:Swift 一侧的输出会变,维护者手里正在比的结果对不上。
  • +
  • 轴做成值、套件按轴参数化:同参数化测试的问题,Xcode 里也看不到按轴分开的套件。
  • +
  • 只抽公共函数、保留四个 enum:轴的四重定义和互相引用还在,没解决「Swift 和 ObjC 各有一套」。
  • +
+
+
+
+ +
+

影响

+
    +
  • 源码兼容性:纯测试改动,不涉及任何公开 API。
  • +
  • ABI 兼容性:不适用 —— 本库以 SPM 源码分发,本提案也只改测试目标。
  • +
  • 下游:只有 IntegrationTests 目标受影响;下游仓库不依赖它。
  • +
  • 文档:ABIEvolutionDesign.md:235-243 改成新路径与套件名;账本、任务报告与已落地提案里的旧名字是历史记录,不改。
  • +
  • API 演进与废弃:不适用;旧测试名直接删除,不留别名。
  • +
+
+ +
+

落地步骤

+
+

验证一律在 Ultra 上做:queued-build swift build --build-tests,默认 Xcode 编一遍,再用 Xcode 26.6(CI 的版本)编一遍。不运行 IntegrationTests。

+
+
    +
  1. 新骨架与四条管线(已完成,Ultra 上 Xcode 26.6 与 27.2 都编过):EvolutionAxis.swift、EvolutionDumpTests.swift、write(_:forImageGroup:) 的新重载;旧文件还在,与新代码并存。 +
      +
    • evolutionAxisForSwiftDropsVersionsWhosePrimaryImageHasNoSwiftSection
    • +
    • evolutionAxisForObjCKeepsEveryCacheHoldingAppKit
    • +
    • imageGroupAxisKeepsAnImageOnlyWhereItsCacheCarriesTheMetadata
    • +
    • singleImageAxisUsesTheSingleImageBuilderEntryPoints
    • +
    • reportWritesTextAndJSONNamedAfterTheNewestVersionsImages
    • +
    • interfaceSpellsAvailabilityInItsOwnLanguagesSpelling
    • +
    +
  2. +
  3. 十个轴套件取代旧文件(已完成,两个 Xcode 版本都编过,新文件没有警告):EvolutionTests.swift;删三个旧文件与随之变空的 SwiftDiffing/、ObjCDiffing/;删旧重载。 +
      +
    • everyAxisPipelinePairOfTheOldSuitesHasOneTestNow(43 个)
    • +
    • noSuiteReadsAnotherSuitesClassProperties
    • +
    • archivedAxesTakeTheCacheListFromTheBaseClass
    • +
    +
  4. +
  5. 文档(已完成;落地前没有收到输出比对结果):ABIEvolutionDesign.md、账本一节、两个索引;提案状态与决策日志随代码同批提交。维护者挑 SwiftUIImageGroupDyldCacheTests 前后各跑一次 file 测试,diff 两次的输出(JSON 忽略 createdAt),结果记进决策日志。
  6. +
+

收尾判断:预计不需要配套专题文章(用法写在新文件的文档注释里);「版本轴」落地时查术语表再定是否登记。

+
+ +
+

决策日志

+
+ 7 条,最近一条:Implemented,取号 0110 +
+
+ + + + + + + + + + + +
日期变更说明
2026-11-26Created as Draft用户要求把 IntegrationTests 里重复的演进测试抽出来,Swift 与 ObjC 各有一套套件,统一成一套。澄清一轮:范围只做演进(不顺带合并 diff 基类与 MachOSymbols 的重复);每种输出保留一对显式测试,不用参数化测试;按规则写轻量档提案。
2026-11-26Accepted用户看过简报后批准,开始实现。
2026-11-26In Progress:第 1 步开工功能分支从本地 next 切出;那上面还有一次未推送的合并(C 导入类型拼写),推送功能分支时作为祖先一并上了远端功能分支。两条轴用两个 let 加 switch 存,不用字典加强制解包。
2026-11-26第 2、3 步完成十个轴套件取代旧的三个文件;SwiftDiffing/ 也随之变空、删除。ABIEvolutionDesign.md 与账本更新。只编译、没运行 IntegrationTests。
2026-11-26收尾判断不配使用指南或实现说明;「版本轴」是描述性说法,不登记术语表。
2026-11-26实现完成,待用户看过后收尾功能分支已推送,并在本地以 --no-ff 合进 next(不推送)。
2026-11-26Implemented,取号 0110与 0109(C 导入类型拼写,先进入 next)一起落地、推送 next。落地前没有收到输出比对结果。
+
+
+
+
+ +
+
+ + diff --git a/Documentations/Evolutions/0110-unify-evolution-integration-suites.md b/Documentations/Evolutions/0110-unify-evolution-integration-suites.md new file mode 100644 index 000000000..d2b8076a8 --- /dev/null +++ b/Documentations/Evolutions/0110-unify-evolution-integration-suites.md @@ -0,0 +1,487 @@ +# 0110 - IntegrationTests 的演进套件合并:Swift 与 ObjC 共用一套版本轴 + +- **状态**: Implemented +- **作者**: JH +- **创建日期**: 2026-11-26 +- **最后更新**: 2026-11-26 +- **所属愿景**: 无 +- **关联提案**: [0082-image-group-evolution](0082-image-group-evolution.md)(镜像组的演进,本提案合并它在集成测试里加的四组镜像组套件);[0080-objc-evolution-interface](0080-objc-evolution-interface.md)(ObjC 带标注头文件的那组套件);[0061-dyld-shared-cache-path-versions](0061-dyld-shared-cache-path-versions.md)(版本轴按 `versionLabel` 命名、跳过没有元数据的版本) +- **实现分支 / PR**: `feature/unify-evolution-integration-suites`(worktree `.worktrees/MachOSwiftSection-UnifyEvolutionIntegrationSuites`) +- **配套文档**: 无(见决策日志「收尾判断」) +- **网页版**: 同目录同名的 `.html` + +## 摘要 + +`Tests/IntegrationTests/` 里有四套演进(evolution)的维护者手检套件:Swift 的时间线报告、Swift 带标注的联合接口、ObjC 的时间线报告、ObjC 带标注的联合头文件,分在三个文件里,一共 21 个套件类、43 个测试。它们读的是同几条版本轴(哪几份 dyld cache、哪几个镜像),却各自把轴再定义一遍、互相引用对方的类属性,四条管线各自又把「单镜像」与「镜像组」写成两条几乎一样的路径。本提案把它们合成一套:新目录 `Tests/IntegrationTests/Evolution/` 下,版本轴只定义一次(一个轴一个套件类,共 10 个),轴按管线读的元数据(`__swift5_*` 或 `__objc_*`)各自筛出版本;四条管线收进一个协议,每条只写一遍,镜像组与单镜像在管线里用一个开关分开。每种输出在轴上仍是一对显式的一行测试(写文件 / 打到控制台),原有的 43 个「轴 × 输出」组合一个不增不减,输出文件名不变,只改测试名。只动 IntegrationTests,不碰库代码。 + +## 动机 + +维护者每次加一条轴或一种管线,都要在四个地方各改一遍,漏一处就悄悄不一致。现状里的具体重复: + +1. **同一条轴定义了四次**。SwiftUI 加 SwiftUICore 这组镜像在默认三版本 cache 上的轴,分别在 `ABIEvolutionTestSuite.SwiftUIImageGroupDyldCacheTests`(`Tests/IntegrationTests/SwiftDiffing/ABIEvolutionTests.swift:239`)、`SwiftEvolutionInterfaceBuilderTestSuite.SwiftUIImageGroupDyldCacheTests`(`Tests/IntegrationTests/SwiftInterface/SwiftEvolutionInterfaceBuilderTests.swift:286`)、`ObjCAPIEvolutionTestSuite.SwiftUIImageGroupDyldCacheTests`(`Tests/IntegrationTests/ObjCDiffing/ObjCAPIEvolutionTests.swift:244`)、`ObjCEvolutionInterfaceTestSuite.SwiftUIImageGroupDyldCacheTests`(同文件 `:460`)各写一次;它在 51 份归档 cache 上的轴同样四次。AppKit 组的两条轴、AppKit 单镜像的两条轴在 ObjC 两组里各写两次。 +2. **轴靠互相引用来对齐**。51 份归档 cache 的版本列表只在 `SwiftEvolutionInterfaceBuilderTestSuite.ArchivedDyldCacheTests.cacheVersions`(`SwiftEvolutionInterfaceBuilderTests.swift:200-266`)里,ObjC 两组和 Swift 报告那组都去引用这个 Swift 接口套件的类属性(`ObjCAPIEvolutionTests.swift:186-188`、`:225-227`、`:401-403`;`ABIEvolutionTests.swift:259-261`)。一个「Swift 接口套件」承担了「全体归档版本清单」的职责,改它的镜像或版本会牵动别的语言的套件。 +3. **ObjC 的轴是继承 Swift 的轴再改一处**。`ObjCAPIEvolutionTestSuite.MultiVersionDyldCacheImageTests`(`ObjCAPIEvolutionTests.swift:152-158`)继承 `ABIEvolutionTestSuite.MultiVersionDyldCacheImageTests`(`ABIEvolutionTests.swift:174-218`),只为覆写 `isOnAxis(_:)`,把 `__swift5_*` 换成 `__objc_*`。两种语言真正不同的只有这一个判据,却因此多出一层基类,ObjC 两组的 12 个套件都挂在这层基类上。 +4. **每条管线把单镜像与镜像组写成两遍**。Swift 报告的「索引一个镜像 → 冻结成快照 → 经 JSON 往返」写了两遍(`ABIEvolutionTests.swift:40-53` 与 `:105-119`);Swift 接口、ObjC 报告、ObjC 头文件也都是「单镜像一组 private 准备函数 + string/file 两个入口」再加「镜像组一组 private 准备函数 + string/file 两个入口」,四条管线合计 16 个入口、8 个准备函数。`indexConfiguration` 在两个协议扩展里各写一份(`ABIEvolutionTests.swift:26`、`SwiftEvolutionInterfaceBuilderTests.swift:34`)。 +5. **注释已经和代码对不上**。`ABIEvolutionTestSuite.DyldCacheTests` 与 `SwiftEvolutionInterfaceBuilderTestSuite.DyldCacheTests` 的注释写着读 AppKit(`ABIEvolutionTests.swift:220`、`SwiftEvolutionInterfaceBuilderTests.swift:137`),实际继承基类默认的 `.SwiftUI`(`ABIEvolutionTests.swift:184`);而 ObjC 的同名套件确实读 AppKit。同名的 `DyldCacheTests` 在两种语言里读的是两个镜像,正是轴分散定义的后果。 + +## 前期调研 + +1. **四条管线的输入与差异**(逐行读过三个文件): + - Swift 报告:每个镜像 `SwiftDiffableInterfaceBuilder(configuration:in:)` + `prepare()` + `snapshot()`,包成 `ABISnapshotDocument` 经 `encoded()` / `decode(from:)` 往返;单镜像走 `ABIEvolutionBuilder().evolution(of: documents)`,镜像组走 `evolution(ofImageGroups:versions:)`;`ABIEvolutionReporter().report(_:)` 出文本,`ABIJSON.encoder()` 出 JSON;单镜像且两个版本时追加一行与 `ABIDiffer` 的结论对照。输出 `-Evolution.txt` / `.json`。 + - Swift 接口:`AnySwiftEvolutionInterfaceBuilder` 的 `versions:labels:` 或 `imageGroups:labels:` 构造器,`prepare()` 后 `printAnnotatedInterface()`,末尾加一行 `// ABI-breaking on this axis:`。输出 `-EvolutionInterface.swiftinterface`。 + - ObjC 报告:每个镜像 `ObjCInterfaceIndexer(machO:imagePath:suppliedClasses:)` + `prepare()`,`ObjCAPISnapshotBuilder(indexer:).snapshot()` 包成 `ObjCAPISnapshotDocument` 往返;单镜像 `ObjCAPIEvolutionBuilder().evolution(of:)`,镜像组 `evolution(ofImageGroups:versions:)`;两版本时对照 `ObjCAPIDiffer`。输出 `-ObjCEvolution.txt` / `.json`。 + - ObjC 头文件:`ObjCEvolutionInterfaceBuilder` 每个版本 `addVersion(indexer:machO:version:)` 或 `addVersion(images:version:)`,`build(availabilityPlatform:)`,末尾加一行 `// API-breaking on this axis:`。输出 `-ObjCEvolutionInterface.h`。 +2. **单镜像与镜像组的输出不同,不能一律走镜像组**。`ABIEvolutionBuilder.evolution(ofImageGroups:versions:)`(`Sources/Output/SwiftDiffing/ABIEvolutionBuilder.swift:51-62`)给每个版本描述写 `imageNames`、按镜像记移动,而 `evolution(of:)`(`:16-27`)带上文档的 provenance;`AnySwiftEvolutionInterfaceBuilder.prepare`(`Sources/Output/SwiftInterface/AnySwiftEvolutionInterfaceBuilder.swift:189-194`)也按构造器记下的 `comparesImageGroups` 二选一。MachOObjCSection 的 `ObjCEvolutionInterfaceBuilder` 同样按加入的版本形态选路径(`../MachOObjCSection/Sources/ObjCInterface/ObjCEvolutionInterfaceBuilder.swift:269-275`:没有镜像组时走 `evolution(of:versions:)`,两种形态混用则抛 `singleImageVersionsMixedWithImageGroups`)。所以合并后要保留「这条轴比的是不是镜像组」这个开关,取值与现状一致:套件声明了不止一个镜像就是镜像组。 +3. **文件命名在单镜像时两种写法相同**。`write(_:for:suffix:fileExtension:)` 用 `-<镜像文件名>-<后缀>`,`write(_:forImageGroup:suffix:fileExtension:)` 用 `<主镜像 buildVersion>-<各镜像文件名用 + 连起来>-<后缀>`(`Tests/IntegrationTests/SwiftInterface/SwiftInterfaceTestSupport.swift:43-71`)。组里只有一个镜像时两者逐字相同,所以合并后一律用镜像组的写法,文件名不变。 +4. **可用性平台两种语言拼法不同**。Swift 接口传 `"macOS"`(`SwiftEvolutionInterfaceBuilderTests.swift:272`,印成 `@available(macOS, …)`),ObjC 头文件传 `"macos"`(`ObjCAPIEvolutionTests.swift:407`,印成 `API_AVAILABLE(macos(…))`);SwiftSectionKit 两边也各有一个拼写函数(`Sources/Commands/SwiftSectionKit/Swift/ABIEvolutionRequest.swift:201`、`Sources/Commands/SwiftSectionKit/ObjC/ObjCAPIRequests.swift:316`)。现状里只有归档轴的两种「接口」管线传平台,报告管线从不传。 +5. **Swift Testing 不继承测试**。`@Test` 只登记在声明它的类型上,子类拿不到父类的测试——这就是现状每个子类都重写一遍 `evolutionFile()` / `evolutionString()` 的原因。合并后每个轴套件仍要自己声明测试,能省的是测试体(缩成一行)和轴的重复定义。 +6. **为什么不用参数化测试**:`@Test(arguments:)` 一点就跑完全部参数;在 51 份归档 cache 的轴上,四条管线各要把 51 个版本整个索引一遍,一次要几个小时。维护者要的是在 Xcode 里单独点跑某一种输出,所以每种输出保留一对显式测试(用户选定)。 +7. **IntegrationTests 不让 agent 运行**(`CLAUDE.md`「Never run `Tests/IntegrationTests/`」),所以本提案只能验证编译;输出是否与改前逐字相同,要维护者挑一条轴前后各跑一次比对。CI 的 `swift test` 会编译所有测试目标,IntegrationTests 也在内,而 CI 用 Xcode 26.6(`.github/workflows/macOS.yml:22`),所以要用 26.6 也编一遍。 +8. **目录无需登记**:IntegrationTests 目标用默认路径 `Tests/IntegrationTests`(`Package.swift:1506`),新子目录自动收进来;Tuist 的映射按目标名列,不按文件(`Tuist/Package.swift:87`)。 + +## 提议方案 + +在 `Tests/IntegrationTests/Evolution/` 下用三个文件取代现在的三个演进文件: + +1. **`EvolutionAxis.swift`:版本轴只定义一次**。 + - `EvolutionMetadataLanguage`(`swift` / `objc`):管线读哪种元数据,`isCarried(by:)` 判镜像有没有对应的 `__swift5_*` / `__objc_*` 节。 + - `EvolutionAvailabilityPlatform`(目前只有 `macOS`):轴给接口标可用性时用的平台,`swiftSpelling` 是 `"macOS"`、`objcSpelling` 是 `"macos"`。 + - `EvolutionImage`(镜像名 + `MachOFile`)、`EvolutionVersion`(标签 + 镜像,主镜像在前)、`EvolutionAxis`(版本、`comparesImageGroups`、`availabilityPlatform`)三个值类型,取代现在到处写的 `(label: String, images: [(imageName: MachOImageName, machO: MachOFile)])` 元组。 + - 基类 `MultiVersionDyldCacheImageTests` 挪到这里:初始化时每份 cache 打开一次,把套件列出的镜像里 cache 有的都收下(不按元数据筛),只要 cache 有主镜像就保留这份 cache;再为两种语言各算一条轴存下——镜像按该语言的元数据筛,主镜像被筛掉的版本不上这条轴。`isOnAxis(_:)` 覆写点删掉。 + - 默认三版本 cache 与 51 份归档 cache 的清单作为基类的两个 `static` 属性放在这里(`defaultMacOSCachePaths`、`archivedMacOSCachePaths`,后者带上 11.0.1 → 11.0、12.0.1 → 12.0 的标签换算),哪个套件都不再引用别的套件。 +2. **`EvolutionDumpTests.swift`:四条管线各写一遍**。 + - 协议 `EvolutionDumpTests: SwiftInterfaceDumpTests` 只要求一个 `evolutionAxis(for:)`。 + - `EvolutionDumpKind`(`swiftReport` / `swiftInterface` / `objcReport` / `objcInterface`)对应 CLI 的四种输出,各自带它读的语言。 + - 协议扩展的 `dump(_:to:)` 是唯一入口:取轴、跑管线得到 `EvolutionDumpOutput`(后缀、正文、正文扩展名、可选的 JSON),再按 `EvolutionDumpDestination`(`.console` / `.file`)打到控制台或写文件,文件一律按最新版本的镜像组命名。 + - 每条管线一个 private 函数,内部按 `axis.comparesImageGroups` 选单镜像或镜像组的构建器入口;「一个镜像 → 一份往返过的快照」每种语言只写一个函数,两种形态共用。 +3. **`EvolutionTests.swift`:十个轴套件**,挂在 `enum EvolutionTestSuite` 下。每个套件只写轴(cache、镜像、可用性平台)和测试,每种输出一对一行测试(`<种类>File` / `<种类>String`): + + | 套件 | 轴 | 测试 | 取代 | + |---|---|---|---| + | `SwiftUIDyldCacheTests` | SwiftUI × 默认三版 | Swift 报告、Swift 接口、pack facade | ABI `DyldCacheTests`、Swift 接口 `DyldCacheTests` | + | `SwiftUICoreDyldCacheTests` | SwiftUICore × 默认三版 | Swift 接口 | Swift 接口 `SwiftUICoreDyldCacheTests` | + | `AppKitDyldCacheTests` | AppKit × 默认三版 | ObjC 报告、ObjC 头文件 | ObjC 两组的 `DyldCacheTests` | + | `SwiftUIArchivedDyldCacheTests` | SwiftUI × 51 份归档,标 macOS 可用性 | Swift 接口 | Swift 接口 `ArchivedDyldCacheTests` | + | `AppKitArchivedDyldCacheTests` | AppKit × 51 份归档,标 macOS 可用性 | ObjC 报告、ObjC 头文件 | ObjC 两组的 `ArchivedDyldCacheTests` | + | `SwiftUIImageGroupDyldCacheTests` | SwiftUI + SwiftUICore × 默认三版 | 四种全有 | 四组各自的同名套件 | + | `SwiftUIImageGroupArchivedDyldCacheTests` | SwiftUI + SwiftUICore × 51 份归档,标可用性 | 四种全有 | 四组各自的同名套件 | + | `AppKitImageGroupDyldCacheTests` | AppKit + UIFoundation + CollectionViewCore + CoreAutoLayout × 默认三版 | ObjC 报告、ObjC 头文件 | ObjC 两组的同名套件 | + | `AppKitImageGroupArchivedDyldCacheTests` | 同一组 × 51 份归档,标可用性 | ObjC 报告、ObjC 头文件 | ObjC 两组的同名套件 | + | `SwiftUICoreSimulatorTests` | SwiftUICore 两个模拟器 runtime 文件(18.5 → 26.5) | Swift 报告 | ABI `SwiftUICoreTests` | + + 测试数:5 + 2 + 4 + 2 + 4 + 8 + 8 + 4 + 4 + 2 = 43,与现状相同。可用性平台只影响两种「接口」输出;报告输出和现状一样从不标。 + +4. **`SwiftInterfaceTestSupport.swift`**:`write(_:forImageGroup:suffix:fileExtension:)` 改收 `[EvolutionImage]`。 + +**采用的假设**(用户可推翻): + +- 默认三版本轴上 Swift 一侧沿用实际读的 SwiftUI、ObjC 一侧沿用 AppKit,拆成两个轴套件,不借合并之机统一成 AppKit;过时的「AppKit」注释改正。 +- 合并只保留现有的「轴 × 输出」组合,不顺手给轴补上别的管线;要补时只是在套件里加一对一行测试。 +- 测试名改变(例如 `ABIEvolutionTestSuite.DyldCacheTests/evolutionFile()` → `EvolutionTestSuite.SwiftUIDyldCacheTests/swiftReportFile()`),旧名字不留别名——这是维护者手点的目标,没有脚本按名字调用它们(已 grep 过 `Scripts/` 与 `.github/`)。 + +### 非目标 + +- 不合并 diff 套件(`SwiftDiffableInterfaceBuilderTestSuite`)的两版本基类,也不改它读 cache 的方式;`SwiftUICoreSimulatorTests` 继续借用它的 `CrossVersionMachOFileTests`。 +- 不动 `SwiftInterfaceBuilderTests.swift`(单镜像接口套件;工作区里有维护者未提交的改动)、MachOSymbols 里的重复,以及其它不属于演进的 IntegrationTests。 +- 不改任何库代码、不改 CLI,也不新增 `Package.swift` 依赖。 +- 不运行 IntegrationTests;输出比对由维护者手动做。 + +## 改动地图 + +| 文件 / 类型 | 动作 | 改什么 | 为什么 | 步骤 | +|---|---|---|---|---| +| `Tests/IntegrationTests/Evolution/EvolutionAxis.swift` · `EvolutionMetadataLanguage` | 新增 | `swift` / `objc`,`isCarried(by:)` 判 `__swift5_*` / `__objc_*` 节 | 取代 `isOnAxis(_:)` 覆写,两种语言的唯一差别收在一处 | 1 | +| 同上 · `EvolutionAvailabilityPlatform` | 新增 | `macOS`,`swiftSpelling` / `objcSpelling` | 两条接口管线拼法不同,轴只声明「标 macOS」 | 1 | +| 同上 · `EvolutionImage` / `EvolutionVersion` / `EvolutionAxis` | 新增 | 镜像、版本、轴三个 `Sendable` 值类型 | 取代嵌套元组,管线只认一种输入 | 1 | +| 同上 · `MultiVersionDyldCacheImageTests` | 新增(自 `ABIEvolutionTests.swift:174-218` 挪来) | 打开 cache、收镜像、按语言算两条轴;`defaultMacOSCachePaths` / `archivedMacOSCachePaths`;`availabilityPlatform` 类属性 | 轴只定义一次,版本清单不再挂在某个套件上 | 1 | +| `Tests/IntegrationTests/Evolution/EvolutionDumpTests.swift` · `EvolutionDumpTests` | 新增 | 协议要求 `evolutionAxis(for:)`;扩展里 `dump(_:to:)`、四条 private 管线、两个快照函数、`preparedObjCIndexer(of:)`、`indexConfiguration` | 取代四个 dump 协议的 16 个入口与 8 个准备函数 | 1 | +| 同上 · `EvolutionDumpKind` / `EvolutionDumpDestination` / `EvolutionDumpOutput` | 新增 | 四种输出、两种去处、一次输出的内容 | 测试体缩成一行 | 1 | +| `Tests/IntegrationTests/SwiftInterface/SwiftInterfaceTestSupport.swift` · `write(_:forImageGroup:suffix:fileExtension:)` | 修改 | 第 1 步加一个收 `[EvolutionImage]` 的重载,第 2 步删掉收元组的旧重载 | 镜像组命名改用新值类型;分两步保证每步都能编 | 1、2 | +| `Tests/IntegrationTests/Evolution/EvolutionTests.swift` · `EvolutionTestSuite` | 新增 | 十个轴套件,43 个一行测试,沿用旧套件里仍成立的注释(11.x 方法名、镜像何时加入组等) | 合并后的套件 | 2 | +| `Tests/IntegrationTests/SwiftDiffing/ABIEvolutionTests.swift` | 删除 | 整个文件(`SwiftDiffing/` 目录随之为空、删除) | 被合并 | 2 | +| `Tests/IntegrationTests/SwiftInterface/SwiftEvolutionInterfaceBuilderTests.swift` | 删除 | 整个文件 | 被合并 | 2 | +| `Tests/IntegrationTests/ObjCDiffing/ObjCAPIEvolutionTests.swift` | 删除 | 整个文件(`ObjCDiffing/` 目录随之为空、删除) | 被合并 | 2 | +| `Documentations/Internal/ABIEvolutionDesign.md:235-243` | 修改 | 集成套件的路径与套件名改成新的 | 这段是现行说明,引用了被删的文件 | 3 | +| `Documentations/Internal/ProjectEvolutionLog.md` | 修改 | 落地时追加一节(节号落地时取) | 账本规则 | 3 | +| `Documentations/Evolutions/README.md`、`Documentations/README.md` | 修改 | 登记本提案(现在 `draft`,落地时换编号) | 索引 | 3 | + +## 架构图 + +改了什么(文件与类型): + +```text +Tests/IntegrationTests/ +- SwiftDiffing/ABIEvolutionTests.swift +- protocol ABIEvolutionDumpTests report: single-image path + image-group path +- enum ABIEvolutionTestSuite +- class MultiVersionDyldCacheImageTests opens caches; isOnAxis = __swift5_* +- DyldCacheTests, SwiftUIImageGroupDyldCacheTests, SwiftUIImageGroupArchivedDyldCacheTests, SwiftUICoreTests +- SwiftInterface/SwiftEvolutionInterfaceBuilderTests.swift +- protocol SwiftEvolutionInterfaceDumpTests interface: single-image path + image-group path +- enum SwiftEvolutionInterfaceBuilderTestSuite 5 suites; ArchivedDyldCacheTests owns the 51 cache versions +- ObjCDiffing/ObjCAPIEvolutionTests.swift +- protocol ObjCAPIEvolutionDumpTests report: single-image path + image-group path +- enum ObjCAPIEvolutionTestSuite +- class MultiVersionDyldCacheImageTests : ABIEvolutionTestSuite.MultiVersionDyldCacheImageTests isOnAxis = __objc_* +- 6 suites +- protocol ObjCEvolutionInterfaceDumpTests header: single-image path + image-group path +- enum ObjCEvolutionInterfaceTestSuite 6 suites ++ Evolution/EvolutionAxis.swift ++ enum EvolutionMetadataLanguage swift (__swift5_*) | objc (__objc_*) ++ enum EvolutionAvailabilityPlatform macOS -> "macOS" | "macos" ++ struct EvolutionImage, EvolutionVersion, EvolutionAxis ++ class MultiVersionDyldCacheImageTests opens caches once; one axis per language ++ static defaultMacOSCachePaths, archivedMacOSCachePaths ++ Evolution/EvolutionDumpTests.swift ++ protocol EvolutionDumpTests requires evolutionAxis(for:) ++ enum EvolutionDumpKind swiftReport | swiftInterface | objcReport | objcInterface ++ dump(_:to:) -> one private pipeline per kind ++ Evolution/EvolutionTests.swift ++ enum EvolutionTestSuite 10 axis suites, 43 one-line tests +~ SwiftInterface/SwiftInterfaceTestSupport.swift +~ write(_:forImageGroup:) takes [EvolutionImage] +``` + +套件之间的引用(改前互相借轴,改后只认基类): + +```text +before after +ObjCEvolutionInterfaceTestSuite.* EvolutionTestSuite.*Tests + └─> ObjCAPIEvolutionTestSuite.* (axes) └─> MultiVersionDyldCacheImageTests + └─> ABIEvolutionTestSuite.MultiVersion… ├── defaultMacOSCachePaths + └─> SwiftEvolutionInterfaceBuilderTestSuite └── archivedMacOSCachePaths + .ArchivedDyldCacheTests.cachePaths EvolutionTestSuite.SwiftUICoreSimulatorTests +ABIEvolutionTestSuite.SwiftUIImageGroupArchived… └─> SwiftDiffableInterfaceBuilderTestSuite + └─> SwiftEvolutionInterfaceBuilderTestSuite .CrossVersionMachOFileTests (unchanged) + .ArchivedDyldCacheTests.cachePaths +``` + +一次测试的调用链: + +```text +@Test swiftReportFile() +└── dump(.swiftReport, to: .file) EvolutionDumpTests + ├── evolutionAxis(for: .swift) stored per language at init + ├── swiftReport(over: axis) + │ ├── measuringPreparation + │ │ └── swiftSnapshotDocument(of:label:) every image of every version + │ ├── axis.comparesImageGroups + │ │ ? ABIEvolutionBuilder.evolution(ofImageGroups:versions:) + │ │ : ABIEvolutionBuilder.evolution(of: documents) (+ ABIDiffer cross-check when N == 2) + │ └── EvolutionDumpOutput(suffix: "Evolution", text, "txt", json) + └── .file -> write(text, forImageGroup: newest.images, …) + write(json, …, "json") + .console -> printResult(text) +``` + +## 详细设计 + +### `EvolutionAxis.swift` + +```swift +import Foundation +import Testing +import MachOKit +import SwiftSectionFixtureSupport +import SwiftSectionTestingSupport + +/// The metadata an evolution pipeline reads, and so which images join +/// its axis: an image without it has nothing to index. +enum EvolutionMetadataLanguage: Sendable { + /// `__swift5_*` sections. AppKit kept its Swift API in + /// `libswiftAppKit.dylib` until macOS 14, so a Swift AppKit axis + /// reaching further back starts at 14.0. + case swift + /// `__objc_*` sections, which AppKit carries in every cache. + case objc + + func isCarried(by machOFile: MachOFile) -> Bool { + let sectionNamePrefix = switch self { + case .swift: "__swift5_" + case .objc: "__objc_" + } + return machOFile.sections.contains { $0.sectionName.hasPrefix(sectionNamePrefix) } + } +} + +/// The platform an evolution interface spells availability for, each +/// pipeline in its own spelling — what `--emit-available --platform` passes. +enum EvolutionAvailabilityPlatform: Sendable { + case macOS + + /// `@available(macOS, …)`. + var swiftSpelling: String { "macOS" } + /// `API_AVAILABLE(macos(…))`. + var objcSpelling: String { "macos" } +} + +struct EvolutionImage: Sendable { + let imageName: String + let machOFile: MachOFile +} + +struct EvolutionVersion: Sendable { + let label: String + /// The primary image first. + let images: [EvolutionImage] + + var primaryImage: EvolutionImage { images[0] } +} + +/// One ordered series of versions (oldest first), as one pipeline reads it. +struct EvolutionAxis: Sendable { + let versions: [EvolutionVersion] + /// Whether every version is a group of images (evolution proposal + /// `image-group-evolution`), which picks the builders' image-group + /// entry points: a group of one still reads differently from one image. + let comparesImageGroups: Bool + /// Set when every label is a version number, so the interfaces can + /// spell each lifecycle one attribute or macro expresses. + let availabilityPlatform: EvolutionAvailabilityPlatform? +} + +@TestActor +class MultiVersionDyldCacheImageTests: Sendable { + /// Retained: the extracted files resolve cross-image references + /// through them while indexing. + let caches: [FullDyldCache] + private let axesByLanguage: [EvolutionMetadataLanguage: EvolutionAxis] + + /// Oldest first; each cache's `versionLabel` labels it on the axis. + class var cachePaths: [DyldSharedCachePath] { defaultMacOSCachePaths } + class var cacheImageName: MachOImageName { .SwiftUI } + /// The images whose declarations make up one version, the primary + /// image first; by default the primary image alone. + class var cacheImageNames: [MachOImageName] { [cacheImageName] } + class var availabilityPlatform: EvolutionAvailabilityPlatform? { nil } + + static var defaultMacOSCachePaths: [DyldSharedCachePath] { [.macOS_15_5, .macOS_26_5_2, .macOS_27_0] } + /// One archived cache per macOS minor on the volume, 11.0.1 → 27.0, + /// 11.0.1 and 12.0.1 labeled 11.0 and 12.0 (AppleDB offers no 11.0 or + /// 12.0 image; an SDK's attributes name 11.0 and 12.0). + static var archivedMacOSCachePaths: [DyldSharedCachePath] { … the 51 versions as today … } + + init() async throws { + // Every cache holding the primary image is opened whole (as + // `--dyld-shared-cache` opens it) and kept, with every listed image + // it holds; each language's axis then keeps the images carrying its + // metadata and drops a version whose primary image does not. + } + + nonisolated func evolutionAxis(for language: EvolutionMetadataLanguage) -> EvolutionAxis { + axesByLanguage[language]! // both languages are computed at init + } +} +``` + +`axesByLanguage` 在 `init` 里算好、以 `let` 存下:类属性(`cacheImageNames`、`availabilityPlatform`)是 `@TestActor` 隔离的,`nonisolated` 的协议实现读不到它们,读一个 `Sendable` 的 `let` 则可以。实现时若字典的强制解包不合适,改成两个 `let`(`swiftAxis`、`objcAxis`)加一个 `switch`。 + +### `EvolutionDumpTests.swift` + +```swift +enum EvolutionDumpKind: Sendable { + /// `swift-section evolution`: `-Evolution.txt` and `.json`. + case swiftReport + /// `swift-section evolution --interface`: `-EvolutionInterface.swiftinterface`. + case swiftInterface + /// `swift-section objc evolution`: `-ObjCEvolution.txt` and `.json`. + case objcReport + /// `swift-section objc evolution --interface`: `-ObjCEvolutionInterface.h`. + case objcInterface + + var language: EvolutionMetadataLanguage { + switch self { + case .swiftReport, .swiftInterface: .swift + case .objcReport, .objcInterface: .objc + } + } +} + +enum EvolutionDumpDestination: Sendable { + case console + case file +} + +struct EvolutionDumpOutput { + let suffix: String + let text: String + let textFileExtension: String + /// The machine-readable form a report also writes; `nil` for an interface. + let json: String? +} + +protocol EvolutionDumpTests: SwiftInterfaceDumpTests { + func evolutionAxis(for language: EvolutionMetadataLanguage) -> EvolutionAxis +} + +@available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) +extension EvolutionDumpTests { + var indexConfiguration: SwiftDeclarationIndexConfiguration { + .init(showCImportedTypes: false) + } + + /// Runs one pipeline over this suite's axis for its language and prints + /// the text, or writes the text (and a report's JSON) named after the + /// newest version's images. + func dump(_ kind: EvolutionDumpKind, to destination: EvolutionDumpDestination) async throws { + let axis = evolutionAxis(for: kind.language) + let output = switch kind { + case .swiftReport: try await swiftReport(over: axis) + case .swiftInterface: try await swiftInterface(over: axis) + case .objcReport: try await objcReport(over: axis) + case .objcInterface: try await objcInterface(over: axis) + } + switch destination { + case .console: + printResult(output.text) + case .file: + guard let newestVersion = axis.versions.last else { return } + try write(output.text, forImageGroup: newestVersion.images, suffix: output.suffix, fileExtension: output.textFileExtension) + if let json = output.json { + try write(json, forImageGroup: newestVersion.images, suffix: output.suffix, fileExtension: "json") + } + } + } + + private func swiftReport(over axis: EvolutionAxis) async throws -> EvolutionDumpOutput + private func swiftInterface(over axis: EvolutionAxis) async throws -> EvolutionDumpOutput + private func objcReport(over axis: EvolutionAxis) async throws -> EvolutionDumpOutput + private func objcInterface(over axis: EvolutionAxis) async throws -> EvolutionDumpOutput + + /// One image indexed and frozen, round-tripped through the persisted + /// form: what the evolution consumes is what a saved baseline decodes to. + private func swiftSnapshotDocument(of image: EvolutionImage, label: String) async throws -> ABISnapshotDocument + private func objcSnapshotDocument(of image: EvolutionImage, label: String) async throws -> ObjCAPISnapshotDocument +} +``` + +各管线内部与现状逐条对应: + +- `swiftReport`:`measuringPreparation` 里对每个版本的每个镜像取 `swiftSnapshotDocument`;`comparesImageGroups` 时把每组配成 `ABIImageSnapshot(imageName:snapshot:)` 交给 `evolution(ofImageGroups:versions:)`、版本描述只带标签,否则把每版唯一的文档交给 `evolution(of:)`,两版本时追加 `ABIDiffer` 对照行。JSON 用同一个 `ABIEvolution` 编码(现状单镜像路径把它算了两遍,结果相同)。 +- `swiftInterface`:按开关选 `AnySwiftEvolutionInterfaceBuilder` 的 `imageGroups:` 或 `versions:` 构造器,平台传 `axis.availabilityPlatform?.swiftSpelling`;`measuringPreparation { try await builder.prepare() }`;正文 = `printAnnotatedInterface().string` 加 `// ABI-breaking on this axis:` 行;扩展名 `swiftinterface`,无 JSON。 +- `objcReport`:同 `swiftReport`,换成 `ObjCAPIImageSnapshot`、`ObjCAPIVersionDescriptor`、`ObjCAPIEvolutionBuilder`、`ObjCAPIDiffer`、`ObjCAPIJSON`;对照行写 `API-breaking`。 +- `objcInterface`:`measuringPreparation` 里逐版本 `addVersion(images:version:)` 或 `addVersion(indexer:machO:version:)`;`build(availabilityPlatform: axis.availabilityPlatform?.objcSpelling)`;正文加 `// API-breaking on this axis:` 行;扩展名 `h`,无 JSON。 + +### `EvolutionTests.swift`(一个套件的样子) + +```swift +enum EvolutionTestSuite { + /// SwiftUI together with SwiftUICore across every archived macOS cache: + /// SwiftUI alone until 14.8, SwiftUICore joining it in 15.0 — where an + /// evolution of SwiftUI alone reads every declaration moved into + /// SwiftUICore as removed. + final class SwiftUIImageGroupArchivedDyldCacheTests: MultiVersionDyldCacheImageTests, nonisolated EvolutionDumpTests, @unchecked Sendable { + override class var cachePaths: [DyldSharedCachePath] { archivedMacOSCachePaths } + override class var cacheImageNames: [MachOImageName] { [.SwiftUI, .SwiftUICore] } + override class var availabilityPlatform: EvolutionAvailabilityPlatform? { .macOS } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftReportFile() async throws { try await dump(.swiftReport, to: .file) } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftReportString() async throws { try await dump(.swiftReport, to: .console) } + + // swiftInterface / objcReport / objcInterface: one pair each, the same shape + } + + /// SwiftUICore across two simulator runtimes (iOS 18.5 → 26.5): the + /// N == 2 case, whose printed pairwise cross-check must agree with the + /// two-sided differ. + final class SwiftUICoreSimulatorTests: SwiftDiffableInterfaceBuilderTestSuite.CrossVersionMachOFileTests, nonisolated EvolutionDumpTests, @unchecked Sendable { + override class var oldFileName: MachOFileName { .iOS_18_5_Simulator_SwiftUICore } + override class var newFileName: MachOFileName { .iOS_26_5_Simulator_SwiftUICore } + + nonisolated func evolutionAxis(for language: EvolutionMetadataLanguage) -> EvolutionAxis { + EvolutionAxis( + versions: [ + EvolutionVersion(label: "18.5", images: [EvolutionImage(imageName: "SwiftUICore", machOFile: oldMachOFile)]), + EvolutionVersion(label: "26.5", images: [EvolutionImage(imageName: "SwiftUICore", machOFile: newMachOFile)]), + ], + comparesImageGroups: false, + availabilityPlatform: nil + ) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftReportFile() async throws { try await dump(.swiftReport, to: .file) } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftReportString() async throws { try await dump(.swiftReport, to: .console) } + } +} +``` + +`SwiftUIDyldCacheTests` 另保留 `swiftInterfaceStringViaPackFacade`(`@available(macOS 14.0, …)`):从 `evolutionAxis(for: .swift).versions` 取三个主镜像交给 `SwiftEvolutionInterfaceBuilder(configuration:versions:_:_:labels:)`,照旧不包 `measuringPreparation`(现状注释说明了原因:`@TestActor` 上的测试把隔离的闭包交出去会触发 region isolation 检查)。 + +### 与现状的行为差异 + +- **测试名**全部改变,套件从四个 enum 合到 `EvolutionTestSuite` 一个下。 +- **空轴**:现状的 file 入口在轴上一个版本都没有时静默返回,string 入口抛 `fewerThanTwoVersions`;合并后两种都抛。只在 cache 卷没挂载、镜像全不在时出现,抛错更容易看出问题。 +- **保留的 cache**:现状只留「主镜像在这条语言的轴上」的 cache,合并后留「有主镜像」的 cache(一个实例要同时服务两种语言)。在这十条轴上结果相同:SwiftUI 在每份归档 cache 里都有 Swift 元数据,AppKit 轴只跑 ObjC 管线、而 AppKit 在每份 cache 里都有 ObjC 元数据。 +- **输出内容与文件名**不变(依据见前期调研第 2、3 条);JSON 里的 `createdAt` 每次运行本来就不同。 + +## 替代方案考量 + +- **参数化测试**:每个轴一个 `@Test(arguments: EvolutionDumpKind.allCases)`。代码最短,但一点就跑全部管线,51 版归档轴要几个小时,也没法在跑之前单独挑一种输出。用户选了显式测试。 +- **所有轴都走镜像组路径**(单镜像当作一个镜像的组):能再删掉每条管线里的开关,但 `evolution(ofImageGroups:)` 给版本描述写 `imageNames`、不带 provenance,报告与 JSON 会变,和 CLI 单镜像的输出也不一致。否。 +- **把默认三版本轴统一成 AppKit**(注释原本这么写):Swift 一侧会从 SwiftUI 换成 AppKit,输出变了,维护者手里正在比的结果也就对不上。保留现状、改注释。 +- **轴做成值、套件按轴参数化**:同参数化测试的问题,而且 Xcode 里看不到按轴分开的套件。否。 +- **只抽公共函数、保留四个 enum**:能去掉管线里的重复,但轴的四重定义和互相引用还在,没解决用户点名的「Swift 和 ObjC 各有一套」。否。 + +## 影响 + +### 源码兼容性(source compatibility) + +纯测试改动,不涉及任何公开 API:IntegrationTests 不是 product,没有调用方。 + +### ABI 兼容性(条件项) + +不适用 —— 本库以 SPM 源码分发,使用方每次重新编译;本提案也只改测试目标。 + +### 下游影响 + +本仓库只有 IntegrationTests 目标受影响。下游仓库(RuntimeViewer、MachOKitUI 等)不依赖 IntegrationTests,无影响。 + +### 文档与示例 + +`Documentations/Internal/ABIEvolutionDesign.md:235-243` 引用了被删的 `ABIEvolutionTests.swift` 与 `ABIEvolutionTestSuite.DyldCacheTests`,改成新路径与套件名。账本、任务报告与已落地提案里的旧套件名是历史记录,不改。 + +## API 演进与废弃策略 + +不适用 —— 没有公开 API 变化;旧测试名直接删除,不留别名(理由见「采用的假设」)。 + +## 落地步骤 + +验证一律在 Ultra 上做(本机是公司那台,不编大工程):`queued-build swift build --build-tests`,scratch 用 `/Volumes/DerivedData/Agents.noindex/claude/SwiftPM/MachOSwiftSection`,默认 Xcode 编一遍,再用 `DEVELOPER_DIR=…/Xcode-26.6.0.app`(CI 的版本)编一遍。不运行 IntegrationTests。 + +1. **新骨架与四条管线**(已完成,Ultra 上 Xcode 26.6 与 27.2 的 `swift build --build-tests` 都通过)—— 改动地图里 `EvolutionAxis.swift` 全部、`EvolutionDumpTests.swift` 全部、`SwiftInterfaceTestSupport.swift` 的新重载。旧的三个文件还在,与新代码并存,名字不冲突(旧基类嵌在 `ABIEvolutionTestSuite` 里)。 + - 行为:`evolutionAxisForSwiftDropsVersionsWhosePrimaryImageHasNoSwiftSection` + - 行为:`evolutionAxisForObjCKeepsEveryCacheHoldingAppKit` + - 行为:`imageGroupAxisKeepsAnImageOnlyWhereItsCacheCarriesTheMetadata` + - 行为:`singleImageAxisUsesTheSingleImageBuilderEntryPoints` + - 行为:`reportWritesTextAndJSONNamedAfterTheNewestVersionsImages` + - 行为:`interfaceSpellsAvailabilityInItsOwnLanguagesSpelling` + - 本步只编译,测试目标能编过即可。 +2. **十个轴套件取代旧文件**(已完成,Ultra 上 Xcode 26.6 与 27.2 的 `swift build --build-tests` 都通过,新文件没有警告)—— `EvolutionTests.swift`;删除三个旧文件与随之变空的 `SwiftDiffing/`、`ObjCDiffing/` 目录;删除 `write(_:forImageGroup:)` 收元组的旧重载。 + - 行为:`everyAxisPipelinePairOfTheOldSuitesHasOneTestNow`(43 个,逐一对照「提议方案」的表) + - 行为:`noSuiteReadsAnotherSuitesClassProperties` + - 行为:`archivedAxesTakeTheCacheListFromTheBaseClass` + - 两个 Xcode 版本各编一遍。 +3. **文档**(已完成;落地前没有收到改前改后的输出比对结果)—— `ABIEvolutionDesign.md`、账本一节、两个索引;提案状态与决策日志随代码同批提交。 + - 维护者比对:挑 `SwiftUIImageGroupDyldCacheTests`(四种输出都有、只开三份 cache)前后各跑一次 file 测试,`diff` 两次的输出(JSON 忽略 `createdAt`)。结果记进决策日志。 + +**收尾时必须判断两件事**(判断结果写进决策日志,不允许沉默跳过): + +- **要不要配套专题文章** —— 预计不需要:这是维护者手检目标的内部整理,用法写在新文件的文档注释里。 +- **有没有引入新术语** —— 「版本轴」在旧注释里就在用;落地时查术语表,没有就判断是否值得登记。 + +## 决策日志 + +| 日期 | 变更 | 说明 | +|------|------|------| +| 2026-11-26 | Created as Draft | 用户要求把 IntegrationTests 里重复的演进测试抽出来,Swift 与 ObjC 各有一套套件,统一成一套。澄清一轮:范围只做演进(不顺带合并 diff 基类与 MachOSymbols 的重复);每种输出保留一对显式测试,不用参数化测试;按规则写轻量档提案。 | +| 2026-11-26 | Accepted | 用户看过简报后批准,开始实现。 | +| 2026-11-26 | In Progress:第 1 步开工 | 功能分支从本地 `next` 切出,按 `create-worktree` 的基线规则。本地 `next` 上还有一次未推送、待用户验收的合并(C 导入类型拼写),因此推送功能分支时它作为祖先一并上了远端功能分支,`next` 本身未推送。`MultiVersionDyldCacheImageTests` 用两个 `let`(`swiftAxis`、`objcAxis`)加 `switch` 存两条轴,不用字典加强制解包(详细设计里留的退路)。 | +| 2026-11-26 | 第 2、3 步完成 | 十个轴套件取代旧的三个文件;`SwiftDiffing/` 也随之变空、删除(改动地图原先只写了 `ObjCDiffing/`)。`ABIEvolutionDesign.md` 的集成套件一段改成新路径与套件名,账本追加一节。只编译、没运行 IntegrationTests。 | +| 2026-11-26 | 收尾判断 | 不配使用指南或实现说明:这是维护者手检目标的内部整理,用法写在新文件的文档注释里。没有新术语:「版本轴」是描述性说法,已在多份提案里直接使用,不登记术语表。 | +| 2026-11-26 | 实现完成,待用户看过后收尾 | 功能分支已推送,并在本地以 `--no-ff` 合进 `.worktrees/MachOSwiftSection` 的 `next`(不推送)。改前改后的输出比对由维护者做。 | +| 2026-11-26 | Implemented,取号 0110 | 用户要求收尾,与 0109(C 导入类型拼写,先进入 `next`)一起落地、推送 `next`。落地前没有收到改前改后的输出比对结果。 | diff --git a/Documentations/Evolutions/0111-unify-diff-and-interface-integration-suites.html b/Documentations/Evolutions/0111-unify-diff-and-interface-integration-suites.html new file mode 100644 index 000000000..879ea606a --- /dev/null +++ b/Documentations/Evolutions/0111-unify-diff-and-interface-integration-suites.html @@ -0,0 +1,563 @@ + + + + + + +0111 - IntegrationTests 的 diff 与接口套件合并:三类手检输出共用一套骨架 + + + + +
+ +
+

MachOSwiftSectionEvolutions0111

+

0111 IntegrationTests 的 diff 与接口套件合并:三类手检输出共用一套骨架

+
+
状态
Implemented
+
最后更新
2026-11-26
+
项目类型
库
+
原文
0111-unify-diff-and-interface-integration-suites.md
+
+
+ + + +
+ +
+

摘要

+

Tests/IntegrationTests/ 里维护者手检的输出有三类:单版本接口、两版本 diff、N 版本演进。演进一类在 0110 里已合并成「一个套件声明一次镜像、dump(.kind, to: .file / .console) 一行一个测试、Swift 与 ObjC 都出」;另两类还是各写各的:diff 自带三个「新旧两版」基类,读 cache 只开主文件,和演进套件、CLI 都不一样;接口套件为了多开一个选项把整份配置抄一遍;两类都只出 Swift。

+

本提案把三类放进同一个目录 Tests/IntegrationTests/InspectionDumps/,共用一套骨架:公共协议 InspectionDumpTests;diff 与演进共用版本轴(diff 就是只有两个版本的轴,cache 对改为整份打开);每类一个「输出种类」枚举加一个 dump 入口;AppKit 的接口套件多出整镜像 ObjC 头文件,AppKit 的 diff 套件多出 ObjC 变更列表与 JSON,Swift diff 报告也多写一份 JSON。

+

测试从 20 个(接口 10、diff 10)变成 38 个(接口 14、diff 24),演进的 43 个不变。只动 IntegrationTests 与它在 Package.swift 里的依赖表,不碰库代码。

+
+ +
+

要你定

+
+

已批准并落地。以下是没问用户就采用的假设:

+
    +
  1. ObjC 输出只加在 AppKit 的四个套件上;别的套件要看 ObjC,加一对一行测试即可。
  2. +
  3. ObjC 头文件开满注释(ivar 偏移、属性特性、方法 IMP 地址、访问器地址),与 Swift 接口开满字段偏移、成员地址对齐。
  4. +
  5. Swift diff 报告多写 -Diff.json;变更列表照旧用两个 builder 的 abiModule(),不改成快照往返。
  6. +
  7. 套件类名保留(DyldCacheTests、MachOFileTests……),只改外层枚举名与测试函数名;旧测试名不留别名。
  8. +
  9. Xcode 的 diff 对改为按版本号("26.3.0" / "26.4.0")取,版本号也当轴标签。
  10. +
  11. diff 轴不足两个版本时打印一行说明、不写文件。
  12. +
+
+
+ +
+

架构图

+
    +
  • 新增
  • +
  • 修改
  • +
  • 移动
  • +
  • 删除
  • +
  • 不变
  • +
+ +

改了什么:文件与类型

+
+ + + Tests/IntegrationTests/ (before) + + SwiftInterface/SwiftInterfaceTestSupport.swift + protocol SwiftInterfaceDumpTests + rootDirectory · measuringPreparation · printResult · write + + SwiftInterface/SwiftInterfaceBuilderTests.swift + protocol SwiftInterfaceBuilderTests — buildFile / buildString + enum SwiftInterfaceBuilderTestSuite — 5 suites, 10 tests + XcodeMachOFileTests restates the whole configuration + + SwiftInterface/SwiftDiffableInterfaceBuilderTests.swift + protocol SwiftDiffableInterfaceBuilderTests — diffFile/String + CrossVersionMachOFileTests · CrossVersionXcodeFrameworkTests + CrossVersionDyldCacheImageTests — DyldCache, main file only + enum SwiftDiffableInterfaceBuilderTestSuite — 5 suites, 10 tests + + Evolution/ (3 files) + EvolutionAxis · EvolutionDumpTests · EvolutionTests + 10 suites, 43 tests + + SwiftInterfaceIndexerTests · RenderingVerificationTests + + + Tests/IntegrationTests/InspectionDumps/ (after) + + InspectionDumpTests.swift + protocol InspectionDumpTests (+ indexConfiguration, deliver) + MetadataLanguage · DumpDestination · DumpFile · DumpOutput + + VersionAxis.swift + AxisImage · AxisVersion · VersionAxis · VersionAxes + protocol VersionAxisDumpTests — versionAxis(for:) + MultiVersionDyldCacheImageTests (FullDyldCache) + CrossVersionMachOFileTests · CrossVersionXcodeFrameworkTests + + InterfaceDumpTests.swift + InterfaceTests.swift + InterfaceDumpKind: swiftInterface | objcInterface + enum InterfaceTestSuite — 5 suites, 14 tests + + DiffDumpTests.swift + DiffTests.swift + DiffDumpKind: swiftReport | swiftInterface | objcReport + enum DiffTestSuite — 5 suites, 24 tests + + EvolutionDumpTests.swift + EvolutionTests.swift + protocol EvolutionDumpTests: VersionAxisDumpTests + enum EvolutionTestSuite — 10 suites, 43 tests (unchanged) + + + + + + + + +
+

两个旧套件文件拆成「管线 + 套件」两个新文件;diff 的两版基类并入版本轴文件;演进三文件随目录移动、换类型名。

+ +

协议与基类

+
+ + + InspectionDumpTests + rootDirectory · indexConfiguration · write · deliver + + + InterfaceDumpTests + dump(_: InterfaceDumpKind, of: machO, to:) + + + VersionAxisDumpTests + versionAxis(for: MetadataLanguage) + + + MachOTestingSupport base classes + DyldCacheTests · MachOFileTests + MachOImageTests · XcodeMachOFileTests + + + DiffDumpTests + first and last version + + + EvolutionDumpTests + every version + + + axis providers — each stores VersionAxes + + MultiVersionDyldCacheImageTests — cachePaths, opened whole + + CrossVersionMachOFileTests — two simulator runtime files + + CrossVersionXcodeFrameworkTests — two Xcode versions + + + + + + + + + +
+

实线箭头指向父协议;虚线是「套件继承这些基类」与「从这些基类拿轴」。

+ +

一个 diff 测试的调用链

+
+ + + DiffTestSuite.DyldCacheTests.objcReportFile() + + dump(.objcReport, to: .file) — DiffDumpTests + + versionAxis(for: .objc) → 26.5.1, 27.0 · AppKit + + objcReport — objcSnapshotDocument ×2 → ObjCAPIDiffer + + deliver → write(forImageGroup: [new.primaryImage]) → -ObjCDiff.txt / .json + + + + + +
+
+ +
+

改动地图

+
+ + + + + + + + + + + + + + + + + +
文件 / 类型动作改什么为什么步骤
InspectionDumps/新增三类手检输出的目录三类共用骨架,放一处1
InspectionDumps/InspectionDumpTests.swift(自 SwiftInterface/SwiftInterfaceTestSupport.swift)移动 修改协议改名;加 indexConfiguration、MetadataLanguage、DumpDestination、DumpFile、DumpOutput、deliver(_:to:writingFile:)、泛型 preparedObjCIndexer(of:);write(_:forImageGroup:) 收 [AxisImage]三类共用的部分只写一次1
InspectionDumps/VersionAxis.swift(自 Evolution/EvolutionAxis.swift)移动 修改去掉 Evolution 前缀;新增 VersionAxes 与 VersionAxisDumpTests(含共享的 objcSnapshotDocument);两个两版基类从 diff 文件搬来并给出轴diff 与演进共用版本轴1
InspectionDumps/EvolutionDumpTests.swift、EvolutionTests.swift(自 Evolution/)移动 修改改继承 VersionAxisDumpTests、用 DumpOutput;SwiftUICoreSimulatorTests 删掉自己拼轴的那段共用骨架1
SwiftInterface/SwiftInterfaceBuilderTests.swift删除第 1 步只改协议名,第 2 步删除分步可编1、2
SwiftInterface/SwiftDiffableInterfaceBuilderTests.swift删除第 1 步只改协议名、删 indexConfiguration,第 3 步删除分步可编1、3
InspectionDumps/InterfaceDumpTests.swift新增InterfaceDumpKind;InterfaceDumpTests(printsExportedDeclarationsOnly);dump(_:of:to:) 与两条管线接口一类的管线2
InspectionDumps/InterfaceTests.swift新增enum InterfaceTestSuite,5 个套件、14 个测试取代旧接口套件2
Package.swift · IntegrationTests修改加 ObjCDeclarationRendering product,改注释ObjCGenerationOptions 在这个 product 里2
InspectionDumps/DiffDumpTests.swift新增DiffDumpKind;DiffDumpTests: VersionAxisDumpTests;dump(_:to:) 与三条管线diff 一类的管线3
InspectionDumps/DiffTests.swift新增enum DiffTestSuite,5 个套件、24 个测试取代旧 diff 套件3
Documentations/Internal/ABIEvolutionDesign.md:235修改目录改 InspectionDumps/路径变了4
账本、两个索引修改追加一节;登记本提案文档规则4
+
+

表中路径都在 Tests/IntegrationTests/ 下(Package.swift 与文档除外)。

+
+ +
+

提议方案

+
+ + + + + + + +
类协议输入输出种类(CLI 对应)
接口InterfaceDumpTests一个镜像,任意读取器swiftInterface(interface)、objcInterface(objc dump)
diffDiffDumpTests版本轴的第一个与最后一个版本swiftReport(diff + --json)、swiftInterface(diff --interface)、objcReport(objc diff + --json)
演进EvolutionDumpTests整条版本轴不变
+
+
+ + + + + + + + + + + + + + +
套件读什么测试数
InterfaceTestSuite.DyldCacheTests本机 cache 的 AppKit · Swift + ObjC4
InterfaceTestSuite.ArchivedDyldCacheTests归档 26.6 的 AppKit · Swift + ObjC4
InterfaceTestSuite.MachOFileTestsSymbolTestsCore · Swift2
InterfaceTestSuite.MachOImageTests进程内 SwiftUICore · Swift2
InterfaceTestSuite.XcodeMachOFileTestsSourceEditor,只印导出声明 · Swift2
DiffTestSuite.SwiftUICoreTests模拟器 18.5 → 26.5 的 SwiftUICore · Swift 报告与接口4
DiffTestSuite.SwiftUITests模拟器 18.5 → 26.5 的 SwiftUI · Swift 报告与接口4
DiffTestSuite.DyldCacheTestscache 26.5.1 → 27.0 的 AppKit · 加 ObjC 报告6
DiffTestSuite.ArchivedDyldCacheTests归档 26.6 → 27.0 的 AppKit · 加 ObjC 报告6
DiffTestSuite.XcodeFrameworkTestsXcode 26.3.0 → 26.4.0 的 DVTProductsUI · Swift 报告与接口4
+
+

采用的假设

+
    +
  • diff 的 cache 对改为整份打开(用户在澄清时选定);输出可能与现状有出入,以与 CLI 一致为准。
  • +
  • 控制台只打印一份:diff 的 swiftInterface 写文件时出 inline 与 unified,打到控制台只出 inline,并只在写文件时渲染 unified。
  • +
  • 维护者在公司那台 next 检出里未提交的接口套件实验不碰(用户在澄清时选定);合回那个检出前由维护者自己收掉,否则合并会被挡住。实验里的「改读 AttributeGraph」在新结构里是给 InterfaceTestSuite.DyldCacheTests 改 cacheImageName。
  • +
  • 其余假设见「要你定」。
  • +
+

非目标

+
    +
  • 不动 SwiftDump/ 的 DumpableTests 一族、RenderingVerificationTests、SwiftInterfaceIndexerTests。
  • +
  • 不给 diff 加镜像组:两个 differ 都没有镜像组入口。
  • +
  • 不改库代码、不改 CLI;不运行 IntegrationTests。
  • +
+
+ +
+

详细设计

+
+ InspectionDumpTests.swift 与 VersionAxis.swift +
+
    +
  • DumpFile { suffix, fileExtension, text }、DumpOutput { consoleText, files };deliver(_:to:writingFile:) 打印 consoleText 或把每个文件交给调用方的命名函数(接口按 write(_:for: machO…),diff 与演进按 write(_:forImageGroup: newest.images…))。
  • +
  • preparedObjCIndexer(of:) 改成对 ObjCMetadataSource & MachORepresentableWithCache 泛型,进程内镜像也能用。
  • +
  • VersionAxes 存两个 let(Swift 轴、ObjC 轴)加 switch;三个轴基类都 @TestActor、都在 init 里建好它、都实现 nonisolated func versionAxis(for:)。
  • +
  • MultiVersionDyldCacheImageTests 的类属性与取镜像逻辑原样保留。CrossVersionMachOFileTests 加 oldVersionLabel / newVersionLabel(默认 "18.5" / "26.5"),镜像名取 imagePath.lastPathComponent。CrossVersionXcodeFrameworkTests 用 oldXcodeVersion / newXcodeVersion 拼 /Applications/Xcode-<版本>.app/…。
  • +
  • objcSnapshotDocument(of:label:) 从演进管线搬到 VersionAxisDumpTests 的扩展里,diff 的 ObjC 报告也用它。
  • +
+
+
+
+ InterfaceDumpTests.swift +
+
    +
  • dump<MachO: MachOFieldLayoutRenderable & ObjCMetadataSource>(_ kind:, of machO:, to:)。
  • +
  • 后缀按 machO.asMachOImage != nil 取 ImageDump 或 FileDump,ObjC 前加 ObjC、扩展名 h。
  • +
  • swiftInterface:与现状逐字相同的配置,只把 printExportedDeclarationsOnly 换成协议属性。
  • +
  • objcInterface:ObjCInterfaceBuilder(indexer:machO:),按 classes、protocols、categories、structs、unions 的顺序、名字排序逐个取接口,每段后接空行,与 objc dump --file 一致。
  • +
  • 在 @MainActor 的基类上改 printsExportedDeclarationsOnly 要写 nonisolated var;XcodeMachOFileTests 的基类不隔离。
  • +
+
+
+
+ DiffDumpTests.swift +
+
    +
  • 取 versionAxis(for: kind.language) 的第一个与最后一个版本;不足两个时打印 No diff: … version(s) carry … metadata 后返回。
  • +
  • swiftReport:两个 SwiftDiffableInterfaceBuilder 在一个 measuringPreparation 里准备;ABIDiffer + ABIDiffReporter + 结论行;JSON 用 ABIJSON.encoder()。
  • +
  • swiftInterface:SwiftDiffableInterfaceRenderer(old:new:).printAnnotatedInterface(format:),inline 必出,unified(.unified())只在写文件时渲染。
  • +
  • objcReport:两边 objcSnapshotDocument,ObjCAPIDiffer + ObjCAPIDiffReporter + API-breaking: … · backward-compatible: …;JSON 用 ObjCAPIJSON.encoder()。
  • +
+
+
+
+ 与现状的行为差异 +
+
+ + + + + + + + + +
方面现状之后
diff 的 cache 对DyldCache(path:) 只开主文件FullDyldCache(path:) 整份打开,与演进、CLI 一致
diff 的输出diffFile 写三个文件;diffString 印变更列表与 inlineswiftReport 写 .txt 与新增的 .json;swiftInterface 写 inline 与 unified,印 inline
新增 ObjC 输出无AppKit 接口:-ObjCFileDump.h;AppKit diff:-ObjCDiff.txt / .json
接口文件名按 is MachOImage不变,改按 asMachOImage
测试标识SwiftInterfaceBuilderTestSuite.*/buildFile()、SwiftDiffableInterfaceBuilderTestSuite.*/diffFile()InterfaceTestSuite.*/swiftInterfaceFile()、DiffTestSuite.*/swiftReportFile() 等;演进不变
+
+
+
+
+ +
+

动机

+
    +
  1. diff 自带三个「新旧两版」基类,和演进的版本轴是同一件事的两种写法;演进的模拟器套件还得借 diff 的基类、自己拼轴。
  2. +
  3. diff 读 cache 只开主文件,演进与 CLI 整份打开:同一个 AppKit 经两条读路径。
  4. +
  5. diff 的 DyldCacheTests 注释写 SwiftUI、15.5 → current,实际读 AppKit、26.5.1 → 27.0。
  6. +
  7. 接口的 XcodeMachOFileTests 为开一个选项抄了整份配置。
  8. +
  9. 接口套件用 machO is MachOImage 判读取器,项目规则要求问 asMachOImage。
  10. +
  11. 只有演进出 ObjC;AppKit 的 ObjC 部分远大于 Swift。
  12. +
  13. indexConfiguration 在三处各写一份。
  14. +
+
+ +
+

调研

+
    +
  • CLI 管线:objc dump 按五种声明、名字排序拼接(ObjCDumpRequest.swift、ObjCInterfaceSession.swift);diff / --json / --interface(ABIDiffRequest.swift:67-150);objc diff 只有变更列表与 JSON,没有带标注的头文件(ObjCAPIRequests.swift:56-108)。
  • +
  • 锁定的 MachOObjCSection 0.8.209 上,用到的 ObjC 接口都在,MachOImage 与 MachOFile 都遵循 ObjCMetadataSource;ObjCGenerationOptions 在 ObjCDeclarationRendering,需要加依赖;Tuist/Package.swift 不用改。
  • +
  • 单镜像时 write(_:for:) 与 write(_:forImageGroup:) 文件名逐字相同,diff 改用轴后文件名不变。
  • +
  • IntegrationTests 外只有 ABIEvolutionDesign.md:235 写着现行路径;别处的旧套件名是历史记录。
  • +
+
+ +
+

替代方案

+
    +
  • 单版本接口也走版本轴:放弃。接口要读进程内 MachOImage,轴与演进构建器只收 MachOFile。
  • +
  • 三类合成一个枚举、一个协议:放弃。三类输入形状不同,分开后编译期就排除了「对单个镜像跑 diff」。
  • +
  • diff 保留自己的基类、只改结构不加 ObjC:用户在澄清时否掉。
  • +
  • ObjC 加在每个套件上:暂不,需要时加一对一行测试即可。
  • +
  • 套件按镜像改名:放弃。接口与 diff 套件是维护者临时指向别的镜像的探针,按镜像命名容易名不副实。
  • +
+
+ +
+

影响

+
    +
  • 纯测试改动,没有公开 API 变化;IntegrationTests 不是 product。
  • +
  • Package.swift 只为 IntegrationTests 多列一个已有的 MachOObjCSection product;下游仓库无影响。
  • +
  • 维护者手动运行时用的测试名会变。
  • +
+
+ +
+

落地步骤

+

验证在 Ultra 上做:queued-build swift build --build-tests,默认 Xcode 与 Xcode 26.6 各编一遍;不运行 IntegrationTests。

+
    +
  1. 公共骨架与版本轴(已完成):新目录,四个文件移入并改名;两个旧文件只做机械改名以保持能编。
  2. +
  3. 接口一类(已完成):InterfaceDumpTests.swift、InterfaceTests.swift;删旧接口文件;Package.swift 加依赖。
  4. +
  5. diff 一类(已完成):DiffDumpTests.swift、DiffTests.swift;删旧 diff 文件。
  6. +
  7. 文档(已完成):ABIEvolutionDesign.md、账本、索引;维护者可选地挑几个 file 测试前后比对。
  8. +
+

收尾判断:预计不需要配套专题文章;不新增术语。

+
+ +
+

决策日志

+
+ 9 条,最近一条:Implemented,取号 0111 +
+
+ + + + + + + + + + + + + +
日期变更说明
2026-11-26Created as Draft0110 合并演进套件后,用户要求把 diff 与单版本接口两类手检套件也按同样的结构统一。澄清一轮:两类都加上 ObjC 输出;diff 改用演进套件的版本轴(cache 对因此整份打开,与 CLI 一致);维护者未提交的接口套件实验不碰,照提交版重构,由维护者自己收掉。
2026-11-26Accepted用户看过简报后批准,开始实现。
2026-11-26In Progress:第 1 步开工功能分支从 next 切出,next 上已有本提案的 Accepted 提交。第 1 步首次在 Xcode 27.2 上编译时,VersionAxis.swift 缺 FoundationToolbox 与 SwiftStdlibToolbox 的导入(成员导入可见性检查),补了一个提交;Xcode 26.6 首次撞上已知的 no such module 'swift_section' 构建顺序竞态,第 2 步重跑通过。
2026-11-26第 2、3 步完成measuringPreparation 改成泛型、返回准备好的值(详细设计原写不变):ObjC 头文件要在计时的一步里拿回索引器,ObjC diff 要拿回两份快照文档。diff 的文件名按新版本的主镜像起([newVersion.primaryImage]),不按整组镜像:diff 只读主镜像,单镜像时文件名与原来相同。带标注的接口两种格式各建一个渲染器,与现状一致。
2026-11-26第 4 步完成ABIEvolutionDesign.md 的集成套件一段改成新目录并链接本提案;账本追加一节(节号落地时取)。只编译、没运行 IntegrationTests。
2026-11-26收尾判断不配使用指南或实现说明:这是维护者手检目标的内部整理,用法写在新文件的文档注释里。没有新术语:「版本轴」0110 已判断不登记。
2026-11-26实现完成,待用户看过后收尾功能分支已推送。合进 .worktrees/MachOSwiftSection 的 next 时被维护者在 SwiftInterfaceBuilderTests.swift 里未提交的实验挡住,没有合并。
2026-11-26维护者的实验先提交,合并按新结构处理用户要求先提交工作区的改动再合并收尾:实验(接口套件读 AttributeGraph、显示 C 导入类型、只印导出声明、注册 SwiftInterfaceBuilderTypeNameProvider)与 Xcode 自动改写的两个工作区设置各成一个提交进 next。合并时功能分支删掉的 SwiftInterfaceBuilderTests.swift 与实验的修改冲突,按澄清时的选择取删除:实验不搬进新套件,只留在历史里。合并后的代码与 Ultra 上编过的功能分支逐字相同(只多两个 Xcode 设置文件),没有重新验证。
2026-11-26Implemented,取号 0111用户要求收尾,以 --no-ff 合进 next 并推送。没有收到改前改后的输出比对结果。
+
+
+
+
+ +
+
+ + diff --git a/Documentations/Evolutions/0111-unify-diff-and-interface-integration-suites.md b/Documentations/Evolutions/0111-unify-diff-and-interface-integration-suites.md new file mode 100644 index 000000000..7055b5680 --- /dev/null +++ b/Documentations/Evolutions/0111-unify-diff-and-interface-integration-suites.md @@ -0,0 +1,445 @@ +# 0111 - IntegrationTests 的 diff 与接口套件合并:三类手检输出共用一套骨架 + +- **状态**: Implemented +- **作者**: JH +- **创建日期**: 2026-11-26 +- **最后更新**: 2026-11-26 +- **所属愿景**: 无 +- **关联提案**: [0110-unify-evolution-integration-suites](0110-unify-evolution-integration-suites.md)(演进套件的合并;本提案把同样的结构推到 diff 与单版本接口,并让 diff 与演进共用它的版本轴);[0061-dyld-shared-cache-path-versions](0061-dyld-shared-cache-path-versions.md)(按版本号取归档 cache、`versionLabel`) +- **实现分支 / PR**: `feature/unify-diff-and-interface-integration-suites`(worktree `.worktrees/MachOSwiftSection-UnifyDiffAndInterfaceIntegrationSuites`) +- **配套文档**: 无(见决策日志「收尾判断」) +- **网页版**: 同目录同名的 `.html` + +## 摘要 + +`Tests/IntegrationTests/` 里维护者手检的输出有三类:单版本接口(`SwiftInterfaceBuilderTests.swift`)、两版本 diff(`SwiftDiffableInterfaceBuilderTests.swift`)、N 版本演进(`Evolution/`,0110 刚合并过)。演进那一类已经是「一个套件声明一次镜像、`dump(.kind, to: .file / .console)` 一行一个测试、Swift 与 ObjC 都出」;另两类还是各写各的:diff 自带三个「新旧两版」基类,读 cache 只开主文件,和演进套件、CLI 都不一样;接口套件为了多开一个选项把整份配置抄一遍;两类都只出 Swift。 + +本提案把三类放进同一个目录 `Tests/IntegrationTests/InspectionDumps/`,共用一套骨架: + +- **一个公共协议 `InspectionDumpTests`**(原 `SwiftInterfaceDumpTests`):输出目录、计时、打印、写文件,以及三类共用的输出形状 `DumpOutput` / `DumpDestination`、元数据语言 `MetadataLanguage`、准备 ObjC 索引的函数。 +- **diff 与演进共用版本轴**:diff 就是只有两个版本的轴。`MultiVersionDyldCacheImageTests`(整份打开每个 cache)给 diff 的 cache 对用;模拟器文件对、Xcode 框架对的两个基类搬到顶层,也各自给出轴。原 `Evolution*` 前缀的轴类型去掉前缀(`VersionAxis`、`AxisVersion`、`AxisImage`、`AvailabilityPlatform`)。 +- **每类一个「输出种类」枚举 + 一个 `dump` 入口**:`InterfaceDumpKind`(`swiftInterface` / `objcInterface`)、`DiffDumpKind`(`swiftReport` / `swiftInterface` / `objcReport`)、`EvolutionDumpKind`(不变)。 +- **新增 ObjC 输出**:AppKit 的两个接口套件多出整镜像的 ObjC 头文件(`objc dump` 的管线),AppKit 的两个 diff 套件多出 ObjC 变更列表与 JSON(`objc diff` 的管线);Swift diff 报告也多写一份 JSON(`diff --json`)。 + +测试从 20 个(接口 10、diff 10)变成 38 个(接口 14、diff 24),演进的 43 个不变。只动 IntegrationTests 与它在 `Package.swift` 里的依赖表,不碰库代码。 + +## 动机 + +0110 合并演进套件时把 diff 与接口划在范围外。现在三类并排,差异本身就成了要维护的东西: + +1. **diff 有自己的一套「新旧两版」基类,和演进的版本轴是同一件事的两种写法**。`SwiftDiffableInterfaceBuilderTestSuite` 里的 `CrossVersionMachOFileTests`(`Tests/IntegrationTests/SwiftInterface/SwiftDiffableInterfaceBuilderTests.swift:95`)、`CrossVersionDyldCacheImageTests`(`:113`)、`CrossVersionXcodeFrameworkTests`(`:138`)各自持有一对 `MachOFile`;演进套件 `EvolutionTestSuite.SwiftUICoreSimulatorTests` 还得借 diff 的 `CrossVersionMachOFileTests`(`Tests/IntegrationTests/Evolution/EvolutionTests.swift:326`),再自己把这一对包成 `EvolutionAxis`(`:330-339`)。 +2. **diff 读 cache 的方式和演进、CLI 都不同**。`CrossVersionDyldCacheImageTests` 用 `DyldCache(path:)` 只打开主文件(`:124-125`),从主 cache 取镜像;`MultiVersionDyldCacheImageTests` 与 `swift-section --dyld-shared-cache` 都整份打开(`FullDyldCache`,见 `Tests/IntegrationTests/Evolution/EvolutionAxis.swift:92-96` 的注释)。同一个 AppKit,在 diff 与演进两个手检输出里经两条读路径。 +3. **注释和代码对不上**。diff 的 `DyldCacheTests` 注释写「The same macOS image (SwiftUI) extracted from two dyld shared caches (macOS 15.5 → current)」(`:190-191`),实际读 AppKit,26.5.1 → 27.0(`:193-195`)。0110 在演进套件里修过同一类问题。 +4. **接口套件为一个选项抄整份配置**。`XcodeMachOFileTests` 只想开 `printExportedDeclarationsOnly`,却把 `builderConfiguration` 的十几个参数整段重写(提交版 `SwiftInterfaceBuilderTests.swift:151-173`),以后改默认配置要改两处。 +5. **接口套件用类型转换判读取器**。`buildFile` 用 `machO is MachOImage` 决定文件后缀(提交版 `:66`)。项目规则要求问 `asMachOImage`,不转具体类型(`CLAUDE.md`「you need to know whether a reader is a MachOImage or a MachOFile」一节);这里是测试代码,扫描不到,但同样会把包装类型认错。 +6. **只有演进出 ObjC**。AppKit 的 ObjC 部分远大于 Swift,维护者却只能在演进套件里看到它;看单个 cache 的 AppKit 头文件、两版之间的 ObjC 变化,得另跑 CLI。 +7. **三类的 `indexConfiguration` 各写一份**(`SwiftDiffableInterfaceBuilderTests.swift:25`、`EvolutionDumpTests.swift:82`、接口配置里的 `indexConfiguration:`),值都是 `.init(showCImportedTypes: false)`。 + +## 前期调研 + +1. **CLI 里对应的管线**(测试要复现的就是它们): + - Swift 单版本接口:`SwiftInterfaceBuilder` + `SwiftInterfaceBuilderOpaqueTypeProvider`,`prepare()` 后 `printRoot()`。现状测试照此做,打印配置开满(字段偏移、地址、vtable/PWT 偏移、布局、按偏移排序等)。 + - ObjC 整镜像头文件:`swift-section objc dump`(`Sources/Commands/SwiftSectionKit/ObjC/ObjCDumpRequest.swift`)。`ObjCInterfaceSession.make` 建 `ObjCInterfaceIndexer(machO:imagePath:suppliedClasses:)`(`suppliedClasses` 用 `ObjCSuppliedClass.swiftClassesWithoutClassObjects(in:)`)、`prepare()`,再用 `ObjCInterfaceBuilder(indexer:machO:)` 按 `classes, protocols, categories, structs, unions` 的顺序、每种名字排序后逐个取 `classInterface(named:…)` / `protocolInterface` / `categoryInterface(uniqueName:…)` / `structInterface` / `unionInterface`,写文件时每段后接一个空行。`ObjCDeclarationKind` 在 SwiftSectionKit 里,IntegrationTests 不依赖 SwiftSectionKit,测试里照这个顺序自己写五个分支。 + - Swift diff:变更列表是 `ABIDiffer().diff(old:new:)` + `ABIDiffReporter().report(_:)` + 一行 `ABI-breaking: … · backward-compatible: …`;`--json` 是 `ABIJSON.encoder().encode(diff)`;`--interface` 是 `SwiftDiffableInterfaceRenderer(old:new:).printAnnotatedInterface(format:)`(`Sources/Commands/SwiftSectionKit/Swift/ABIDiffRequest.swift:67-150`)。现状测试的变更列表直接用两个 builder 的 `abiModule()`,不经快照文档。 + - ObjC diff:`ObjCAPIDiffRequest`(`Sources/Commands/SwiftSectionKit/ObjC/ObjCAPIRequests.swift:56-108`)把两边各读成 `ObjCAPISnapshotDocument`,`ObjCAPIDiffer().diff(old:new:)`,变更列表 `ObjCAPIDiffReporter().report(_:)` + 一行 `API-breaking: … · backward-compatible: …`,`--json` 是 `ObjCAPIJSON.encoder().encode(diff)`。ObjC diff **没有**带标注的头文件。 +2. **用到的 ObjC 接口在锁定版本里都有**。`Package.resolved` 锁 MachOObjCSection 0.8.209;在这个 tag 上 `ObjCInterfaceBuilder` 的五个 `…Interface` 方法、`ObjCInterfaceIndexer` 的五个 `…Names`、`ObjCGenerationOptions.printExportedDeclarationsOnly` 都在,`MachOImage` 与 `MachOFile` 都遵循 `ObjCMetadataSource`。`ObjCGenerationOptions` 在 `ObjCDeclarationRendering` 这个 product 里,IntegrationTests 目前没依赖它,要在 `Package.swift` 加一行;`Tuist/Package.swift` 不逐个列 MachOObjCSection 的 product,不用改。 +3. **`swiftClassesWithoutClassObjects(in:)` 收 `some MachORepresentableWithCache`**(`Sources/Declaration/SwiftIndexing/ObjCSuppliedClass+SwiftClassesWithoutClassObjects.swift:26`),`ObjCInterfaceIndexer` 对 `MachO: ObjCMetadataSource` 泛型,所以准备 ObjC 索引的函数可以改成泛型,接口套件的进程内镜像也能用。 +4. **测试支撑的基类**(MachOKitExtensions 的 `MachOTestingSupport`):`DyldCacheTests` 在 `cachePath == .current` 时用 `FullDyldCache.cachedHost`,否则 `FullDyldCache(path:)`,`machOFileInCache` 取自整份 cache;`MachOFileTests`、`MachOImageTests` 是 `@MainActor`;`XcodeMachOFileTests` 没有隔离。接口套件继续用这些基类,不需要版本轴。 +5. **文件命名**:`write(_:for:…)` 与 `write(_:forImageGroup:…)` 在单镜像时逐字相同(0110 调研第 3 条),所以 diff 改用轴之后输出文件名不变。 +6. **IntegrationTests 外引用这些名字的地方**:`Documentations/Internal/ABIEvolutionDesign.md:235` 写着 `Tests/IntegrationTests/Evolution/`;账本、任务报告、已落地提案里的 `SwiftInterfaceBuilderTestSuite` 等旧名是历史记录。`Scripts/`、`Sources/`、别的测试目标都不引用。 + +## 提议方案 + +### 三类的分工 + +| 类 | 协议 | 输入 | 输出种类(CLI 对应) | 文件后缀 | +|---|---|---|---|---| +| 接口 | `InterfaceDumpTests` | 一个镜像,任意读取器(文件、cache 里的文件、进程内镜像) | `swiftInterface`(`interface`)、`objcInterface`(`objc dump`) | `-FileDump.swiftinterface` / `-ImageDump.swiftinterface`;`-ObjCFileDump.h` / `-ObjCImageDump.h` | +| diff | `DiffDumpTests` | 版本轴的第一个与最后一个版本(主镜像) | `swiftReport`(`diff` + `diff --json`)、`swiftInterface`(`diff --interface`,inline 与 unified)、`objcReport`(`objc diff` + `--json`) | `-Diff.txt` / `.json`;`-AnnotatedInterface-Inline` / `-Unified.swiftinterface`;`-ObjCDiff.txt` / `.json` | +| 演进 | `EvolutionDumpTests` | 整条版本轴 | 不变 | 不变 | + +diff 与演进都是 `VersionAxisDumpTests`(要求 `versionAxis(for:)`),都由三个轴基类之一供轴: + +| 轴基类 | 版本来自 | 谁用 | +|---|---|---| +| `MultiVersionDyldCacheImageTests` | `cachePaths` 列出的 cache,整份打开 | 演进的九个 cache 套件;diff 的两个 AppKit 套件 | +| `CrossVersionMachOFileTests` | 两个模拟器运行时里的同一个文件 | 演进的 `SwiftUICoreSimulatorTests`;diff 的 `SwiftUICoreTests`、`SwiftUITests` | +| `CrossVersionXcodeFrameworkTests` | 两个已安装的 Xcode 里同一个共享框架 | diff 的 `XcodeFrameworkTests` | + +### 套件与测试 + +套件类名保留现状(接口与 diff 的套件是「指向任意镜像」的探针,维护者常临时改读别的镜像,按来源命名比按镜像命名更不易过时);外层的枚举改名,测试函数改成「种类 + 去向」: + +| 套件 | 读什么 | 测试 | +|---|---|---| +| `InterfaceTestSuite.DyldCacheTests` | 本机 cache 的 AppKit | `swiftInterfaceFile/String`、`objcInterfaceFile/String` | +| `InterfaceTestSuite.ArchivedDyldCacheTests` | 归档 26.6 cache 的 AppKit | 同上 4 个 | +| `InterfaceTestSuite.MachOFileTests` | SymbolTestsCore fixture | `swiftInterfaceFile/String` | +| `InterfaceTestSuite.MachOImageTests` | 进程内 SwiftUICore | `swiftInterfaceFile/String` | +| `InterfaceTestSuite.XcodeMachOFileTests` | Xcode 的 SourceEditor,只印导出声明 | `swiftInterfaceFile/String` | +| `DiffTestSuite.SwiftUICoreTests` | 模拟器 18.5 → 26.5 的 SwiftUICore | `swiftReportFile/String`、`swiftInterfaceFile/String` | +| `DiffTestSuite.SwiftUITests` | 模拟器 18.5 → 26.5 的 SwiftUI | 同上 4 个 | +| `DiffTestSuite.DyldCacheTests` | cache 26.5.1 → 27.0 的 AppKit | 同上 4 个 + `objcReportFile/String` | +| `DiffTestSuite.ArchivedDyldCacheTests` | 归档 cache 26.6 → 27.0 的 AppKit | 同上 6 个 | +| `DiffTestSuite.XcodeFrameworkTests` | Xcode 26.3.0 → 26.4.0 的 DVTProductsUI | `swiftReportFile/String`、`swiftInterfaceFile/String` | + +ObjC 输出只加在 AppKit 套件上(ObjC 是 AppKit 的大头;别的套件要看 ObjC,加一对一行测试即可)。 + +### 采用的假设 + +- **diff 的 cache 对改为整份打开**(用户在澄清时选定)。输出可能与现状有出入,以与 CLI 一致为准。 +- **ObjC 头文件开满注释**:ivar 偏移、属性特性、方法 IMP 地址、访问器地址四种注释都开。Swift 接口这边本来就开满了字段偏移与成员地址,手检输出以信息最多为目标。 +- **Swift diff 报告多写一份 `-Diff.json`**,与演进报告、ObjC diff 报告对齐;变更列表照旧用两个 builder 的 `abiModule()`,不改成快照文档往返(不改变现有输出)。 +- **diff 比较轴上第一个与最后一个版本的主镜像**。diff 套件只声明两个版本、一个镜像;轴筛掉版本后不足两个时,打印一行说明、不写文件(与演进轴为空时直接返回一致,IntegrationTests 不设断言)。 +- **控制台只打印一份**:diff 的 `swiftInterface` 写文件时出 inline 与 unified 两份,打到控制台只出 inline(现状 `diffString` 也只印 inline);为此这条管线按去向决定要不要渲染 unified,省一次完整渲染。 +- **Xcode 对按版本号取**:`CrossVersionXcodeFrameworkTests` 的类属性从 `oldXcodeApplicationPath` / `newXcodeApplicationPath` 改为 `oldXcodeVersion` / `newXcodeVersion`(`"26.3.0"` / `"26.4.0"`),路径拼成 `/Applications/Xcode-<版本>.app`,版本号也当轴标签,与归档 cache 按版本号取一致。 +- **旧测试名直接删除,不留别名**:IntegrationTests 没有调用方,测试名只在维护者手动运行时用到。 +- **维护者在公司那台 `next` 检出里未提交的 `SwiftInterfaceBuilderTests.swift` 实验不碰**(用户在澄清时选定):本提案照提交版重构;合回那个检出前,由维护者自己提交或丢弃那份实验,否则合并会被它挡住。实验里的「改读 AttributeGraph」在新结构里是给 `InterfaceTestSuite.DyldCacheTests` 改 `cacheImageName`。 + +### 非目标 + +- 不动 `SwiftDump/` 的 `DumpableTests` 一族(`dump` 子命令的手检,结构另成一套)。 +- 不动 `RenderingVerificationTests`(渲染 A/B 验证的 MachOImage 腿,有自己的约定)与 `SwiftInterfaceIndexerTests`。 +- 不给 diff 加镜像组:`ABIDiffer` 与 `ObjCAPIDiffer` 没有镜像组入口。 +- 不改库代码、不改 CLI。 + +## 改动地图 + +| 文件 · 类型 | 动作 | 改什么 | 为什么 | 步骤 | +|---|---|---|---|---| +| `Tests/IntegrationTests/InspectionDumps/` | 新增目录 | 三类手检输出的家 | 三类共用骨架,放一处 | 1 | +| `InspectionDumps/InspectionDumpTests.swift`(`git mv` 自 `SwiftInterface/SwiftInterfaceTestSupport.swift`) | 移动 + 修改 | 协议改名 `InspectionDumpTests`;加 `indexConfiguration`、`MetadataLanguage`(自 `EvolutionMetadataLanguage`)、`DumpDestination`、`DumpFile`、`DumpOutput`、`deliver(_:to:writingFile:)`、泛型的 `preparedObjCIndexer(of:)`;`write(_:forImageGroup:)` 收 `[AxisImage]` | 三类共用的部分只写一次 | 1 | +| `InspectionDumps/VersionAxis.swift`(`git mv` 自 `Evolution/EvolutionAxis.swift`) | 移动 + 修改 | 去掉 `Evolution` 前缀:`AvailabilityPlatform`、`AxisImage`、`AxisVersion`、`VersionAxis`;新增 `VersionAxes`(两种语言各一条轴)与协议 `VersionAxisDumpTests`(含共享的 `objcSnapshotDocument(of:label:)`);`MultiVersionDyldCacheImageTests` 改存 `VersionAxes`;`CrossVersionMachOFileTests`、`CrossVersionXcodeFrameworkTests` 从 diff 文件搬来,加版本标签与轴 | diff 与演进共用版本轴 | 1 | +| `InspectionDumps/EvolutionDumpTests.swift`(`git mv` 自 `Evolution/`) | 移动 + 修改 | 改继承 `VersionAxisDumpTests`;`EvolutionDumpOutput` 换成 `DumpOutput`;`evolutionAxis(for:)` 改名 `versionAxis(for:)`;删自己的 `indexConfiguration`、`preparedObjCIndexer`、`objcSnapshotDocument` | 共用骨架 | 1 | +| `InspectionDumps/EvolutionTests.swift`(`git mv` 自 `Evolution/`) | 移动 + 修改 | 换新类型名;`SwiftUICoreSimulatorTests` 改继承顶层 `CrossVersionMachOFileTests`,删掉自己拼轴的那段 | 轴由基类给 | 1 | +| `SwiftInterface/SwiftDiffableInterfaceBuilderTests.swift` | 修改(第 1 步)→ 删除(第 3 步) | 第 1 步只把协议名改成 `InspectionDumpTests`、删自己的 `indexConfiguration`,保证能编 | 分步可编 | 1、3 | +| `SwiftInterface/SwiftInterfaceBuilderTests.swift` | 修改(第 1 步)→ 删除(第 2 步) | 第 1 步只改协议名 | 分步可编 | 1、2 | +| `InspectionDumps/InterfaceDumpTests.swift` | 新增 | `InterfaceDumpKind`;协议 `InterfaceDumpTests`(`printsExportedDeclarationsOnly`);`builderConfiguration`、`objcGenerationOptions`;`dump(_:of:to:)` 与两条管线 | 接口一类的管线 | 2 | +| `InspectionDumps/InterfaceTests.swift` | 新增 | `enum InterfaceTestSuite`,五个套件、14 个测试 | 取代旧接口套件 | 2 | +| `InspectionDumps/DiffDumpTests.swift` | 新增 | `DiffDumpKind`;协议 `DiffDumpTests: VersionAxisDumpTests`;`dump(_:to:)` 与三条管线 | diff 一类的管线 | 3 | +| `InspectionDumps/DiffTests.swift` | 新增 | `enum DiffTestSuite`,五个套件、24 个测试 | 取代旧 diff 套件 | 3 | +| `Tests/IntegrationTests/Evolution/` | 删除(目录) | 三个文件移走后为空 | — | 1 | +| `Package.swift` · `IntegrationTests` 目标 | 修改 | 加 `.product(name: "ObjCDeclarationRendering", package: "MachOObjCSection")`;注释从「ObjC API evolution dumps」改为三类 ObjC 输出 | `ObjCGenerationOptions` 在这个 product 里 | 2 | +| `Documentations/Internal/ABIEvolutionDesign.md:235` | 修改 | 目录改 `Tests/IntegrationTests/InspectionDumps/` | 路径变了 | 4 | +| `Documentations/Internal/ProjectEvolutionLog.md` | 修改 | 追加一节 | 账本 | 4 | +| `Documentations/Evolutions/README.md`、`Documentations/README.md` | 修改 | 登记本提案 | 索引 | 起草时 / 4 | + +## 架构图 + +改了什么(文件与类型): + +``` +Tests/IntegrationTests/ +- SwiftInterface/SwiftInterfaceTestSupport.swift protocol SwiftInterfaceDumpTests +- SwiftInterface/SwiftInterfaceBuilderTests.swift protocol SwiftInterfaceBuilderTests + enum SwiftInterfaceBuilderTestSuite (5) +- SwiftInterface/SwiftDiffableInterfaceBuilderTests.swift +- protocol SwiftDiffableInterfaceBuilderTests +- enum SwiftDiffableInterfaceBuilderTestSuite +- CrossVersionMachOFileTests / CrossVersionDyldCacheImageTests (DyldCache, main file only) / CrossVersionXcodeFrameworkTests +- 5 suites +- Evolution/EvolutionAxis.swift / EvolutionDumpTests.swift / EvolutionTests.swift + SwiftInterface/SwiftInterfaceIndexerTests.swift, RenderingVerificationTests.swift (unchanged) ++ InspectionDumps/ ++ InspectionDumpTests.swift protocol InspectionDumpTests ++ MetadataLanguage, DumpDestination, DumpFile, DumpOutput, preparedObjCIndexer(of:) ++ VersionAxis.swift AvailabilityPlatform, AxisImage, AxisVersion, VersionAxis, VersionAxes ++ protocol VersionAxisDumpTests: InspectionDumpTests ++ MultiVersionDyldCacheImageTests (FullDyldCache) ++ CrossVersionMachOFileTests, CrossVersionXcodeFrameworkTests ++ InterfaceDumpTests.swift InterfaceDumpKind { swiftInterface, objcInterface } ++ protocol InterfaceDumpTests: InspectionDumpTests ++ InterfaceTests.swift enum InterfaceTestSuite (5 suites, 14 tests) ++ DiffDumpTests.swift DiffDumpKind { swiftReport, swiftInterface, objcReport } ++ protocol DiffDumpTests: VersionAxisDumpTests ++ DiffTests.swift enum DiffTestSuite (5 suites, 24 tests) +~ EvolutionDumpTests.swift protocol EvolutionDumpTests: VersionAxisDumpTests +~ EvolutionTests.swift enum EvolutionTestSuite (10 suites, 43 tests) +``` + +协议与基类的关系: + +``` +InspectionDumpTests (rootDirectory, indexConfiguration, measuringPreparation, printResult, write, deliver) +├── InterfaceDumpTests dump(_: InterfaceDumpKind, of: machO, to:) +│ suites inherit MachOTestingSupport bases: DyldCacheTests / MachOFileTests / MachOImageTests / XcodeMachOFileTests +└── VersionAxisDumpTests versionAxis(for: MetadataLanguage) -> VersionAxis + ├── DiffDumpTests dump(_: DiffDumpKind, to:) reads versions.first / versions.last + └── EvolutionDumpTests dump(_: EvolutionDumpKind, to:) reads every version + axis providers: MultiVersionDyldCacheImageTests | CrossVersionMachOFileTests | CrossVersionXcodeFrameworkTests + each stores VersionAxes (swift axis, objc axis) built in init +``` + +一个 diff 测试的调用链: + +``` +DiffTestSuite.DyldCacheTests.objcReportFile() + └─ dump(.objcReport, to: .file) DiffDumpTests + ├─ versionAxis(for: .objc) MultiVersionDyldCacheImageTests (26.5.1, 27.0 / AppKit) + ├─ old = versions.first, new = versions.last + ├─ objcReport(old:new:) + │ ├─ measuringPreparation { objcSnapshotDocument(of: old.primaryImage) ; … new … } + │ │ └─ preparedObjCIndexer(of:) → ObjCAPISnapshotBuilder.snapshot() → JSON round trip + │ ├─ ObjCAPIDiffer().diff(old:new:) + │ └─ DumpOutput(console: report, files: [ObjCDiff.txt, ObjCDiff.json]) + └─ deliver(output, to: .file) → write(_:forImageGroup: [new.primaryImage], …) +``` + +## 详细设计 + +### `InspectionDumpTests.swift` + +```swift +/// Shared scaffolding for the maintainer-inspection dumps: the single-version +/// interfaces, the two-version diffs and the N-version evolutions. +protocol InspectionDumpTests {} + +@available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) +extension InspectionDumpTests { + var rootDirectory: URL // unchanged: Documents/SwiftInterfaceTests + var indexConfiguration: SwiftDeclarationIndexConfiguration { .init(showCImportedTypes: false) } + func measuringPreparation(_ prepare: () async throws -> Prepared) async rethrows -> Prepared // now returns what it prepared + func printResult(_ string: String) // unchanged + func write(_:for:suffix:fileExtension:) throws // unchanged + func write(_:forImageGroup images: [AxisImage], suffix:fileExtension:) throws + + /// Prints the console text, or writes every file through `writeFile`. + func deliver(_ output: DumpOutput, to destination: DumpDestination, writingFile writeFile: (DumpFile) throws -> Void) rethrows +} + +enum MetadataLanguage: Sendable { case swift, objc; func isCarried(by machOFile: MachOFile) -> Bool } +enum DumpDestination: Sendable { case console, file } + +/// One file a dump writes: named `--.`. +struct DumpFile: Sendable { let suffix: String; let fileExtension: String; let text: String } + +/// What one pipeline produced: what the console destination prints, and +/// what the file destination writes. +struct DumpOutput: Sendable { let consoleText: String; let files: [DumpFile] } + +/// One image indexed the way the `objc` subcommands index it. +@available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) +func preparedObjCIndexer(of machO: MachO) async throws -> ObjCInterfaceIndexer +``` + +`BuildVersionCommand` 与 `Platform.stringValue` 的扩展原样搬来。`deliver` 让三类各自决定文件名怎么起:接口按 `write(_:for: machO…)`,演进按 `write(_:forImageGroup: newest.images…)`,diff 按 `write(_:forImageGroup: [newVersion.primaryImage]…)`(diff 只读主镜像;单镜像时三种写法得到同一个文件名)。`measuringPreparation` 改成泛型、返回准备好的值:ObjC 头文件与 ObjC diff 要在计时的那一步里拿回索引器或快照文档。 + +### `VersionAxis.swift` + +`AvailabilityPlatform`、`AxisImage`、`AxisVersion`(含 `keepingImages(carrying:)`)、`VersionAxis` 只改名,语义不变。新增: + +```swift +/// One axis per metadata language, each keeping the versions whose primary +/// image carries that language's metadata. Built once at initialization: +/// the class properties it derives from are isolated to the test actor, +/// the pipelines are not. +struct VersionAxes: Sendable { + init(versions: [AxisVersion], comparesImageGroups: Bool, availabilityPlatform: AvailabilityPlatform?) + func axis(for language: MetadataLanguage) -> VersionAxis +} + +/// A dump over an ordered series of versions: a diff reads its first and +/// last version, an evolution every version. +protocol VersionAxisDumpTests: InspectionDumpTests { + func versionAxis(for language: MetadataLanguage) -> VersionAxis +} + +extension VersionAxisDumpTests { + /// moved from EvolutionDumpTests (was private); the diff's ObjC report uses it too + func objcSnapshotDocument(of image: AxisImage, label: String) async throws -> ObjCAPISnapshotDocument +} +``` + +`VersionAxes` 存成两个 `let`(`swiftAxis`、`objcAxis`)加 `switch`,与 0110 落地时的写法一致。三个轴基类都 `@TestActor`,都存一个 `let axes: VersionAxes`,都实现 `nonisolated func versionAxis(for:) -> VersionAxis { axes.axis(for: language) }`: + +- `MultiVersionDyldCacheImageTests`:类属性(`cachePaths`、`cacheImageName`、`cacheImageNames`、`availabilityPlatform`、`defaultMacOSCachePaths`、`archivedMacOSCachePaths` 与 51 个版本)与 `init` 的取镜像逻辑原样保留,最后一步改成 `self.axes = VersionAxes(versions:comparesImageGroups:availabilityPlatform:)`。文档注释里指向 diff 基类的那句改掉。 +- `CrossVersionMachOFileTests`:保留 `oldMachOFile` / `newMachOFile`、`oldFileName` / `newFileName`(默认 SwiftUICore 18.5 / 26.5);新增 `oldVersionLabel` / `newVersionLabel`(默认 `"18.5"` / `"26.5"`)。轴的镜像名取 `machOFile.imagePath.lastPathComponent`(单镜像轴的管线不读这个名字,演进输出不变)。`comparesImageGroups: false`、`availabilityPlatform: nil`。 +- `CrossVersionXcodeFrameworkTests`:`oldXcodeVersion` / `newXcodeVersion`(`"26.3.0"` / `"26.4.0"`)、`sharedFrameworkName`(`"DVTProductsUI"`);路径 `/Applications/Xcode-<版本>.app/Contents/SharedFrameworks/<名>.framework/Versions/A/<名>`;轴标签就是版本号。 + +### `InterfaceDumpTests.swift` + +```swift +/// The two single-version outputs, each the pipeline of one subcommand. +enum InterfaceDumpKind: Sendable { + /// `swift-section interface`: `-FileDump.swiftinterface` / `-ImageDump.swiftinterface`. + case swiftInterface + /// `swift-section objc dump`: every Objective-C declaration of the image, + /// `-ObjCFileDump.h` / `-ObjCImageDump.h`. + case objcInterface +} + +protocol InterfaceDumpTests: InspectionDumpTests { + /// Whether both interfaces print only what the image exports — what + /// `interface --exported-only` and `objc dump --exported-only` do. + var printsExportedDeclarationsOnly: Bool { get } +} + +@available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) +extension InterfaceDumpTests { + var printsExportedDeclarationsOnly: Bool { false } + var builderConfiguration: SwiftInterfaceBuilderConfiguration // today's configuration + printExportedDeclarationsOnly: printsExportedDeclarationsOnly + var objcGenerationOptions: ObjCGenerationOptions // .default + the four comment options + printExportedDeclarationsOnly + + func dump( + _ kind: InterfaceDumpKind, of machO: MachO, to destination: DumpDestination + ) async throws +} +``` + +- 读取器后缀:`machO.asMachOImage != nil ? "ImageDump" : "FileDump"`,ObjC 加前缀 `ObjC`。 +- `swiftInterface`:`SwiftInterfaceBuilder(configuration: builderConfiguration, eventHandlers: [], in: machO)` + `addExtraDataProvider(SwiftInterfaceBuilderOpaqueTypeProvider(machO:))`,`measuringPreparation { prepare() }`,`printRoot().string`。与现状逐字相同。 +- `objcInterface`:`measuringPreparation` 里 `preparedObjCIndexer(of: machO)`;`ObjCInterfaceBuilder(indexer:machO:)`;按 classes、protocols、categories、structs、unions 的顺序,名字排序,逐个取接口(类别用 `categoryInterface(uniqueName:)`),每段后接 `"\n\n"`,与 `objc dump --file` 的拼法一致。 +- 套件若要改 `printsExportedDeclarationsOnly`,在 `@MainActor` 的基类上要写 `nonisolated var`;`XcodeMachOFileTests` 的基类不隔离,直接写 `var`。 + +### `DiffDumpTests.swift` + +```swift +enum DiffDumpKind: Sendable { + /// `swift-section diff` and `diff --json`: `-Diff.txt` / `-Diff.json`. + case swiftReport + /// `swift-section diff --interface`: `-AnnotatedInterface-Inline.swiftinterface` + /// and `-AnnotatedInterface-Unified.swiftinterface`; the console prints the inline one. + case swiftInterface + /// `swift-section objc diff` and `objc diff --json`: `-ObjCDiff.txt` / `-ObjCDiff.json`. + case objcReport + var language: MetadataLanguage +} + +protocol DiffDumpTests: VersionAxisDumpTests {} + +extension DiffDumpTests { + func dump(_ kind: DiffDumpKind, to destination: DumpDestination) async throws { + let axis = versionAxis(for: kind.language) + guard axis.versions.count >= 2, let oldVersion = axis.versions.first, let newVersion = axis.versions.last else { + printResult("No diff: \(axis.versions.count) version(s) carry \(kind.language) metadata") + return + } + let output: DumpOutput = switch kind { … } + try deliver(output, to: destination) { file in + try write(file.text, forImageGroup: [newVersion.primaryImage], suffix: file.suffix, fileExtension: file.fileExtension) + } + } +} +``` + +- `swiftReport`:两个 `SwiftDiffableInterfaceBuilder` 在一个 `measuringPreparation` 里各 `prepare()`(与现状同);`ABIDiffer().diff(old: abiModule(), new: abiModule())`;正文 = 报告 + `\n\n` + 结论行;JSON = `ABIJSON.encoder().encode(diff)`。 +- `swiftInterface`:同样准备两个 builder;inline 必出,unified(`.unified()`,与现状相同的默认标签)只在去向是文件时渲染。两种格式各建一个 `SwiftDiffableInterfaceRenderer`,与现状相同。 +- `objcReport`:两边 `objcSnapshotDocument(of: version.primaryImage, label: version.label)`,`ObjCAPIDiffer().diff(old:new:)`,正文 = `ObjCAPIDiffReporter().report(diff)` + 结论行(`API-breaking: … · backward-compatible: …`,与 CLI 同),JSON = `ObjCAPIJSON.encoder().encode(diff)`。 + +### 套件的样子 + +```swift +enum DiffTestSuite { + /// AppKit extracted from two dyld shared caches (macOS 26.5.1 → 27.0), each + /// opened whole the way `swift-section --dyld-shared-cache` opens it. + final class DyldCacheTests: MultiVersionDyldCacheImageTests, nonisolated DiffDumpTests, @unchecked Sendable { + override class var cachePaths: [DyldSharedCachePath] { [.macOS_26_5_1, .macOS_27_0] } + override class var cacheImageName: MachOImageName { .AppKit } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftReportFile() async throws { + try await dump(.swiftReport, to: .file) + } + // swiftReportString, swiftInterfaceFile/String, objcReportFile/String: the same shape + } +} + +enum InterfaceTestSuite { + class XcodeMachOFileTests: SwiftSectionTestingSupport.XcodeMachOFileTests, InterfaceDumpTests { + override class var fileName: XcodeMachOFileName { .sharedFrameworks(.SourceEditor) } + var printsExportedDeclarationsOnly: Bool { true } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftInterfaceFile() async throws { + try await dump(.swiftInterface, of: machOFile, to: .file) + } + // swiftInterfaceString: the same shape + } +} +``` + +### 与现状的行为差异 + +| 方面 | 现状 | 之后 | +|---|---|---| +| diff 的 cache 对 | `DyldCache(path:)` 只开主文件,从主 cache 取镜像 | `FullDyldCache(path:)` 整份打开,与演进、CLI 一致;输出可能有出入 | +| diff 的输出 | `diffFile` 写三个文件;`diffString` 印变更列表与 inline | `swiftReport` 写 `-Diff.txt` 与新增的 `-Diff.json`,印变更列表;`swiftInterface` 写 inline 与 unified,印 inline | +| 新增 ObjC 输出 | 无 | AppKit 接口套件:`-ObjCFileDump.h`;AppKit diff 套件:`-ObjCDiff.txt` / `.json` | +| 接口的文件名 | `-FileDump` / `-ImageDump`,按 `is MachOImage` | 文件名不变,按 `asMachOImage` | +| Xcode diff 的类属性 | 两个 `.app` 路径 | 两个版本号 | +| 测试标识 | `SwiftInterfaceBuilderTestSuite.*/buildFile()` 等、`SwiftDiffableInterfaceBuilderTestSuite.*/diffFile()` 等 | `InterfaceTestSuite.*/swiftInterfaceFile()` 等、`DiffTestSuite.*/swiftReportFile()` 等;演进的不变 | +| 演进 | — | 输出与测试标识都不变;只换类型名与目录 | + +## 替代方案考量 + +1. **单版本接口也走版本轴(一个版本的轴)**:放弃。接口套件要读进程内的 `MachOImage`(SwiftUICore),而轴里的镜像是 `MachOFile`,演进构建器也只收 `MachOFile`;为接口把 `AxisImage` 泛型化,会让 diff 与演进的每条管线都背上它用不到的泛型。接口套件继续用 MachOKitExtensions 的四个基类,`dump` 直接收这个镜像。 +2. **三类合成一个大的 `DumpKind` 枚举、一个协议**:放弃。三类的输入不同(一个镜像 / 两个版本 / N 个版本),合成一个就得让每个种类在运行时检查自己拿到的输入形状对不对;分三个枚举,编译期就排除了「对单个镜像跑 diff」这类组合。 +3. **diff 保留自己的两版基类**:用户在澄清时否掉——两套写法表达同一件事,读 cache 的方式还和 CLI 不一致。 +4. **只统一结构、不加 ObjC**:用户在澄清时否掉——三类都能一处声明镜像、同时看两种语言,才算统一。 +5. **ObjC 输出加在每个套件上**:暂不。SymbolTestsCore、SwiftUICore、SourceEditor、DVTProductsUI 的 ObjC 部分不是维护者常看的;需要时加一对一行测试即可。 +6. **套件按镜像改名(如 `AppKitDyldCacheTests`)**:放弃。接口与 diff 的套件是维护者临时指向别的镜像的探针(任务报告里出现过改读 SnippetUI,未提交的实验在改读 AttributeGraph),按镜像命名会随手变得名不副实。 + +## 影响 + +### 源码兼容性(source compatibility) + +纯测试改动,不涉及任何公开 API:IntegrationTests 不是 product,没有调用方。 + +### ABI 兼容性(条件项) + +不适用 —— 本库以 SPM 源码分发,使用方每次重新编译;本提案也只改测试目标。 + +### 下游影响 + +本仓库只有 IntegrationTests 目标受影响,`Package.swift` 只为它多列一个已有的 MachOObjCSection product。下游仓库不依赖 IntegrationTests,无影响。维护者手动运行时用的测试名会变(见行为差异表)。 + +### 文档与示例 + +`Documentations/Internal/ABIEvolutionDesign.md:235` 的目录改成 `Tests/IntegrationTests/InspectionDumps/`。账本、任务报告与已落地提案里的旧套件名是历史记录,不改。 + +## API 演进与废弃策略 + +不适用 —— 没有公开 API 变化;旧测试名直接删除,不留别名。 + +## 落地步骤 + +验证一律在 Ultra 上做(本机是公司那台,不编大工程):`queued-build swift build --build-tests`,scratch 用 `/Volumes/DerivedData/Agents.noindex/claude/SwiftPM/MachOSwiftSection-UnifyDiffAndInterfaceIntegrationSuites`,默认 Xcode 编一遍,再用 `DEVELOPER_DIR=…/Xcode-26.6.0.app`(CI 的版本)编一遍。第一次 26.6 构建若报 `no such module 'swift_section'`,是已知的构建顺序竞态,原样重跑。不运行 IntegrationTests。 + +1. **公共骨架与版本轴**(已完成,Ultra 上 Xcode 27.2 编过;26.6 首次撞上已知的构建顺序竞态,随第 2 步重跑通过)——`InspectionDumps/` 目录;`InspectionDumpTests.swift`、`VersionAxis.swift`、`EvolutionDumpTests.swift`、`EvolutionTests.swift` 移入并改名;两个旧文件只做机械改名以保持能编。 + - 行为:`evolutionSuitesKeepTheirFortyThreeTestsAndOutputs` + - 行为:`multiVersionCacheAxisStoresOneAxisPerLanguage` + - 行为:`simulatorFilePairGivesItsOwnAxisLabeledByVersion` + - 行为:`objcSnapshotDocumentIsSharedByDiffAndEvolution` +2. **接口一类**(已完成,Ultra 上 Xcode 26.6 与 27.2 都编过,新文件没有警告)——`InterfaceDumpTests.swift`、`InterfaceTests.swift`;删除 `SwiftInterface/SwiftInterfaceBuilderTests.swift`;`Package.swift` 加 `ObjCDeclarationRendering`。 + - 行为:`swiftInterfaceMatchesTodaysConfigurationAndFileName` + - 行为:`exportedOnlySuiteOverridesOneFlagInsteadOfTheWholeConfiguration` + - 行为:`objcInterfaceConcatenatesEveryKindInObjcDumpOrder` + - 行为:`readerSuffixComesFromAsMachOImage` + - 行为:`appKitInterfaceSuitesWriteBothLanguages` +3. **diff 一类**(已完成,Ultra 上 Xcode 26.6 与 27.2 都编过,新文件没有警告)——`DiffDumpTests.swift`、`DiffTests.swift`;删除 `SwiftInterface/SwiftDiffableInterfaceBuilderTests.swift`。 + - 行为:`diffCachePairOpensEachCacheWhole` + - 行为:`swiftReportWritesChangeListAndJSON` + - 行为:`swiftInterfaceRendersUnifiedOnlyForFiles` + - 行为:`objcReportUsesTheObjCDifferAndVerdictLine` + - 行为:`diffWithFewerThanTwoVersionsPrintsANoteAndWritesNothing` + - 行为:`xcodePairIsPickedByVersion` +4. **文档**(已完成)——`ABIEvolutionDesign.md`、账本一节、两个索引;提案状态与决策日志随代码同批提交。 + - 维护者比对(可选):挑 `InterfaceTestSuite.MachOFileTests.swiftInterfaceFile` 与 `DiffTestSuite.SwiftUICoreTests` 的两个 file 测试前后各跑一次,`diff` 输出;cache 对的 diff 预期可能因整份打开而不同。 + +**收尾时必须判断两件事**(判断结果写进决策日志,不允许沉默跳过): + +- **要不要配套专题文章** —— 预计不需要:这是维护者手检目标的内部整理,用法写在新文件的文档注释里。 +- **有没有引入新术语** —— 「版本轴」0110 已判断不登记;本提案不新增术语。 + +## 决策日志 + +| 日期 | 变更 | 说明 | +|------|------|------| +| 2026-11-26 | Created as Draft | 0110 合并演进套件后,用户要求把 diff 与单版本接口两类手检套件也按同样的结构统一。澄清一轮:两类都加上 ObjC 输出;diff 改用演进套件的版本轴(cache 对因此整份打开,与 CLI 一致);维护者未提交的接口套件实验不碰,照提交版重构,由维护者自己收掉。 | +| 2026-11-26 | Accepted | 用户看过简报后批准,开始实现。 | +| 2026-11-26 | In Progress:第 1 步开工 | 功能分支从 `next` 切出,`next` 上已有本提案的 Accepted 提交。第 1 步首次在 Xcode 27.2 上编译时,`VersionAxis.swift` 缺 `FoundationToolbox` 与 `SwiftStdlibToolbox` 的导入(成员导入可见性检查),补了一个提交;Xcode 26.6 首次撞上已知的 `no such module 'swift_section'` 构建顺序竞态,第 2 步重跑通过。 | +| 2026-11-26 | 第 2、3 步完成 | `measuringPreparation` 改成泛型、返回准备好的值(详细设计原写不变):ObjC 头文件要在计时的一步里拿回索引器,ObjC diff 要拿回两份快照文档。diff 的文件名按新版本的主镜像起(`[newVersion.primaryImage]`),不按整组镜像:diff 只读主镜像,单镜像时文件名与原来相同。带标注的接口两种格式各建一个渲染器,与现状一致。 | +| 2026-11-26 | 第 4 步完成 | `ABIEvolutionDesign.md` 的集成套件一段改成新目录并链接本提案;账本追加一节(节号落地时取)。只编译、没运行 IntegrationTests。 | +| 2026-11-26 | 收尾判断 | 不配使用指南或实现说明:这是维护者手检目标的内部整理,用法写在新文件的文档注释里。没有新术语:「版本轴」0110 已判断不登记。 | +| 2026-11-26 | 实现完成,待用户看过后收尾 | 功能分支已推送。合进 `.worktrees/MachOSwiftSection` 的 `next` 时被维护者在 `SwiftInterfaceBuilderTests.swift` 里未提交的实验挡住,没有合并。 | +| 2026-11-26 | 维护者的实验先提交,合并按新结构处理 | 用户要求先提交工作区的改动再合并收尾:实验(接口套件读 AttributeGraph、显示 C 导入类型、只印导出声明、注册 `SwiftInterfaceBuilderTypeNameProvider`)与 Xcode 自动改写的两个工作区设置各成一个提交进 `next`。合并时功能分支删掉的 `SwiftInterfaceBuilderTests.swift` 与实验的修改冲突,按澄清时的选择取删除:实验不搬进新套件,只留在历史里。合并后的代码与 Ultra 上编过的功能分支逐字相同(只多两个 Xcode 设置文件),没有重新验证。 | +| 2026-11-26 | Implemented,取号 0111 | 用户要求收尾,以 `--no-ff` 合进 `next` 并推送。没有收到改前改后的输出比对结果。 | diff --git a/Documentations/Evolutions/0112-objc-ivar-type-recovery.html b/Documentations/Evolutions/0112-objc-ivar-type-recovery.html new file mode 100644 index 000000000..5aaf81ab8 --- /dev/null +++ b/Documentations/Evolutions/0112-objc-ivar-type-recovery.html @@ -0,0 +1,388 @@ + + + + + + +0112 - @objc @implementation 只剩 ivar 的存储属性按 ObjC 类型还原 Swift 类型 + + + + +
+ +
+

MachOSwiftSectionEvolutions0112

+

0112 @objc @implementation 只剩 ivar 的存储属性按 ObjC 类型还原 Swift 类型

+
+
状态
Implemented
+
最后更新
2026-11-27
+
项目类型
库
+
原文
0112-objc-ivar-type-recovery.md
+
+
+ + + +
+ +
+

摘要

+

@objc @implementation 类的存储属性一旦没有了 …vpWvd 字段偏移符号(系统框架剥过符号后几乎全是这样),Swift interface 只打一行注释 // stored property x: Swift type not recoverable (ObjC ivar, offset …, encoding "…")。本提案让 interface 与 dump 在 ObjC 一侧给得出类型时还原出声明:ivar 的 type encoding 是编译器写的完整 encoding(不是空串也不是 ?)时,Swift 类型就是这个 ObjC 类型本身(不桥接),按 encoding 还原;encoding 是 ? 时,Swift 类型是 ObjC 属性类型的桥接形态,按 ObjC 属性的 T 特性还原(NSString → String)。对象类型的可空性未记录,写成 T!;var / let / weak 按 ObjC 属性的特性;C 基本类型可以按调用方给的 C 类型替换表改写(double → CGFloat),与 ObjC 头文件一侧的 C Type Replacement 一致。空 encoding(非 @objc 的纯 Swift 属性)仍然只打注释。

+
+ +
+

提议方案

+

在 SwiftObjCInterop 加一个只依赖 ivar 事实与 ObjC 属性的还原函数,interface 与 dump 共用:

+
  1. encoding 完整(非空、非 ?):ObjCTypeEncodingParser.type(from:) 解析后按「原样表示」规则转成 Type 节点——与导入规则只差三处:桥接类保持类本身(NSString 还是 NSString),id 是 AnyObject,block / 位域 / 不认识的类型 / 无名结构体还原不出(返回 nil,保持注释)。
  2. encoding 是 ?:找 ivar 对应的 ObjC 属性,按它的 T 特性走现有的导入规则(NSString → String、NSArray → [Any]、id → Any);只认桥接表里的类与裸 id——? 证明 Swift 类型不是 ObjC 的类本身,导入成类自己的(unowned 属性的存储也写 ?)、表外的桥接类都不可信。没有 ObjC 属性、或 T 不是这几种,保持注释。weak 属性例外:weak 的存储不能原样表示成 ObjC 类型,编译器对类类型也写 ?,而 weak 只能是类,所以按「原样表示」规则读它的 T 特性,不桥接。
  3. 空 encoding:保持注释,二进制里没有任何类型信息。
  4. 可空性:可空的类型写 T!(ClangImporter 对无可空性标注的声明的写法,Generated Interface 也这样写);ObjC 属性是 weak 时写 weak var x: T?(weak 必为可选)。
  5. var / let:有 ObjC 属性且是 readonly 写 let,否则 var。
  6. C 类型替换:SwiftDeclarationPrintConfiguration 新增 cTypeReplacements: [Transformer.CType.Pattern: String](默认空)与 applyTransformers(_: Transformer.ObjCConfiguration);还原出的类型本身是 C 基本类型、且表里有替换时,打替换的名字(var interactiveProgress: CGFloat)。调用方(RuntimeViewer)把 ObjC 一侧的 C Type Replacement 设置原样交进来,两侧显示一致。
  7. dump:同一个还原函数,ivar 行打成 var name: Type,注释里的 Swift type not recoverable 换成类型来源(Swift type from the ObjC type encoding / Swift type from the ObjC property)。
+

没有询问就采用的假设(用户可以推翻):

+
  • 还原出的声明不加「类型来自 encoding」的逐行标注,也不加 @objc(与已有的「只有 Wvd 符号」分支一致)。打出的是 ClangImporter 给这个 C 类型的 Swift 类型;上面「encoding 不带的信息」列出的那些情况(typedef、枚举、^v、# 等)是已知近似,与 ObjC 头文件一侧显示的一致;! 说明可空性未知;dump 的注释写明来源。
  • 没有 ObjC 属性时写 var:只有 ivar 时没有任何信息说它不可写。已有的 printThrowingObjCImplementationStoredProperty 在「没有 setter 符号也没有 ObjC 属性」时写 let,那里有 accessor 符号可依,这里没有。
  • Generated Interface 里没有 stand-in 的 ivar 也走这条还原:它的类体本来就是 Swift 一侧的实现。
  • C 类型替换只作用于「类型本身就是 C 基本类型」的情况,不改指针参数、元组里的基本类型;dump 不接替换表。
  • copy 特性不还原成 @NSCopying:对桥接值类型没有意义,对类类型也无从确认源码写了它。
  • Generated Interface 已有的 stand-in(0096)不变:它的定位是「ObjC 一侧如何导入」,与本提案的 Swift 一侧不同。
+

非目标

+
  • 不改有 Wvd 符号或有 accessor 类型的存储属性。
  • 不给空 encoding 的 ivar 猜类型(按大小猜 Bool、闭包之类)。
  • 不让 swift-section interface 新增 --c-type-replacement 参数(CLI 另议,写进后续项)。
  • RuntimeViewer 一侧的接入(把 transformer.objc.cType 交给 Swift 打印、抬依赖版本)不在本仓库,见后续项。
+
+ +
+

架构图

+
    +
  • 新增
  • +
  • 修改
  • +
  • 不变
  • +
+
+ + + SwiftObjCInterop + ObjCImplementationClassFactsivar (name, typeEncoding, swiftTypeNode?) · property (T…,R,W,V…) + ObjCInstanceVariableSwiftTypecomplete encoding → as represented · "?" → property, bridgedweak "?" → property, unbridged · "" → nil + ObjCImportedTypes+ triviallyRepresentedTypeNode · + bridgedTypeNode+ Position.weakStorage · Mapping (imported / triviallyRepresented) + ObjCTypeEncodingParser + + SwiftPrinting · SwiftDump + renderUnrepresentedObjCImplementationInstanceVariablesWvd → var · stand-in → imported · + recovered → [weak] var|letelse → // stored property …: Swift type not recoverable + SwiftDeclarationPrintConfiguration+ cTypeReplacements · + applyTransformers(ObjCConfiguration) + ObjCImplementationClassDumperrecovered var|let, comment names the source + Transformer.CType (ObjCOutputTransformer)double → CGFloat, as in the ObjC header + + + + + + + + +
+

Wvd 符号还在时照旧;不在时先按 ivar 的 encoding(完整)或 ObjC 属性(?)还原,都给不出才打注释。

+
+ 原文的文本图 +
+
SwiftObjCInterop
+  ObjCImplementationClassFacts.InstanceVariable   (typeEncoding, swiftTypeNode?)
+  ObjCImplementationClassFacts.Property           (attributes: T…,R,W,V…)
++ ObjCInstanceVariableSwiftType(instanceVariable:objcProperty:in:)
++   encoding complete   -> ObjCTypeEncodingParser.type(from:)          -> ObjCImportedTypes.triviallyRepresentedTypeNode
++   encoding "?"        -> ObjCTypeEncodingParser.propertyType(fromAttributes:) -> ObjCImportedTypes.bridgedTypeNode
++   encoding ""         -> nil
+  ObjCImportedTypes
+    typeNode(_:position:)                          (unchanged: imported declarations)
++   triviallyRepresentedTypeNode(_:) -> Node?
++   bridgedTypeNode(_:) -> Node?
+
+SwiftPrinting
+  SwiftDeclarationPrintConfiguration
++   cTypeReplacements: [Transformer.CType.Pattern: String]
+  renderUnrepresentedObjCImplementationInstanceVariables
+    swiftTypeNode (Wvd)?           -> var name: Type
+    standIn (Generated Interface)? -> imported ObjC property
++   ObjCInstanceVariableSwiftType? -> [weak] var|let name: Type[!|?]   (C primitive -> replacement)
+    else                           -> // stored property …: Swift type not recoverable (…)
+
+SwiftDump
+  ObjCImplementationClassDumper
+~   ivar row: + recovered `var name: Type`, comment names the type's source
+
_UISplitViewControllerAdaptiveLayoutTransition (UIKitCore, stripped)
+  ivar mutableContainerView  "@\"UIView\""                      -> var mutableContainerView: UIView!
+  ivar mutableNewLayout      "@\"<_UISplitView…AdaptiveLayout>\"" -> var mutableNewLayout: (any _UISplitView…AdaptiveLayout)!
+  ivar mutableIsAnimated     "B"                                -> var mutableIsAnimated: Bool
+  ivar mutableInteractiveProgress "d"  + [double: CGFloat]      -> var mutableInteractiveProgress: CGFloat
+  ivar identifier            "?"  + property T@"NSString",R     -> let identifier: String!
+  ivar animations            ""                                 -> // stored property animations: Swift type not recoverable (…)
+
+
+
+ +
+

改动地图

+
文件 / 类型动作改什么为什么步骤
Sources/Analysis/SwiftObjCInterop/ObjCInstanceVariableSwiftType.swift · ObjCInstanceVariableSwiftType新增还原结果(Type 节点、来源、读出类型的 ObjCEncodedType、ObjC 属性的 readonly / weak)与 init?(instanceVariable:objcProperty:in:)interface 与 dump 共用一处判定1–3
Sources/Analysis/SwiftObjCInterop/ObjCImportedTypes.swift · ObjCImportedTypes修改新增 triviallyRepresentedTypeNode(_:position:) 与 bridgedTypeNode(_:position:)(还原不出时 nil)、Position.weakStorage(T?),内部给 bareTypeNode / objectNode 加 Mapping(导入 / 原样表示)复用导入规则,只换三处差异2–3
Sources/Output/SwiftPrinting/SwiftDeclarationPrintConfiguration.swift修改新增 cTypeReplacements调用方传 C 类型替换表1
Sources/Output/SwiftPrinting/SwiftDeclarationPrintConfiguration+Transformers.swift修改新增 applyTransformers(_: Transformer.ObjCConfiguration)与 Swift 一侧的 applyTransformers 对称4
Package.swift(SwiftPrinting target)修改依赖 ObjCOutputTransformer 与 OutputTransformerTransformer.CType.Pattern 在前者,Transformer 命名空间在后者1
Package.swift(SwiftInterfaceTests target)修改同样两个依赖测试要写 cTypeReplacements 与 Transformer.ObjCConfiguration;两者都是图里已有包的 product,Tuist 清单不用改4
Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+ObjCImplementation.swift修改renderUnrepresentedObjCImplementationInstanceVariables 先试还原,还原不出才打注释行为本身2–4
Sources/Output/SwiftDump/Dumper/ObjCImplementationClassDumper.swift修改ivar 行用同一还原,注释写来源dump 与 interface 一致5
Sources/TestSupport/SwiftSectionTestingSupport/ObjCImplementationFixture.swift修改新增 ObjC 协议 AdaptiveLayout、遵循它的 Swift 类 StandInAdaptiveLayout(给协议属性一个初值)与 AdaptiveTransitionWidget(照 _UISplitViewControllerAdaptiveLayoutTransition):NSObject、NSMutableString(不桥接的类)、协议存在类型、BOOL、CGFloat(夹具里导入成 Double)、NSInteger、readonly NSInteger、NSRange、readonly NSString、weak、NSArray<NSString *>、id、纯 Swift 属性覆盖每种 encoding1
Tests/SwiftInterfaceTests/ObjCImplementationInstanceVariableFactsTests.swift新增前提测试:剥过符号后新类的 ivar 名、encoding、ObjC 属性对应(含 R / W)与识别档位后面几步失败时能分清是编译器写法变了还是还原错了1
Tests/SwiftObjCInteropTests/ObjCInstanceVariableSwiftTypeTests.swift新增逐个 encoding 检查还原结果,含夹具造不出的形状(@"NSString"、@、@?、^{CGColor=})@objc @implementation 的匹配规则不允许实现里把头文件的 NSString * 写成 NSString2–3
Tests/SwiftInterfaceTests/ObjCImplementationClassRecognitionTests.swift修改类集合断言加新类;count 的断言改成还原后的声明;新增还原的测试行为清单1–4
Tests/SwiftDumpTests/ObjCImplementationClassDumpTests.swift修改dump 的还原断言行为清单5
Documentations/Internal/Modules/SwiftObjCInterop.md、Documentations/Internal/ObjCImplementationClassRecognition.md修改记录还原规则与新入口文档同批5
Documentations/Internal/ProjectEvolutionLog.md修改一节记录本次改动节号落地时取收尾
+
+ +
+

落地步骤

+
  1. 骨架(已完成):ObjCInstanceVariableSwiftType(恒返回 nil)、cTypeReplacements、SwiftPrinting 依赖 ObjCOutputTransformer;夹具加 AdaptiveTransitionWidget,类集合断言跟上;前提测试。
    • 行为:夹具的 @objc @implementation 类集合多出 AdaptiveTransitionWidget,其余输出不变。
    • 行为:剥过符号后新类的 ivar 仍有名字与编译器写的 encoding,@objc 的都能对上 ObjC 属性。
  2. 完整 encoding 还原(已完成):triviallyRepresentedTypeNode,interface 接入。
    • 行为:剥过符号的类类型 ivar 打成 var x: Class!。
    • 行为:协议存在类型打成 var x: (any P)!。
    • 行为:B / d / q 打成 Bool / Double / Int,结构体按结构体名。
    • 行为:readonly 的 ObjC 属性打 let。
    • 行为:完整 encoding 的 NSString 不桥接成 String、@ 是 AnyObject(单元测试;夹具造不出,见改动地图);夹具里不桥接的类用 NSMutableString 验。
    • 行为:block、指向结构体的指针、位域、无名结构体还原不出。
    • 行为:空 encoding 仍是注释。
  3. ? 按 ObjC 属性还原(已完成):bridgedTypeNode。
    • 行为:? 且有 NSString 属性的打成 String!,NSArray 的打成 [Any]!,id 的打成 Any!。
    • 行为:? 且没有 ObjC 属性的仍是注释。
    • 行为:weak 的 ObjC 属性打 weak var x: T?,类不桥接(weak 的存储让 ivar 写 ?)。
  4. C 类型替换(已完成):applyTransformers(_: Transformer.ObjCConfiguration),打印时替换;SwiftInterfaceTests 为此依赖 ObjCOutputTransformer 与 OutputTransformer。
    • 行为:配置 double → CGFloat 时 d 打成 CGFloat。
    • 行为:没有配置或模块关闭时仍是 Double。
  5. dump 与文档(已完成):ObjCImplementationClassDumper 接入;模块说明 Internal/Modules/SwiftObjCInterop.md 与实现说明 Internal/ObjCImplementationClassRecognition.md。演进账本的节号按项目规则在落地时取,由收尾时补。
    • 行为:dump 的 ivar 行打出还原的类型,注释写明来源。
    • 行为:还原不出的 ivar 注释仍写 Swift type not recoverable。
+

收尾时必须判断两件事:要不要配套专题文章、有没有引入新术语(写进决策日志)。

+
+ +
+

动机

+
+ 为什么要做 +
+

RuntimeViewer 看 Mac Catalyst 的 UIKitCore,__C._UISplitViewControllerAdaptiveLayoutTransition 的 24 个存储属性全部是注释,而同一个类的 ObjC 头文件一侧已经把其中 12 个的类型打出来了(@property (nonatomic, strong) UIView *mutableContainerView;、BOOL mutableIsAnimated、CGFloat mutableInteractiveProgress 等)。用户看 Swift 一侧时得自己去翻 ObjC 一侧、再在脑子里换成 Swift 类型。

+

现状来自两次有意的决定:0046 给只剩 ivar 的存储属性打「诚实注释、不编类型」;0096 让 Generated Interface 用 ObjC 属性的导入形式代替注释,但明确「Swift 一侧的 interface 照旧打注释——那里要的是 Swift 的类型,ObjC 的类型不是它」。这条理由只对需要桥接的类型成立:编译器写完整 encoding 的前提恰恰是 Swift 类型能原样表示成 ObjC 类型(见前期调研),这时 ObjC 类型就是 Swift 类型;需要桥接的写 ?,桥接规则又是确定的。所以两类都能还原,只是可空性与集合的泛型参数不在 encoding 里。

+
+
+
+
+

前期调研

+
+ 编译器怎么写 encoding、已有的转换与渲染路径 +
+
  • 编译器怎么写 ivar 的 encoding:swift/lib/IRGen/GenClass.cpp 的 buildIvar(约 2083–2096 行):只有 varDecl->isObjC() && varDecl->hasStorage() 才写 encoding;类型 isTriviallyRepresentableIn(ForeignLanguage::ObjectiveC, …) 时调 getObjCEncodingForPropertyType,否则写 "?"(注释原文:「"Unknown type" - used when ObjC classes are bridged to separate Swift types」);不是 @objc 的存储属性 encoding 为空串。isTriviallyRepresentableIn(lib/AST/Type.cpp 3481 行)对 Trivial 与 Object 返回 true,对 Bridged / BridgedError / StaticBridged / None 返回 false。
  • encoding 与 ObjC 属性的 T 特性是同一个函数算的:getObjCEncodingForPropertyType(lib/IRGen/GenObjC.cpp 1267 行)取 getter 的 foreign 结果类型对应的 clang 类型,交给 clang 的 getObjCEncodingForPropertyType;属性表的 T 特性也走它(GenClass.cpp 2192 行)。所以 encoding 为 ? 的 ivar,它的 ObjC 属性 T 特性给的是桥接后的 ObjC 类型(T@"NSString")。
  • encoding 不带的信息:可空性(UIView / UIView? / UIView! 都是 @"UIView")、typedef 与枚举(CGFloat、NSTimeInterval 都是 d;NSInteger、Int 与 NS_ENUM(NSInteger) 的枚举都是 q,NS_OPTIONS 是 Q)、NSArray 等的泛型参数(T@"NSArray")、block 的签名(ivar 与属性都只写 @?),以及几处同码异型:^v 是 UnsafeMutableRawPointer 也可能是 OpaquePointer,# 是 AnyClass 也可能是某个类的 .Type,* 是任何 char 类指针,arm64 上 B 也可能是 ObjCBool,: 不分 Selector 与 Selector?。
  • weak 的 ivar 写 ?(本提案的前提测试实测):weak var observer: NSObject? 的存储类型不能原样表示成 ObjC 类型,ivar encoding 是 ?;ObjC 属性的 T 特性仍是 @"NSObject"、带 W。
  • 已有的转换:Sources/Analysis/SwiftObjCInterop/ObjCImportedTypes.swift 的 ObjCImportedTypes.typeNode(_:position:) 按 ClangImporter 的规则把 ObjCEncodedType 转成 Type 节点:桥接类(ObjCBridgedStructures、NSArray / NSDictionary / NSSet / NSError)转值类型,id 转 Any,可空的对象类型转 T!,类名经 ObjCRuntimeNames.classNode(forRuntimeName:in:) 找 Swift 类、找不到就是 __C.<Name>;__C 名在打印时经 C 导入类型名改写(0106,接 swift-type-indexing 的 SDK 索引)换成 Swift 名。ObjCTypeEncodingParser.type(from:) 与 propertyType(fromAttributes:) 解析 encoding 与 T 特性(ObjCTypeEncoding.swift 115–132 行)。
  • 现状的渲染路径:Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+ObjCImplementation.swift 的 renderUnrepresentedObjCImplementationInstanceVariables:有 Wvd 符号的 ivar 打 var name: Type,否则(Generated Interface 有 stand-in 时打 stand-in)打 unrecoverableStoredPropertyComment。dump 一侧在 Sources/Output/SwiftDump/Dumper/ObjCImplementationClassDumper.swift 约 142–160 行,注释部分写 Swift type not recoverable。ObjC 属性与 ivar 的对应:ObjCImplementationClassFacts.objcProperty(storedIn:swiftPropertyName:)(先认 V<ivar>,再认同名)。
  • ObjC 一侧的 C 类型替换:MachOObjCSection 的 Transformer.CType(ObjCOutputTransformer,Pattern 13 种 C 基本类型)。RuntimeViewer 在 RuntimeObjCSection.builderInputs(for:) 里把它转成 [ObjCPrimitiveTypePattern: String] 交给 ObjC 渲染;Swift 打印目前拿不到这份替换表。ObjCOutputTransformer 只依赖 OutputTransformer 与 Semantic。
  • 实例:UIKitCore(macOS 27.2 的 iOSSupport)_UISplitViewControllerAdaptiveLayoutTransition 的 24 个 ivar:12 个空 encoding、1 个 ?(identifier,ObjC 属性 NSString *)、11 个完整 encoding(@"UIView"、@"<_UISplitViewControllerAdaptiveLayout>"、B、d 等)。
+
+
+
+
+

详细设计

+
+ 还原结果的类型与判定规则 +
+
// SwiftObjCInterop
+package struct ObjCInstanceVariableSwiftType {
+    package enum Source: Sendable, Hashable {
+        /// The ivar's own type encoding, written only for a Swift type that
+        /// Objective-C represents as it is.
+        case instanceVariableEncoding
+        /// The `T` attribute of the Objective-C property synthesized on the
+        /// ivar, whose type is the bridged one when the ivar says `?`.
+        case objcProperty
+    }
+
+    /// The `Type` node, unknown nullability already spelled (`T!`, or `T?`
+    /// for a `weak` property).
+    package let typeNode: Node
+    package let source: Source
+    /// The Objective-C type the Swift type was read from, which tells a
+    /// printer when the type is a C primitive it may spell otherwise.
+    package let encodedType: ObjCEncodedType
+    package let isReadOnly: Bool
+    package let isWeak: Bool
+
+    package init?(instanceVariable: ObjCImplementationClassFacts.InstanceVariable, objcProperty: ObjCImplementationClassFacts.Property?, in machO: some MachOSwiftSectionRepresentableWithCache)
+}
+
  • encodedType 存读出类型的 ObjCEncodedType(package,同一个包内可见),SwiftPrinting 自己把其中的 C 基本类型对到 Transformer.CType.Pattern,SwiftObjCInterop 不必依赖 ObjCOutputTransformer。
  • typeNode 由 ObjCImportedTypes 产出;可空判定沿用 isNullable(对象、block、Class、char *、指针)。
  • 「原样表示」判定(determinesStoredPropertyType):void、block、位域、不认识的类型、无名结构体与联合、导入规则表示不了的数组,以及指向 void 和标量以外的指针(指向结构体的指针与 CF 类型 encoding 相同,指向对象或指针的,导入规则会给出自己的类型)都还原不出。
  • 打印:cTypeReplacements 对该基本类型有非空替换时打 TypeName(kind: .other, replacement),否则 printType(typeNode)。
  • 打印用的节点是每次打印新建的 transient 节点,由局部常量持有到打印结束,满足「交给 interface printer 的节点必须活过这次打印」。
+
+
+
+
+

替代方案

+
+ 放弃的路径 +
+
  • 只用 ObjC 属性、不看 ivar 的 encoding:两者对完整 encoding 给的是同一个类型,但没有 ObjC 属性的 ivar 就还原不出;encoding 是 ? 时又只能看属性。所以按 encoding 分流。
  • Swift 一侧也直接打 Generated Interface 的 stand-in:stand-in 按导入规则桥接,完整 encoding 的 NSString 会被打成 String,id(AnyObject)打成 Any,是错的。
  • 可空性一律写 T? 或 T:都是在猜;T! 是 ClangImporter 对「可空性未知」的既有写法。用户确认用 T!。
  • d 一律写 CGFloat:NSTimeInterval 等也是 d。用户决定走调用方的 C 类型替换表,默认仍是 Double。
+
+
+
+
+

影响

+
+ 源码兼容、下游、文档 +
+

源码兼容性(source compatibility)

+

纯新增:SwiftDeclarationPrintConfiguration.cTypeReplacements 与 applyTransformers(_: Transformer.ObjCConfiguration) 是新增的公开成员,默认值不改变任何现有调用的输出之外的行为。输出变化:剥过符号的 @objc @implementation 类,原来是注释的存储属性有一部分变成声明。

+

ABI 兼容性(条件项)

+

不适用 —— 本库以 SPM 源码分发,使用方每次重新编译。

+

下游影响

+
  • 本仓库:SwiftPrinting(新依赖 ObjCOutputTransformer)、SwiftDump、SwiftObjCInterop。
  • RuntimeViewer:抬 MachOSwiftSection 依赖后,Swift 接口自动带上还原;C 类型替换要它在 RuntimeSwiftSection 里把 transformer.objc.cType 交给打印配置(后续项)。
+

文档与示例

+

模块说明 Internal/Modules/SwiftObjCInterop.md、SwiftPrinting.md(如有对应段落)与演进账本。

+

API 演进与废弃策略

+

无废弃:只新增成员。不需要 major 版本号跃迁。

+
+
+
+
+

后续项

+
+ 本次不做的 +
+
  • 已有问题(基线上就有):renderUnrepresentedObjCImplementationInstanceVariables 里「只有 Wvd 符号」那条分支把 var name: 与类型放成 Rows 的两个子项,打出来分成两行。本提案的新分支踩过同一个坑,改成了一个子项;那条旧分支要配一个「Wvd 在、accessor 已剥」的夹具才能复现,留到之后。
+
  • RuntimeViewer:RuntimeSwiftSection 把 transformer.objc.cType 交给 Swift 打印配置(applyTransformers(_: Transformer.ObjCConfiguration)),C Type Replacement 改动时让 Swift 输出重印;随 MachOSwiftSection 依赖版本一起抬。 2026-11-27 已完成:内容区与 Find 语料两个打印器都拿到 transformer.objc,设置不变时不重配打印器;RuntimeViewer 的五个锁文件抬到本仓库 next 的 edbf2966(分支 feature/swift-c-type-replacements)。
  • swift-section interface 的 --c-type-replacement。
  • Generated Interface 的 stand-in 对完整 encoding 的 ivar 是否改用本提案的 Swift 类型(NSString 不桥接)。
+
+
+
+
+

决策日志

+
+ 17 条 +
+
日期变更说明
2026-11-26Created as Draft用户在 RuntimeViewer 里看到 UIKitCore 一个 @objc @implementation 类的存储属性大半只有注释,而 ObjC 一侧已显示出类型,要求能还原的都还原,类名经 type indexing 转 Swift 名
2026-11-26用户经 implement-feature 批准,提案由 agent 起草、用户事前未审阅用户事先定了四点:对象类型写 T!;d 走 C 类型替换表;桥接集合也还原([Any]);方案照此开工
2026-11-26开始实现在 feature/objc-ivar-type-recovery 上按落地步骤做
2026-11-26还原结果存 ObjCEncodedType,不另设 ObjCPrimitiveTypeObjCEncodedType 在同一个包内可见,打印器直接对到 Transformer.CType.Pattern,少一个只为转一手的类型
2026-11-26夹具的 CGFloat 属性在 Swift 一侧写 Double夹具只 import Foundation,头文件的 CGFloat 导入成 Double,写 CGFloat 时 @implementation 的类型匹配报错
2026-11-26加前提测试第 1 步审查指出:ivar 名在即时编译夹具里曾观测为空(ObjCImplementationClassFacts.InstanceVariable.name 的注释),名字空了就对不上 ObjC 属性;先钉住剥过符号后的事实
2026-11-26weak 属性挪到第 3 步,按 ObjC 属性读、不桥接前提测试实测:weak var observer: NSObject? 的 ivar encoding 是 ?,不是 @"NSObject"
2026-11-26第 2 步的两处修正与第 3 步同一个提交第 2 步的首个提交在 Ultra 上编不过(解析器名写错,单独一个提交修好);之后又发现声明被 Rows 拆成两行、ObjC 属性的查找名与 stand-in 不一致,这两处修正与第 3 步的改动落在同几个文件里
2026-11-26完整 encoding 的近似(枚举、^v、# 等)照打,写进假设第 2 步审查指出;与 CGFloat / Double 同性质,ObjC 头文件一侧显示的也是同一个 C 类型
2026-11-26? 只认桥接表里的类与裸 id第 3、4 步审查指出:? 证明 Swift 类型不是那个类本身,按导入规则照单全收会把 unowned 属性的存储(也写 ?、特性里没有 W)和表外的桥接类(NSAffineTransform → AffineTransform)打成错的类
2026-11-26weak 与 readonly 同时出现时仍写 weak varweak let(SE-0481)要 Swift 6.2,源码更常见的是 weak private(set) var;无从区分时取更常见的写法
2026-11-26applyTransformers(_: Transformer.ObjCConfiguration) 与 Swift 一侧同名重载调用点传的都是有类型的值(transformer.objc),不会歧义;只装 cType,ivarOffset 是 ObjC 头文件的 ivar 注释,Swift 一侧的偏移注释仍走 fieldOffsetTransformer
2026-11-26C 类型替换只换类型本身,替换名照原样打印与假设一致;替换表的文档写明只收不带模块的名字。ObjC 一侧会递归替换指针里的类型,Swift 一侧不跟
2026-11-26实现完成,待用户看过后收尾五步都在 Ultra 上过了针对性测试;整套测试结果见收尾;RuntimeViewer 的接入随依赖版本一起做(后续项)
2026-11-26Implemented,取号 0112用户看过后收尾。合进 next;落地时演进账本记为第 158 节。没做的:RuntimeViewer 一侧的接入(把 transformer.objc.cType 交给 Swift 打印、抬依赖版本)、swift-section interface --c-type-replacement、只有 Wvd 那条旧分支分两行的问题,都在后续项
2026-11-26文档判断不另写使用指南:调用方的契约只有 cTypeReplacements 一个属性,文档注释已写清。实现说明更新了已有的 ObjCImplementationClassRecognition.md,模块说明更新了 SwiftObjCInterop.md。没有新术语:「原样表示」对应编译器自己的 isTriviallyRepresentableIn,不是本项目造的词
2026-11-26验证Ultra 上五个相关套件全过(界面 33、单元 9、前提 3 条,另含 dump 与 Generated Interface 套件)。整套测试(跳过 IntegrationTests)红约 800 处,全部是构建槽位的检出里没有 SymbolTestsCore fixture(「Fixture binary not found」「cannot load the SymbolTestsCore fixture」),其余原因的失败为零;完整结果要先把 fixture 编进那个检出
2026-11-27后续项:RuntimeViewer 一侧接入完成RuntimeViewer 的 Swift section 把 ObjC 一侧的 C Type Replacement 设置交给内容区与 Find 语料的打印器,锁文件随之抬到 edbf2966;用户看过后收尾。远端解析依赖的构建要等 MachOKitExtensions 发 3.3.0 之后的版本
2026-11-29更正 2026-11-26「unowned 属性的特性里没有 W」:W 与只读桥接类改为照实标注另一种读法代码库体检第 2 条。编译器对带 ReferenceOwnershipAttr 的属性(weak 与各种 unowned)一律写 W(GenClass.cpp 2212–2214 行),@implementation 能对上头文件声明的 unowned 只有 unowned(unsafe)(头文件的 unsafe_unretained / assign)。实测它的存储写 ?:可写的带 W、与 weak 无从区分;只读的只有 R、与桥接成值的 let 无从区分。改法:照旧印常见的读法,后面加注释写出另一种;只读桥接类只在 ivar 占一个指针时才可能是 unowned(unsafe);还有访问器符号、知道类型时按类型分,不是 Optional 的是 unowned(unsafe) var。用户批准修复
+
+
+
+ +
+
+ + diff --git a/Documentations/Evolutions/0112-objc-ivar-type-recovery.md b/Documentations/Evolutions/0112-objc-ivar-type-recovery.md new file mode 100644 index 000000000..ee0411eeb --- /dev/null +++ b/Documentations/Evolutions/0112-objc-ivar-type-recovery.md @@ -0,0 +1,241 @@ +# 0112 - `@objc @implementation` 只剩 ivar 的存储属性按 ObjC 类型还原 Swift 类型 + +- **状态**: Implemented +- **作者**: JH +- **创建日期**: 2026-11-26 +- **最后更新**: 2026-11-27 +- **所属愿景**: 无 +- **关联提案**: [0046 objc-implementation-class-recognition](0046-objc-implementation-class-recognition.md)、[0096 swift-first-imported-declarations](0096-swift-first-imported-declarations.md)、[0090 objc-imported-declarations](0090-objc-imported-declarations.md)、[0106 c-imported-type-name-spelling](0106-c-imported-type-name-spelling.md) +- **实现分支 / PR**: `feature/objc-ivar-type-recovery` +- **配套文档**: 实现说明 [ObjCImplementationClassRecognition.md](../Internal/ObjCImplementationClassRecognition.md)(存储属性一段);模块说明 [SwiftObjCInterop.md](../Internal/Modules/SwiftObjCInterop.md) +- **网页版**: 同目录同名的 `.html` + +## 摘要 + +`@objc @implementation` 类的存储属性一旦没有了 `…vpWvd` 字段偏移符号(系统框架剥过符号后几乎全是这样),Swift interface 只打一行注释 `// stored property x: Swift type not recoverable (ObjC ivar, offset …, encoding "…")`。本提案让 interface 与 `dump` 在 ObjC 一侧给得出类型时还原出声明:ivar 的 type encoding 是编译器写的完整 encoding(不是空串也不是 `?`)时,Swift 类型就是这个 ObjC 类型本身(不桥接),按 encoding 还原;encoding 是 `?` 时,Swift 类型是 ObjC 属性类型的桥接形态,按 ObjC 属性的 `T` 特性还原(`NSString` → `String`)。对象类型的可空性未记录,写成 `T!`;`var` / `let` / `weak` 按 ObjC 属性的特性;C 基本类型可以按调用方给的 C 类型替换表改写(`double` → `CGFloat`),与 ObjC 头文件一侧的 C Type Replacement 一致。空 encoding(非 `@objc` 的纯 Swift 属性)仍然只打注释。 + +## 动机 + +RuntimeViewer 看 Mac Catalyst 的 UIKitCore,`__C._UISplitViewControllerAdaptiveLayoutTransition` 的 24 个存储属性全部是注释,而同一个类的 ObjC 头文件一侧已经把其中 12 个的类型打出来了(`@property (nonatomic, strong) UIView *mutableContainerView;`、`BOOL mutableIsAnimated`、`CGFloat mutableInteractiveProgress` 等)。用户看 Swift 一侧时得自己去翻 ObjC 一侧、再在脑子里换成 Swift 类型。 + +现状来自两次有意的决定:0046 给只剩 ivar 的存储属性打「诚实注释、不编类型」;0096 让 Generated Interface 用 ObjC 属性的导入形式代替注释,但明确「Swift 一侧的 interface 照旧打注释——那里要的是 Swift 的类型,ObjC 的类型不是它」。这条理由只对需要桥接的类型成立:编译器写完整 encoding 的前提恰恰是 Swift 类型能原样表示成 ObjC 类型(见前期调研),这时 ObjC 类型就是 Swift 类型;需要桥接的写 `?`,桥接规则又是确定的。所以两类都能还原,只是可空性与集合的泛型参数不在 encoding 里。 + +## 前期调研 + +- **编译器怎么写 ivar 的 encoding**:`swift/lib/IRGen/GenClass.cpp` 的 `buildIvar`(约 2083–2096 行):只有 `varDecl->isObjC() && varDecl->hasStorage()` 才写 encoding;类型 `isTriviallyRepresentableIn(ForeignLanguage::ObjectiveC, …)` 时调 `getObjCEncodingForPropertyType`,否则写 `"?"`(注释原文:「"Unknown type" - used when ObjC classes are bridged to separate Swift types」);不是 `@objc` 的存储属性 encoding 为空串。`isTriviallyRepresentableIn`(`lib/AST/Type.cpp` 3481 行)对 `Trivial` 与 `Object` 返回 true,对 `Bridged` / `BridgedError` / `StaticBridged` / `None` 返回 false。 +- **encoding 与 ObjC 属性的 `T` 特性是同一个函数算的**:`getObjCEncodingForPropertyType`(`lib/IRGen/GenObjC.cpp` 1267 行)取 getter 的 foreign 结果类型对应的 clang 类型,交给 clang 的 `getObjCEncodingForPropertyType`;属性表的 `T` 特性也走它(`GenClass.cpp` 2192 行)。所以 encoding 为 `?` 的 ivar,它的 ObjC 属性 `T` 特性给的是桥接后的 ObjC 类型(`T@"NSString"`)。 +- **encoding 不带的信息**:可空性(`UIView` / `UIView?` / `UIView!` 都是 `@"UIView"`)、typedef 与枚举(`CGFloat`、`NSTimeInterval` 都是 `d`;`NSInteger`、`Int` 与 `NS_ENUM(NSInteger)` 的枚举都是 `q`,`NS_OPTIONS` 是 `Q`)、`NSArray` 等的泛型参数(`T@"NSArray"`)、block 的签名(ivar 与属性都只写 `@?`),以及几处同码异型:`^v` 是 `UnsafeMutableRawPointer` 也可能是 `OpaquePointer`,`#` 是 `AnyClass` 也可能是某个类的 `.Type`,`*` 是任何 char 类指针,arm64 上 `B` 也可能是 `ObjCBool`,`:` 不分 `Selector` 与 `Selector?`。 +- **`weak` 的 ivar 写 `?`**(本提案的前提测试实测):`weak var observer: NSObject?` 的存储类型不能原样表示成 ObjC 类型,ivar encoding 是 `?`;ObjC 属性的 `T` 特性仍是 `@"NSObject"`、带 `W`。 +- **已有的转换**:`Sources/Analysis/SwiftObjCInterop/ObjCImportedTypes.swift` 的 `ObjCImportedTypes.typeNode(_:position:)` 按 ClangImporter 的规则把 `ObjCEncodedType` 转成 `Type` 节点:桥接类(`ObjCBridgedStructures`、`NSArray` / `NSDictionary` / `NSSet` / `NSError`)转值类型,`id` 转 `Any`,可空的对象类型转 `T!`,类名经 `ObjCRuntimeNames.classNode(forRuntimeName:in:)` 找 Swift 类、找不到就是 `__C.`;`__C` 名在打印时经 C 导入类型名改写(0106,接 swift-type-indexing 的 SDK 索引)换成 Swift 名。`ObjCTypeEncodingParser.type(from:)` 与 `propertyType(fromAttributes:)` 解析 encoding 与 `T` 特性(`ObjCTypeEncoding.swift` 115–132 行)。 +- **现状的渲染路径**:`Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+ObjCImplementation.swift` 的 `renderUnrepresentedObjCImplementationInstanceVariables`:有 `Wvd` 符号的 ivar 打 `var name: Type`,否则(Generated Interface 有 stand-in 时打 stand-in)打 `unrecoverableStoredPropertyComment`。`dump` 一侧在 `Sources/Output/SwiftDump/Dumper/ObjCImplementationClassDumper.swift` 约 142–160 行,注释部分写 `Swift type not recoverable`。ObjC 属性与 ivar 的对应:`ObjCImplementationClassFacts.objcProperty(storedIn:swiftPropertyName:)`(先认 `V`,再认同名)。 +- **ObjC 一侧的 C 类型替换**:MachOObjCSection 的 `Transformer.CType`(`ObjCOutputTransformer`,`Pattern` 13 种 C 基本类型)。RuntimeViewer 在 `RuntimeObjCSection.builderInputs(for:)` 里把它转成 `[ObjCPrimitiveTypePattern: String]` 交给 ObjC 渲染;Swift 打印目前拿不到这份替换表。`ObjCOutputTransformer` 只依赖 `OutputTransformer` 与 `Semantic`。 +- **实例**:UIKitCore(macOS 27.2 的 iOSSupport)`_UISplitViewControllerAdaptiveLayoutTransition` 的 24 个 ivar:12 个空 encoding、1 个 `?`(`identifier`,ObjC 属性 `NSString *`)、11 个完整 encoding(`@"UIView"`、`@"<_UISplitViewControllerAdaptiveLayout>"`、`B`、`d` 等)。 + +## 提议方案 + +在 `SwiftObjCInterop` 加一个只依赖 ivar 事实与 ObjC 属性的还原函数,interface 与 dump 共用: + +1. **encoding 完整**(非空、非 `?`):`ObjCTypeEncodingParser.type(from:)` 解析后按「原样表示」规则转成 `Type` 节点——与导入规则只差三处:桥接类保持类本身(`NSString` 还是 `NSString`),`id` 是 `AnyObject`,block / 位域 / 不认识的类型 / 无名结构体还原不出(返回 `nil`,保持注释)。 +2. **encoding 是 `?`**:找 ivar 对应的 ObjC 属性,按它的 `T` 特性走现有的导入规则(`NSString` → `String`、`NSArray` → `[Any]`、`id` → `Any`);只认桥接表里的类与裸 `id`——`?` 证明 Swift 类型不是 ObjC 的类本身,导入成类自己的(`unowned` 属性的存储也写 `?`)、表外的桥接类都不可信。没有 ObjC 属性、或 `T` 不是这几种,保持注释。`weak` 属性例外:`weak` 的存储不能原样表示成 ObjC 类型,编译器对类类型也写 `?`,而 `weak` 只能是类,所以按「原样表示」规则读它的 `T` 特性,不桥接。 +3. **空 encoding**:保持注释,二进制里没有任何类型信息。 +4. **可空性**:可空的类型写 `T!`(ClangImporter 对无可空性标注的声明的写法,Generated Interface 也这样写);ObjC 属性是 `weak` 时写 `weak var x: T?`(`weak` 必为可选)。 +5. **`var` / `let`**:有 ObjC 属性且是 `readonly` 写 `let`,否则 `var`。 +6. **C 类型替换**:`SwiftDeclarationPrintConfiguration` 新增 `cTypeReplacements: [Transformer.CType.Pattern: String]`(默认空)与 `applyTransformers(_: Transformer.ObjCConfiguration)`;还原出的类型本身是 C 基本类型、且表里有替换时,打替换的名字(`var interactiveProgress: CGFloat`)。调用方(RuntimeViewer)把 ObjC 一侧的 C Type Replacement 设置原样交进来,两侧显示一致。 +7. **dump**:同一个还原函数,ivar 行打成 `var name: Type`,注释里的 `Swift type not recoverable` 换成类型来源(`Swift type from the ObjC type encoding` / `Swift type from the ObjC property`)。 + +**没有询问就采用的假设**(用户可以推翻): + +- 还原出的声明不加「类型来自 encoding」的逐行标注,也不加 `@objc`(与已有的「只有 `Wvd` 符号」分支一致)。打出的是 ClangImporter 给这个 C 类型的 Swift 类型;上面「encoding 不带的信息」列出的那些情况(typedef、枚举、`^v`、`#` 等)是已知近似,与 ObjC 头文件一侧显示的一致;`!` 说明可空性未知;`dump` 的注释写明来源。 +- 没有 ObjC 属性时写 `var`:只有 ivar 时没有任何信息说它不可写。已有的 `printThrowingObjCImplementationStoredProperty` 在「没有 setter 符号也没有 ObjC 属性」时写 `let`,那里有 accessor 符号可依,这里没有。 +- Generated Interface 里没有 stand-in 的 ivar 也走这条还原:它的类体本来就是 Swift 一侧的实现。 +- C 类型替换只作用于「类型本身就是 C 基本类型」的情况,不改指针参数、元组里的基本类型;`dump` 不接替换表。 +- `copy` 特性不还原成 `@NSCopying`:对桥接值类型没有意义,对类类型也无从确认源码写了它。 +- Generated Interface 已有的 stand-in(0096)不变:它的定位是「ObjC 一侧如何导入」,与本提案的 Swift 一侧不同。 + +### 非目标 + +- 不改有 `Wvd` 符号或有 accessor 类型的存储属性。 +- 不给空 encoding 的 ivar 猜类型(按大小猜 `Bool`、闭包之类)。 +- 不让 `swift-section interface` 新增 `--c-type-replacement` 参数(CLI 另议,写进后续项)。 +- RuntimeViewer 一侧的接入(把 `transformer.objc.cType` 交给 Swift 打印、抬依赖版本)不在本仓库,见后续项。 + +## 改动地图 + +| 文件 / 类型 | 动作 | 改什么 | 为什么 | 步骤 | +|---|---|---|---|---| +| `Sources/Analysis/SwiftObjCInterop/ObjCInstanceVariableSwiftType.swift` · `ObjCInstanceVariableSwiftType` | 新增 | 还原结果(`Type` 节点、来源、读出类型的 `ObjCEncodedType`、ObjC 属性的 `readonly` / `weak`)与 `init?(instanceVariable:objcProperty:in:)` | interface 与 dump 共用一处判定 | 1–3 | +| `Sources/Analysis/SwiftObjCInterop/ObjCImportedTypes.swift` · `ObjCImportedTypes` | 修改 | 新增 `triviallyRepresentedTypeNode(_:position:)` 与 `bridgedTypeNode(_:position:)`(还原不出时 `nil`)、`Position.weakStorage`(`T?`),内部给 `bareTypeNode` / `objectNode` 加 `Mapping`(导入 / 原样表示) | 复用导入规则,只换三处差异 | 2–3 | +| `Sources/Output/SwiftPrinting/SwiftDeclarationPrintConfiguration.swift` | 修改 | 新增 `cTypeReplacements` | 调用方传 C 类型替换表 | 1 | +| `Sources/Output/SwiftPrinting/SwiftDeclarationPrintConfiguration+Transformers.swift` | 修改 | 新增 `applyTransformers(_: Transformer.ObjCConfiguration)` | 与 Swift 一侧的 `applyTransformers` 对称 | 4 | +| `Package.swift`(`SwiftPrinting` target) | 修改 | 依赖 `ObjCOutputTransformer` 与 `OutputTransformer` | `Transformer.CType.Pattern` 在前者,`Transformer` 命名空间在后者 | 1 | +| `Package.swift`(`SwiftInterfaceTests` target) | 修改 | 同样两个依赖 | 测试要写 `cTypeReplacements` 与 `Transformer.ObjCConfiguration`;两者都是图里已有包的 product,Tuist 清单不用改 | 4 | +| `Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+ObjCImplementation.swift` | 修改 | `renderUnrepresentedObjCImplementationInstanceVariables` 先试还原,还原不出才打注释 | 行为本身 | 2–4 | +| `Sources/Output/SwiftDump/Dumper/ObjCImplementationClassDumper.swift` | 修改 | ivar 行用同一还原,注释写来源 | dump 与 interface 一致 | 5 | +| `Sources/TestSupport/SwiftSectionTestingSupport/ObjCImplementationFixture.swift` | 修改 | 新增 ObjC 协议 `AdaptiveLayout`、遵循它的 Swift 类 `StandInAdaptiveLayout`(给协议属性一个初值)与 `AdaptiveTransitionWidget`(照 `_UISplitViewControllerAdaptiveLayoutTransition`):`NSObject`、`NSMutableString`(不桥接的类)、协议存在类型、`BOOL`、`CGFloat`(夹具里导入成 `Double`)、`NSInteger`、`readonly NSInteger`、`NSRange`、`readonly NSString`、`weak`、`NSArray`、`id`、纯 Swift 属性 | 覆盖每种 encoding | 1 | +| `Tests/SwiftInterfaceTests/ObjCImplementationInstanceVariableFactsTests.swift` | 新增 | 前提测试:剥过符号后新类的 ivar 名、encoding、ObjC 属性对应(含 `R` / `W`)与识别档位 | 后面几步失败时能分清是编译器写法变了还是还原错了 | 1 | +| `Tests/SwiftObjCInteropTests/ObjCInstanceVariableSwiftTypeTests.swift` | 新增 | 逐个 encoding 检查还原结果,含夹具造不出的形状(`@"NSString"`、`@`、`@?`、`^{CGColor=}`) | `@objc @implementation` 的匹配规则不允许实现里把头文件的 `NSString *` 写成 `NSString` | 2–3 | +| `Tests/SwiftInterfaceTests/ObjCImplementationClassRecognitionTests.swift` | 修改 | 类集合断言加新类;`count` 的断言改成还原后的声明;新增还原的测试 | 行为清单 | 1–4 | +| `Tests/SwiftDumpTests/ObjCImplementationClassDumpTests.swift` | 修改 | dump 的还原断言 | 行为清单 | 5 | +| `Documentations/Internal/Modules/SwiftObjCInterop.md`、`Documentations/Internal/ObjCImplementationClassRecognition.md` | 修改 | 记录还原规则与新入口 | 文档同批 | 5 | +| `Documentations/Internal/ProjectEvolutionLog.md` | 修改 | 一节记录本次改动 | 节号落地时取 | 收尾 | + +## 架构图 + +```text +SwiftObjCInterop + ObjCImplementationClassFacts.InstanceVariable (typeEncoding, swiftTypeNode?) + ObjCImplementationClassFacts.Property (attributes: T…,R,W,V…) ++ ObjCInstanceVariableSwiftType(instanceVariable:objcProperty:in:) ++ encoding complete -> ObjCTypeEncodingParser.type(from:) -> ObjCImportedTypes.triviallyRepresentedTypeNode ++ encoding "?" -> ObjCTypeEncodingParser.propertyType(fromAttributes:) -> ObjCImportedTypes.bridgedTypeNode ++ encoding "" -> nil + ObjCImportedTypes + typeNode(_:position:) (unchanged: imported declarations) ++ triviallyRepresentedTypeNode(_:) -> Node? ++ bridgedTypeNode(_:) -> Node? + +SwiftPrinting + SwiftDeclarationPrintConfiguration ++ cTypeReplacements: [Transformer.CType.Pattern: String] + renderUnrepresentedObjCImplementationInstanceVariables + swiftTypeNode (Wvd)? -> var name: Type + standIn (Generated Interface)? -> imported ObjC property ++ ObjCInstanceVariableSwiftType? -> [weak] var|let name: Type[!|?] (C primitive -> replacement) + else -> // stored property …: Swift type not recoverable (…) + +SwiftDump + ObjCImplementationClassDumper +~ ivar row: + recovered `var name: Type`, comment names the type's source +``` + +```text +_UISplitViewControllerAdaptiveLayoutTransition (UIKitCore, stripped) + ivar mutableContainerView "@\"UIView\"" -> var mutableContainerView: UIView! + ivar mutableNewLayout "@\"<_UISplitView…AdaptiveLayout>\"" -> var mutableNewLayout: (any _UISplitView…AdaptiveLayout)! + ivar mutableIsAnimated "B" -> var mutableIsAnimated: Bool + ivar mutableInteractiveProgress "d" + [double: CGFloat] -> var mutableInteractiveProgress: CGFloat + ivar identifier "?" + property T@"NSString",R -> let identifier: String! + ivar animations "" -> // stored property animations: Swift type not recoverable (…) +``` + +## 详细设计 + +```swift +// SwiftObjCInterop +package struct ObjCInstanceVariableSwiftType { + package enum Source: Sendable, Hashable { + /// The ivar's own type encoding, written only for a Swift type that + /// Objective-C represents as it is. + case instanceVariableEncoding + /// The `T` attribute of the Objective-C property synthesized on the + /// ivar, whose type is the bridged one when the ivar says `?`. + case objcProperty + } + + /// The `Type` node, unknown nullability already spelled (`T!`, or `T?` + /// for a `weak` property). + package let typeNode: Node + package let source: Source + /// The Objective-C type the Swift type was read from, which tells a + /// printer when the type is a C primitive it may spell otherwise. + package let encodedType: ObjCEncodedType + package let isReadOnly: Bool + package let isWeak: Bool + + package init?(instanceVariable: ObjCImplementationClassFacts.InstanceVariable, objcProperty: ObjCImplementationClassFacts.Property?, in machO: some MachOSwiftSectionRepresentableWithCache) +} +``` + +- `encodedType` 存读出类型的 `ObjCEncodedType`(`package`,同一个包内可见),SwiftPrinting 自己把其中的 C 基本类型对到 `Transformer.CType.Pattern`,SwiftObjCInterop 不必依赖 `ObjCOutputTransformer`。 +- `typeNode` 由 `ObjCImportedTypes` 产出;可空判定沿用 `isNullable`(对象、block、`Class`、`char *`、指针)。 +- 「原样表示」判定(`determinesStoredPropertyType`):`void`、block、位域、不认识的类型、无名结构体与联合、导入规则表示不了的数组,以及指向 `void` 和标量以外的指针(指向结构体的指针与 CF 类型 encoding 相同,指向对象或指针的,导入规则会给出自己的类型)都还原不出。 +- 打印:`cTypeReplacements` 对该基本类型有非空替换时打 `TypeName(kind: .other, replacement)`,否则 `printType(typeNode)`。 +- 打印用的节点是每次打印新建的 transient 节点,由局部常量持有到打印结束,满足「交给 interface printer 的节点必须活过这次打印」。 + +## 替代方案考量 + +- **只用 ObjC 属性、不看 ivar 的 encoding**:两者对完整 encoding 给的是同一个类型,但没有 ObjC 属性的 ivar 就还原不出;encoding 是 `?` 时又只能看属性。所以按 encoding 分流。 +- **Swift 一侧也直接打 Generated Interface 的 stand-in**:stand-in 按导入规则桥接,完整 encoding 的 `NSString` 会被打成 `String`,`id`(`AnyObject`)打成 `Any`,是错的。 +- **可空性一律写 `T?` 或 `T`**:都是在猜;`T!` 是 ClangImporter 对「可空性未知」的既有写法。用户确认用 `T!`。 +- **`d` 一律写 `CGFloat`**:`NSTimeInterval` 等也是 `d`。用户决定走调用方的 C 类型替换表,默认仍是 `Double`。 + +## 影响 + +### 源码兼容性(source compatibility) + +纯新增:`SwiftDeclarationPrintConfiguration.cTypeReplacements` 与 `applyTransformers(_: Transformer.ObjCConfiguration)` 是新增的公开成员,默认值不改变任何现有调用的输出之外的行为。输出变化:剥过符号的 `@objc @implementation` 类,原来是注释的存储属性有一部分变成声明。 + +### ABI 兼容性(条件项) + +不适用 —— 本库以 SPM 源码分发,使用方每次重新编译。 + +### 下游影响 + +- 本仓库:`SwiftPrinting`(新依赖 `ObjCOutputTransformer`)、`SwiftDump`、`SwiftObjCInterop`。 +- RuntimeViewer:抬 MachOSwiftSection 依赖后,Swift 接口自动带上还原;C 类型替换要它在 `RuntimeSwiftSection` 里把 `transformer.objc.cType` 交给打印配置(后续项)。 + +### 文档与示例 + +模块说明 `Internal/Modules/SwiftObjCInterop.md`、`SwiftPrinting.md`(如有对应段落)与演进账本。 + +## API 演进与废弃策略 + +无废弃:只新增成员。不需要 major 版本号跃迁。 + +## 落地步骤 + +1. **骨架**(已完成):`ObjCInstanceVariableSwiftType`(恒返回 `nil`)、`cTypeReplacements`、`SwiftPrinting` 依赖 `ObjCOutputTransformer`;夹具加 `AdaptiveTransitionWidget`,类集合断言跟上;前提测试。 + - 行为:夹具的 `@objc @implementation` 类集合多出 `AdaptiveTransitionWidget`,其余输出不变。 + - 行为:剥过符号后新类的 ivar 仍有名字与编译器写的 encoding,`@objc` 的都能对上 ObjC 属性。 +2. **完整 encoding 还原**(已完成):`triviallyRepresentedTypeNode`,interface 接入。 + - 行为:剥过符号的类类型 ivar 打成 `var x: Class!`。 + - 行为:协议存在类型打成 `var x: (any P)!`。 + - 行为:`B` / `d` / `q` 打成 `Bool` / `Double` / `Int`,结构体按结构体名。 + - 行为:`readonly` 的 ObjC 属性打 `let`。 + - 行为:完整 encoding 的 `NSString` 不桥接成 `String`、`@` 是 `AnyObject`(单元测试;夹具造不出,见改动地图);夹具里不桥接的类用 `NSMutableString` 验。 + - 行为:block、指向结构体的指针、位域、无名结构体还原不出。 + - 行为:空 encoding 仍是注释。 +3. **`?` 按 ObjC 属性还原**(已完成):`bridgedTypeNode`。 + - 行为:`?` 且有 `NSString` 属性的打成 `String!`,`NSArray` 的打成 `[Any]!`,`id` 的打成 `Any!`。 + - 行为:`?` 且没有 ObjC 属性的仍是注释。 + - 行为:`weak` 的 ObjC 属性打 `weak var x: T?`,类不桥接(`weak` 的存储让 ivar 写 `?`)。 +4. **C 类型替换**(已完成):`applyTransformers(_: Transformer.ObjCConfiguration)`,打印时替换;`SwiftInterfaceTests` 为此依赖 `ObjCOutputTransformer` 与 `OutputTransformer`。 + - 行为:配置 `double → CGFloat` 时 `d` 打成 `CGFloat`。 + - 行为:没有配置或模块关闭时仍是 `Double`。 +5. **dump 与文档**(已完成):`ObjCImplementationClassDumper` 接入;模块说明 `Internal/Modules/SwiftObjCInterop.md` 与实现说明 `Internal/ObjCImplementationClassRecognition.md`。演进账本的节号按项目规则在落地时取,由收尾时补。 + - 行为:dump 的 ivar 行打出还原的类型,注释写明来源。 + - 行为:还原不出的 ivar 注释仍写 `Swift type not recoverable`。 + +**收尾时必须判断两件事**:要不要配套专题文章、有没有引入新术语(写进决策日志)。 + +## 后续项 + +- 已有问题(基线上就有):`renderUnrepresentedObjCImplementationInstanceVariables` 里「只有 `Wvd` 符号」那条分支把 `var name: ` 与类型放成 `Rows` 的两个子项,打出来分成两行。本提案的新分支踩过同一个坑,改成了一个子项;那条旧分支要配一个「`Wvd` 在、accessor 已剥」的夹具才能复现,留到之后。 + +- ~~RuntimeViewer:`RuntimeSwiftSection` 把 `transformer.objc.cType` 交给 Swift 打印配置(`applyTransformers(_: Transformer.ObjCConfiguration)`),C Type Replacement 改动时让 Swift 输出重印;随 MachOSwiftSection 依赖版本一起抬。~~ 2026-11-27 已完成:内容区与 Find 语料两个打印器都拿到 `transformer.objc`,设置不变时不重配打印器;RuntimeViewer 的五个锁文件抬到本仓库 `next` 的 `edbf2966`(分支 `feature/swift-c-type-replacements`)。 +- `swift-section interface` 的 `--c-type-replacement`。 +- Generated Interface 的 stand-in 对完整 encoding 的 ivar 是否改用本提案的 Swift 类型(`NSString` 不桥接)。 + +## 决策日志 + +| 日期 | 变更 | 说明 | +|------|------|------| +| 2026-11-26 | Created as Draft | 用户在 RuntimeViewer 里看到 UIKitCore 一个 `@objc @implementation` 类的存储属性大半只有注释,而 ObjC 一侧已显示出类型,要求能还原的都还原,类名经 type indexing 转 Swift 名 | +| 2026-11-26 | 用户经 `implement-feature` 批准,提案由 agent 起草、用户事前未审阅 | 用户事先定了四点:对象类型写 `T!`;`d` 走 C 类型替换表;桥接集合也还原(`[Any]`);方案照此开工 | +| 2026-11-26 | 开始实现 | 在 `feature/objc-ivar-type-recovery` 上按落地步骤做 | +| 2026-11-26 | 还原结果存 `ObjCEncodedType`,不另设 `ObjCPrimitiveType` | `ObjCEncodedType` 在同一个包内可见,打印器直接对到 `Transformer.CType.Pattern`,少一个只为转一手的类型 | +| 2026-11-26 | 夹具的 `CGFloat` 属性在 Swift 一侧写 `Double` | 夹具只 `import Foundation`,头文件的 `CGFloat` 导入成 `Double`,写 `CGFloat` 时 `@implementation` 的类型匹配报错 | +| 2026-11-26 | 加前提测试 | 第 1 步审查指出:ivar 名在即时编译夹具里曾观测为空(`ObjCImplementationClassFacts.InstanceVariable.name` 的注释),名字空了就对不上 ObjC 属性;先钉住剥过符号后的事实 | +| 2026-11-26 | `weak` 属性挪到第 3 步,按 ObjC 属性读、不桥接 | 前提测试实测:`weak var observer: NSObject?` 的 ivar encoding 是 `?`,不是 `@"NSObject"` | +| 2026-11-26 | 第 2 步的两处修正与第 3 步同一个提交 | 第 2 步的首个提交在 Ultra 上编不过(解析器名写错,单独一个提交修好);之后又发现声明被 `Rows` 拆成两行、ObjC 属性的查找名与 stand-in 不一致,这两处修正与第 3 步的改动落在同几个文件里 | +| 2026-11-26 | 完整 encoding 的近似(枚举、`^v`、`#` 等)照打,写进假设 | 第 2 步审查指出;与 `CGFloat` / `Double` 同性质,ObjC 头文件一侧显示的也是同一个 C 类型 | +| 2026-11-26 | `?` 只认桥接表里的类与裸 `id` | 第 3、4 步审查指出:`?` 证明 Swift 类型不是那个类本身,按导入规则照单全收会把 `unowned` 属性的存储(也写 `?`、特性里没有 `W`)和表外的桥接类(`NSAffineTransform` → `AffineTransform`)打成错的类 | +| 2026-11-26 | `weak` 与 `readonly` 同时出现时仍写 `weak var` | `weak let`(SE-0481)要 Swift 6.2,源码更常见的是 `weak private(set) var`;无从区分时取更常见的写法 | +| 2026-11-26 | `applyTransformers(_: Transformer.ObjCConfiguration)` 与 Swift 一侧同名重载 | 调用点传的都是有类型的值(`transformer.objc`),不会歧义;只装 `cType`,`ivarOffset` 是 ObjC 头文件的 ivar 注释,Swift 一侧的偏移注释仍走 `fieldOffsetTransformer` | +| 2026-11-26 | C 类型替换只换类型本身,替换名照原样打印 | 与假设一致;替换表的文档写明只收不带模块的名字。ObjC 一侧会递归替换指针里的类型,Swift 一侧不跟 | +| 2026-11-26 | 实现完成,待用户看过后收尾 | 五步都在 Ultra 上过了针对性测试;整套测试结果见收尾;RuntimeViewer 的接入随依赖版本一起做(后续项) | +| 2026-11-26 | Implemented,取号 0112 | 用户看过后收尾。合进 `next`;落地时演进账本记为第 158 节。没做的:RuntimeViewer 一侧的接入(把 `transformer.objc.cType` 交给 Swift 打印、抬依赖版本)、`swift-section interface --c-type-replacement`、只有 `Wvd` 那条旧分支分两行的问题,都在后续项 | +| 2026-11-26 | 文档判断 | 不另写使用指南:调用方的契约只有 `cTypeReplacements` 一个属性,文档注释已写清。实现说明更新了已有的 `ObjCImplementationClassRecognition.md`,模块说明更新了 `SwiftObjCInterop.md`。没有新术语:「原样表示」对应编译器自己的 `isTriviallyRepresentableIn`,不是本项目造的词 | +| 2026-11-26 | 验证 | Ultra 上五个相关套件全过(界面 33、单元 9、前提 3 条,另含 dump 与 Generated Interface 套件)。整套测试(跳过 IntegrationTests)红约 800 处,全部是构建槽位的检出里没有 `SymbolTestsCore` fixture(「Fixture binary not found」「cannot load the SymbolTestsCore fixture」),其余原因的失败为零;完整结果要先把 fixture 编进那个检出 | +| 2026-11-27 | 后续项:RuntimeViewer 一侧接入完成 | RuntimeViewer 的 Swift section 把 ObjC 一侧的 C Type Replacement 设置交给内容区与 Find 语料的打印器,锁文件随之抬到 `edbf2966`;用户看过后收尾。远端解析依赖的构建要等 MachOKitExtensions 发 3.3.0 之后的版本 | +| 2026-11-29 | 更正 2026-11-26「`unowned` 属性的特性里没有 `W`」:`W` 与只读桥接类改为照实标注另一种读法 | 代码库体检第 2 条。编译器对带 `ReferenceOwnershipAttr` 的属性(`weak` 与各种 `unowned`)一律写 `W`(`GenClass.cpp` 2212–2214 行),`@implementation` 能对上头文件声明的 `unowned` 只有 `unowned(unsafe)`(头文件的 `unsafe_unretained` / `assign`;写 `unowned` 编译器报类型不符)。实测它的存储写 `?`:可写的带 `W`、与 `weak` 无从区分,被印成 `weak var x: NSObject?`;只读的只有 `R`、与桥接成值的 `let` 无从区分,被印成 `let x: String!`。改法:照旧印常见的读法,后面加 `/* or unowned(unsafe) var x: NSObject: the Objective-C property reads the same for both */`;只读桥接类只在 ivar 占一个指针时才可能是 `unowned(unsafe)`(`String` 占两个,不加);还有访问器符号、知道类型时按类型分——不是 `Optional` 的是 `unowned(unsafe) var`。用户批准修复 | diff --git a/Documentations/Evolutions/0113-cross-reference-recall-gaps.html b/Documentations/Evolutions/0113-cross-reference-recall-gaps.html new file mode 100644 index 000000000..4974a5ee2 --- /dev/null +++ b/Documentations/Evolutions/0113-cross-reference-recall-gaps.html @@ -0,0 +1,647 @@ + + + + + + +0113 - 交叉引用补漏:按 Swift 类型查询、GOT 槽地址、selector 引用与 ivar 读法 + + + + +
+ +
+

MachOSwiftSectionEvolutions0113

+

0113 交叉引用补漏:按 Swift 类型查询、GOT 槽地址、selector 引用与 ivar 读法

+
+
状态
Implemented
+
最后更新
2026-11-26
+
项目类型
库
+
原文
0113-cross-reference-recall-gaps.md
+
+
+ + + +
+ +
+

摘要

+

2026-11-26 在 Finder 26.5.2 与 ControlCenter 26.7 上按 2026-11-18 的方法复测交叉引用的召回:swift-section refs 0.25.0 找到 527 条代码引用里的 476 条(90.3%),IDA 一次查询 97.0%、两跳 99.4%。漏掉的 51 条里,13 条是按设计不报的 __objc_superrefs 载入,其余 38 条来自四处缺口:CLI 没有按 Swift 类型查的入口(27 条)、Swift 代码把 ObjC 类的 GOT 槽地址交给编译器生成的元数据辅助函数时不认类引用(8 条)、selector 只被当作参数用时不报(2 条)、一种 ivar 偏移的读法漏记(1 条)。

+

本提案补齐这四处,改动跨 MachOKitExtensions(核心层)、MachOObjCSection(ObjC 层)、本库(Swift 层、门面与 CLI)和 RuntimeViewer(三处穷尽 switch),并把这次的测量脚本收进本库当验收工具:补完后同一组样本应到 514/527(97.5%),剩下的 13 条就是 super 的载入。第 5 步还把「取函数地址」记成对函数的引用——它不在这次测量的类别里,但决定了调用链能不能穿过 block 与闭包。

+

所属愿景:不依赖 IDA 的逆向(第 1 阶段的补漏)。关联提案:0097、0098、RuntimeViewer 0056。

+
+ +
+

要你定

+
+

已落地

+

验收:测量脚本对功能分支 514/527(97.5%),多报 0;吞吐慢 1.9%–2.4%,在 5% 以内。2026-11-26 合进四个仓库的 next(MachOKitExtensions 也合进 main)并推送,取号 0113。下游远程构建要等 MachOKitExtensions 与 MachOObjCSection 发版。

+
+
+ +
+

提议方案

+
    +
  1. CLI 加 --type。swift-section refs --type <mangling> 列出对一个 Swift 结构体、枚举或类的全部引用,写法与 RuntimeViewer 相同:类型的 mangling(7SwiftUI4TextV),也收它的描述符、访问器或元数据符号($s…Mn、$s…Ma、$s…N,前面的 _ 可有可无),去掉前后缀得到 mangling。定义它的镜像先按 $s<mangling>Mn 符号在全部镜像里找;找不到(缓存里的内部类型没有这个符号)时,独立文件逐个镜像按 key 找,dyld cache 要求用 --type-image 指定镜像,否则报错并提示。结果是这些身份在各候选镜像里的 references(toSwiftType:inImageAt:) 之并。
  2. +
  3. 取到引用槽地址也算一次槽引用(核心层)。adrp; add 或 adr 算出的地址如果正好落在引用槽上(本镜像的 GOT 与会话报的引用节,或 cache 的共用 GOT 池),就在这条指令上按读槽处理:走 noteSlotReference(fromSlot:at:),路线记 .pointerSlot,由会话认出类,或在独立文件里记成导入符号。寄存器记下「已作为槽引用记过」,之后经它做零位移载入时不再重记,免得 adrp; add; ldr [x] 在同一处用法上记两行;寄存器里的地址照常保留,后面的发送仍能认出类字面量接收者。与语言无关,不写任何运行时名字。
  4. +
  5. selector 引用(ObjC 层)。查询里含 selector 键时,ObjC 会话也观察 __objc_selrefs 的载入:每次载入先记为待定;经典发送或 super 发送用 x1 里这个 selector 发送时,把它消掉;离开函数时,没被消掉的记成 selector 引用(新目标 CodeReferenceTarget.selector(String),种类 .reference),归在已有的 .selector 表键下,--selector 因此同时返回发送与引用。libobjc 的发送入口(objc_opt_respondsToSelector 等)不消掉它,那里的 x1 是参数。核心层的会话协议加一个 leaveFunction(),默认什么都不做。经 __objc_stubs 的发送在代码里不载入 selref,不受影响。
  6. +
  7. ivar 读法(核心层)。先用夹具编出这段指令写复现测试,确认修复前失败,再定位、修复。
  8. +
  9. 取函数地址记成对函数的引用(核心层)。adrp; add 或 adr 算出的地址正好是本镜像函数表里的一个函数起点时,记一条 .reference,目标是 .function(location),路线 .addressMaterialization;会话同时认领它(Swift 访问器)时两条都记。只在查询含函数键或建整表时找。--function 和 RuntimeViewer 的调用层级因此会列出取了它地址的代码:建栈上 block 的函数、把回调传给 dispatch_async / CFRunLoop 的函数、返回闭包的函数。这一步不在这次测量的类别里,用户决定并入。
  10. +
  11. 测量脚本进仓库,作为验收。收进 Scripts/CrossReferenceRecall/,03_query_swift_section.py 对 G 类改用 --type(mangling 取自访问器的符号名);落地时重跑,结果写回愿景。
  12. +
+
+ 非目标(6 条) +
+
    +
  • __objc_superrefs 的载入不算类引用:0097 定下的理由不变(见「替代方案」)。这 13 条是验收目标与 100% 之间的差。
  • +
  • 数据引用(方法表的 IMP、vtable 与见证表里的函数、函数指针表、GOT 槽本身作为被引用者):愿景第 3 阶段。
  • +
  • 按点分隔的 Swift 名字查类型(ControlCenter.Foo):要知道每一层的种类(结构体、类、枚举)才能拼出 mangling,先只收 mangling 与符号。
  • +
  • RuntimeViewer 显示 selector 引用:先在三处 switch 里补 case 并过滤掉,与 0097 处理新目标的做法一致;界面上怎么显示另提。第 5 步若并入,调用层级里取地址的行会和调用行一样显示,区分显示也另提。
  • +
  • 按辅助函数形状认 ObjC 类(见「替代方案」)。
  • +
  • x86_64;Binary Ninja 一列不重测(2026-11-18 的结论是它经 MCP 只有 67.6%,不作参照)。
  • +
+
+
+
+ +
+

架构图

+
    +
  • 新增
  • +
  • 修改
  • +
  • 不变
  • +
+

扫描一个函数时的分派

+
+ + + MachOCodeReferences · ReferenceScanner.scanFunction + adrp / add / adr → noteAddress(address, destination)takes the register it built into + + address in a reference slot → noteSlotReferenceown GOT, classrefs, cache GOT pool; mark the register + + address == function start (step 5)recordFunctionAddressReference + other data → sessions.recordAddressReference + ldr / ldrsw [base, #d] → noteLoad / noteWatchedLoad+ skip when base is a recorded slot address and d == 0 + RegisterFile + recordedSlotMaskcleared on overwrite, compared on meet; address kept + + function scanned → session.leaveFunction()CodeReferenceRecognitionSession, empty by default + ivar load at a merge point (step 4 fixes a miss) + + + ObjCCodeReferences · session + noteWatchedSlotLoad__objc_ivar → ivar reference + + __objc_selrefs → pending selector loadonly when findsSelectorReferences + recordCallStandInclassic / super send + consumes the pending load behind x1 + entry point (objc_opt_respondsToSelector) keeps it + + leaveFunction → recordSelectorReferenceeach pending load left over + recordClassReference (now also from slot addresses) + + + CrossReferenceAnalysis + CodeReferenceTarget + .selector(String) + ReferenceCollector · Table · Index + AddressSymbolication: selref slot → .selector + + + RuntimeViewer + CrossReferenceQuery: three switches + .selector (hidden) + + + + + + + +
+

核心层两处新增的地址判断与一个寄存器位;ObjC 会话多观察 __objc_selrefs,发送消掉、离开函数时冲刷;门面加一个目标;RuntimeViewer 只补 switch。

+ +

CLI 的查询分支

+
+ + ReferencesCommand+ --type, --type-image; --selector help + ReferencesRequestCrossReferenceSubject + .swiftType + keys path (unchanged)--selector: sends + selector refs (step 3)--function: calls + address-taking (step 5) + + swiftTypes pathnormalize: strip _ / $s, Mn / Ma / Ndefining images, else --type-image + references(to:inImageAt:) + + + + + locations(ofSymbolNamed:among:) + + swiftTypeDescriptorLocations(withKey:inImageAt:) + + swiftTypeIdentity(ofDescriptorAt:) + + imageIndices(referencingSwiftType:among:) + + references(toSwiftType:inImageAt:) + + +
+

新分支照搬 RuntimeViewer 按类型查引用的那条路:找定义镜像 → 描述符 → 身份 → 预筛 → 每个候选镜像查一次,取并集。

+
+ +
+

改动地图

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
文件 / 类型动作改什么为什么步骤
本库 Scripts/CrossReferenceRecall/(prepare.sh、ground_truth.py、verify_reproduction.py、query_swift_section.py、score.py、run_all.sh、ida-2026-11-18.txt、README.md)新增2026-11-26 的测量脚本;README 写样本路径、怎么跑、怎么读结果、基线数字验收工具不能再丢0
本库 Scripts/CrossReferenceRecall/query_swift_section.py新增被测的二进制由 SWIFT_SECTION 指定;G 类仍用 --function验收0
本库 Sources/Commands/SwiftSectionKit/CrossReferences/ReferencesRequest.swift · CrossReferenceSubject修改加 .swiftType(String, imageName: String?);ResolvedQuery 加按类型的查询分支;写法归一与定义镜像的查找--type 的库侧1
本库 ReferencesRequest.swift · CrossReferenceRequestError修改加 swiftTypeNotFound(String)、swiftTypeNeedsImage(String)找不到类型、缓存里的内部类型1
本库 Sources/Executables/swift-section/Commands/ReferencesCommand.swift修改--type、--type-image;validate() 计入新主体;--selector 的帮助文字改成「发送与引用」CLI 入口1、3
本库 Sources/Executables/swift-section/…/CommandLineErrorTranslation修改两个新错误的措辞用法错误照旧是退出码 641
本库 Sources/Commands/SwiftSectionKit/CrossReferences/CrossReferenceFormatting.swift修改.selector 目标的文字(selector <名字>)与 JSON({"selector": …})新目标的输出3
本库 Sources/Analysis/CrossReferenceAnalysis/Models/CodeReference.swift · CodeReferenceTarget修改加 case selector(String)selector 引用的目标3
本库 Models/CodeReferenceTable.swift修改.selector 目标归 .selector 键--selector 与 RuntimeViewer 的 selector 查询都能取到3
本库 Models/CodeReferenceIndex.swift · Target修改常驻索引加 .selector 组RuntimeViewer 常驻用的紧凑索引要能存3
本库 CrossReferenceAnalyzer.swift · ReferenceCollector修改实现 recordSelectorReference;findsSelectorReferences(键含 .selector 或建整表)传给 ObjC 会话;第 5 步实现 recordFunctionAddressReference 与开关门面拼装3、5
本库 Symbolication/AddressSymbolication.swift修改selref 槽的含义从 .messageSend(selector:receiver: .unknown) 改为 .selector0097 第 6 步留的说明「目标类型里没有单独的 selector」不再成立3
本库 AgentPlugins/swift-section/skills/swift-section-cli/references/cross-references.md(及 SKILL.md 里列到 refs 选项的地方)修改--type、--type-image、selector 引用、取槽地址的类引用;第 5 步的取地址行项目规定:改 CLI 同批改 skill1、3、5
本库 README.md 的 refs 一节修改加 --type 的例子对外文档1
本库 Tests/SwiftSectionKitTests/…(ReferencesRequestSwiftTypeTests.swift)新增--type 的解析、写法、错误第 1 步行为1
本库 Tests/CrossReferenceAnalysisTests/…(SelectorReferenceTests.swift、SlotAddressReferenceTests.swift,第 5 步 FunctionAddressReferenceTests.swift)新增经门面的行为测试各步行为2、3、5
本库 Documentations/Internal/Modules/CrossReferenceAnalysis.md修改引用种类、类引用、selector、--type、测试锚点;召回一节指向愿景总说明1–5
本库 Documentations/Visions/ReverseEngineeringWithoutIDA.md修改复测段(本批已写);落地后补上修复后的数字愿景是活文档6
MachOKitExtensions Sources/Analysis/MachOCodeReferences/Scanning/ReferenceScanner.swift · noteAddress修改落在引用槽上的地址改走 noteSlotReference;需要知道目标寄存器,签名加 destination第 2 步2
MachOKitExtensions ReferenceScanner.swift · scanFunction 的载入分支修改经已记过槽引用的寄存器做零位移载入时不重记防重复2
MachOKitExtensions ReferenceScanner.swift(具体位置待第 4 步的测试定位)修改修 ivar 漏记第 4 步4
MachOKitExtensions ReferenceScanner.swift · noteAddress修改落在函数起点的地址记成对函数的引用第 5 步5
MachOKitExtensions Sources/Analysis/MachOCodeReferences/Scanning/RegisterFile.swift修改加一个按寄存器的位 recordedSlotMask:这个地址已作为槽引用记过;改写寄存器时清掉,汇合时比较防重复,且不丢地址(现成的 setTag 会把地址状态覆盖掉)2
MachOKitExtensions Recognition/CodeReferenceRecognition.swift · CodeReferenceRecognitionSession修改加 func leaveFunction(),协议扩展给空实现;扫描器在每个函数扫完时调用selector 待定载入的冲刷点3
MachOKitExtensions CodeReferenceRecognition.swift · CodeReferenceRecording修改加 recordFunctionAddressReference(toFunctionAt:at:)第 5 步5
MachOKitExtensions Tests/MachOCodeReferencesTests/…(SlotAddressScanTests.swift、InstanceVariableMergePointTests.swift)新增用 FixtureCompiler 编带内联汇编的夹具,钉住指令序列复现测试2、4
MachOKitExtensions Documentations/Internal/MachOCodeReferences.md修改新契约与测试实现说明2、4、5
MachOObjCSection Sources/ObjCCodeReferences/ObjCCodeReferenceRecognizer.swift · ObjCCodeReferenceRecording修改加 recordSelectorReference(selector:at:)第 3 步3
MachOObjCSection ObjCCodeReferenceRecognizer.swift · 会话修改findsSelectorReferences 开关;watchedSlotRanges 加 selectorReferenceRange;待定载入、发送消掉、leaveFunction 冲刷第 3 步3
MachOObjCSection Tests/ObjCCodeReferencesTests/…(SelectorReferenceRecognitionTests.swift)新增ObjC 夹具:respondsToSelector:、setAction:、经典发送不重复第 3 步3
MachOObjCSection Documentations/Internal/ObjCCodeReferences.md修改selector 引用的认法实现说明3
RuntimeViewer RuntimeViewerCore/Sources/RuntimeViewerCrossReferences/Analysis/CrossReferenceQuery.swift修改:92、:727、:949 三处 switch 补 .selector(不显示);selector 查询结果滤掉 .selector 目标穷尽 switch 会编译失败;界面先不变3
+
+
+ +
+

详细设计

+
+ 第 1 步:--type +
+
public enum CrossReferenceSubject: Sendable, Hashable {
+    // … the six existing cases …
+    /// A Swift struct, enum or class by its mangling — `7SwiftUI4TextV` — or a
+    /// `$s…Mn`, `$s…Ma` or `$s…N` symbol of it, defined in the image
+    /// `imageName` names, or in whichever image exports its descriptor.
+    case swiftType(String, imageName: String?)
+}
+
// ReferencesCommand
+@Option(name: .customLong("type"), help: "Every reference to the Swift struct, enum or class with this mangling (7SwiftUI4TextV), or to the one a $s…Mn, $s…Ma or $s…N symbol names.")
+var swiftType: String?
+
+@Option(name: .customLong("type-image"), help: "The image that defines --type's type, by path or file name: needed in a dyld shared cache for a type no image exports.")
+var swiftTypeImage: String?
+
    +
  • validate():--type 计入「恰好一个主体」;--type-image 只能和 --type 一起用(与 --function-image 同样的报错写法)。
  • +
  • 写法归一:去掉前导 _,去掉前导 $s;末尾依次试 Mn、Ma、N,去掉后剩下的部分能 demangle 成一个名义类型才算数,否则当作原样的 mangling。名义类型的 mangling 以种类字母(V、C、O,__C 类型的 a 等)结尾,不会被误剥。
  • +
  • 找定义镜像:--type-image 给了就只在它里面找;否则 locations(ofSymbolNamed: "_$s" + key + "Mn", among: 全部镜像);仍然没有时,独立文件逐个镜像 swiftTypeDescriptorLocations(withKey:inImageAt:),dyld cache 抛 swiftTypeNeedsImage(逐镜像算 key 要几分钟)。macOS 与 Mac Catalyst 两个变体都定义时,两个身份都查,结果取并集。
  • +
  • 查询:ResolvedQuery.Search 加 case swiftTypes([SwiftTypeIdentity], candidates: [Int]);run(output:) 在候选镜像上并发调 references(toSwiftType:inImageAt:),与 .callers 的并发写法相同(ReferencesRequest.swift:142)。--in-image 照旧限定扫描范围。
  • +
  • 输出:目标照已有的 swiftType / swiftTypeName / objectiveCClass(Swift 类也比它的 ObjC 类对象位置)格式输出,不新增格式。
  • +
+
+
+
+ 第 2 步:取到引用槽地址 +
+
// ReferenceScanner (MachOCodeReferences)
+private mutating func noteAddress(_ address: UInt64, builtInto destination: Int, at site: ScanSite, mayNameAString: Bool) {
+    if isReferenceSlot(address) {
+        noteSlotReference(fromSlot: address, at: site.reached(by: .pointerSlot))
+        registers.markRecordedSlotAddress(of: destination)
+        return
+    }
+    // … unchanged …
+}
+
+/// A slot of this image's GOT or of a session's reference sections, or one
+/// of the GOT pool the shared cache keeps outside every image.
+private func isReferenceSlot(_ address: UInt64) -> Bool
+
    +
  • isReferenceSlot 复用 noteSlotReference 开头的判断(referenceSlotRanges 与 images.isSlotOutsideEveryImage),两处共用一个私有函数,免得以后只改一处。
  • +
  • 载入分支:load.displacement == 0 且 registers.isRecordedSlotAddress(load.base) 时不调 noteLoad,寄存器照常更新(目标寄存器仍是 .loadedFromSlot,类字面量接收者照认)。
  • +
  • RegisterFile 的 Contents 加 recordedSlotMask,与 constantMask 同样处理:overwrite 清位,Snapshot.agrees 比较它,meet 不一致时清掉。不用现成的 setTag:它把寄存器改成 .tagged 状态,地址就没了(RegisterFile.swift:83)。
  • +
  • 只在 looksForAddressReferences 为真时做,与现状一致:只查 selector 或函数时不付这份代价。
  • +
+
+
+
+ 第 3 步:selector 引用 +
+
// MachOObjCSection, ObjCCodeReferences
+@_spi(Internals) public protocol ObjCCodeReferenceRecording: CodeReferenceRecording {
+    // … existing …
+    /// A load of the selector reference to `selector` that no send used:
+    /// the selector handed on as data — to `respondsToSelector:`,
+    /// `performSelector:`, a control's action.
+    func recordSelectorReference(selector: String, at site: ScanSite)
+}
+
+// MachOKitExtensions, MachOCodeReferences
+@_spi(Internals) public protocol CodeReferenceRecognitionSession: AnyObject {
+    // … existing …
+    /// The scan is done with the function it last entered.
+    func leaveFunction()
+}
+
+extension CodeReferenceRecognitionSession {
+    @_spi(Internals) public func leaveFunction() {}
+}
+
+// MachOSwiftSection, CrossReferenceAnalysis
+public enum CodeReferenceTarget: Hashable, Sendable {
+    // … existing …
+    /// A selector the code loads but sends no message with: it hands the
+    /// selector on — to `respondsToSelector:`, `performSelector:`, a
+    /// control's action.
+    case selector(String)
+}
+
    +
  • ObjC 会话:findsSelectorReferences 为真时 watchedSlotRanges 加上 sections.selectorReferenceRange(ObjCImageSections 已有这个字段)。noteWatchedSlotLoad 落在它上面时读出 selector 名,追加到 pendingSelectorLoads: [(slot: UInt64, site: ScanSite)]。
  • +
  • 消掉:recordCallStandIn 的 .classicSend 与 .superSend 分支取 registers.slotAddress(of: 1),从 pendingSelectorLoads 末尾往前删掉第一个同槽的条目。.entryPoint 与 .selector(__objc_stubs)不删。
  • +
  • 冲刷:leaveFunction() 把剩下的逐条交给 recordSelectorReference,清空数组。enterFunction 也清一次,防扫描器提前返回时漏冲刷(scanFunction 的 guard 早退)。
  • +
  • 顺序:冲刷发生在函数末尾,所以一个函数里 selector 引用排在该函数的其它引用之后;收集器按地址排序后输出,不影响结果顺序(实现时核对 ReferenceCollector 是否排序,若不排则在冲刷前按地址插入)。
  • +
  • 门面:ReferenceCollector.findsSelectorReferences = 查询键含 .selector,或建整表。recordSelectorReference → keep(.selector(selector), at: site);CodeReferenceTable 把它归在 .selector(selector) 键下。
  • +
  • 符号化:selref 槽的含义改为 .selector(name)(AddressSymbolication.swift),swift-section symbolicate 对 selref 槽的输出从 send <名字> 变成 selector <名字>。
  • +
+
+
+
+ 第 4 步:ivar +
+
    +
  • 夹具:一个 ObjC 类,三个 ivar;一个方法用 __asm__ 写出与 Finder 0x1002bba08 同构的序列——前面几个分支 b 到同一个标签,标签处 adrp x9, _OBJC_IVAR_$_…@PAGE; add x9, x9, _OBJC_IVAR_$_…@PAGEOFF; ldrsw x9, [x9]; str w8, [x0, x9]。另写一个不经汇合点的对照方法。
  • +
  • 测试先红(经汇合点的那条找不到、对照那条找到),由此确认是汇合还是别的原因,再修。
  • +
  • 结果:根因与修法见决策日志 2026-11-26「第 4 步定位到根因」。夹具改为两条路径各算一个偏移变量地址、在载入处汇合;对照方法的引用记在 add 上而不是 ldrsw 上。
  • +
+
+
+
+ 第 5 步:取函数地址 +
+
// MachOKitExtensions, CodeReferenceRecording
+/// Code built the address of the function at the unslid `address` — to call
+/// it later, sign it and hand it on, or put it in a block.
+func recordFunctionAddressReference(toFunctionAt address: UInt64, at site: ScanSite)
+
    +
  • noteAddress 里 isCode 且这个地址是函数起点时记一条;会话随后照常被问(Swift 会话认领访问器,两条都记)。开关 recordsFunctionAddressReferences 由门面按查询键(含 .function)或建整表给出。
  • +
  • 判断是不是函数起点:ImageFunctionTable.functionIndex(containing:)(ImageFunctionTable.swift:249)取到的函数起点等于这个地址。
  • +
  • 门面把它记成 kind == .reference、目标 .function(location),归 .function 键。
  • +
+
+
+
+ +
+

调研

+
+ 分类别结果(两个镜像合计,代码引用) +
+
+ + + + + + + + + + + + +
类别标准答案IDA 一次IDA 两跳本库 0.25.0
A selector 发送97929795
B ObjC 类引用87768466
C 导入函数91919191
D 内部函数 bl70707070
E 字符串46464646
F ivar(仅 Finder)32323231
G Swift 元数据访问器(仅 ControlCenter)10410410477
合计52797.0%99.4%90.3%
+
+

另有 49 条数据引用(方法表的 IMP、只在 vtable / 见证表里出现的函数、GOT 槽本身等),IDA 全中,本库按 0097 的非目标不做,记 0。本库多报 1 条:0x1005273f8 ldr x0, [x20],是先 adrp; add x20, <NSAppleEventDescriptor 的 GOT 槽> 再经 x20 载入,标准答案的线性跟踪把这条引用记在 add 上,核对后是真引用。

+
+
+
+ 测量方法与复现 +
+
    +
  • 样本:/Volumes/RE/Finder/26.5.2/Finder(ObjC 为主)与 /Volumes/RE/ControlCenter/26.7/ControlCenter(Swift 为主)的 arm64e 切片,UUID 分别是 1E2E81F7-9B9D-317A-A102-F55ADAF6A0A0、5782ED6B-471B-3CAC-9258-93734B6009C3,与卷上两个 .i64 相同。
  • +
  • 标准答案:不依赖任何一个被测工具,由 otool -tV 加独立的 adrp 寄存器跟踪、dyld_info -fixups、相对方法列表与 __swift5_types 解码生成。代码从 2026-11-18 那次对比的子 agent 对话记录(~/.claude/projects/-Users-JH/4cad8a68-…/subagents/agent-a43f33e89a2f7bb07.jsonl 的第 24、31、51、56 次工具调用)原样取回,只换了临时目录。
  • +
  • 复现核对:两份标准答案的引用总数(511,138 与 359,773)、__objc_stubs 数(8,809 与 1,363)、各类目标列表与 2026-11-18 的输出逐项一致;按原打分规则(第 69 次工具调用)重算 IDA 一列,仍是 97.0% / 99.4%。所以这次的数字可以直接与那次比。
  • +
  • 查询:每个目标调一次 swift-section refs <文件> --json(--selector、--class、--symbol、--function、--string、--ivar),共 128 次,零报错;Finder 单次中位 0.31 秒、ControlCenter 0.13 秒,都含建分析器的时间。外部类另加一次 --symbol _OBJC_CLASS_$_<类>,结果与只查 --class 相同,说明 --class 已经覆盖导入的类。
  • +
  • 脚本:在 /tmp/claude-xref-2026-11-26/scripts/(run_all.sh 一条命令跑完,约 30 秒)。/tmp 会被系统清理,所以落地步骤第 0 步先把它们收进本库;万一已被清掉,可从 2026-11-26 那次会话的对话记录里取回(脚本都是用 Write 工具写的)。
  • +
+
+
+
+ 51 条漏报的五组原因 +
+
    +
  1. 取访问器地址当函数指针用(27 条,G 类)。形如 ControlCenter 0x1000cd564:adrp x16, …; add x16, x16, #0xd38(访问器 0x1003e3d38)→ mov x17, #0x882f; pacia x16, x17; mov x1, x16,把签过名的访问器地址交给调用方。分析器其实记下了:refs --function=0x1000cd568 --callees 显示 0x1000cd568 reference addressMaterialization swiftType(Swift 会话把访问器地址认领为类型引用,见 CrossReferenceAnalysis.md「Swift 类型引用」第 2 种来源)。漏在 CLI:--function 只返回调用者,而 ReferencesRequest(Sources/Commands/SwiftSectionKit/CrossReferences/ReferencesRequest.swift:262-310)的六种主体里没有 Swift 类型。Swift 类型的引用表按描述符位置归档(CodeReferenceTable.Key.swiftTypeDescriptor),查询要经比对器 references(toSwiftType:inImageAt:)(Sources/Analysis/CrossReferenceAnalysis/CrossReferenceAnalyzer+SwiftTypes.swift:57),不能像其它主体那样换成表键。
  2. +
  3. __objc_superrefs 的载入(13 条,B 类,按设计)。Finder 0x1006604a0 ldr x8, [x8, #0x358] 读的是 __objc_superrefs 的 0x100b4b358,随后 stp x0, x8, [sp] 拼出 objc_super 交给 _objc_msgSendSuper2。13 条全是这种。CrossReferenceAnalysis.md「类引用(第二批)」写明这一载入不算类引用(「报出来只会让每个调 super 的方法都『引用』了自己的类」),引用记成带类名的 superMessageSend。标准答案把 __objc_superrefs 算作类引用的槽(2026-11-18 的报告「经 __objc_superrefs 加载类对象,这类已并入 ground truth」)。
  4. +
  5. GOT 槽地址交给元数据辅助函数(8 条,B 类)。ControlCenter 0x1006455c8:adrp x2, …; add x2, x2, #0x2a0(_OBJC_CLASS_$_OS_os_log 的 GOT 槽 0x10083a2a0)→ mov x0, #0; bl 0x10000b4a8。0x10000b4a8 是编译器生成的共用辅助函数:ldr x0, [x1]; cbnz …; ldr x0, [x2]; bl _objc_opt_self; bl _swift_getObjCClassMetadata; stlr x0, [x19]——x1 是缓存变量,x2 是类的 GOT 槽。ControlCenter 里有 554 处调用它。核心层 ReferenceScanner.noteAddress(MachOKitExtensions Sources/Analysis/MachOCodeReferences/Scanning/ReferenceScanner.swift:366)把数据段里的地址交给会话的 recordAddressReference,ObjC 会话只认类对象本身(MachOObjCSection Sources/ObjCCodeReferences/ObjCCodeReferenceRecognizer.swift:305),GOT 槽的地址不是类对象,于是什么都不记。读槽的入口 noteSlotReference(fromSlot:at:)(ReferenceScanner.swift:441)已经能解本镜像的 GOT、classref、cache 的共用 GOT 池与独立文件的 bind,只是取槽地址的路径没有走到它。IDA 也要两跳(2026-11-18 报告的 IDA 漏报第 2 条,同一个 0x1006455cc)。
  6. +
  7. selector 只当参数用(2 条,A 类)。Finder 0x1003ee048:adrp x8, …; ldr x1, [x8, #0x6d0](coalescingNodeObserver:openSyncCompleted: 的 selref)→ mov x0, x19; bl _objc_opt_respondsToSelector;ControlCenter 0x100674e00:adrp x8, …; ldr x0, [x8, #0x378]; ret,一个返回 selector name 的函数。ObjC 会话只在发送时从 x1 的来源槽读出 selector(selectorInSelectorRegister),它观察的槽只有 __objc_superrefs 与 __objc_ivar(ObjCCodeReferenceRecognizer.swift:209),没被发送用掉的 selref 载入什么都不留。objc_opt_respondsToSelector 作为 libobjc 的发送入口记成一次 respondsToSelector: 发送(recordCallStandIn 的 .entryPoint),x1 里那个作参数的 selector 被丢掉。
  8. +
  9. adrp; add 之后 ldrsw [xN] 读 ivar 偏移(1 条,F 类,原因待查)。Finder -[TTaskErrorOrConflictViewController setResolutionsForKind:] 的 0x1002bbb14:adrp x9, …; add x9, x9, #0x28; ldrsw x9, [x9]; str w8, [x0, x9](ivar _rightResolution)。同一个 ivar 在别的函数里的两处 adrp; ldrsw [x8, #imm] 都找到了,同一函数里别的 ivar 的 11 处也都找到了。读代码排除了几种可能:机器码 d00047a9 9100a129 b9800129 都在解码器覆盖内(ARM64InstructionWord.wordLoad 认 0xB980_0000,addImmediate 认 0x9100_0000);函数起点表里 0x1002bba08–0x1002bbb28 是一个函数;RegisterFile.add 对 .address 状态的源寄存器给出 .address。0x1002bbb14 是三条 b 的共同目标、又从上一条顺序落下,是汇合点——推测问题与汇合处的寄存器状态有关,未证实。第 4 步先写复现测试再定位。
  10. +
+
+
+
+ 赢过 IDA 的地方、相关的现成能力 +
+
    +
  • Finder 的三个页对齐类对象(adrp; add #0x0,如 0x100131f8c)IDA 漏,本库一次查到。
  • +
  • 经 ldr 读 selref 的经典发送,本库一次查到;IDA 要再查 selref 一跳(A 类 IDA 一次 92、本库 95)。
  • +
  • 不需要先建 IDA 库;单次查询 0.1–0.3 秒。
  • +
  • RuntimeViewer 按类型查引用时用类型的 mangling(RuntimeObject.name,如 7SwiftUI4TextV)找描述符:swiftTypeDescriptorLocations(withKey:inImageAt:) → swiftTypeIdentity(ofDescriptorAt:) → 预筛 imageIndices(referencingSwiftType:among:) → 每个候选镜像 references(toSwiftType:inImageAt:)(RuntimeViewer RuntimeViewerCore/Sources/RuntimeViewerCrossReferences/Analysis/CrossReferenceQuery.swift:300-380)。CLI 照搬这条路即可,写法也与它一致。
  • +
  • 按名字定位符号:locations(ofSymbolNamed:among:)(CrossReferenceAnalyzer+Linkage.swift:11),查 $s…Mn 比逐镜像算 key 快得多。
  • +
  • 核心层的读槽、槽认领缓存(slotClaims)与导入名(importedSlotNames)都现成。寄存器表有按寄存器的标记(RegisterFile.setTag / tag(of:),ObjC 会话用它标方法接收者),但打标记会把寄存器改成 .tagged 状态、丢掉地址(RegisterFile.swift:83),不能拿来标「已记过」;按寄存器的位掩码(constantMask、blendedMask)是现成的另一种写法。
  • +
  • 下游穷尽 switch:RuntimeViewer CrossReferenceQuery.swift 的 switch reference.target(:92、:727)与 switch target(:949)。0097 加三种新目标时的做法是在 RuntimeViewer 里补 case、先不显示(0097「源码兼容性」一节与决策日志 2026-11-19「第 8 步完成」)。
  • +
+
+
+
+ 动机 +
+

完整动机见愿景《不依赖 IDA 的逆向》。这一步特有的部分:

+
    +
  • 0097 落地时没有做全面核对。0097 决策日志 2026-11-19「第 4 步完成」一行只抽样了 ControlCenter 的 3 个函数,「全面核对没有重做」一段说明生成标准答案的脚本已经不在卷上。2026-11-26 从 2026-11-18 那次对比的对话记录里原样取回了标准答案与选目标的代码,复现出同一批 120 个目标,补做了这次核对,结论写进了愿景「我们选的方向」第 1 条的复测段。
  • +
  • 差距集中在几处可以修的地方,而不是扫描整体不行。导入函数、内部 bl、字符串三类与 IDA 一样全中;selector 发送(95/97)与类引用里的页对齐类对象还比 IDA 一次查询多中几条。漏报按原因归成五组,每组都有具体地址。
  • +
  • 影响面比样本里的条数大。GOT 槽地址那一组:ControlCenter 里有 554 处 bl 0x10000b4a8,每一处都把一个 ObjC 类的 GOT 槽地址放进 x2,这是 Swift 代码取 ObjC 类元数据的通用写法。Swift 类型那一组:经 CLI 工作的 agent 现在根本问不了「哪些代码用到了 Swift 类型 X」,只有 RuntimeViewer 的界面能问。selector 那一组:respondsToSelector: 的参数、返回 selector 的函数;performSelector:、target-action 的 setAction: 也是同一形态(推测,样本里没有抽到)。
  • +
+
+
+
+ +
+

替代方案

+
+ 六条,全部否决 +
+
    +
  • 只让 --function 查访问器时也返回类型引用,不加 --type:能补上这 27 条,但只覆盖访问器;泛型实例的访问器、按 mangled name 实例化、元数据地址这几种类型引用仍然问不到,而 RuntimeViewer 早已按类型查。否。
  • +
  • GOT 槽地址按辅助函数的形状认:在 Swift 层认出 ldr x0, [x2]; bl objc_opt_self; bl swift_getObjCClassMetadata 这种函数,在调用点从 x2 取类。更准,但只覆盖这一个辅助函数,还要 Swift 层认 libobjc 的名字;核心层按「地址落在引用槽」处理与语言无关,覆盖一切先取槽地址再用的写法。否。
  • +
  • 每次 selref 载入都记一条引用:实现最简单,但经典发送(不走 __objc_stubs 的二进制)每次发送都会多一条同位置的引用行。否。
  • +
  • selector 引用另开一个表键:--selector 就要查两个键,RuntimeViewer 的 selector 查询也要改;归在同一键下、靠目标区分更省事,下游想只要发送时按目标过滤即可。否。
  • +
  • 把 __objc_superrefs 的载入报成类引用:召回能到 100%、与 IDA 对齐,但每个调 super 的方法都会「引用」自己的类,按类查引用的结果会被这些行淹没(Foundation 1,803 处、AppKit 8,336 处 super 发送,见 CrossReferenceAnalysis.md「类引用」)。0097 的理由仍然成立。否。
  • +
  • 测量脚本放在 /Volumes/RE 或个人目录:2026-11-18 那次就是这样丢的。进仓库、跟着交叉引用的代码走。否。
  • +
+
+
+
+ +
+

影响

+
+ 源码兼容性:有破坏(一个新 enum case) +
+
    +
  • CodeReferenceTarget 加 case selector(String):下游对它的穷尽 switch 编译失败。已知调用点是 RuntimeViewer CrossReferenceQuery.swift 的 :92、:727、:949。改法是多一个 case .selector: return nil,先不显示。
  • +
  • CrossReferenceSubject(SwiftSectionKit)加 case swiftType:本库以外没有使用方(RuntimeViewer 用自己的查询层)。
  • +
  • MachOKitExtensions 与 MachOObjCSection 的改动全在 @_spi(Internals) 接口上(CodeReferenceRecognitionSession.leaveFunction 有默认实现;ObjCCodeReferenceRecording 与 CodeReferenceRecording 各加一个要求,实现方只有本库的 ReferenceCollector 与 MachOKitExtensions 测试里的识别器)。SPI 不承诺稳定。
  • +
  • 行为变化(不是编译错误):--selector 与 RuntimeViewer 按 selector 的查询多出 .selector 目标的行(RuntimeViewer 先滤掉);按类查引用多出取槽地址的行;symbolicate 对 selref 槽的说法变了;第 5 步若并入,--function 与调用层级多出取地址的行。
  • +
+
+
+
+ ABI 兼容性、下游、文档、版本 +
+
    +
  • ABI:不适用 —— 本库以 SPM 源码分发,使用方每次重新编译。
  • +
  • 本仓库:CrossReferenceAnalysis、SwiftSectionKit、swift-section 可执行文件,以及 CrossReferenceAnalysisTests、SwiftSectionKitTests。整表变大,ScanThroughputBenchmarkTests 要重量。
  • +
  • MachOKitExtensions、MachOObjCSection:同批改、同批发版,依赖顺序 MachOKitExtensions → MachOObjCSection → 本库。
  • +
  • RuntimeViewer:三处 switch;本库 next 一合进新 case,RuntimeViewer 的 next 要同批跟上。
  • +
  • MachOKitUI、REAgent:不用交叉引用,不受影响。
  • +
  • 文档:README.md 的 refs 一节、CLI 的 skill、三份模块文档、愿景的复测段。
  • +
  • 版本:不废弃任何东西。本库 0.x 的下一个 minor;MachOKitExtensions 下一个 minor;MachOObjCSection 下一个 minor。
  • +
+
+
+
+ +
+

落地步骤

+
    +
  1. 测量脚本进仓库(已完成) +
    • run_all.sh 对 0.25.0 复现 476/527(90.3%),IDA 列 97.0% / 99.4%,复现核对通过
    • README 记下基线数字与每类的漏报原因
  2. +
  3. --type(已完成) +
    • typeSubjectFindsTheReferencesTheAnalyzersSwiftTypeQueryFinds
    • typeSubjectAcceptsTheManglingAndItsDescriptorAccessorAndMetadataSymbols
    • typeSubjectLooksForAnUnexportedTypeInEveryStandaloneFile
    • typeSubjectInACacheNeedsTheTypeImageForAnUnexportedType
    • typeImageWithoutTypeIsAUsageError
    • 测量脚本 G 类 104/104
  4. +
  5. 取到引用槽地址也算槽引用(已完成) +
    • slotAddressHandedToAHelperIsAClassReference
    • slotAddressInAStandaloneFileIsAnImportedSymbolReference
    • aLoadThroughARecordedSlotAddressIsNotRecordedAgain
    • slotAddressesAddOnlySlotReferencesToTheWholeImageTable
    • 测量脚本 B 类 74/87(剩下 13 条是 super)
  6. +
  7. selector 引用(已完成) +
    • respondsToSelectorArgumentIsASelectorReference
    • anActionSelectorHandedToSetActionIsASelectorReference
    • aClassicSendLeavesNoSelectorReferenceBehind
    • stubSendsLeaveNoSelectorReference
    • selectorQueriesReturnSendsAndSelectorReferences
    • selectorReferencesSurviveTheCompactIndex
    • symbolicationCallsASelectorReferenceSlotASelector
    • RuntimeViewer selectorReferencesAreNotShownYet
    • 测量脚本 A 类 97/97
  8. +
  9. ivar 读法(已完成) +
    • instanceVariableLoadThroughAnAddedAddressAtAMergePoint(修复前失败)
    • instanceVariableLoadThroughAnAddedAddressOutsideAMergePoint(对照)
    • 测量脚本 F 类 32/32
  10. +
  11. 取函数地址(已完成) +
    • takingAFunctionsAddressIsAReferenceToIt
    • aSignedAccessorAddressIsBothAFunctionAndATypeReference
    • aStackBlockIsReferencedByTheFunctionThatBuildsIt
    • functionQueriesReturnCallsAndAddressTakingSites
  12. +
  13. 验收与文档(已完成) +
    • 测量脚本代码引用 ≥ 514/527(97.5%),多报为 0,或逐条核对为真引用
    • ScanThroughputBenchmarkTests 各项比改前慢不超过 5%(超过就把数字和原因写进模块文档,由用户定)
    • 愿景复测段补上修复后的数字
  14. +
+
+

收尾时要判断的两件事

+
    +
  • 配套专题文章:预计不另写,契约写进 CLI 的 skill 与 README,实现细节写进三份模块文档。
  • +
  • 新术语:「selector 引用」(selector 被载入但没有用来发送)可能要登记进 Documentations/Glossary.md,落地时判断。
  • +
+
+
+ +
+

决策日志

+
+ 13 条,最近一条:Implemented,取号 0113 +
+
+ + + + + + + + + + + + + + + + + +
日期变更说明
2026-11-26Created as Draft按 2026-11-18 的方法补做 0097 落地时没做的全面核对:本库 90.3%、IDA 一次查询 97.0%。用户批准写一份提案修复测出的四处缺口,并把结果写进愿景
2026-11-26第 5 步列为待定「取函数地址」不在这次测量的类别里,但决定调用链能不能穿过 block 与闭包;是否并入本提案由用户定
2026-11-26第 5 步并入用户决定把「取函数地址记成对函数的引用」并入本提案,同批实现
2026-11-26Accepted用户批准,开始实现。四个仓库各开 feature/cross-reference-recall-gaps,按依赖顺序 MachOKitExtensions → MachOObjCSection → 本库 → RuntimeViewer 提交;构建与测试都在 Ultra 上跑(四个工程都在公司那台不编译的清单里),用 /Volumes/DerivedData/Agents.noindex/claude/LocalDependencies/CrossReferenceRecallGaps/ 下按仓库名放的功能分支拷贝解析本地依赖
2026-11-26第 4 步定位到根因,修法推广到观察的槽Finder 那个函数开头是跳转表,0x1002bba68 的 b 0x1002bbb1c 带着 _middleResolution 的偏移变量地址(add x9, x9, #0x24)直接跳到 ldrsw,与顺序落下、带着 _rightResolution(#0x28)的路径在载入处汇合,x9 两边不一致被作废——这条载入本来就读两个 ivar 之一,标准答案和 IDA 都把引用记在各自的 add 上。核心测试按这个形状写出后先红;修法与第 2 步同一套:算出的地址落在会话观察的槽上(__objc_ivar、__objc_superrefs、__objc_selrefs)时,在这条指令上通知会话、给寄存器打「已记过」的位,之后零位移的 32 位与 64 位载入不再重记。代价是 ObjC 会话总观察 __objc_superrefs,每个 add / adr 都要进 noteAddress,吞吐另量
2026-11-26核心层接口名寄存器表用 markRecordedSlotAddress(of:) / isRecordedSlotAddress(_:) 与位掩码 recordedSlotMask(与设计相同);取函数地址的记录方法定为 recordFunctionAddressReference(to: CodeLocation, at:),传位置而不是裸地址:核心层知道镜像下标,门面不必再拼
2026-11-26--type 的写法归一不 demangle只对 $s(可带 _)开头的符号去掉 Mn / Ma / N 后缀;不带 $s 的原样当 mangling。名义类型的 mangling 本身以种类字母结尾,不会撞上这些后缀,不必解开验证。测试发现 mangling 会对与模块名重复的词做替换(HiddenTypeReferences 里的 Hidden 类型不是 6HiddenV),这正是只收准确 mangling、不收点分名字的原因
2026-11-26验收时 G 类仍用 --function第 5 步让 --function 也列出取访问器地址处,正好覆盖那 27 条;--type 还会列出元数据地址、mangled name 等标准答案不算的类型引用,打分时会被算成多报。--type 由 ReferencesRequestSwiftTypeTests 单独验证,测量脚本不改 G 类
2026-11-26selector 引用在 cache 里认不出,记为后续项dyld cache 的构建器把 selref 载入改写成 adrp; add selector 字符串的地址(selectorInSelectorRegister 里已有说明),所以只在独立文件与 cache 外的镜像里有 selector 引用;cache 里的要从「地址落在 selector 字符串上」去认,另提
2026-11-26测量脚本按完整命名改写后进仓库从对话记录取回的脚本满是缩写,按仓库「标识符不缩写」的规定改写成 Scripts/CrossReferenceRecall/(标准答案合成一个 ground_truth.py,数据里的键也改成完整单词)。verify_reproduction.py 核对改写后仍复现 11 月 18 日的总数与目标列表,0.25.0 仍是 476/527
2026-11-26第 6 步验收测量脚本对功能分支:514/527(97.5%),多报 0,剩下 13 条是 __objc_superrefs;selector 发送 97/97、ivar 32/32、访问器 104/104、类引用 74/87。吞吐(Ultra,release,与三个仓库的 next 交替各两轮取最好):整表 2.419 → 2.464 秒(+1.9%,引用 1.296 亿 → 1.338 亿条),init 调用者扫描 1.516 → 1.545 秒(+1.9%),makeKeyAndOrderFront: 0.292 → 0.299 秒(+2.4%),都在 5% 以内;数字记进模块文档的吞吐一节
2026-11-26实现完成,待用户看过后收尾第 0–6 步都已完成。验证都在 Ultra:MachOKitExtensions 全量测试通过;本库全量(跳过 IntegrationTests)通过;MachOObjCSection 全量有 MachOObjCSectionTests.testCategories2InCacheFile(读不到 cache 文件后崩溃)与 ObjectiveCSymbolLanguageTests.cAndCPlusPlusStoreLeavesObjectiveCNamesOut 两处失败,在三个仓库的 next 上同样失败,属基线;RuntimeViewer 交叉引用模块整模块并发跑时「分析器换新后重新读名字」两条失败、单跑这一组 18 条全过,与 0097 决策日志记的基线现象相同。文档判断:不另写使用指南或实现说明(见头部「配套文档」);新术语「selector 引用」已登记进术语表。四个仓库的功能分支在本地合进各自的 next 检出,没有推送
2026-11-26Implemented,取号 0113用户看过后批准收尾。本库 next 合并时带进了 0112,落地前在合并结果上重跑了全量测试,全部通过;四个仓库按依赖顺序推送(MachOKitExtensions 的 main 与 next,其余的 next),演进账本第 160 节。下游远程构建(含 CI)要等 MachOKitExtensions 与 MachOObjCSection 发版、抬依赖下限。后续项:dyld cache 里的 selector 引用;RuntimeViewer 界面显示 selector 引用
+
+
+
+
+ +
+
+ + diff --git a/Documentations/Evolutions/0113-cross-reference-recall-gaps.md b/Documentations/Evolutions/0113-cross-reference-recall-gaps.md new file mode 100644 index 000000000..3ca34d539 --- /dev/null +++ b/Documentations/Evolutions/0113-cross-reference-recall-gaps.md @@ -0,0 +1,402 @@ +# 0113 - 交叉引用补漏:按 Swift 类型查询、GOT 槽地址、selector 引用与 ivar 读法 + +- **状态**: Implemented +- **作者**: JH +- **创建日期**: 2026-11-26 +- **最后更新**: 2026-11-26 +- **所属愿景**: [不依赖 IDA 的逆向](../Visions/ReverseEngineeringWithoutIDA.md)(第 1 阶段的补漏) +- **关联提案**: [0097-offline-cross-references-and-symbolication](0097-offline-cross-references-and-symbolication.md)(离线交叉引用与这次复测的对象)、[0098-move-cross-reference-layers](0098-move-cross-reference-layers.md)(三层的归属)、RuntimeViewer [0056-cross-references](https://github.com/MxIris-Reverse-Engineering/RuntimeViewer/blob/next/Documentations/Evolutions/0056-cross-references.md)(界面与查询层) +- **实现分支 / PR**: `feature/cross-reference-recall-gaps`(MachOKitExtensions、MachOObjCSection、本库、RuntimeViewer 同名分支),2026-11-26 合进四个仓库的 `next`(MachOKitExtensions 也合进 `main`)并推送;分支与 worktree 已删除 +- **配套文档**: 不另写——调用方契约在 CLI 的 skill(`AgentPlugins/swift-section/skills/swift-section-cli/references/cross-references.md`)与 README,实现细节在三份模块文档;测量办法在 `Scripts/CrossReferenceRecall/README.md` +- **网页版**: 同目录同名的 `.html` + +## 摘要 + +2026-11-26 在 Finder 26.5.2 与 ControlCenter 26.7 上按 2026-11-18 的方法复测交叉引用的召回:`swift-section refs` 0.25.0 找到 527 条代码引用里的 476 条(90.3%),IDA 一次查询 97.0%、两跳 99.4%。漏掉的 51 条里,13 条是按设计不报的 `__objc_superrefs` 载入,其余 38 条来自四处缺口:CLI 没有按 Swift 类型查的入口(27 条)、Swift 代码把 ObjC 类的 GOT 槽地址交给编译器生成的元数据辅助函数时不认类引用(8 条)、selector 只被当作参数用时不报(2 条)、一种 ivar 偏移的读法漏记(1 条)。本提案补齐这四处,改动跨 MachOKitExtensions(核心层)、MachOObjCSection(ObjC 层)、本库(Swift 层、门面与 CLI)和 RuntimeViewer(两处穷尽 switch),并把这次的测量脚本收进本库当验收工具:补完后同一组样本应到 514/527(97.5%),剩下的 13 条就是 `super` 的载入。第 5 步还把「取函数地址」记成对函数的引用——它不在这次测量的类别里,但决定了调用链能不能穿过 block 与闭包。 + +## 动机 + +完整动机见愿景《[不依赖 IDA 的逆向](../Visions/ReverseEngineeringWithoutIDA.md)》。这一步特有的部分: + +- **0097 落地时没有做全面核对。** 0097 决策日志 2026-11-19「第 4 步完成」一行只抽样了 ControlCenter 的 3 个函数,「全面核对没有重做」一段说明生成标准答案的脚本已经不在卷上。2026-11-26 从 2026-11-18 那次对比的对话记录里原样取回了标准答案与选目标的代码,复现出同一批 120 个目标,补做了这次核对(方法与数字见「前期调研」,结论写进了愿景「我们选的方向」第 1 条的复测段)。 +- **差距集中在几处可以修的地方,而不是扫描整体不行。** 导入函数、内部 `bl`、字符串三类与 IDA 一样全中;selector 发送(95/97)与类引用里的页对齐类对象还比 IDA 一次查询多中几条。漏报按原因归成五组,每组都有具体地址(见「前期调研」)。 +- **影响面比样本里的条数大。** + - GOT 槽地址那一组:ControlCenter 里有 554 处 `bl 0x10000b4a8`,每一处都把一个 ObjC 类的 GOT 槽地址放进 `x2`。这是 Swift 代码取 ObjC 类元数据的通用写法,Swift 为主的镜像里按类查引用会整批漏掉这一类。 + - Swift 类型那一组:经 CLI 工作的 agent 现在根本问不了「哪些代码用到了 Swift 类型 X」,只有 RuntimeViewer 的界面能问(Find 导航页的 Type References)。 + - selector 那一组:`respondsToSelector:` 的参数、返回 selector 的函数;`performSelector:`、target-action 的 `setAction:` 也是同一形态(推测,样本里没有抽到)。逆向时「谁把这个方法设成了按钮的 action」是常见问题。 + +## 前期调研 + +### 测量方法与复现 + +- **样本**:`/Volumes/RE/Finder/26.5.2/Finder`(ObjC 为主)与 `/Volumes/RE/ControlCenter/26.7/ControlCenter`(Swift 为主)的 arm64e 切片,UUID 分别是 `1E2E81F7-9B9D-317A-A102-F55ADAF6A0A0`、`5782ED6B-471B-3CAC-9258-93734B6009C3`,与卷上两个 `.i64` 相同。 +- **标准答案**:不依赖任何一个被测工具,由 `otool -tV` 加独立的 `adrp` 寄存器跟踪、`dyld_info -fixups`、相对方法列表与 `__swift5_types` 解码生成。代码从 2026-11-18 那次对比的子 agent 对话记录(`~/.claude/projects/-Users-JH/4cad8a68-…/subagents/agent-a43f33e89a2f7bb07.jsonl` 的第 24、31、51、56 次工具调用)原样取回,只换了临时目录。 +- **复现核对**:两份标准答案的引用总数(511,138 与 359,773)、`__objc_stubs` 数(8,809 与 1,363)、各类目标列表与 2026-11-18 的输出逐项一致;按原打分规则(第 69 次工具调用)重算 IDA 一列,仍是 97.0% / 99.4%。所以这次的数字可以直接与那次比。 +- **查询**:每个目标调一次 `swift-section refs <文件> --json`(`--selector`、`--class`、`--symbol`、`--function`、`--string`、`--ivar`),共 128 次,零报错;Finder 单次中位 0.31 秒、ControlCenter 0.13 秒,都含建分析器的时间。外部类另加一次 `--symbol _OBJC_CLASS_$_<类>`,结果与只查 `--class` 相同,说明 `--class` 已经覆盖导入的类。 +- **脚本**:在 `/tmp/claude-xref-2026-11-26/scripts/`(`run_all.sh` 一条命令跑完,约 30 秒)。`/tmp` 会被系统清理,所以落地步骤第 0 步先把它们收进本库;万一已被清掉,可从 2026-11-26 那次会话的对话记录里取回(脚本都是用 Write 工具写的)。 + +### 分类别结果(两个镜像合计,代码引用) + +| 类别 | 标准答案 | IDA 一次 | IDA 两跳 | 本库 0.25.0 | +|---|---|---|---|---| +| A selector 发送 | 97 | 92 | 97 | 95 | +| B ObjC 类引用 | 87 | 76 | 84 | 66 | +| C 导入函数 | 91 | 91 | 91 | 91 | +| D 内部函数 `bl` | 70 | 70 | 70 | 70 | +| E 字符串 | 46 | 46 | 46 | 46 | +| F ivar(仅 Finder) | 32 | 32 | 32 | 31 | +| G Swift 元数据访问器(仅 ControlCenter) | 104 | 104 | 104 | 77 | +| 合计 | 527 | 97.0% | 99.4% | 90.3% | + +另有 49 条数据引用(方法表的 IMP、只在 vtable / 见证表里出现的函数、GOT 槽本身等),IDA 全中,本库按 0097 的非目标不做,记 0。本库多报 1 条:`0x1005273f8 ldr x0, [x20]`,是先 `adrp; add x20, ` 再经 `x20` 载入,标准答案的线性跟踪把这条引用记在 `add` 上,核对后是真引用。 + +### 51 条漏报的五组原因 + +1. **取访问器地址当函数指针用(27 条,G 类)。** 形如 ControlCenter `0x1000cd564`:`adrp x16, …; add x16, x16, #0xd38`(访问器 `0x1003e3d38`)→ `mov x17, #0x882f; pacia x16, x17; mov x1, x16`,把签过名的访问器地址交给调用方。分析器其实记下了:`refs --function=0x1000cd568 --callees` 显示 `0x1000cd568 reference addressMaterialization swiftType`(Swift 会话把访问器地址认领为类型引用,见 `CrossReferenceAnalysis.md`「Swift 类型引用」第 2 种来源)。漏在 CLI:`--function` 只返回调用者,而 `ReferencesRequest`(`Sources/Commands/SwiftSectionKit/CrossReferences/ReferencesRequest.swift:262-310`)的六种主体里没有 Swift 类型。Swift 类型的引用表按描述符位置归档(`CodeReferenceTable.Key.swiftTypeDescriptor`),查询要经比对器 `references(toSwiftType:inImageAt:)`(`Sources/Analysis/CrossReferenceAnalysis/CrossReferenceAnalyzer+SwiftTypes.swift:57`),不能像其它主体那样换成表键。 +2. **`__objc_superrefs` 的载入(13 条,B 类,按设计)。** Finder `0x1006604a0 ldr x8, [x8, #0x358]` 读的是 `__objc_superrefs` 的 `0x100b4b358`,随后 `stp x0, x8, [sp]` 拼出 `objc_super` 交给 `_objc_msgSendSuper2`。13 条全是这种。`CrossReferenceAnalysis.md`「类引用(第二批)」写明这一载入不算类引用(「报出来只会让每个调 `super` 的方法都『引用』了自己的类」),引用记成带类名的 `superMessageSend`。标准答案把 `__objc_superrefs` 算作类引用的槽(2026-11-18 的报告「经 `__objc_superrefs` 加载类对象,这类已并入 ground truth」)。 +3. **GOT 槽地址交给元数据辅助函数(8 条,B 类)。** ControlCenter `0x1006455c8`:`adrp x2, …; add x2, x2, #0x2a0`(`_OBJC_CLASS_$_OS_os_log` 的 GOT 槽 `0x10083a2a0`)→ `mov x0, #0; bl 0x10000b4a8`。`0x10000b4a8` 是编译器生成的共用辅助函数:`ldr x0, [x1]; cbnz …; ldr x0, [x2]; bl _objc_opt_self; bl _swift_getObjCClassMetadata; stlr x0, [x19]`——`x1` 是缓存变量,`x2` 是类的 GOT 槽。ControlCenter 里有 554 处调用它。核心层 `ReferenceScanner.noteAddress`(MachOKitExtensions `Sources/Analysis/MachOCodeReferences/Scanning/ReferenceScanner.swift:366`)把数据段里的地址交给会话的 `recordAddressReference`,ObjC 会话只认类对象本身(MachOObjCSection `Sources/ObjCCodeReferences/ObjCCodeReferenceRecognizer.swift:305`),GOT 槽的地址不是类对象,于是什么都不记。读槽的入口 `noteSlotReference(fromSlot:at:)`(`ReferenceScanner.swift:441`)已经能解本镜像的 GOT、classref、cache 的共用 GOT 池与独立文件的 bind,只是取槽地址的路径没有走到它。IDA 也要两跳(2026-11-18 报告的 IDA 漏报第 2 条,同一个 `0x1006455cc`)。 +4. **selector 只当参数用(2 条,A 类)。** Finder `0x1003ee048`:`adrp x8, …; ldr x1, [x8, #0x6d0]`(`coalescingNodeObserver:openSyncCompleted:` 的 selref)→ `mov x0, x19; bl _objc_opt_respondsToSelector`;ControlCenter `0x100674e00`:`adrp x8, …; ldr x0, [x8, #0x378]; ret`,一个返回 selector `name` 的函数。ObjC 会话只在发送时从 `x1` 的来源槽读出 selector(`selectorInSelectorRegister`),它观察的槽只有 `__objc_superrefs` 与 `__objc_ivar`(`ObjCCodeReferenceRecognizer.swift:209`),没被发送用掉的 selref 载入什么都不留。`objc_opt_respondsToSelector` 作为 libobjc 的发送入口记成一次 `respondsToSelector:` 发送(`recordCallStandIn` 的 `.entryPoint`),`x1` 里那个作参数的 selector 被丢掉。 +5. **`adrp; add` 之后 `ldrsw [xN]` 读 ivar 偏移(1 条,F 类,原因待查)。** Finder `-[TTaskErrorOrConflictViewController setResolutionsForKind:]` 的 `0x1002bbb14`:`adrp x9, …; add x9, x9, #0x28; ldrsw x9, [x9]; str w8, [x0, x9]`(ivar `_rightResolution`)。同一个 ivar 在别的函数里的两处 `adrp; ldrsw [x8, #imm]` 都找到了,同一函数里别的 ivar 的 11 处也都找到了。读代码排除了几种可能:机器码 `d00047a9 9100a129 b9800129` 都在解码器覆盖内(`ARM64InstructionWord.wordLoad` 认 `0xB980_0000`,`addImmediate` 认 `0x9100_0000`);函数起点表里 `0x1002bba08`–`0x1002bbb28` 是一个函数;`RegisterFile.add` 对 `.address` 状态的源寄存器给出 `.address`。`0x1002bbb14` 是三条 `b` 的共同目标、又从上一条顺序落下,是汇合点——推测问题与汇合处的寄存器状态有关,未证实。第 4 步先写复现测试再定位。 + +### 赢过 IDA 的地方 + +- Finder 的三个页对齐类对象(`adrp; add #0x0`,如 `0x100131f8c`)IDA 漏,本库一次查到。 +- 经 `ldr` 读 selref 的经典发送,本库一次查到;IDA 要再查 selref 一跳(A 类 IDA 一次 92、本库 95)。 +- 不需要先建 IDA 库;单次查询 0.1–0.3 秒。 + +### 相关的现成能力 + +- RuntimeViewer 按类型查引用时用类型的 mangling(`RuntimeObject.name`,如 `7SwiftUI4TextV`)找描述符:`swiftTypeDescriptorLocations(withKey:inImageAt:)` → `swiftTypeIdentity(ofDescriptorAt:)` → 预筛 `imageIndices(referencingSwiftType:among:)` → 每个候选镜像 `references(toSwiftType:inImageAt:)`(RuntimeViewer `RuntimeViewerCore/Sources/RuntimeViewerCrossReferences/Analysis/CrossReferenceQuery.swift:300-380`)。CLI 照搬这条路即可,写法也与它一致。 +- 按名字定位符号:`locations(ofSymbolNamed:among:)`(`CrossReferenceAnalyzer+Linkage.swift:11`),查 `$s…Mn` 比逐镜像算 key 快得多。 +- 核心层的读槽、槽认领缓存(`slotClaims`)与导入名(`importedSlotNames`)都现成。寄存器表有按寄存器的标记(`RegisterFile.setTag` / `tag(of:)`,ObjC 会话用它标方法接收者),但打标记会把寄存器改成 `.tagged` 状态、丢掉地址(`RegisterFile.swift:83`),不能拿来标「已记过」;按寄存器的位掩码(`constantMask`、`blendedMask`)是现成的另一种写法。 +- 下游穷尽 switch:RuntimeViewer `CrossReferenceQuery.swift` 的 `switch reference.target`(`:92`、`:727`)与 `switch target`(`:949`)。0097 加三种新目标时的做法是在 RuntimeViewer 里补 case、先不显示(0097「源码兼容性」一节与决策日志 2026-11-19「第 8 步完成」)。 + +## 提议方案 + +1. **CLI 加 `--type`。** `swift-section refs --type ` 列出对一个 Swift 结构体、枚举或类的全部引用,写法与 RuntimeViewer 相同:类型的 mangling(`7SwiftUI4TextV`),也收它的描述符、访问器或元数据符号(`$s…Mn`、`$s…Ma`、`$s…N`,前面的 `_` 可有可无),去掉前后缀得到 mangling。定义它的镜像先按 `$sMn` 符号在全部镜像里找;找不到(缓存里的内部类型没有这个符号)时,独立文件逐个镜像按 key 找,dyld cache 要求用 `--type-image` 指定镜像,否则报错并提示。结果是这些身份在各候选镜像里的 `references(toSwiftType:inImageAt:)` 之并。 +2. **取到引用槽地址也算一次槽引用(核心层)。** `adrp; add` 或 `adr` 算出的地址如果正好落在引用槽上(本镜像的 GOT 与会话报的引用节,或 cache 的共用 GOT 池),就在这条指令上按读槽处理:走 `noteSlotReference(fromSlot:at:)`,路线记 `.pointerSlot`,由会话认出类,或在独立文件里记成导入符号。寄存器记下「已作为槽引用记过」,之后经它做零位移载入时不再重记,免得 `adrp; add; ldr [x]` 在同一处用法上记两行;寄存器里的地址照常保留,后面的发送仍能认出类字面量接收者。与语言无关,不写任何运行时名字。 +3. **selector 引用(ObjC 层)。** 查询里含 selector 键时,ObjC 会话也观察 `__objc_selrefs` 的载入:每次载入先记为待定;经典发送或 `super` 发送用 `x1` 里这个 selector 发送时,把它消掉;离开函数时,没被消掉的记成 selector 引用(新目标 `CodeReferenceTarget.selector(String)`,种类 `.reference`),归在已有的 `.selector` 表键下,`--selector` 因此同时返回发送与引用。libobjc 的发送入口(`objc_opt_respondsToSelector` 等)不消掉它,那里的 `x1` 是参数。核心层的会话协议加一个 `leaveFunction()`,默认什么都不做。经 `__objc_stubs` 的发送在代码里不载入 selref,不受影响。 +4. **ivar 读法(核心层)。** 先用夹具编出这段指令写复现测试,确认修复前失败,再定位、修复。 +5. **取函数地址记成对函数的引用(核心层)。** `adrp; add` 或 `adr` 算出的地址正好是本镜像函数表里的一个函数起点时,记一条 `.reference`,目标是 `.function(location)`,路线 `.addressMaterialization`;会话同时认领它(Swift 访问器)时两条都记。只在查询含函数键或建整表时找。`--function` 和 RuntimeViewer 的调用层级因此会列出取了它地址的代码:建栈上 block 的函数、把回调传给 `dispatch_async` / `CFRunLoop` 的函数、返回闭包的函数。这一步不在这次测量的类别里,用户决定并入(见决策日志)。 +6. **测量脚本进仓库,作为验收。** 收进 `Scripts/CrossReferenceRecall/`,`03_query_swift_section.py` 对 G 类改用 `--type`(mangling 取自访问器的符号名);落地时重跑,结果写回愿景。 + +### 非目标 + +- **`__objc_superrefs` 的载入不算类引用**:0097 定下的理由不变(见「替代方案考量」)。这 13 条是验收目标与 100% 之间的差。 +- **数据引用**(方法表的 IMP、vtable 与见证表里的函数、函数指针表、GOT 槽本身作为被引用者):愿景第 3 阶段。 +- **按点分隔的 Swift 名字查类型**(`ControlCenter.Foo`):要知道每一层的种类(结构体、类、枚举)才能拼出 mangling,先只收 mangling 与符号。 +- **RuntimeViewer 显示 selector 引用**:先在两处 switch 里补 case 并过滤掉,与 0097 处理新目标的做法一致;界面上怎么显示另提。第 5 步若并入,调用层级里取地址的行会和调用行一样显示,区分显示也另提。 +- **按辅助函数形状认 ObjC 类**(见「替代方案考量」)。 +- **x86_64**;**Binary Ninja 一列不重测**(2026-11-18 的结论是它经 MCP 只有 67.6%,不作参照)。 + +## 改动地图 + +| 文件 / 类型 | 动作 | 改什么 | 为什么 | 步骤 | +|---|---|---|---|---| +| 本库 `Scripts/CrossReferenceRecall/`(`prepare.sh`、`ground_truth.py`、`verify_reproduction.py`、`query_swift_section.py`、`score.py`、`run_all.sh`、`ida-2026-11-18.txt`、`README.md`) | 新增 | 2026-11-26 的测量脚本,按完整命名改写;IDA 的逐类结果存成数据文件;README 写样本路径、怎么跑、怎么读结果、基线数字 | 验收工具不能再丢 | 0 | +| 本库 `Scripts/CrossReferenceRecall/query_swift_section.py` | 新增 | 被测的二进制由 `SWIFT_SECTION` 指定;G 类仍用 `--function`(决策日志 2026-11-26「验收时 G 类仍用 `--function`」) | 验收 | 0 | +| 本库 `Sources/Commands/SwiftSectionKit/CrossReferences/ReferencesRequest.swift` · `CrossReferenceSubject` | 修改 | 加 `.swiftType(String, imageName: String?)`;`ResolvedQuery` 加按类型的查询分支;写法归一与定义镜像的查找 | `--type` 的库侧 | 1 | +| 本库 `Sources/Commands/SwiftSectionKit/CrossReferences/ReferencesRequest.swift` · `CrossReferenceRequestError` | 修改 | 加 `swiftTypeNotFound(String)`、`swiftTypeNeedsImage(String)` | 找不到类型、缓存里的内部类型 | 1 | +| 本库 `Sources/Executables/swift-section/Commands/ReferencesCommand.swift` | 修改 | `--type`、`--type-image`;`validate()` 计入新主体;`--selector` 的帮助文字改成「发送与引用」 | CLI 入口 | 1、3 | +| 本库 `Sources/Executables/swift-section/…/CommandLineErrorTranslation` | 修改 | 两个新错误的措辞 | 用法错误照旧是退出码 64 | 1 | +| 本库 `Sources/Commands/SwiftSectionKit/CrossReferences/CrossReferenceFormatting.swift` | 修改 | `.selector` 目标的文字(`selector <名字>`)与 JSON(`{"selector": …}`) | 新目标的输出 | 3 | +| 本库 `Sources/Analysis/CrossReferenceAnalysis/Models/CodeReference.swift` · `CodeReferenceTarget` | 修改 | 加 `case selector(String)` | selector 引用的目标 | 3 | +| 本库 `Sources/Analysis/CrossReferenceAnalysis/Models/CodeReferenceTable.swift` | 修改 | `.selector` 目标归 `.selector` 键 | `--selector` 与 RuntimeViewer 的 selector 查询都能取到 | 3 | +| 本库 `Sources/Analysis/CrossReferenceAnalysis/Models/CodeReferenceIndex.swift` · `Target` | 修改 | 常驻索引加 `.selector` 组 | RuntimeViewer 常驻用的紧凑索引要能存 | 3 | +| 本库 `Sources/Analysis/CrossReferenceAnalysis/CrossReferenceAnalyzer.swift` · `ReferenceCollector` | 修改 | 实现 `recordSelectorReference`;`findsSelectorReferences`(键含 `.selector` 或建整表)传给 ObjC 会话;第 5 步实现 `recordFunctionAddressReference` 与开关 | 门面拼装 | 3、5 | +| 本库 `Sources/Analysis/CrossReferenceAnalysis/Symbolication/AddressSymbolication.swift` | 修改 | selref 槽的含义从 `.messageSend(selector:receiver: .unknown)` 改为 `.selector` | 0097 第 6 步留的说明「目标类型里没有单独的 selector」不再成立 | 3 | +| 本库 `AgentPlugins/swift-section/skills/swift-section-cli/references/cross-references.md`(及 `SKILL.md` 里列到 `refs` 选项的地方) | 修改 | `--type`、`--type-image`、selector 引用、取槽地址的类引用;第 5 步的取地址行 | 项目规定:改 CLI 同批改 skill | 1、3、5 | +| 本库 `README.md` 的 `refs` 一节 | 修改 | 加 `--type` 的例子 | 对外文档 | 1 | +| 本库 `Tests/SwiftSectionKitTests/…`(新文件 `ReferencesRequestSwiftTypeTests.swift`) | 新增 | `--type` 的解析、写法、错误 | 第 1 步行为 | 1 | +| 本库 `Tests/CrossReferenceAnalysisTests/…`(新文件 `SelectorReferenceTests.swift`、`SlotAddressReferenceTests.swift`,第 5 步 `FunctionAddressReferenceTests.swift`) | 新增 | 经门面的行为测试 | 各步行为 | 2、3、5 | +| 本库 `Documentations/Internal/Modules/CrossReferenceAnalysis.md` | 修改 | 引用种类、类引用、selector、`--type`、测试锚点;召回一节指向愿景 | 总说明 | 1–5 | +| 本库 `Documentations/Visions/ReverseEngineeringWithoutIDA.md` | 修改 | 复测段(本批已写);落地后补上修复后的数字 | 愿景是活文档 | 6 | +| MachOKitExtensions `Sources/Analysis/MachOCodeReferences/Scanning/ReferenceScanner.swift` · `noteAddress` | 修改 | 落在引用槽上的地址改走 `noteSlotReference`;需要知道目标寄存器,签名加 `destination` | 第 2 步 | 2 | +| MachOKitExtensions `ReferenceScanner.swift` · `scanFunction` 的载入分支 | 修改 | 经已记过槽引用的寄存器做零位移载入时不重记 | 防重复 | 2 | +| MachOKitExtensions `ReferenceScanner.swift`(具体位置待第 4 步的测试定位) | 修改 | 修 ivar 漏记 | 第 4 步 | 4 | +| MachOKitExtensions `ReferenceScanner.swift` · `noteAddress` | 修改 | 落在函数起点的地址记成对函数的引用 | 第 5 步 | 5 | +| MachOKitExtensions `Sources/Analysis/MachOCodeReferences/Scanning/RegisterFile.swift` | 修改 | 加一个按寄存器的位 `recordedSlotMask`:这个地址已作为槽引用记过;改写寄存器时清掉,汇合时比较 | 防重复,且不丢地址(现成的 `setTag` 会把地址状态覆盖掉) | 2 | +| MachOKitExtensions `Sources/Analysis/MachOCodeReferences/Recognition/CodeReferenceRecognition.swift` · `CodeReferenceRecognitionSession` | 修改 | 加 `func leaveFunction()`,协议扩展给空实现;扫描器在每个函数扫完时调用 | selector 待定载入的冲刷点 | 3 | +| MachOKitExtensions `CodeReferenceRecognition.swift` · `CodeReferenceRecording` | 修改 | 加 `recordFunctionAddressReference(toFunctionAt:at:)` | 第 5 步 | 5 | +| MachOKitExtensions `Tests/MachOCodeReferencesTests/…`(新文件 `ScanShapesFixture.swift`、`SlotAddressScanTests.swift`、`InstanceVariableMergePointTests.swift`、`FunctionAddressScanTests.swift`;测试目标加 `MachOFixtureSupport`) | 新增 | 用 `FixtureCompiler` 汇编出夹具库,钉住指令序列 | 复现测试 | 2、4、5 | +| MachOKitExtensions `Documentations/Internal/MachOCodeReferences.md` | 修改 | 新契约与测试 | 实现说明 | 2、4、5 | +| MachOObjCSection `Sources/ObjCCodeReferences/ObjCCodeReferenceRecognizer.swift` · `ObjCCodeReferenceRecording` | 修改 | 加 `recordSelectorReference(selector:at:)` | 第 3 步 | 3 | +| MachOObjCSection `ObjCCodeReferenceRecognizer.swift` · 会话 | 修改 | `findsSelectorReferences` 开关;`watchedSlotRanges` 加 `selectorReferenceRange`;待定载入、发送消掉、`leaveFunction` 冲刷 | 第 3 步 | 3 | +| MachOObjCSection `Tests/ObjCCodeReferencesTests/…`(新文件 `SelectorReferenceRecognitionTests.swift`) | 新增 | ObjC 夹具:`respondsToSelector:`、`setAction:`、经典发送不重复 | 第 3 步 | 3 | +| MachOObjCSection `Documentations/Internal/ObjCCodeReferences.md` | 修改 | selector 引用的认法 | 实现说明 | 3 | +| RuntimeViewer `RuntimeViewerCore/Sources/RuntimeViewerCrossReferences/Analysis/CrossReferenceQuery.swift` | 修改 | `:92`、`:727`、`:949` 三处 switch 补 `.selector`(不显示);selector 查询结果滤掉 `.selector` 目标 | 穷尽 switch 会编译失败;界面先不变 | 3 | + +## 架构图 + +改了什么(扫描一个函数时的分派,`+` 新增,`~` 修改): + +```text +ReferenceScanner.scanFunction (MachOCodeReferences) +├── adrp/add/adr → noteAddress(address, destination) ~ takes the register +│ ├── + address in a reference slot (own GOT, classrefs, cache GOT pool) +│ │ → noteSlotReference(fromSlot:) → ObjC session: class │ file mode: imported symbol +│ │ → mark the register: slot address recorded (address kept) +│ ├── + address == a function start → recording.recordFunctionAddressReference (step 5) +│ └── other data → sessions.recordAddressReference (unchanged) +├── ldr/ldrsw [base, #d] → noteLoad / noteWatchedLoad +│ ├── + base marked as recorded slot address and d == 0 → skip (no second row) +│ └── ObjC session.noteWatchedSlotLoad +│ ├── __objc_ivar → ivar reference ~ step 4 fixes a miss +│ └── + __objc_selrefs → pending selector load +├── bl → ObjC session.recordCallStandIn +│ ├── classic / super send → messageSend + consumes the pending load behind x1 +│ └── entry point (objc_opt_respondsToSelector …) → send (x1 stays pending: an argument) +└── + function scanned → session.leaveFunction() + → ObjC: each pending load left → recordSelectorReference → target .selector(name), key .selector +``` + +CLI 的查询分支(`+` 新增): + +```text +swift-section refs (ReferencesCommand → SwiftSectionKit.ReferencesRequest) +├── --selector S → keys [.selector(S)] → sends + selector references (step 3) +├── --function A → keys [.function(loc), imported names] → calls (+ address-taking, step 5) +├── --class / --symbol / --ivar / --string (unchanged) +└── + --type T [--type-image I] + → normalize T: strip _ / $s prefix, Mn / Ma / N suffix → mangling key + → defining images: locations(ofSymbolNamed: "_$s" + key + "Mn") + else every image (files) │ else --type-image required (cache) + → swiftTypeDescriptorLocations(withKey:inImageAt:) → swiftTypeIdentity(ofDescriptorAt:) + → candidates: imageIndices(referencingSwiftType:among: scope) + → per candidate image: references(toSwiftType:inImageAt:) (union over identities) +``` + +## 详细设计 + +### 第 1 步:`--type` + +```swift +public enum CrossReferenceSubject: Sendable, Hashable { + // … the six existing cases … + /// A Swift struct, enum or class by its mangling — `7SwiftUI4TextV` — or a + /// `$s…Mn`, `$s…Ma` or `$s…N` symbol of it, defined in the image + /// `imageName` names, or in whichever image exports its descriptor. + case swiftType(String, imageName: String?) +} +``` + +```swift +// ReferencesCommand +@Option(name: .customLong("type"), help: "Every reference to the Swift struct, enum or class with this mangling (7SwiftUI4TextV), or to the one a $s…Mn, $s…Ma or $s…N symbol names.") +var swiftType: String? + +@Option(name: .customLong("type-image"), help: "The image that defines --type's type, by path or file name: needed in a dyld shared cache for a type no image exports.") +var swiftTypeImage: String? +``` + +- `validate()`:`--type` 计入「恰好一个主体」;`--type-image` 只能和 `--type` 一起用(与 `--function-image` 同样的报错写法)。 +- 写法归一:去掉前导 `_`,去掉前导 `$s`;末尾依次试 `Mn`、`Ma`、`N`,去掉后剩下的部分能 demangle 成一个名义类型才算数,否则当作原样的 mangling。名义类型的 mangling 以种类字母(`V`、`C`、`O`,`__C` 类型的 `a` 等)结尾,不会被误剥。 +- 找定义镜像:`--type-image` 给了就只在它里面找;否则 `locations(ofSymbolNamed: "_$s" + key + "Mn", among: 全部镜像)`;仍然没有时,独立文件逐个镜像 `swiftTypeDescriptorLocations(withKey:inImageAt:)`,dyld cache 抛 `swiftTypeNeedsImage`(逐镜像算 key 要几分钟)。macOS 与 Mac Catalyst 两个变体都定义时,两个身份都查,结果取并集。 +- 查询:`ResolvedQuery.Search` 加 `case swiftTypes([SwiftTypeIdentity], candidates: [Int])`;`run(output:)` 在候选镜像上并发调 `references(toSwiftType:inImageAt:)`,与 `.callers` 的并发写法相同(`ReferencesRequest.swift:142`)。`--in-image` 照旧限定扫描范围。 +- 输出:目标照已有的 `swiftType` / `swiftTypeName` / `objectiveCClass`(Swift 类也比它的 ObjC 类对象位置)格式输出,不新增格式。 + +### 第 2 步:取到引用槽地址 + +```swift +// ReferenceScanner (MachOCodeReferences) +private mutating func noteAddress(_ address: UInt64, builtInto destination: Int, at site: ScanSite, mayNameAString: Bool) { + if isReferenceSlot(address) { + noteSlotReference(fromSlot: address, at: site.reached(by: .pointerSlot)) + registers.markRecordedSlotAddress(of: destination) + return + } + // … unchanged … +} + +/// A slot of this image's GOT or of a session's reference sections, or one +/// of the GOT pool the shared cache keeps outside every image. +private func isReferenceSlot(_ address: UInt64) -> Bool +``` + +- `isReferenceSlot` 复用 `noteSlotReference` 开头的判断(`referenceSlotRanges` 与 `images.isSlotOutsideEveryImage`),两处共用一个私有函数,免得以后只改一处。 +- 载入分支:`load.displacement == 0` 且 `registers.isRecordedSlotAddress(load.base)` 时不调 `noteLoad`,寄存器照常更新(目标寄存器仍是 `.loadedFromSlot`,类字面量接收者照认)。 +- `RegisterFile` 的 `Contents` 加 `recordedSlotMask`,与 `constantMask` 同样处理:`overwrite` 清位,`Snapshot.agrees` 比较它,`meet` 不一致时清掉。不用现成的 `setTag`:它把寄存器改成 `.tagged` 状态,地址就没了(`RegisterFile.swift:83`)。 +- 只在 `looksForAddressReferences` 为真时做,与现状一致:只查 selector 或函数时不付这份代价。 + +### 第 3 步:selector 引用 + +```swift +// MachOObjCSection, ObjCCodeReferences +@_spi(Internals) public protocol ObjCCodeReferenceRecording: CodeReferenceRecording { + // … existing … + /// A load of the selector reference to `selector` that no send used: + /// the selector handed on as data — to `respondsToSelector:`, + /// `performSelector:`, a control's action. + func recordSelectorReference(selector: String, at site: ScanSite) +} +``` + +```swift +// MachOKitExtensions, MachOCodeReferences +@_spi(Internals) public protocol CodeReferenceRecognitionSession: AnyObject { + // … existing … + /// The scan is done with the function it last entered. + func leaveFunction() +} + +extension CodeReferenceRecognitionSession { + @_spi(Internals) public func leaveFunction() {} +} +``` + +```swift +// MachOSwiftSection, CrossReferenceAnalysis +public enum CodeReferenceTarget: Hashable, Sendable { + // … existing … + /// A selector the code loads but sends no message with: it hands the + /// selector on — to `respondsToSelector:`, `performSelector:`, a + /// control's action. + case selector(String) +} +``` + +- ObjC 会话:`findsSelectorReferences` 为真时 `watchedSlotRanges` 加上 `sections.selectorReferenceRange`(`ObjCImageSections` 已有这个字段)。`noteWatchedSlotLoad` 落在它上面时读出 selector 名,追加到 `pendingSelectorLoads: [(slot: UInt64, site: ScanSite)]`。 +- 消掉:`recordCallStandIn` 的 `.classicSend` 与 `.superSend` 分支取 `registers.slotAddress(of: 1)`,从 `pendingSelectorLoads` 末尾往前删掉第一个同槽的条目。`.entryPoint` 与 `.selector`(`__objc_stubs`)不删。 +- 冲刷:`leaveFunction()` 把剩下的逐条交给 `recordSelectorReference`,清空数组。`enterFunction` 也清一次,防扫描器提前返回时漏冲刷(`scanFunction` 的 `guard` 早退)。 +- 顺序:冲刷发生在函数末尾,所以一个函数里 selector 引用排在该函数的其它引用之后;收集器按地址排序后输出,不影响结果顺序(实现时核对 `ReferenceCollector` 是否排序,若不排则在冲刷前按地址插入)。 +- 门面:`ReferenceCollector.findsSelectorReferences` = 查询键含 `.selector`,或建整表。`recordSelectorReference` → `keep(.selector(selector), at: site)`;`CodeReferenceTable` 把它归在 `.selector(selector)` 键下。 +- 符号化:selref 槽的含义改为 `.selector(name)`(`AddressSymbolication.swift`),`swift-section symbolicate` 对 selref 槽的输出从 `send <名字>` 变成 `selector <名字>`。 + +### 第 4 步:ivar + +- 夹具:一个 ObjC 类,三个 ivar;一个方法用 `__asm__` 写出与 Finder `0x1002bba08` 同构的序列——前面几个分支 `b` 到同一个标签,标签处 `adrp x9, _OBJC_IVAR_$_…@PAGE; add x9, x9, _OBJC_IVAR_$_…@PAGEOFF; ldrsw x9, [x9]; str w8, [x0, x9]`。另写一个不经汇合点的对照方法。 +- 测试先红(经汇合点的那条找不到、对照那条找到),由此确认是汇合还是别的原因,再修。 +- 结果(实现时补记):根因与修法见决策日志 2026-11-26「第 4 步定位到根因」。夹具改为两条路径各算一个偏移变量地址、在载入处汇合;对照方法的引用记在 `add` 上而不是 `ldrsw` 上。 + +### 第 5 步:取函数地址 + +```swift +// MachOKitExtensions, CodeReferenceRecording +/// Code built the address of the function at the unslid `address` — to call +/// it later, sign it and hand it on, or put it in a block. +func recordFunctionAddressReference(toFunctionAt address: UInt64, at site: ScanSite) +``` + +- `noteAddress` 里 `isCode` 且这个地址是函数起点时记一条;会话随后照常被问(Swift 会话认领访问器,两条都记)。开关 `recordsFunctionAddressReferences` 由门面按查询键(含 `.function`)或建整表给出。 +- 判断是不是函数起点:`ImageFunctionTable.functionIndex(containing:)`(`ImageFunctionTable.swift:249`)取到的函数起点等于这个地址。 +- 门面把它记成 `kind == .reference`、目标 `.function(location)`,归 `.function` 键。 + +## 替代方案考量 + +- **只让 `--function` 查访问器时也返回类型引用,不加 `--type`**:能补上这 27 条,但只覆盖访问器;泛型实例的访问器、按 mangled name 实例化、元数据地址这几种类型引用仍然问不到,而 RuntimeViewer 早已按类型查。否。 +- **GOT 槽地址按辅助函数的形状认**:在 Swift 层认出 `ldr x0, [x2]; bl objc_opt_self; bl swift_getObjCClassMetadata` 这种函数,在调用点从 `x2` 取类。更准,但只覆盖这一个辅助函数,还要 Swift 层认 libobjc 的名字;核心层按「地址落在引用槽」处理与语言无关,覆盖一切先取槽地址再用的写法。否。 +- **每次 selref 载入都记一条引用**:实现最简单,但经典发送(不走 `__objc_stubs` 的二进制)每次发送都会多一条同位置的引用行。否。 +- **selector 引用另开一个表键**:`--selector` 就要查两个键,RuntimeViewer 的 selector 查询也要改;归在同一键下、靠目标区分更省事,下游想只要发送时按目标过滤即可。否。 +- **把 `__objc_superrefs` 的载入报成类引用**:召回能到 100%、与 IDA 对齐,但每个调 `super` 的方法都会「引用」自己的类,按类查引用的结果会被这些行淹没(Foundation 1,803 处、AppKit 8,336 处 super 发送,见 `CrossReferenceAnalysis.md`「类引用」)。0097 的理由仍然成立。否。 +- **测量脚本放在 `/Volumes/RE` 或个人目录**:2026-11-18 那次就是这样丢的。进仓库、跟着交叉引用的代码走。否。 + +## 影响 + +### 源码兼容性(source compatibility) + +**有破坏**: + +- `CodeReferenceTarget` 加 `case selector(String)`:下游对它的穷尽 switch 编译失败。已知调用点是 RuntimeViewer `CrossReferenceQuery.swift` 的 `:92`、`:727`、`:949`。改法: + + ```swift + // before + switch reference.target { + case .function(let location): … + // … every case … + case .constantString(let characters): … + } + // after: one more case, shown as nothing for now + case .selector: + return nil + ``` + +- `CrossReferenceSubject`(SwiftSectionKit)加 `case swiftType`:本库以外没有使用方(RuntimeViewer 用自己的查询层)。 +- MachOKitExtensions 与 MachOObjCSection 的改动全在 `@_spi(Internals)` 接口上(`CodeReferenceRecognitionSession.leaveFunction` 有默认实现;`ObjCCodeReferenceRecording` 与 `CodeReferenceRecording` 各加一个要求,实现方只有本库的 `ReferenceCollector` 与 MachOKitExtensions 测试里的识别器)。SPI 不承诺稳定(`MachOCodeReferences.md`「接口只给 MachOSwiftSection 用」)。 +- 行为变化(不是编译错误):`--selector` 与 RuntimeViewer 按 selector 的查询多出 `.selector` 目标的行(RuntimeViewer 先滤掉);按类查引用多出取槽地址的行;`symbolicate` 对 selref 槽的说法变了;第 5 步若并入,`--function` 与调用层级多出取地址的行。 + +### ABI 兼容性(条件项) + +不适用 —— 本库以 SPM 源码分发,使用方每次重新编译。 + +### 下游影响 + +- 本仓库:`CrossReferenceAnalysis`、`SwiftSectionKit`、`swift-section` 可执行文件,以及 `CrossReferenceAnalysisTests`、`SwiftSectionKitTests`。整表变大(多出取槽地址、selector 引用,第 5 步再多出取函数地址),`ScanThroughputBenchmarkTests` 要重量。 +- MachOKitExtensions(核心层)、MachOObjCSection(ObjC 层):同批改、同批发版。依赖顺序 MachOKitExtensions → MachOObjCSection → 本库。 +- RuntimeViewer:三处 switch;按 0097 的经验,本库 `next` 一合进新 case,RuntimeViewer 的 `next` 要同批跟上(它按本地路径依赖本库)。 +- MachOKitUI、REAgent:不用交叉引用(`grep` 过 `CrossReferenceAnalysis`、`ObjCCodeReferences`),不受影响。 + +### 文档与示例 + +- `README.md` 的 `refs` 一节、`AgentPlugins/swift-section/skills/swift-section-cli/references/cross-references.md`。 +- 三份模块文档:本库 `Documentations/Internal/Modules/CrossReferenceAnalysis.md`、MachOKitExtensions `Documentations/Internal/MachOCodeReferences.md`、MachOObjCSection `Documentations/Internal/ObjCCodeReferences.md`。 +- 愿景的复测段,落地后补修复后的数字。 + +## API 演进与废弃策略 + +- 没有被替代的 API,不废弃任何东西。 +- 版本:本库 0.x 的下一个 minor(`CodeReferenceTarget` 新 case 按 0.x 惯例走 minor,0097 同样处理);MachOKitExtensions 下一个 minor(SPI 变化,但 MachOObjCSection 要求它的新版本);MachOObjCSection 下一个 minor。 + +## 落地步骤 + +0. **测量脚本进仓库**(已完成) —— 改动地图第 1 行 + - 行为:`run_all.sh` 对 0.25.0 复现 476/527(90.3%),IDA 列 97.0% / 99.4%,复现核对通过 + - 行为:README 记下基线数字与每类的漏报原因,供以后对照 +1. **`--type`**(已完成) —— 改动地图第 2–7、13–15 行 + - 行为:`typeSubjectFindsTheReferencesTheAnalyzersSwiftTypeQueryFinds`(与直接调 `references(toSwiftType:)` 的结果逐条相同,在进程内的 SwiftUICore 上) + - 行为:`typeSubjectAcceptsTheManglingAndItsDescriptorAccessorAndMetadataSymbols` + - 行为:`typeSubjectLooksForAnUnexportedTypeInEveryStandaloneFile` + - 行为:`typeSubjectInACacheNeedsTheTypeImageForAnUnexportedType`(报 `swiftTypeNeedsImage`,CLI 退出码 64) + - 行为:`typeImageWithoutTypeIsAUsageError` + - 行为:测量脚本 G 类改用 `--type` 后 104/104 +2. **取到引用槽地址也算槽引用**(已完成) —— 改动地图第 19–20、22、26 行 + - 行为:`slotAddressHandedToAHelperIsAClassReference`(Swift 夹具引用一个 ObjC 类的元类型,生成同形的辅助函数调用) + - 行为:`slotAddressInAStandaloneFileIsAnImportedSymbolReference` + - 行为:`aLoadThroughARecordedSlotAddressIsNotRecordedAgain` + - 行为:`slotAddressesAddOnlySlotReferencesToTheWholeImageTable`(AppKit、SwiftUICore、Foundation 整表与改前比,多出的只有取槽地址的类引用) + - 行为:测量脚本 B 类 74/87(剩下的 13 条是 `super`) +3. **selector 引用**(已完成) —— 改动地图第 6、8–12、23、25、28–32 行 + - 行为:`respondsToSelectorArgumentIsASelectorReference` + - 行为:`anActionSelectorHandedToSetActionIsASelectorReference` + - 行为:`aClassicSendLeavesNoSelectorReferenceBehind` + - 行为:`stubSendsLeaveNoSelectorReference` + - 行为:`selectorQueriesReturnSendsAndSelectorReferences` + - 行为:`selectorReferencesSurviveTheCompactIndex` + - 行为:`symbolicationCallsASelectorReferenceSlotASelector` + - 行为:RuntimeViewer `selectorReferencesAreNotShownYet` + - 行为:测量脚本 A 类 97/97 +4. **ivar 读法**(已完成) —— 改动地图第 21、26–27 行 + - 行为:`instanceVariableLoadThroughAnAddedAddressAtAMergePoint`(修复前失败) + - 行为:`instanceVariableLoadThroughAnAddedAddressOutsideAMergePoint`(对照) + - 行为:测量脚本 F 类 32/32 +5. **取函数地址**(已完成) —— 改动地图第 23–24 行及第 11、16 行的第 5 步部分 + - 行为:`takingAFunctionsAddressIsAReferenceToIt` + - 行为:`aSignedAccessorAddressIsBothAFunctionAndATypeReference` + - 行为:`aStackBlockIsReferencedByTheFunctionThatBuildsIt` + - 行为:`functionQueriesReturnCallsAndAddressTakingSites` +6. **验收与文档**(已完成) —— 改动地图第 17–18 行与三份模块文档 + - 行为:测量脚本代码引用 ≥ 514/527(97.5%),多报为 0,或逐条核对为真引用 + - 行为:`ScanThroughputBenchmarkTests` 各项比改前慢不超过 5%(超过就把数字和原因写进模块文档,由用户定) + - 行为:愿景复测段补上修复后的数字 + +**收尾时必须判断两件事**(判断结果写进决策日志,不允许沉默跳过): + +- **要不要配套专题文章** —— 预计不另写:调用方契约写进 CLI 的 skill 与 README,实现细节写进三份模块文档。 +- **有没有引入新术语** —— 「selector 引用」(selector 被载入但没有用来发送)可能要登记进 `Documentations/Glossary.md`;落地时判断。 + +## 决策日志 + +| 日期 | 变更 | 说明 | +|------|------|------| +| 2026-11-26 | Created as Draft | 按 2026-11-18 的方法补做 0097 落地时没做的全面核对:本库 90.3%、IDA 一次查询 97.0%。用户批准写一份提案修复测出的四处缺口,并把结果写进愿景 | +| 2026-11-26 | 第 5 步列为待定 | 「取函数地址」不在这次测量的类别里,但决定调用链能不能穿过 block 与闭包;是否并入本提案由用户定 | +| 2026-11-26 | 第 5 步并入 | 用户决定把「取函数地址记成对函数的引用」并入本提案,同批实现 | +| 2026-11-26 | Accepted | 用户批准,开始实现。四个仓库各开 `feature/cross-reference-recall-gaps`,按依赖顺序 MachOKitExtensions → MachOObjCSection → 本库 → RuntimeViewer 提交;构建与测试都在 Ultra 上跑(四个工程都在公司那台不编译的清单里),用 `/Volumes/DerivedData/Agents.noindex/claude/LocalDependencies/CrossReferenceRecallGaps/` 下按仓库名放的功能分支拷贝解析本地依赖 | +| 2026-11-26 | 第 4 步定位到根因,修法推广到观察的槽 | Finder 那个函数开头是跳转表,`0x1002bba68` 的 `b 0x1002bbb1c` 带着 `_middleResolution` 的偏移变量地址(`add x9, x9, #0x24`)直接跳到 `ldrsw`,与顺序落下、带着 `_rightResolution`(`#0x28`)的路径在载入处汇合,`x9` 两边不一致被作废——这条载入本来就读两个 ivar 之一,标准答案和 IDA 都把引用记在各自的 `add` 上。核心测试按这个形状写出后先红;修法与第 2 步同一套:算出的地址落在会话观察的槽上(`__objc_ivar`、`__objc_superrefs`、`__objc_selrefs`)时,在这条指令上通知会话、给寄存器打「已记过」的位,之后零位移的 32 位与 64 位载入不再重记。代价是 ObjC 会话总观察 `__objc_superrefs`,每个 `add` / `adr` 都要进 `noteAddress`,吞吐另量 | +| 2026-11-26 | 核心层接口名 | 寄存器表用 `markRecordedSlotAddress(of:)` / `isRecordedSlotAddress(_:)` 与位掩码 `recordedSlotMask`(与设计相同);取函数地址的记录方法定为 `recordFunctionAddressReference(to: CodeLocation, at:)`,传位置而不是裸地址:核心层知道镜像下标,门面不必再拼 | +| 2026-11-26 | `--type` 的写法归一不 demangle | 只对 `$s`(可带 `_`)开头的符号去掉 `Mn` / `Ma` / `N` 后缀;不带 `$s` 的原样当 mangling。名义类型的 mangling 本身以种类字母结尾,不会撞上这些后缀,不必解开验证。测试发现 mangling 会对与模块名重复的词做替换(`HiddenTypeReferences` 里的 `Hidden` 类型不是 `6HiddenV`),这正是只收准确 mangling、不收点分名字的原因 | +| 2026-11-26 | 验收时 G 类仍用 `--function` | 第 5 步让 `--function` 也列出取访问器地址处,正好覆盖那 27 条;`--type` 还会列出元数据地址、mangled name 等标准答案不算的类型引用,打分时会被算成多报。`--type` 由 `ReferencesRequestSwiftTypeTests` 单独验证,测量脚本不改 G 类 | +| 2026-11-26 | selector 引用在 cache 里认不出,记为后续项 | dyld cache 的构建器把 selref 载入改写成 `adrp; add` selector 字符串的地址(`selectorInSelectorRegister` 里已有说明),所以只在独立文件与 cache 外的镜像里有 selector 引用;cache 里的要从「地址落在 selector 字符串上」去认,另提 | +| 2026-11-26 | 测量脚本按完整命名改写后进仓库 | 从对话记录取回的脚本满是缩写,按仓库「标识符不缩写」的规定改写成 `Scripts/CrossReferenceRecall/`(标准答案合成一个 `ground_truth.py`,数据里的键也改成完整单词)。`verify_reproduction.py` 核对改写后仍复现 11 月 18 日的总数与目标列表,0.25.0 仍是 476/527 | +| 2026-11-26 | 第 6 步验收 | 测量脚本对功能分支:514/527(97.5%),多报 0,剩下 13 条是 `__objc_superrefs`;selector 发送 97/97、ivar 32/32、访问器 104/104、类引用 74/87。吞吐(Ultra,release,与三个仓库的 `next` 交替各两轮取最好):整表 2.419 → 2.464 秒(+1.9%,引用 1.296 亿 → 1.338 亿条),`init` 调用者扫描 1.516 → 1.545 秒(+1.9%),`makeKeyAndOrderFront:` 0.292 → 0.299 秒(+2.4%),都在 5% 以内;数字记进模块文档的吞吐一节 | +| 2026-11-26 | 实现完成,待用户看过后收尾 | 第 0–6 步都已完成。验证都在 Ultra:MachOKitExtensions 全量测试通过;本库全量(跳过 IntegrationTests)通过;MachOObjCSection 全量有 `MachOObjCSectionTests.testCategories2InCacheFile`(读不到 cache 文件后崩溃)与 `ObjectiveCSymbolLanguageTests.cAndCPlusPlusStoreLeavesObjectiveCNamesOut` 两处失败,在三个仓库的 `next` 上同样失败,属基线;RuntimeViewer 交叉引用模块整模块并发跑时「分析器换新后重新读名字」两条失败、单跑这一组 18 条全过,与 0097 决策日志记的基线现象相同。文档判断:不另写使用指南或实现说明(见头部「配套文档」);新术语「selector 引用」已登记进术语表。四个仓库的功能分支在本地合进各自的 `next` 检出,没有推送 | +| 2026-11-26 | Implemented,取号 0113 | 用户看过后批准收尾。本库 `next` 合并时带进了 0112,落地前在合并结果上重跑了全量测试(跳过 IntegrationTests),全部通过;RuntimeViewer 的 `next` 只在 app 层多了两个提交,`RuntimeViewerCore` 与测过的相同,MachOKitExtensions 与 MachOObjCSection 的合并结果也与测过的相同,沿用实现完成时的结果;四个仓库按依赖顺序推送:MachOKitExtensions 的 `main` 与 `next`,MachOObjCSection、本库、RuntimeViewer 的 `next`;演进账本第 160 节。下游远程构建(含 CI)要等 MachOKitExtensions 与 MachOObjCSection 发版、本库与 MachOObjCSection 抬依赖下限:`ReferenceScanner(recordsFunctionAddressReferences:)`、`CodeReferenceRecording.recordFunctionAddressReference(to:at:)`、`leaveFunction()` 与 `MachOFixtureSupport` 都只在新版本里有。后续项:dyld cache 里的 selector 引用;RuntimeViewer 界面显示 selector 引用 | diff --git a/Documentations/Evolutions/draft-swift-declaration-model-indexing-layout.md b/Documentations/Evolutions/0114-swift-declaration-model-indexing-layout.md similarity index 88% rename from Documentations/Evolutions/draft-swift-declaration-model-indexing-layout.md rename to Documentations/Evolutions/0114-swift-declaration-model-indexing-layout.md index 260e5e65a..b1980079a 100644 --- a/Documentations/Evolutions/draft-swift-declaration-model-indexing-layout.md +++ b/Documentations/Evolutions/0114-swift-declaration-model-indexing-layout.md @@ -1,10 +1,11 @@ -# Draft - SwiftDeclaration 的目录分成公开模型与索引代码两块 +# 0114 - SwiftDeclaration 的目录分成公开模型与索引代码两块 -- **状态**: In Progress +- **状态**: Implemented - **创建日期**: 2026-11-06 -- **最后更新**: 2026-11-06 -- **关联提案**: [0042-swift-declaration-file-layout](0042-swift-declaration-file-layout.md)(上一次整理这个模块的文件;本提案沿用它「`Members/` 是模型、`Building/` 是索引期机器」的分界,把这条分界推到整个模块) -- **实现分支 / PR**: `refactor/swift-declaration-layout` +- **最后更新**: 2026-12-01 +- **关联提案**: [0042-swift-declaration-file-layout](0042-swift-declaration-file-layout.md)(上一次整理这个模块的文件;本提案沿用它「`Members/` 是模型、`Building/` 是索引期机器」的分界,把这条分界推到整个模块)、[0115-swift-declaration-type-naming](0115-swift-declaration-type-naming.md)(同一批整理的下一步:理顺名字) +- **实现分支 / PR**: `refactor/swift-declaration-layout`,2026-11-06 合入 `next`,随 0.25.0 发布 +- **配套文档**: 模块说明 [SwiftDeclaration.md](../Internal/Modules/SwiftDeclaration.md)(文件对照表与归位判据) ## 摘要 @@ -58,3 +59,4 @@ Sources/Declaration/SwiftDeclaration/ | 2026-11-06 | 按轻量档写精简提案;状态 Draft → Accepted → In Progress | 用户批准方案;提案随功能分支落盘,不先单独提交进 `next`:`next` 的检出里有别处未提交的改动 | | 2026-11-06 | 实现完成,待用户看过后收尾 | 52 个文件按方案搬完,三处剪切照方案;从空 scratch 编译库与全部测试 target,原始退出码 0。文档:模块参考的两张对照表重写,术语表与四份实现说明改路径,演进账本加一节;不另写实现说明或使用指南,布局与判据写在模块参考里;没有新术语 | | 2026-11-06 | `AGENTS.md` 的 SwiftDeclaration 条目加一句归位规则 | 用户同意:0042 的布局就是被随手放进 `Definitions/` 的新文件冲乱的,agent 加新的索引步骤时默认会放在 `TypeDefinition.swift` 旁边 | +| 2026-12-01 | 补记落地:取号 0114,状态 In Progress → Implemented | 实现 2026-11-06 已合入 `next` 并随 0.25.0 发布,当时漏了取号与改状态。编号取自补记当天各共享分支的最大号加一,所以排在 0113 之后,不按合入顺序;同批的类型名整理取 0115。配套文档就是模块说明,不另写使用指南或实现说明;没有新术语 | diff --git a/Documentations/Evolutions/draft-swift-declaration-type-naming.md b/Documentations/Evolutions/0115-swift-declaration-type-naming.md similarity index 83% rename from Documentations/Evolutions/draft-swift-declaration-type-naming.md rename to Documentations/Evolutions/0115-swift-declaration-type-naming.md index 433042377..fe22016c4 100644 --- a/Documentations/Evolutions/draft-swift-declaration-type-naming.md +++ b/Documentations/Evolutions/0115-swift-declaration-type-naming.md @@ -1,10 +1,11 @@ -# Draft - SwiftDeclaration 的类型名按角色统一后缀 +# 0115 - SwiftDeclaration 的类型名按角色统一后缀 -- **状态**: In Progress +- **状态**: Implemented - **创建日期**: 2026-11-06 -- **最后更新**: 2026-11-06 -- **关联提案**: [draft-swift-declaration-model-indexing-layout](draft-swift-declaration-model-indexing-layout.md)(同一批整理的上一步:先把文件分成 `Model/` 与 `Indexing/`,本提案再理顺名字) -- **实现分支 / PR**: `refactor/swift-declaration-layout` +- **最后更新**: 2026-12-01 +- **关联提案**: [0114-swift-declaration-model-indexing-layout](0114-swift-declaration-model-indexing-layout.md)(同一批整理的上一步:先把文件分成 `Model/` 与 `Indexing/`,本提案再理顺名字) +- **实现分支 / PR**: `refactor/swift-declaration-layout`,2026-11-06 合入 `next`,随 0.25.0 发布 +- **配套文档**: 模块说明 [SwiftDeclaration.md](../Internal/Modules/SwiftDeclaration.md)(命名空间的后缀规则) ## 摘要 @@ -46,3 +47,4 @@ | 2026-11-06 | 第二类用 `…Matcher`,不用 `…Application` | 用户指出 `Application` 会被读成「应用程序」;`…Matcher` 与模块里已有的 `OverrideSymbolMatcher` 同类,用户选定。`…Applier` 读着别扭,`…Join` 不像名词,`…Annotator` 会和输出里的 annotation 撞词 | | 2026-11-06 | 按轻量档写精简提案;状态 Draft → Accepted → In Progress | 用户批准方案;接着在目录整理的分支上做 | | 2026-11-06 | 实现完成,待用户看过后收尾 | 按方案改完;`OverrideSymbolMatcher.swift` 原来两段文档注释叠在 `memberJoinKey` 上,收进 enum 时各归各位;SwiftIndexing 里私有的 `resolvedWitnessProjections` 一并改成 `resolvedAssociatedTypeWitnesses`。增量编译库与全部测试 target,原始退出码 0。文档:模块参考写上后缀规则,术语表与十份现行文档换成新名,演进账本加一节;不另写实现说明或使用指南;没有新术语 | +| 2026-12-01 | 补记落地:取号 0115,状态 In Progress → Implemented | 实现 2026-11-06 已合入 `next` 并随 0.25.0 发布,当时漏了取号与改状态;编号取法同 0114。方案里「废弃别名与 0057 的转发一起在 0.25.0 删除」没有照做:改名本身就随 0.25.0 发布,同一版里不能既废弃又删除,所以 `AssociatedTypeWitnessProjection`、`ConditionalWitnessCandidate`、`ObjCProtocolRequirementDefinition.Source` / `source` 的别名至今仍在,留到以后某个版本再删。配套文档就是模块说明,不另写使用指南或实现说明;没有新术语 | diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index 8009ed185..5687639ec 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -107,9 +107,24 @@ | [0095](0095-observable-nested-expansion.md) | `@Observable` 的展开分两层:先出 `@ObservationTracked`,再展开它 | Implemented | | [0096](0096-swift-first-imported-declarations.md) | Swift 实现的类,导入声明以 Swift 一侧为准 | Implemented | | [0097](0097-offline-cross-references-and-symbolication.md) | 交叉引用与地址符号化扩展到磁盘文件和归档 dyld cache(所属愿景:[不依赖 IDA 的逆向](../Visions/ReverseEngineeringWithoutIDA.md)) | Implemented | -| draft | [SwiftDeclaration 的目录分成公开模型与索引代码两块](draft-swift-declaration-model-indexing-layout.md) | In Progress | -| draft | [SwiftDeclaration 的类型名按角色统一后缀](draft-swift-declaration-type-naming.md) | In Progress | | [0098](0098-move-cross-reference-layers.md) | 交叉引用的核心层与 ObjC 层迁出本库,进 MachOKitExtensions 与 MachOObjCSection(所属愿景:[不依赖 IDA 的逆向](../Visions/ReverseEngineeringWithoutIDA.md)) | Implemented | | [cross-repository MachOKitExtensions 0002](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Evolutions/0002-move-reading-and-resolving-modules.md) | 把 MachOReading 与 MachOResolving 迁入 MachOKitExtensions 2.0.0:由那边维护唯一提案;本库删掉这两个 target,同时删掉 0057 废弃的读取写法 | Implemented | | [cross-repository MachOKitExtensions 0003](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Evolutions/0003-move-macho-infrastructure-modules.md) | 其余 MachO 基础模块迁入 MachOKitExtensions 2.0.0,`MachOSymbols` 拆出 C/C++ 符号索引:由那边维护唯一提案;本库的 Swift 符号索引改名 `SwiftSymbols` / `SwiftSymbolIndexStore` | Implemented | | [cross-repository MachOKitExtensions 0004](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Evolutions/0004-split-symbol-language.md) | 符号语言的判断归各自的包:由那边维护唯一提案;本库在 `SwiftSymbols` 定义 `SymbolLanguage.swift` 与 Swift 名字的判断,新 C target `SwiftSymbolsRegistration` 在镜像加载时注册;MachOKitExtensions 下限抬到 3.0.0 | Implemented | +| [0099](0099-tuist-workspace.md) | Tuist 开发 workspace:第三方依赖走二进制缓存,上游库可切换为本地检出 | Implemented | +| [0100](0100-fixture-suite-macro.md) | `@FixtureSuite` 宏:夹具测试套件开头的固定写法由宏生成 | Implemented | +| [0101](0101-swift6-mode-and-upcoming-features.md) | MachO 系列库统一 Swift 6 语言模式并开启三项 upcoming feature:MachOKit 切 Swift 6,六个包开启 `ExistentialAny`、`MemberImportVisibility`、`InferIsolatedConformances`(跨仓库唯一提案) | Implemented | +| [0102](0102-multiline-type-formatting.md) | 长类型拆行:放不下的类型按括号结构拆成多行 | Implemented | +| [0103](0103-cross-reference-test-scan-load.md) | 跨引用测试的整份 cache 扫描限并发,Tuist 工作区里扫描模块在 Debug 下开优化 | Implemented | +| [0104](0104-shared-macho-testing-support.md) | 测试支持的通用部分迁入 MachOKitExtensions:两个包共用 MachOFixtureSupport 与 MachOTestingSupport | Implemented | +| [0105](0105-swift-type-indexing-package.md) | 类型索引独立成 swift-type-indexing 包,并接入 MachOObjCSection 与 RuntimeViewer(跨仓库唯一提案) | Implemented | +| [0106](0106-c-imported-type-name-spelling.md) | C 导入类型的名字统一成 Swift 名,并能切换回 C 名(跨仓库唯一提案,RuntimeViewer 参与) | Implemented | +| [0107](0107-moved-swift-type-modules.md) | 被 SDK 搬过家的 Swift 类型,按现在声明它的模块打印(跨仓库唯一提案,swift-type-indexing 参与) | Implemented | +| [0108](0108-private-cf-type-modules.md) | 私有 CF 类型按导出 `GetTypeID` 的镜像解析所属模块 | Implemented | +| [0109](0109-consistent-c-imported-type-spelling.md) | C 导入类型的拼写补齐:同名类型去掉 `__C`,布局注释跟着打印器的拼写 | Implemented | +| [0110](0110-unify-evolution-integration-suites.md) | IntegrationTests 的演进套件合并:Swift 与 ObjC 共用一套版本轴 | Implemented | +| [0111](0111-unify-diff-and-interface-integration-suites.md) | IntegrationTests 的 diff 与接口套件合并:三类手检输出共用一套骨架 | Implemented | +| [0112](0112-objc-ivar-type-recovery.md) | `@objc @implementation` 只剩 ivar 的存储属性按 ObjC 类型还原 Swift 类型 | Implemented | +| [0113](0113-cross-reference-recall-gaps.md) | 交叉引用补漏:按 Swift 类型查询、GOT 槽地址、selector 引用与 ivar 读法(所属愿景:[不依赖 IDA 的逆向](../Visions/ReverseEngineeringWithoutIDA.md)) | Implemented | +| [0114](0114-swift-declaration-model-indexing-layout.md) | SwiftDeclaration 的目录分成公开模型与索引代码两块(2026-11-06 落地,2026-12-01 补记编号) | Implemented | +| [0115](0115-swift-declaration-type-naming.md) | SwiftDeclaration 的类型名按角色统一后缀(2026-11-06 落地,2026-12-01 补记编号) | Implemented | diff --git a/Documentations/Glossary.md b/Documentations/Glossary.md index b18aa182e..dd2bac639 100644 --- a/Documentations/Glossary.md +++ b/Documentations/Glossary.md @@ -75,6 +75,13 @@ - **主要出现在**:`Sources/Symbols/SwiftSymbols/SwiftSymbolIndexStore.swift`、MachOKitExtensions `Sources/MachOSymbols/SymbolRowBucket.swift` - **延伸阅读**:[提案 0003](Evolutions/0003-symbol-row-bucket-flattening.md) +### C-imported type name spelling(C 导入类型名拼写,`CImportedTypeNameSpelling`) + +C 导入类型(mangling 放在 `__C` / `__C_Synthesized` 里的 C 结构体、枚举、typedef、CF 类型与 ObjC 类)在打印里写哪个名字。它有两个名字:描述符记着 Swift 代码用的(`AnyWeakAttribute`),每处 mangled 引用记着 C 声明自己的(`__C.AGWeakAttribute`)。`.swiftName`(默认)让声明、成员类型、扩展头与 interface 的展开字段偏移注释都写 Swift 名:解析器找得到模块就带模块;本镜像有描述符、且描述符的名字已知就是 Swift 名的写裸名——改过名的(`AnyWeakAttribute`),以及没有 ABI 名、即 Swift 名就是 C 名的(`AGDescriptionOption`,编译器只在两个名字不同时才写 ABI 名);其余保留 mangled 拼写(本镜像没有它的描述符,或描述符的名字可能只是成员导入的叶子)。`.cName` 一律照 mangling 写 C 名,不问解析器。改过名的描述符名字只在**可信**时采用:ABI 名以描述符名字结尾的不信——导入成成员的类型(`NSAttributedStringKey` 的描述符只存 `Key`,父路径不在二进制里)由此退回 C 名,代价是 `NSDecimal` → `Decimal` 这类顶层改名也退回。`marksCImportedTypeNames` 打开时,打印器在每个这样的名字上标出另一种写法,宿主(RuntimeViewer 的行尾标签)据此显示与切换;`swift-section interface` 的开关是 `--c-imported-type-name-spelling`。 + +- **主要出现在**:`Sources/Output/SwiftPrinting/CImportedTypeNameSpelling.swift`、`CImportedTypeSwiftNameTable.swift`(`knownSwiftName(ofDescriptorNamed:importInfo:isDirectlyInImportedModule:)`、`trustsUserFacingName(_:importInfo:)`)、`AnnotationRegionKind+CImportedTypeName.swift`、`SwiftDeclarationPrintConfiguration`;展开字段偏移注释经 `DeclarationRenderConfiguration.fieldLayoutTypeName(printedName:typeNode:)` +- **延伸阅读**:[提案 0106](Evolutions/0106-c-imported-type-name-spelling.md)、[提案 0109](Evolutions/0109-consistent-c-imported-type-spelling.md)、[TypeImportInfo](#typeimportinfoc-导入类型身份) + ### cache scope(缓存范围,`ReadingContextCacheScope`) 一个 `ReadingContext` 声明的「按它读出来的东西,memo 缓存该存到哪一层」:`.image(identifier:)` 按镜像存(键就是 reader 的 `identifier`,与其它按镜像缓存同一个键,随镜像一起驱逐),`.process` 存进全进程共享的一层(地址是绝对地址,两个镜像不会撞),`.uncached` 不缓存。`MachOContext` 声明 `.image`,`InProcessContext` 声明 `.process`,其余实现默认 `.uncached`——以文件偏移为地址的第三方 context 如果落进全进程那层,两个镜像的偏移会互相串结果。反混淆 memo(`SymbolicDemanglerCache`)与节点驻留池(`InternedNodeReferenceCache`)按它选层。 @@ -103,6 +110,14 @@ macOS 27 与 iOS 27 的 dyld shared cache 不再给每个镜像留自己的 `__o - **主要出现在**:`Sources/Analysis/SwiftObjCInterop/ObjCImportedContainerIndex.swift`、`ObjCImplementationClassIndex.swift` 的 `importedMethods(of:)` - **延伸阅读**:[0090-objc-imported-declarations](Evolutions/0090-objc-imported-declarations.md) +### claim record(占用记录,Tuist 开发 workspace) + +本库与 RuntimeViewer 的 `TuistScript.sh` 共用的互斥记录:往一个检出里生成工程之前先「占用」它。被占检出的 git 目录里写 `tuist-generated-project-owner`(占用者检出的路径、在占用者那里释放它的命令、生成进来的工程名),占用者在自己的 `Tuist/.claimed-checkouts` 里列着它才算有效,否则是陈旧记录、直接接管。另一个检出占着时命令失败,并给出那边的释放命令。 + +- **不要混淆**:与按镜像缓存的 claim(`SharedCacheRegistry`,见「eviction group、claim、live owner」)无关。 +- **主要出现在**:`TuistScript.sh`(`claim_checkout`、`release_checkout`)、RuntimeViewer 的 `TuistScript.sh` +- **延伸阅读**:[TuistDevelopment.md](Internal/TuistDevelopment.md)「与 RuntimeViewer 共用的占用记录」、[提案 0099](Evolutions/0099-tuist-workspace.md) + ### class without a class object(没有 class object 的类,`SwiftClassWithoutClassObject`) `__objc_classlist` 里没有 class object 的 Swift 类:泛型类,父类在别的 resilience domain 的类,父类是本模块泛型类的类。它们的 `class_ro_t` 都静态存在,但只有经 Swift 元数据才找得到(generic metadata pattern、`ResilientClassMetadataPattern`、静态的 incomplete metadata)。后两种有 ObjC 祖先时还在 `__objc_stublist` 里登记一个 stub。交给 MachOObjCSection 时它们叫 supplied class(`ObjCSuppliedClass`),即宿主补进 ObjC 索引器的类。与 `@objc @implementation` 类的区别:那种类有 class object,没有的是 Swift 元数据。 @@ -244,6 +259,15 @@ sweep 覆盖范围之外的名字走的旁路:demangle 后 intern 进 `Storage - **主要出现在**:`Sources/Output/SwiftInterface/EvolutionMarking.swift`、`EvolutionAnnotationIndex.swift` - **延伸阅读**:[提案 0013](Evolutions/0013-swift-evolution-interface-builder.md)、[提案 0060](Evolutions/0060-evolution-interface-available-annotations.md)(`@available` 属性) +### long type(长类型)与 multiline type formatting(长类型拆行,`MultilineTypeFormatting`) + +**long type** 指一行里放不下的类型:一个不在其它泛型参数列表里面的泛型参数列表(类型的最外层 `<…>`),它的闭括号 `>` 落在第 `maximumLineWidth` 列之后。列号从这一行的缩进之后数起,所以同一个声明嵌得多深都算得一样。只有泛型参数列表会让一个类型成为 long type:行之所以长是因为参数多或行尾注释时,这一行不算。 + +**multiline type formatting** 是把打印好的源码里每个 long type 按括号结构拆成多行的那一步:long type 内部,有两个及以上参数的泛型参数列表每个参数一行;任何列表(单参数泛型、元组、函数类型与声明的参数列表、`[…]`)在某个元素已是多行时才拆。它在打印完成之后、交出产物之前做一次,只加换行和缩进,打印器本身不知道它的存在。规则借自 TypeAliasFormatter,加了行宽这道闸门。 + +- **主要出现在**:`Sources/Output/SwiftDeclarationRendering/MultilineTypeFormatting*.swift`;`InterfaceRequest` / `DumpRequest` 的 `multilineTypeFormatting`;CLI `--multiline-types` / `--maximum-line-width` +- **延伸阅读**:[提案 0102](Evolutions/0102-multiline-type-formatting.md) + ### macro folding(宏展开的折叠,folded form / expanded form) interface 把一个 attached macro 生成的东西收回成源码里的写法:`@Observable` 展开的类印成 `@Observation.Observable` 加普通的 `var x: T`,这是**折叠形态**;`expandsMacros` 打开时照二进制原样印出 registrar、存储 `_x`、computed `x`、生成的方法与 conformance,这是**展开形态**。二进制不记宏本身,只记它生成的东西,所以「这个类用了宏」是从生成物推断出来的(`TypeDefinition.attachedMacros`)。折叠只发生在单版本 interface;模型、dump、diff、evolution 始终是展开形态,dump 另在类头上写出宏的名字。 @@ -264,6 +288,13 @@ interface 把一个 attached macro 生成的东西收回成源码里的写法: - **延伸阅读**:[提案 0001](Evolutions/0001-symbol-name-offsetization.md)、[提案 0002](Evolutions/0002-declaration-model-descriptor-slimming.md) +### moved type(搬家的类型,`@_originallyDefinedIn`) + +被 SDK 从一个模块搬进另一个模块的 Swift 类型:声明上带 `@_originallyDefinedIn(module: "旧模块", 平台 版本)`,编译器在每个部署目标上都继续按旧模块做 mangling,嵌套在它里面的类型也一样,所以二进制只写得出 `CoreGraphics.CGFloat`、`SwiftUI.View`,而 SDK 的接口写的是 `CoreFoundation::CGFloat`、`SwiftUICore.View`。swift-type-indexing 从 SDK 的文本 `.swiftinterface` 读出这些记录;打印器经 `MovedTypeModuleResolving` 角色按最外层类型的名字提问,`interface --resolve-moved-type-modules` 打开。是否改写看二进制编译所用的 SDK 版本(`LC_BUILD_VERSION` 的 `sdk`)是否不早于搬家版本,所以 macOS 14 的 SwiftUI 仍印 `SwiftUI.View`。只改显示:diff、snapshot、evolution 与一切查找键照旧用 mangling 的模块。 + +- **主要出现在**:`Sources/Output/SwiftPrinting/NodePrintables/TypeNameResolving.swift`(`MovedTypeModuleResolving`)、`NodePrintable.resolvedModuleName(of:siblingIdentifier:)`、`SwiftDeclarationPrinter+Headers.swift`(扩展头)、`Sources/Output/SwiftTypeNameResolution/TypeDatabaseMovedTypeModuleResolver.swift`、swift-type-indexing 的 `MovedTypeIndex` +- **延伸阅读**:[提案 0107-moved-swift-type-modules](Evolutions/0107-moved-swift-type-modules.md)、swift-type-indexing 的 `Documentations/Internal/TypeIndexingPipeline.md`「搬家记录」一节 + ### 名字兜底(name fallback) opaque 尖括号参数归属的第三条规则:协议无任何 anchor 命中时,若它**自身声明**了与约束同名的关联类型、该名字候选约束**恰一条**、且候选的 anchor **不在组合成员之内**,则把参数挂给它——用于恢复被「等价类塌缩」吃掉的 sugar(`TestCollection<[A]>`)。「anchor 在组合外」的限定是防捏造判据:anchor 协议自己在组合里时,其余同名成员写没写 sugar 无从知道(塌缩与未 pin 同形),挂了就是编造。 @@ -315,7 +346,7 @@ opaque 尖括号参数归属的第三条规则:协议无任何 anchor 命中 ### recognizer(识别器,`CodeReferenceRecognitionSession`) -交叉引用扫描里认某一种语言的那一层。核心层只认与语言无关的东西(调用、桩、槽、寄存器跟踪、字符串),在五个时机问各语言层的识别会话:进入函数、遇到只有它认得的调用目标、调用点、算出一个地址、读一个槽。ObjC 层认发送、类与 ivar,Swift 层认类型元数据与 mangled name。核心不 import 任何语言层,新语言加识别器即可,不改核心。 +交叉引用扫描里认某一种语言的那一层。核心层只认与语言无关的东西(调用、桩、槽、寄存器跟踪、字符串),在五个时机问各语言层的识别会话:进入函数、遇到只有它认得的调用目标、调用点、算出一个地址、读一个槽,扫完函数时再告诉它一声。ObjC 层认发送、类与 ivar,Swift 层认类型元数据与 mangled name。核心不 import 任何语言层,新语言加识别器即可,不改核心。 - **主要出现在**:MachOKitExtensions 的 `Sources/MachOCodeReferences/Recognition/`、MachOObjCSection 的 `ObjCCodeReferences`、`CrossReferenceAnalysis/Scanning/SwiftCodeReferenceRecognizer.swift` - **延伸阅读**:[0097-offline-cross-references-and-symbolication](Evolutions/0097-offline-cross-references-and-symbolication.md)、MachOKitExtensions 的 [MachOCodeReferences.md](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Internal/MachOCodeReferences.md) @@ -403,6 +434,13 @@ opaque 尖括号参数归属的第三条规则:协议无任何 anchor 命中 - **主要出现在**:MachOKitExtensions `Sources/MachOSymbols/SymbolTable.swift` +### selector reference(selector 引用,`CodeReferenceTarget.selector`) + +代码从 `__objc_selrefs` 载入了一个 selector,却没有用它发送消息:交给 `respondsToSelector:` 或 `performSelector:`、作为返回值、设成控件的 action。与这个 selector 的发送归在同一个表键下,`refs --selector` 两者都列。发送自己载入的 selector(经典的 `objc_msgSend` 在 `x1` 里用的那个)不算;dyld cache 的构建器把 selref 载入改写成取字符串地址,所以 cache 里的镜像没有。 + +- **主要出现在**:`CodeReferenceTarget.selector`、`ObjCCodeReferenceRecording.recordSelectorReference(selector:at:)`、`swift-section refs` 的 `selector <名字>` 行 +- **延伸阅读**:[0113-cross-reference-recall-gaps](Evolutions/0113-cross-reference-recall-gaps.md)、[Modules/CrossReferenceAnalysis.md](Internal/Modules/CrossReferenceAnalysis.md)「引用种类与路线」 + ### stand-in member symbol(替身成员符号) 为镜像里没有实现符号的成员造的成员符号,照它顶替的那个实现符号的样子造:mangled 名与成员树都与实现符号相同,偏移是镜像里留下的那个入口。下游按名字推导的东西(导出判定、ObjC 方法表联结、`@objc` 标记)和按树推导的东西(vtable 联结、ABI 身份)因此都把它当成实现符号来读,不用分支。来源有三种:vtable 槽的 `Tq`(descriptor-only member)、`@objc` thunk(thunk-only member)、只剩 initializing entry point 的 initializer(`…fc` 改写成 allocator 的形状)。只补真实符号没有声明的成员,按成员实体节点结构相等判断。 @@ -425,10 +463,10 @@ dyld shared cache 在子缓存之间放的跳板:`bl` 只能跳 ±128 MB,跨 ### supplementary APINotes(补充映射) -TypeIndexing 的外部知识入口:标准 `.apinotes` 格式的**用户自备**类型映射文件,为 **SDK 里没有模块的私有框架**(AttributeGraph 等)提供 `__C` 类型的归属与改名——这类框架的 `swift_name` 改名在二进制里只剩类型记录里的最后一截(`Graph`),所属模块与嵌套关系都不记录,完整名字只能靠外部知识。库自身不内置任何映射(首版的内置 SPM resource bundle 因 `Bundle.module` 分发即崩问题在 review 后移除);宿主经 provider 的 `supplementaryAPINotesURLs:`、CLI 经 `--supplementary-apinotes` 传入,覆盖顺序 SDK APINotes → 用户文件按传入序,后写覆盖同名。CF-bridged 类型须登记两个 C 拼写(typedef 名进 Typedefs、storage tag 名进 Tags)。描述符按 import info 里的 ABI name 打印(提案 0023),不会再出现 Swift spelling 的 `__C.Graph`;SwiftName spelling 仍会登进归属表,让改名条目所在的模块胜过只做标注的其它模块(`NSObject` 归 ObjectiveC,不归同样列出它的 Foundation)。 +类型索引(swift-type-indexing 的 `TypeIndexing`,原是本仓库的同名 target)的外部知识入口:标准 `.apinotes` 格式的**用户自备**类型映射文件,为 **SDK 里没有模块的私有框架**(AttributeGraph 等)提供 `__C` 类型的归属与改名——这类框架的 `swift_name` 改名在二进制里只剩类型记录里的最后一截(`Graph`),所属模块与嵌套关系都不记录,完整名字只能靠外部知识。库自身不内置任何映射(首版的内置 SPM resource bundle 因 `Bundle.module` 分发即崩问题在 review 后移除);宿主经 provider 的 `supplementaryAPINotesURLs:`、CLI 经 `--supplementary-apinotes` 传入,覆盖顺序 SDK APINotes → 用户文件按传入序,后写覆盖同名。CF-bridged 类型须登记两个 C 拼写(typedef 名进 Typedefs、storage tag 名进 Tags)。描述符按 import info 里的 ABI name 打印(提案 0023),不会再出现 Swift spelling 的 `__C.Graph`;SwiftName spelling 仍会登进归属表,让改名条目所在的模块胜过只做标注的其它模块(`NSObject` 归 ObjectiveC,不归同样列出它的 Foundation)。 -- **主要出现在**:`Sources/Declaration/TypeIndexing/SupplementaryAPINotes.swift` -- **延伸阅读**:[提案 0010](Evolutions/0010-community-type-mapping-bundles.md)、[SupplementaryTypeMappings.md](SupplementaryTypeMappings.md)(公开使用指引)、[TypeIndexingPipeline.md](Internal/TypeIndexingPipeline.md) +- **主要出现在**:swift-type-indexing 的 `Sources/TypeIndexing/SupplementaryAPINotes.swift` +- **延伸阅读**:[提案 0010](Evolutions/0010-community-type-mapping-bundles.md)、[SupplementaryTypeMappings.md](SupplementaryTypeMappings.md)(公开使用指引)、[TypeIndexingPipeline.md](https://github.com/MxIris-Reverse-Engineering/swift-type-indexing/blob/main/Documentations/Internal/TypeIndexingPipeline.md) ### sweep(构建扫描) @@ -489,6 +527,21 @@ Swift runtime 的 descriptor 布局惯例:固定头之后按 flags 跟着可 - **不要混淆**:`.machOFile(path:)` 是显式指定一个文件;system root 是按 install name 在目录树里现找。 - **延伸阅读**:MachOKitExtensions 的 [DependencyResolution.md](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Internal/DependencyResolution.md)、[提案 standalone-file-thunk-resolution](Evolutions/0030-standalone-file-thunk-resolution.md) +### Tuist development workspace(Tuist 开发 workspace) + +`./TuistScript.sh` 用 Tuist 生成的 `MachOSwiftSection-Tuist.xcworkspace`,原生 `MachOSwiftSection.xcworkspace` 之外只供日常开发的第二条路:第三方依赖预编进本机的 Tuist 二进制缓存,本库与五个上游库从源码编,上游库可用 `--local-dependencies` 切到本地检出。发版、CI、`swift build` / `swift test` 都不走它。 + +- **不要混淆**:「原生 workspace」指 `MachOSwiftSection.xcworkspace`(SwiftPM 包直接放进 Xcode),与它无关。 +- **主要出现在**:`TuistScript.sh`、`Tuist/`、`Workspace.swift`、`Tuist.swift` +- **延伸阅读**:[TuistDevelopment.md](Internal/TuistDevelopment.md)、[提案 0099](Evolutions/0099-tuist-workspace.md) + +### type index(类型索引) + +swift-type-indexing 的 `TypeIndexing`(原是本仓库的同名 target)从 SDK 建的索引:每个平台的模块接口与 API notes,回答一个 `__C` 类型属于哪个模块、Swift 里叫什么(`__C.UICellConfigurationState` → `UIKit.__UICellConfigurationState`),按 SDK 版本缓存在盘上;另外从各模块的文本 `.swiftinterface` 读出被 SDK 搬过家的 Swift 类型现在由哪个模块声明(见 moved type)。本仓库只留适配层 `SwiftTypeNameResolution`,`swift-section interface --resolve-c-module-names` 经它解析;MachOObjCSection 的 `ObjCTypeIndexing` 是 ObjC 一侧的接入。 + +- **主要出现在**:`Sources/Output/SwiftTypeNameResolution/`;swift-type-indexing 的 `Sources/TypeIndexing/` +- **延伸阅读**:[提案 0105](Evolutions/0105-swift-type-indexing-package.md)、[TypeIndexingPipeline.md](https://github.com/MxIris-Reverse-Engineering/swift-type-indexing/blob/main/Documentations/Internal/TypeIndexingPipeline.md) + ### type-construction evaluation(类型构造求值) 离线读 kind-9 accessor thunk 的方法:不执行 thunk,按指令顺序做符号求值——寄存器和栈槽里放「类型表达式」(参数缓冲区第 k 个词、某 descriptor 的 accessor 以若干实参调用的结果、常量 metadata 地址、mangled name 实例化)而不是数值。thunk 只用几种运行时入口(泛型类型的 metadata accessor、`swift_getWitnessTable`、`__swift_instantiateConcreteTypeFromMangledName`)构造类型,每一种的语义都是类型层面的,所以函数返回时 `x0` 里的表达式就是答案。条件跳转能判定的(运行时能力标志、已知立即数)直接判定,判定不了的(版本检查的结果)按「假设为假 / 假设为真」各跑一遍,两次结果即 `if #available` 的两支。与「查表」读法(只认 `csel` 的两个操作数或分支里唯一一次调用)的区别:后者忽略了尾调用,会把 `ModifiedContent<…, X>` 读成 `X`、把中间调用的结果当答案。 diff --git a/Documentations/Internal/ABIEvolutionDesign.md b/Documentations/Internal/ABIEvolutionDesign.md index c76216642..d5f9c78eb 100644 --- a/Documentations/Internal/ABIEvolutionDesign.md +++ b/Documentations/Internal/ABIEvolutionDesign.md @@ -232,14 +232,7 @@ swift-section evolution ... \ 8. **兼容性推广**:逐转换 additive/breaking 与 `firstBreakingTransitionIndex`。 9. **reporter**:小型 evolution 的整段文本断言(确定性输出)。 -另有**维护者手检集成套件** `Tests/IntegrationTests/SwiftDiffing/ABIEvolutionTests.swift` -(遵循 IntegrationTests 约定:只打印/写文件、无断言、agent 不运行): -`ABIEvolutionTestSuite.DyldCacheTests` 对三份 macOS dyld cache(15.5 → 26.5.1 → -27.0-beta.1)提取同一 image(AppKit)跑完整 pipeline——逐版本索引 → 冻结 → -**经持久化 JSON 往返**(codec + 版本头在真实数据上过一遍)→ lineage 矩阵 → -timeline 报告(`-Evolution.txt` / `-Evolution.json` 落盘); -`SwiftUICoreTests`(iOS 18.5 → 26.5 模拟器运行时)覆盖 N == 2 情形并打印与双侧 -diff 的 verdict 交叉核对行。 +另有**维护者手检集成套件**,在 `Tests/IntegrationTests/InspectionDumps/`(遵循 IntegrationTests 约定:只打印/写文件、无断言、agent 不运行;Swift 与 ObjC 的报告和联合接口共用这一套,见提案 [0110-unify-evolution-integration-suites](../Evolutions/0110-unify-evolution-integration-suites.md);与单版本接口、两版本 diff 的手检套件同在一个目录、共用版本轴,见提案 [0111-unify-diff-and-interface-integration-suites](../Evolutions/0111-unify-diff-and-interface-integration-suites.md)):每种版本来源一个套件,挂在 `Evolution` 下(`Caches`、`ArchivedCaches`、`SimulatorFiles`),读哪些镜像由套件指向的具名配置决定(`CacheImagesConfiguration.swiftUIGroup`、`.appKit` 等,要看别的框架就加一份配置),各按读的元数据筛版本。报告的 `swiftReportFile` / `swiftReportString` 跑完整 pipeline——逐版本索引 → 冻结 → **经持久化 JSON 往返**(codec + 版本头在真实数据上过一遍)→ lineage 矩阵 → timeline 报告(`-Evolution.txt` / `-Evolution.json` 落盘)。`Evolution.Caches` 默认对三份 macOS dyld cache(15.5 → 26.5.2 → 27.0)提取 SwiftUI 与 SwiftUICore;`Evolution.SimulatorFiles`(iOS 18.5 → 26.5 模拟器运行时)覆盖 N == 2 情形并打印与双侧 diff 的 verdict 交叉核对行。 ## 后续项(不在首轮范围) diff --git a/Documentations/Internal/FieldLayoutRendererReaderSpecialization.md b/Documentations/Internal/FieldLayoutRendererReaderSpecialization.md index 781a537b4..2197adf11 100644 --- a/Documentations/Internal/FieldLayoutRendererReaderSpecialization.md +++ b/Documentations/Internal/FieldLayoutRendererReaderSpecialization.md @@ -93,6 +93,7 @@ configuration/isGeneric/staticAggregateFieldLayout,不含 `Self`)传递 rend - `nestedFieldOffsetTree(forMangledTypeName:baseOffset:depthLimit:) -> [NestedFieldOffset]`:expanded 嵌套树。在 SwiftLayout 内完成解析(多镜像 universe、按 mangled name 跨闭包定位 descriptor、逐层重建泛型环境、 在解析所得 image 上算偏移),renderer 只负责树 → `// ├──` 注释的呈现。 + 每一行的类型名两条后端走同一个入口 `DeclarationRenderConfiguration.fieldLayoutTypeName(printedName:typeNode:)`:interface 打印器打开 `spellsFieldLayoutTypeNamesThroughResolver`,行经它的 `typeDemangleResolver` 印出、与字段声明同拼写;dump 不打开,行保持 `.default`。进程内的 `NestedFieldOffsetLevel` 缓存的行同样带着节点,渲染时不再 demangle(提案 [0109-consistent-c-imported-type-spelling](../Evolutions/0109-consistent-c-imported-type-spelling.md))。 - `fieldLayout(ofStruct:/ofClass:)` 抽出 `in image:` 参数,使嵌套树能在依赖镜像里计算。 ### 4. 渲染细节 diff --git a/Documentations/Internal/FixtureTestingAndContinuousIntegration.md b/Documentations/Internal/FixtureTestingAndContinuousIntegration.md index c286c56b8..644ecb38a 100644 --- a/Documentations/Internal/FixtureTestingAndContinuousIntegration.md +++ b/Documentations/Internal/FixtureTestingAndContinuousIntegration.md @@ -29,8 +29,10 @@ CI 上可复现性是唯一判据: ## 路径锚定——fixture 二进制怎么被找到(易踩坑) `MachOFileName.SymbolTestsCore` 存的是相对路径 -`../../Tests/Projects/SymbolTests/DerivedData/...`,**不是**对 CWD 解析,而是对 -`Sources/TestSupport/SwiftSectionFixtureSupport/Extensions.swift` 的 `#filePath` 解析——`../../` 爬回仓库根再下行。 +`../../../Tests/Projects/SymbolTests/DerivedData/...`,**不是**对 CWD 解析,而是对 +`Sources/TestSupport/SwiftSectionFixtureSupport/MachOFileName+SymbolTests.swift` 的 `#filePath` 解析——`../../../` 爬回仓库根再下行。 +`MachOFileName` 本身自 2026-11-21 起是 MachOKitExtensions 的类型(`MachOFixtureSupport`),它不知道别的包的源码在哪, +所以锚点由本包在 extension 里传进去(`MachOFileName(path:relativeTo:)`)。 而构建端 `xcodebuild -derivedDataPath Tests/Projects/SymbolTests/DerivedData` 是对 `xcodebuild` 自己的 CWD 解析。两者对齐**当且仅当**构建从仓库根发起——任何从子目录跑 `xcodebuild` 的 CI 步骤都会悄悄打破对齐。CI 还遇到过第三种形态:runner 上 `xcodebuild` @@ -72,6 +74,17 @@ workflow 里的 "Normalize SymbolTestsCore fixture path" 步骤用符号链接 ObjC class wrapper、canonical specialized metadata、foreign types、value generics 等形态 (见下文 ABI 覆盖层)。 +### 测试支持的通用部分在 MachOKitExtensions(2026-11-21) + +与 Swift 无关的测试支持搬到了 MachOKitExtensions 3.2.0 的两个 product,本包的 `SwiftSectionFixtureSupport` / `SwiftSectionTestingSupport` re-export 它们(提案 [0104-shared-macho-testing-support](../Evolutions/0104-shared-macho-testing-support.md),契约见 MachOKitExtensions 的 `Documentations/Internal/TestingSupport.md`): + +- **夹具基类**:`MachOSwiftSectionFixtureTests` 是 MachOKitExtensions `MachOFixtureTests` 的子类,只说明夹具是 SymbolTestsCore(`fixtureFileName` / `fixtureImageName`),读取器、上下文和跨读取器写法都来自基类;读不到夹具时仍抛带重编说明的 `FixtureLoadError`。 +- **跨读取器写法**:两边只差被测对象时用成对传入、单个闭包的重载(`acrossAllReaders(file, image) { … }`、`acrossAllContexts(file, image) { subject, context in … }`);带 `inProcess:` 或两边确有不同时才写三个闭包。 +- **现场编译**:用 `FixtureCompiler`(同一份请求每个进程只编一次,产物放在进程退出时删掉的临时目录,install name 是 `@rpath/lib<名字>.dylib`),保留原来的源文件名——private 判别符由文件名哈希得出。产物是共享缓存,要改写(`CompiledFixture.load` 的 `rewrite`)就先复制一份。还有约 25 处要的能力它没有(模块名与产物名不同、`-emit-module` 等额外输出、编完再 strip),仍手写,列在提案的后续项里。 +- **选 slice**:`HostSlice` 按本进程的 CPU 挑,故意读别的架构的测试照旧手写。 +- **本机 cache**:只读的测试经 `FullDyldCache.cachedHost` 共用一份打开,要新实例的写明原因。 +- **静默输出**:`.print()` 改由运行时环境变量 `MACHO_TESTING_SILENT=1` 控制;CI 与 Tuist 的测试 scheme 都设了它,`SILENT_TEST` 编译条件仍留给本包自己的 target。 + ### 现场编译的 fixture 为什么都带一个 class(2026-08-26 至 2026-09-26) 测试里现场编译的 dylib 几乎都带一个用不上的 class(`FixtureAnchor`、`Anchor` 之类),这是在绕 MachOKit 0.52.103 之前的一个越界读。`dyld_chained_starts_in_image` 里没有 fixup 的段,`seg_info_offset` 是 0,dyld 会跳过它;MachOKit 却照样在偏移 0 处读 `dyld_chained_starts_in_segment`,把镜像级的头部当成这一段的 starts。只含 struct 的模块编出来没有 `__DATA` 段,只有三个段,误读出来的 `page_count` 正好落在真实段的 `page_size`(0x4000)上,于是往后多读 32 KB,越过文件映射的末尾就是 SIGSEGV / SIGBUS,而且时有时无。 @@ -117,6 +130,18 @@ fixture.framework (SymbolTestsCore) `MethodKey`,在单个 `@Test` 内一并验证;覆盖守护按 `(typeName, memberName)` 比对不区分重载。 - baseline 头部记录 toolchain 版本 + 生成日期;`--suite ` 支持局部重生成以缩小 review 面。 +### 套件头由 `@FixtureSuite` 生成(2026-11-20) + +夹具套件开头原本要手抄三样东西:遵循 `FixtureSuite`、`static let testedTypeName = "X"`、返回 +`XBaseline.registeredTestMethodNames` 的 `registeredTestMethodNames`。171 个套件里 170 个照这个形状写, +被测类型名抄错一个字母,覆盖率守护就静默地对不上源码里的类型。现在由 attached 宏 `@FixtureSuite` +(声明在 `SwiftSectionTestingSupport`,实现在只给测试用的宏 target `SwiftSectionTestingMacros`)生成: +被测类型名默认取类名去掉 `Tests`,baseline 默认取同一个词干加 `Baseline`,不同时用字面量写明 +(`OpaqueTypeFixtureTests`、`EnumFunctionsTests`、`TupleTypeMetadataElementTests`、`GenericContextTests`、 +`GenericRequirementContentTests` 五处)。`SuiteBehaviorScanner` 按源码读被测类型名,所以同时认宏的参数与 +类名词干。`CoroFunctionPointerTests` 自己编夹具、没有 baseline,注册名单是字面量,保持手写。 +提案:[0100-fixture-suite-macro](../Evolutions/0100-fixture-suite-macro.md)。 + ### 信任危机与 sentinel 收紧(2026-05-05) 原始落地被 review 发现**系统性失真**:157 个 suite 里 88 个(56%)从不调用 @@ -189,6 +214,19 @@ GitHub 的 `macos-26` runner 是 3 核、7 GB 内存。Swift Concurrency 的 coo **排查这类卡住的办法**:`swift test` 的控制台输出是分块缓冲后才进日志的,只看日志分不清是哪个测试卡住。当时用的诊断 workflow 在 PR #128 的提交 `e473b89d` 里,可以照搬:测试放后台跑并打开 `--event-stream-output-path`(每个事件单独写一行),超过 12 分钟就列出「已开始但没结束」的测试、内存状态,并对 `swiftpm-testing-helper` 做 `sample`(它带 `get-task-allow`,不需要 sudo)。 +## 整份 cache 扫描共用一份并发名额(2026-11-21) + +`CrossReferenceAnalysisTests` 里有几处测试要把整份 dyld shared cache 的上千个镜像各扫一遍:调用者、Swift 类型、ObjC 类三种预筛的抽样复查,以及找 `__text` 之外的函数起点。它们原先各自用 `DispatchQueue.concurrentPerform` 按镜像数开满并发。Debug 构建下扫一遍要好几分钟,测试期间整台机器被占满:2026-11-21 在 28 核的 Ultra 上,xctest 持续占 2300% 以上的 CPU,这一个 target 跑了 14 分钟。 + +**规则**:这个 target 里并行扫描很多镜像,一律走 `ImageScanConcurrency.concurrentPerform(iterations:execute:)`,不直接调 `DispatchQueue.concurrentPerform`。 + +- **名额是 `max(2, 核心数 / 2)`,全进程共用**:Swift Testing 会并行跑几个套件,每次调用各自限宽的话加起来又是满核。`ImageScanConcurrencyTests.twoCallsAtOnceShareTheBudget` 钉住这一点:只按调用限宽、不共用名额的实现会让它失败。 +- **每次调用最多起「名额」个工作者**,各自从共享游标领下一个下标、扫之前取一个名额。只靠信号量的话,`concurrentPerform` 仍按核心数起线程,多出来的线程全阻塞在等名额上。 +- **不会卡住 cooperative thread**:名额只在扫一个镜像期间持有,扫描是同步的 CPU 工作、不等任何线程池,所以调用线程是 cooperative thread 也总能等到名额,不违反上一节的规则。**闭包里不能再调它**:嵌套调用在外层占着名额时再去等名额,名额全被这样占住就再也放不出来。 +- **`ParallelScanSourceTests` 拦下新的直接调用**:扫这个 target 的源码,名额之外出现 `DispatchQueue.concurrentPerform(` 就失败。例外只有 `ScanThroughputBenchmarkTests`:它要设 `CROSS_REFERENCE_BENCHMARK_OUTPUT` 才跑,量的就是全核吞吐。 + +Debug 下扫描本身为什么慢、Tuist workspace 怎么处理,见 [TuistDevelopment.md](TuistDevelopment.md) 的「扫描模块在 Debug 下也开优化」一节;设计来历与测量数据见提案 [0103-cross-reference-test-scan-load](../Evolutions/0103-cross-reference-test-scan-load.md)。 + ## 相关文档 - [AGENTS.md](../../AGENTS.md) —— 覆盖体系的现行操作规程(invariants、regen-baselines、环境漂移排查) diff --git a/Documentations/Internal/Modules/CrossReferenceAnalysis.md b/Documentations/Internal/Modules/CrossReferenceAnalysis.md index 09e529e23..e661bec2d 100644 --- a/Documentations/Internal/Modules/CrossReferenceAnalysis.md +++ b/Documentations/Internal/Modules/CrossReferenceAnalysis.md @@ -35,12 +35,16 @@ - **ivar**:`.objectiveCInstanceVariable(className:name:)`。代码经 `adrp; ldrsw`(或 ld64 改写出的字面量 `ldrsw`、Swift 的 64 位 `ldr`)读 `__objc_ivar` 里的偏移变量;ObjC 会话把这个节作为「观察的槽」,核心在 32 位与 64 位载入时都问它。名字先取 `_OBJC_IVAR_$_<类>.<变量>` 符号,没有符号再从类的 ivar 列表反查(列表项的第一个字段指向偏移变量,第二个是名字),在 ObjC 层的附件 `ObjCInstanceVariableNames` 里,第一次碰到时读。父类是 `NSObject` 的类,clang 直接用常量偏移,不经偏移变量;Swift 类经 ObjC ivar 列表登记的偏移变量是 `__data` 里的 Swift 字段偏移全局量,不在 `__objc_ivar`,眼下不收。 - **字符串**:`.cString(String)`(`adrp; add` 或 `adr` 落进 C 字符串节——`__cstring`、`__objc_methname`、`__oslogstring` 等 `S_CSTRING_LITERALS` 节)与 `.constantString(String)`(落进 `__cfstring`,按 `{ isa, flags, characters, length }` 读,`flags & 0x10` 是 UTF-16)。核心层认,默认不记:分析器用 `recordingStringReferences: true` 打开(`recordsStringReferences`),查询里含 `.cString` / `.constantString` 键时那次扫描也会找。减法算出的地址从不当作字符串:Swift 的大字符串字面量是 `adrp; add; sub #0x20`,`add` 已经指到字符串起点,`sub` 之后的地址会落进前一个字符串中间。 - **对导入符号的数据引用**:从引用槽(GOT 等)读到一个 bind,而它绑到的符号不在分析器覆盖的镜像里——只给一个 app 时读 `_OBJC_CLASS_$_CALayer`、ivar、全局量都是这样——记成 `.importedSymbol(name:)`、`kind == .reference`。进程内槽里都是地址,不会出现。查一个类的全部引用时,调用方还要查 `_OBJC_CLASS_$_<类>` 这个导入名。 +- **selector 引用**(提案 [cross-reference-recall-gaps](../../Evolutions/0113-cross-reference-recall-gaps.md)):`.selector(String)`、`kind == .reference`——从 `__objc_selrefs` 载入、却没有用来发送的 selector:`respondsToSelector:` 与 `performSelector:` 的参数、返回的 selector、控件的 action。ObjC 会话把载入先记为待定,经典发送与 `super` 发送用 `x1` 里的它发送时消掉,离开函数时把剩下的记下(实现见 MachOObjCSection 的 `ObjCCodeReferences.md`)。归在与发送相同的 `.selector` 键下,`--selector` 和 RuntimeViewer 的 selector 查询都取得到(RuntimeViewer 暂不显示)。收集器把它按指令地址插回所在函数的引用之间,被调仍按指令顺序。dyld cache 的构建器把 selref 载入改写成取 selector 字符串的地址,所以只在独立文件里有;符号化把 selref 槽说成 `.selector`,不再说成一次发送。 +- **取函数地址**(同一提案):`adrp; add` 或 `adr` 算出本镜像某个函数的起点,记一条 `kind == .reference`、路线 `addressMaterialization`、目标 `.function(location)` 的引用,归 `.function` 键:`--function` 与调用层级因此列出建栈上 block、把回调交给 `dispatch_async_f`、返回闭包的函数。只在查询含函数键或建整表时找(`ReferenceCollector.findsFunctionAddressReferences`)。指向函数的数据(方法表的 IMP、vtable)仍不算。 - **路线**:`CodeReference.route`(`CodeReferenceRoute`,核心层定义)说明这条引用是怎么到达目标的,不说明目标是什么。`direct`(`bl` / `b` 直达)、`imageStub`(本镜像的 `__stubs`、`__auth_stubs`、`__objc_stubs`)、`stubIsland`(cache 镜像之间的 stub island,可多跳)、`cacheSharedStub`(macOS / iOS 27 整个 cache 共用的 selector 桩与 GOT 桩)、`pointerSlot`(经指针槽载入:GOT、ObjC 引用节、ivar 偏移变量)、`addressMaterialization`(`adrp; add` 或 `adr` 算地址)、`literalLoad`(字面量 `ldr`)、`indirect`(经寄存器的调用与跳转,认证与否看证据)。调用的路线由 `CallTargetResolver.resolveWithRoute(_:)` 给出,经多跳时取第一种跳板;会话认领的目标按地址落在哪定(本镜像代码直达、本镜像其他节经本镜像桩、镜像之外经 cache 共用桩)。常驻索引把路线存在每条记录 `flags` 的第 5–7 位。 ## 地址符号化 `symbolication(of:)` 回答「这个未滑动地址是什么」(第 6 步):在哪个镜像、段与节,以及在那里的意思——函数体里(起点、名字、偏移;名字的来源与 `functions(inImageAt:)` 相同,含 ObjC 方法表与 Swift 元数据的后备名)、桩或跳板(经过的每一跳与最终目标)、指针槽(种类与里面装的东西)、字符串、最近的符号加偏移、映射着但什么都不是(`.data`),或没有映射。核心层的 `AddressPlace`(MachOKitExtensions 的 `MachOCodeReferences/Symbolication/`)判断结构:先找镜像(按各镜像用到的 slide 逐一试,cache 优先),再看节——`__text` 是函数,`S_SYMBOL_STUBS` 是本镜像的桩(经 `CallTargetResolver` 解目标),镜像之间的可执行映射是跳板链(逐跳读 `ARM64Trampoline`),GOT、懒指针与语言层报上来的引用节是槽(经读取层解槽),C 字符串节与 `__cfstring` 是字符串,其余给最近的符号。门面再补语言层知道的:`__objc_stubs` 的 selector、槽里的类与 Swift 类型、selector 引用的 selector、protocol 引用的名字、`__objc_ivar` 的 ivar。一组独立文件各留自己的地址,两个文件都有的地址取第一个,`symbolication(of:inImageAt:)` 指定镜像。符号化用留存的函数表:地址很少只问一个。 +槽里的东西照扫描的读法说(2026-11-29 代码库体检第 4、11 条):值落在某镜像的 `__TEXT` 里时,是类型描述符就是 `.swiftType`,落在函数里才是 `.function`,其余(protocol 描述符、方法描述符、常量)是 `.unrecognized(address:)`,不再一律说成函数;值是 struct、enum 等值类型的元数据时,与扫描的 `recordSlotReference` 共用 `SwiftTypeIndex.descriptorLocation(ofValueMetadataAt:in:typeIndex:)`,说成它的类型。protocol 引用读 `protocol_t` 的名字前先确认 `value + 8` 已映射,C 字符串只读到映射的尽头、最多 `maximumCStringLength`(4096)字节,没有终止符就不当字符串——进程内的读取不做边界检查,畸形或半初始化镜像的一个槽就能让宿主崩溃。`swift-section symbolicate --in-image` 给的名字对应多个镜像(cache 里框架的 macOS 版与 Mac Catalyst 版)时,取映射着这个地址的那个,都没有才取第一个。 + ## 子系统 | 子系统 | 文件 | 分工 | @@ -147,6 +151,8 @@ SwiftThunkAnalysis 自己的 Capstone 解码器原先也把字面量 `ldr` 当 按字符串取类(`objc_getClass("NSFoo")`,AppKit 183 处)不算类引用。 +**取到类的 GOT 槽地址也是类引用**(提案 [cross-reference-recall-gaps](../../Evolutions/0113-cross-reference-recall-gaps.md))。优化过的 Swift 代码取 ObjC 类的元数据时,先 `adrp x2; add x2, <类的 GOT 槽>`,再调合并后的访问器(`$sSo22NSAppleEventDescriptorCMaTm` 这类),由它载入槽、`objc_opt_self`、`swift_getObjCClassMetadata`;ControlCenter 26.7 有 554 处这种调用,2026-11-26 以前全部漏掉。核心层把落在引用槽上的地址当作在这条 `add` 上读槽,之后经同一寄存器的零位移载入不再重记(MachOKitExtensions 的 `MachOCodeReferences.md`)。 + **代价**(release,28 核,与只有分支跟踪的那次提交交替跑三轮取最好):全缓存整表 2.03 → 2.40 秒(引用多了 326 万条,+17%),查 `init` 的调用者 1.54 → 1.70 秒,`makeKeyAndOrderFront:` 0.29 → 0.33 秒。扫描器自己缓存类索引,查类不抢分析器的锁;地址落在本镜像 `__TEXT`、或载入的槽是本镜像的非类槽时,在任何查表之前就排除。 ### Swift 类型引用(第二批) @@ -155,7 +161,7 @@ SwiftThunkAnalysis 自己的 Capstone 解码器原先也把字面量 `ldr` 当 1. **调用类型的元数据访问器。** 调用照常报一条,另加一条目标为 `.swiftType(descriptor:)` 的引用。访问器靠各镜像 `__swift5_types` 列出的描述符认(描述符 +12 处是访问器的相对指针),`Scanning/SwiftTypeIndex` 按需给每个镜像建一份。 2. **取访问器或元数据的地址。** `adrp` / `add` 出、或从 GOT 槽载入访问器地址,或结构体、枚举、`Optional`、导入类型的元数据——元数据首字是种类(0x200–0x204),次字是描述符。Swift 类的元数据就是它的 ObjC 类对象,按类引用报(见上一节)。 -3. **按 mangled 名字实例化。** 调用本镜像的 `__swift_instantiateConcreteTypeFromMangledName…` 辅助函数,或运行时的 `swift_getTypeByMangledName…`。macOS 27.2 上几乎都是 V2:`x1` 指向 `{到名字的 int32 偏移, int32 长度}` 记录;旧形态的名字在 `x0` 的缓存变量里,类型一经实例化缓存里就只剩元数据,名字读不到,不报。没有符号的辅助函数按形态认:不超过 0x90 字节、调用运行时那几个入口;读 `[x1]` 的是 V2。目标是 `.swiftTypeName(.mangledName(location:length:))`:名字里可能夹着符号引用,解开一个要几十微秒,扫描不解开,表也不按类型归档它。没有描述符的访问器——泛型实例(`$sSay7SwiftUI4TextVGMa`)、存在类型、导入类型——按符号名认,报 `.swiftTypeName(.accessorSymbol(…))`。 +3. **按 mangled 名字实例化。** 调用本镜像的 `__swift_instantiateConcreteTypeFromMangledName…` 辅助函数,或运行时的 `swift_getTypeByMangledName…`。macOS 27.2 上几乎都是 V2:`x1` 指向 `{到名字的 int32 偏移, int32 长度}` 记录;旧形态的名字在 `x0` 的缓存变量里,类型一经实例化缓存里就只剩元数据,名字读不到,不报。没有符号的辅助函数按形态认:不超过 0x90 字节、调用运行时那几个入口;读 `[x1]` 的是 V2。目标是 `.swiftTypeName(.mangledName(location:length:))`:名字里可能夹着符号引用,解开一个要几十微秒,扫描不解开,表也不按类型归档它。没有描述符的访问器——泛型实例(`$sSay7SwiftUI4TextVGMa`)、存在类型、导入类型——按符号名认,报 `.swiftTypeName(.accessorSymbol(…))`。一组独立文件里没有 libswiftCore,运行时入口只能经桩解析成导入符号:调用点与「按形态认」都同时认导入符号的名字(`SwiftRuntimeFunctions.nameRegister(ofTypeByMangledNameEntryNamed:)`),否则剥过符号的 app 里所有经 mangled 名字的实例化都漏报(2026-11-29 代码库体检第 3 条)。 **表按描述符位置归档**(`CodeReferenceTable.Key.swiftTypeDescriptor`),不按类型的 key。key 是名义类型的 mangling(`7SwiftUI4TextV`、`Sa`),取自描述符的 `…Mn` 符号(demangle 再 mangle,与名字、符号里的拼法一致);没有符号时才 demangle 描述符的上下文,而那样拼出的 key 会偏:受约束扩展里的嵌套类型带上扩展的要求(SwiftUICore 有 58 处访问器调用拼法不同),其他模块类型的扩展里的 private 类型干脆丢了自己(Foundation 的 `Mutex<…>.LockResult` 成了 `15Synchronization5MutexV`)。位置没有这些问题,扫描时也不必解开任何东西。从名字取 key 时,泛型实参各算一个类型,嵌套在泛型类型(或它的受约束扩展)里的类型去掉父类型的实参:`Regex.Match` 是 `17_StringProcessing5RegexV5MatchV` 加上 `AnyRegexOutput`。 @@ -214,7 +220,7 @@ Swift 符号改按链接关系预筛(`imageIndices(linkingImageAt:among:)`,` `CodeReferenceTable` 是值,宿主想留多久就留多久,按 `approximateByteCount` 计预算(不含字符串的堆存储;同一次扫描里重复的名字共用一份)。大镜像的整表很大(GeoServices 约 121 MiB,全缓存合计约 9 GB),28 个线程同时建整表时峰值约 1.5 GB,分配器之后还留着 1.2 GB 脏页不还。**查调用者用 `references(to:inImageAt:)`**:扫描时只留命中的引用,同样扫完全缓存后常驻约 170 MB(4 线程约 106 MB)。 -**要为少数几个镜像常驻、反复查,用 `CodeReferenceIndex`**(`referenceIndex(ofImageAt:)`,2026-10-18 为 RuntimeViewer 的预先准备新增)。它按目标分组存放:选择子、导入名、类名每个只存一份,引用所在的函数与指令存成相对 `__text` 起点的 32 位偏移(一条 16 字节),只留查调用者与查类型引用会读的引用,间接调用与落在镜像外的跳转不留。macOS 27.2 实测(`approximateByteCount`,含名字的堆存储):AppKit 21 MiB(整表 67 MiB,87.5 万条引用里留 85.6 万条),Foundation 9 MiB(34),SwiftUICore 9 MiB(35),libswiftCore 1 MiB(7)。`index.references(to:)` 与 `references(toSwiftType:in:)` 回答的和过滤扫描完全相同,顺序也相同(按指令地址,同一条指令的调用排在它顺带的类型引用前面)。建索引会**留住**镜像的函数表——给结果起名要用;名字本身还要第一次起名时读,宿主要连这一步也提前,再调 `prepareNames(inImageAt:)`(见上文「名字从哪来」)。分析器被换掉后,索引照样能读(它不持有分析器),宿主用 `keepFunctionTable(ofImageAt:)` 让新分析器重新留住。`referenceIndex(ofImageAt:reportingProgress:)` 每扫 2,048 个函数报一次进度,回答「停」就不建了。Debug 构建建 AppKit 的索引约 6 秒。 +**要为少数几个镜像常驻、反复查,用 `CodeReferenceIndex`**(`referenceIndex(ofImageAt:)`,2026-10-18 为 RuntimeViewer 的预先准备新增)。它按目标分组存放:选择子、导入名、类名每个只存一份,引用所在的函数与指令存成 32 位偏移(一条 16 字节),从镜像最低的函数起点算起。这个起点通常就是 `__text` 的起点,但主可执行文件的符号表把 `__mh_execute_header`(Mach header 本身)记在 `__text` 下,扫描把 header 连同 load commands 当成 `__text` 之前的一个函数来读。2026-11-20 之前偏移从 `__text` 起点算,那里扫出的引用存不下:Debug 构建触发断言,Release 构建存进截断的偏移、还原出的函数地址差 4 GiB(RuntimeViewer 在 iOS 27 上给 `Preferences` 建索引时撞上)。只留查调用者与查类型引用会读的引用,间接调用与落在镜像外的跳转不留。macOS 27.2 实测(`approximateByteCount`,含名字的堆存储):AppKit 21 MiB(整表 67 MiB,87.5 万条引用里留 85.6 万条),Foundation 9 MiB(34),SwiftUICore 9 MiB(35),libswiftCore 1 MiB(7)。`index.references(to:)` 与 `references(toSwiftType:in:)` 回答的和过滤扫描完全相同,顺序也相同(按指令地址,同一条指令的调用排在它顺带的类型引用前面)。建索引会**留住**镜像的函数表——给结果起名要用;名字本身还要第一次起名时读,宿主要连这一步也提前,再调 `prepareNames(inImageAt:)`(见上文「名字从哪来」)。分析器被换掉后,索引照样能读(它不持有分析器),宿主用 `keepFunctionTable(ofImageAt:)` 让新分析器重新留住。`referenceIndex(ofImageAt:reportingProgress:)` 每扫 2,048 个函数报一次进度,回答「停」就不建了。Debug 构建建 AppKit 的索引约 6 秒。 分析器是一个快照:之后才加载的镜像需要新的分析器。 @@ -256,6 +262,17 @@ Swift 符号改按链接关系预筛(`imageIndices(linkingImageAt:among:)`,` **搬家之后**(2026-11-19,同一台 Ultra,Xcode 26.6,release;提案 [0098 move-cross-reference-layers](../../Evolutions/0098-move-cross-reference-layers.md)):核心层与 ObjC 层跨包、接口改成 SPI 之后没有变慢,各项比 `next` 快 1% 到 11%(整 cache 建表进程内 2.67 → 2.53 秒、归档 27.2 cache 文件 2.75 → 2.51 秒),引用逐条一致。逐项数字记在 MachOKitExtensions 的 `Documentations/Internal/MachOCodeReferences.md`「吞吐」一节。 +**召回补漏的代价**(提案 [cross-reference-recall-gaps](../../Evolutions/0113-cross-reference-recall-gaps.md),2026-11-26,JHs-Mac-Studio-Ultra,macOS 27.2,Xcode 27.2,release,`ScanThroughputBenchmarkTests`;基线是三个仓库的 `next`,与候选交替各两轮、取最好,计时期间机器上没有别的构建): + +| 操作 | 基线 | 候选 | +|---|---|---| +| 建分析器 | 0.054 秒 | 0.055 秒 | +| 每个镜像都建整表 | 2.419 秒(129,592,499 条) | 2.464 秒(133,847,503 条) | +| `init` 的调用者(2,880 个镜像) | 0.034 + 1.516 秒(336,063 条) | 0.034 + 1.545 秒(336,075 条) | +| `makeKeyAndOrderFront:` 的调用者(105 个镜像) | 0.059 + 0.292 秒(439 条) | 0.058 + 0.299 秒(442 条) | + +整表慢 1.9%、多 425 万条引用(取函数地址为主);两条调用者查询慢 1.9% 与 2.4%,多出的几条是进程里 cache 外镜像的 selector 引用。都在提案定的 5% 以内。 + ## 测试锚点 - `ARM64InstructionWordTests` / `ARM64TrampolineTests`:手写编码器造指令字;`capstoneAgreesWithTheEncoders` 让 Capstone 反汇编同一批字,编码器写错也藏不住。`linkerRewrittenAddressesAndLoads` 与 `linkerRewrittenSlotStub` 核对 ld64 改写出的 `adr`、字面量 `ldr` 与桩。 @@ -266,6 +283,7 @@ Swift 符号改按链接关系预筛(`imageIndices(linkingImageAt:among:)`,` - `ObjectiveCClassReferenceTests`:AppKit 里三种取法都有(取本镜像类的地址、载入本镜像的类、载入别的镜像的类,`NSString` 在其中);`+[NSThread currentThread]` 发给类字面量 `NSNotificationCenter`;`_BenchmarkHost._started(test:)` 经 `objc_opt_self` 发给 `NSApplication`;分类方法与类方法的 super 类;Block 里的 super 发送按 `__objc_superrefs` 得到所在方法的类(Block 的符号不是方法名,只有槽位能给出类;分类方法那个测试里槽位与符号给出的类相同,分辨不出);Matter 里没有符号的方法,super 类与方法表一致;两个 SwiftUI 的同名类各自指向自己;类预筛(`NSWindow`、`NSUUID`、`__NSStackBlock__`、`OS_xpc_dictionary`)丢掉的镜像里抽样一处引用也没有。其中三个在去掉对应做法时变红过:经 `objc_opt_self` 不保留 `x0`、不读 `__objc_superrefs`、预筛只认 `_OBJC_CLASS_$_`。 - `SwiftTypeReferenceTests`:SwiftUICore 里访问器调用报出的类型与访问器符号全部一致(一万处以上);紧邻的 `adrp` / `add` 取出的地址上若有符号,报出的类型与符号一致;Foundation 的名字取自 `x1` 的记录、落在 `__swift5_typeref`、能解开;Foundation 与 SwiftData 里,查询保留的名字恰是解开后提到该类型的名字(40 个最常被符号引用的类型;另四个标准库类型,查询退回的正是同一套解开,所以它们只守着符号引用不指错描述符);两个 SwiftUI 的同名类型按位置分开;类型预筛(Foundation 的 `URL` 与 `JSONEncoder`、SwiftUICore 的 `Text`)丢掉的镜像里抽样一处引用也没有——按导入符号预筛时三者都漏;Foundation 与 AppKit 的每一个类型,按名字先筛再比 key 的查找与比每个类型的 key 结果相同(`typeLookupsCompareSameNamedTypesOnly`),按名字查导出表与读整个导出表判断导出与否相同(`exportLookupsAgreeWithTheWholeTrie`);查导入类型时不从不透明类型的描述符读名字,子进程里拿一页末尾的假描述符核对(`importedTypeQueriesReadNoNameWhereNoTypeDescriptorIs`,修复前子进程 SIGBUS)。 - `FallbackNamingTests`:导出表给的名字落在导出的地址上(SiriAppIntents);AppKit 里方法表给的名字与 `-[C sel]` 符号一致(去掉分类名后 99.9% 以上);SwiftUICore 里从元数据重建的名字与真实的 `…Ma`、`…Mr`、方法符号一致(99% 以上);Matter 的方法在没有符号时由方法表起名;SiriAppIntents 几乎每个类型的访问器都有名字,重建的名字 demangle 出来是元数据访问器。 +- 召回补漏(提案 [cross-reference-recall-gaps](../../Evolutions/0113-cross-reference-recall-gaps.md)):`SelectorReferenceTests`(经典发送的 ObjC 库里,`copy`、`name` 与 `respondsToSelector:` 的参数是 selector 引用、发送不重复、常驻索引存得下、被调按指令顺序、selref 槽符号化成 selector)、`SlotAddressReferenceTests`(`-O` 编的 Swift 库里,`Timer.self` 在 `add x2` 上引用 `_OBJC_CLASS_$_NSTimer`)、`FunctionAddressReferenceTests`(`dispatch_async_f` 的回调与栈上 block 的 invoke 函数被取地址处引用、整表也有);SwiftSectionKit 的 `ReferencesRequestSwiftTypeTests`(`--type` 的三种符号写法与 mangling 结果相同、cache 里没导出的类型要给镜像、独立文件里去掉符号的类型逐个文件找)。召回的数字与测量办法在愿景《[不依赖 IDA 的逆向](../../Visions/ReverseEngineeringWithoutIDA.md)》「我们选的方向」第 1 条,脚本在 `Scripts/CrossReferenceRecall/`。 - `StandaloneImageTests`:SymbolTestsCore fixture 经自己的桩调用 libswiftCore,没有一条停在只有名字的导入上;它的路径是加载路径而不是 `@rpath/…`,安装名也能查回它;测试包(`MH_BUNDLE`,没有安装名)的路径等于 `dladdr` 给的;测试包算作主程序的依赖方。 - `RegisterFileTests`:48 条汇编器编出的指令,每条写的寄存器都被作废,Capstone 的寄存器访问表独立核对这张表;普通读写只作废目标寄存器。 - `RenamedReexportTests`:AppKit 按 `_strlen`、`_CGSMainConnectionID` 调用 `__platform_strlen`、`_SLSMainConnectionID`,CharacterPicker 按 `NSEmojiImageAsset` 引用 CoreText 的类,三者的预筛都留住了它们;别名经伞形框架的那一种(`_xkMDConfigErase`)。 @@ -275,7 +293,7 @@ Swift 符号改按链接关系预筛(`imageIndices(linkingImageAt:among:)`,` - `CodeReferenceIndexTests`:Foundation 整表的每一个键,索引给出的引用与整表逐条相同、顺序相同,条数等于整表里有键的加上 Swift 类型名;AppKit 里一次查几个键(selector、libswiftCore 的函数、`NSWindow`)与过滤扫描逐条相同;Foundation 里 `URL`、`JSONEncoder`(类,经类对象)与标准库的 `Sa`(名字里拼出来,要解开)从索引查与按类型扫描逐条相同;索引不到整表的一半大;建索引留住函数表;进度从 0 报到函数总数,回答「停」就不建。 - 层的边界:下层搬走之后 SwiftPM 本身就不让它们 import 本库的模块,原来的 import 白名单测试删了。核心层源码里没有 `objc_` / `swift_` 开头的字面量、只有 `InProcessCrossReferenceMemory` 把地址变成指针、不写地址掩码常量,由 MachOKitExtensions 的 `SourceScanTests` 守着;ObjC 层只经 `CrossReferenceMemory` 读内存、不写 `swift_` 字面量,由 MachOObjCSection 的 `SourceScanTests` 守着;本库的 `MemoryAccessScanTests` 只扫 `CrossReferenceAnalysis`。核心层不装任何语言层也能扫,见 MachOKitExtensions 的 `CoreOnlyScanTests`。 - `RecognizerExtensionPointTests`:测试里定义的会话(代替一切调用 libobjc 的调用)接进核心的扫描,核心不改就生效;只查 selector 时 Swift 会话不建任何镜像的类型索引。`PublicNameTests`:只 `import CrossReferenceAnalysis` 也看得到下移的 `CodeLocation`、`CodeReference.Kind`、`ReceiverClassHint`、`IndirectCallEvidence`。 -- `FunctionStartOutsideTextTests`:符号表把函数起点放在 `__text` 起点之下的镜像照常扫描(第 1 步曾因此下溢陷入)。 +- `FunctionStartOutsideTextTests`:符号表把函数起点放在 `__text` 起点之下的镜像照常扫描(第 1 步曾因此下溢陷入);这样的函数里扫出的引用,索引照样存得下:编一个可执行文件,在 `__text` 前的填充区写一条 `bl`,从 `__mh_execute_header` 这个函数里调用,索引与整表逐键相同。 - 两个按环境变量启用的 A/B 套件,库里没有可存的基线:`ReferenceTableDigestTests`(AppKit、SwiftUICore、Foundation 的整表摘要,在基线检出上生成、在候选上比对,也能整表导出逐行比较)与 `ScanThroughputBenchmarkTests`(上面「读取层与拆层的代价」那张表,release 下跑)。用法写在各自的文档注释里。 - `FileModeTests`(文件模式,提案第 4 步):运行中的 cache 从文件读与进程内读,AppKit、SwiftUICore、Foundation 的整张引用表逐行一致,函数名、ObjC 方法表与 Swift 元数据给的名字、selector 预筛也一致;cache 的每个指针槽(v5 与没有 slide info 的模拟器 cache)解出的与 MachOKit 一致;归档 27.0、27.2 里 `UINSPasteboardWritingItemProvider` 的两个经 GOT 的调用者;iOS 26.3.1 设备 cache 里经 stub island 的发送;现编的独立文件——`-interposable` 的 dylib(self-bind 落到自己的函数、`puts` 是导入名)、Objective-C 可执行文件(`__TEXT` 在 0x100000000 时 rebase 与 objc 桩都解对)、C++ 的 `retab` 之后的异常清理代码。归档卷不在时相应用例跳过。 - `StandaloneFileReferenceDumpTests`:按环境变量启用,把一个独立文件(universal 取 arm64e 切片)的全部引用按函数导出成文本,供与反汇编器对照。第 4 步拿它与 IDA 抽样核对过 ControlCenter 26.7。 diff --git a/Documentations/Internal/Modules/README.md b/Documentations/Internal/Modules/README.md index 2d72afbc9..97cf50be8 100644 --- a/Documentations/Internal/Modules/README.md +++ b/Documentations/Internal/Modules/README.md @@ -34,7 +34,7 @@ | SwiftObjCInterop | [SwiftObjCInterop.md](SwiftObjCInterop.md) | ✅ 已写(拆分来历:[0089-swift-objc-interop-module](../../Evolutions/0089-swift-objc-interop-module.md)) | | SwiftLayout | [SwiftLayout.md](SwiftLayout.md) | ✅ 已写(专题:[StaticLayoutEngine.md](../StaticLayoutEngine.md)、[StaticLayoutDependencyClosure.md](../StaticLayoutDependencyClosure.md)) | | SwiftDiffing | — | 待写(专题:[ABIDiffDesignAndLimitations.md](../ABIDiffDesignAndLimitations.md)、[ABIEvolutionDesign.md](../ABIEvolutionDesign.md)) | -| TypeIndexing | — | 待写(专题:[TypeIndexingPipeline.md](../TypeIndexingPipeline.md)) | +| SwiftTypeNameResolution | — | 适配层,打印器与 swift-type-indexing 之间(索引本身的说明在 [swift-type-indexing 的 TypeIndexingPipeline.md](https://github.com/MxIris-Reverse-Engineering/swift-type-indexing/blob/main/Documentations/Internal/TypeIndexingPipeline.md)) | | SwiftOutputTransformer | — | 待写(专题:[OutputTransformerMigration.md](../OutputTransformerMigration.md)) | | MachOSwiftSection | — | 待写 | | MachOFoundation | — | 由 MachOKitExtensions 提供(2.0.0 起,同名 product):再导出 `MachOBase`、`MachOSymbols`、`MachODependencies` | @@ -48,6 +48,6 @@ | MachOSwiftSectionC | — | 待写 | | SwiftSectionMacros | — | 待写 | | Utilities | — | 待写 | -| SwiftSectionFixtureSupport / SwiftSectionTestingSupport(C) / baseline-generator | — | 待写(测试基础设施,可合并成一篇) | +| SwiftSectionFixtureSupport / SwiftSectionTestingSupport(C) / baseline-generator | — | 待写(测试基础设施,可合并成一篇);通用部分建在 MachOKitExtensions 的 `MachOFixtureSupport` / `MachOTestingSupport` 上,见 [FixtureTestingAndContinuousIntegration.md](../FixtureTestingAndContinuousIntegration.md)「测试支持的通用部分在 MachOKitExtensions」 | (`Demangling` / `Semantic` 来自上游包 swift-demangling / swift-semantic-string,`MachOKitExtensions` / `MachOObjCSection` 是 sibling 外部包,文档归各自仓库——上表标「由 MachOKitExtensions 提供」的模块也一样。) diff --git a/Documentations/Internal/Modules/SwiftDeclaration.md b/Documentations/Internal/Modules/SwiftDeclaration.md index ba1c8c402..53add7906 100644 --- a/Documentations/Internal/Modules/SwiftDeclaration.md +++ b/Documentations/Internal/Modules/SwiftDeclaration.md @@ -13,7 +13,7 @@ SwiftDeclaration 是**共享声明模型**:`SwiftIndexing` 往里填,`SwiftP ## 文件 → 子系统对照 -模块分成两棵树,判据是可见性(提案 [draft-swift-declaration-model-indexing-layout](../../Evolutions/draft-swift-declaration-model-indexing-layout.md)):`Model/` 是下游读的公开模型,索引结束后还留着;`Indexing/` 是把模型填满的代码,里面每个声明都是 `package` 或 `internal`,只在 `index(in:)` 与 `SwiftDeclarationIndexer.prepare()` 期间有人调用。新文件按这条判据归位:类型是 `public` 的、会出现在公开 API 的返回值里,进 `Model/`;只在索引期活着,进 `Indexing/`。将来要把索引代码整体挪到 `SwiftIndexing`,边界已经画好了。 +模块分成两棵树,判据是可见性(提案 [0114-swift-declaration-model-indexing-layout](../../Evolutions/0114-swift-declaration-model-indexing-layout.md)):`Model/` 是下游读的公开模型,索引结束后还留着;`Indexing/` 是把模型填满的代码,里面每个声明都是 `package` 或 `internal`,只在 `index(in:)` 与 `SwiftDeclarationIndexer.prepare()` 期间有人调用。新文件按这条判据归位:类型是 `public` 的、会出现在公开 API 的返回值里,进 `Model/`;只在索引期活着,进 `Indexing/`。将来要把索引代码整体挪到 `SwiftIndexing`,边界已经画好了。 | 子系统 | 文件 | |---|---| @@ -23,7 +23,7 @@ SwiftDeclaration 是**共享声明模型**:`SwiftIndexing` 往里填,`SwiftP | 4. 种类枚举 | `Model/Kinds/` | | 5. 挂在声明上的独立概念 | `Model/` 根下的 `ExportStatus`、`SwiftAttribute`、`SwiftAttachedMacro`、`ResolvedAssociatedTypeWitness`、`ObjCCategoryConformance` | | 6. 各声明的索引 | `Indexing/`:`DefinitionIndexing`(每个定义只索引一次,见下文)、`TypeDefinition/` 下的十个扩展(见下表)、`ExtensionDefinition/` 下的 `+Indexing` / `+ObjCMembers` / `+ThunkAttributes`、`ProtocolDefinition+Indexing`、`ObjCProtocolDefinition+Indexing`、`ObjCImportedDefinitions+Indexing`(三种 ObjC 导入定义) | -| 7. 构建期机器 | `Indexing/Building/`(`MemberDefinitionBuilder`、`MemberSymbolBucketing`、`OverrideSymbolMatcher`、`ClassDispatchLookups`、`StandInMemberSymbolBuilder`、`AnnotatedSymbol`、`WrappedPropertyRecovery`、`ObservableMacroExpansionRecovery`、`ThunkAttributeMatcher`、`ObjCMemberMatcher`、`ObjCProtocolNameBuilder`)——各声明的索引扩展调用的构件;`TypeDefinition+ThunkAttributes` 与 `ExtensionDefinition+ThunkAttributes` 共用 `ThunkAttributeMatcher`,两个 `+ObjCMembers` 共用 `ObjCMemberMatcher`。命名空间按角色取后缀(提案 [draft-swift-declaration-type-naming](../../Evolutions/draft-swift-declaration-type-naming.md)):造出新东西的叫 `…Builder`,拿二进制里另一处的证据(thunk 符号、ObjC 方法表、override 描述符)对到已建好的成员上的叫 `…Matcher`,补回二进制丢掉的事实的叫 `…Recovery`;不用 `…Application`,它会被读成「应用程序」 | +| 7. 构建期机器 | `Indexing/Building/`(`MemberDefinitionBuilder`、`MemberSymbolBucketing`、`OverrideSymbolMatcher`、`ClassDispatchLookups`、`StandInMemberSymbolBuilder`、`AnnotatedSymbol`、`WrappedPropertyRecovery`、`ObservableMacroExpansionRecovery`、`ThunkAttributeMatcher`、`ObjCMemberMatcher`、`ObjCProtocolNameBuilder`)——各声明的索引扩展调用的构件;`TypeDefinition+ThunkAttributes` 与 `ExtensionDefinition+ThunkAttributes` 共用 `ThunkAttributeMatcher`,两个 `+ObjCMembers` 共用 `ObjCMemberMatcher`。命名空间按角色取后缀(提案 [0115-swift-declaration-type-naming](../../Evolutions/0115-swift-declaration-type-naming.md)):造出新东西的叫 `…Builder`,拿二进制里另一处的证据(thunk 符号、ObjC 方法表、override 描述符)对到已建好的成员上的叫 `…Matcher`,补回二进制丢掉的事实的叫 `…Recovery`;不用 `…Application`,它会被读成「应用程序」 | | 8. 对上游类型的扩展 | `Extensions/`(按被扩展的类型分文件:`ProtocolConformance+Names`、`TypeContext+Names`、`FieldRecord+DemangledType`、`Node+TypeKind`、`DemanglingNode+StoredVariable`……) | | 9. 事件 | `Events/SwiftIndexEvents` | diff --git a/Documentations/Internal/Modules/SwiftInterface.md b/Documentations/Internal/Modules/SwiftInterface.md index 804696264..a705c08fd 100644 --- a/Documentations/Internal/Modules/SwiftInterface.md +++ b/Documentations/Internal/Modules/SwiftInterface.md @@ -52,7 +52,7 @@ SwiftInterface 是接口生成的**编排层**(thin orchestrator):它自 **宏展开的折叠**(提案 [0093-observable-macro-folding](../../Evolutions/0093-observable-macro-folding.md)):`@Observable` 展开的类默认按源码的样子打印——类型头上一行 `@Observation.Observable`,被跟踪的属性在它存储字段 `_x` 的位置印成 `var x: T`(字段的偏移与布局注释照旧;`declaredMember` 来源带上 computed `x` 的 vtable 与地址注释,`synthesized` 来源在上方加 note 写明是从哪个存储字段合成的),宏不跟踪的存储 `var` 上方加一行 `@Observation.ObservationIgnored`(单独占一行、与声明同样缩进;property wrapper 的属性也各占一行,`lazy` 留在声明行;提案 [0095-observable-nested-expansion](../../Evolutions/0095-observable-nested-expansion.md)),registrar、computed `x`、生成的方法与生成的 conformance 都不印。`expandsMacros` 打开时逐字节回到折叠之前的样子。打印器每次打印从 `TypeDefinition.observableMacroExpansion` 算一份视图(`SwiftDeclarationPrinter+ObservableMacro.swift`),接在字段块、两种成员排序、导出过滤、类型头与 `printExtensionDefinition` 上;`marksOptionalContent` 打开时两种形态都印,各自在 `SwiftVisibilityOption.expandsMacros` 的区域里,`VisibilityRegionProjectionTests` 对 fixture 的四个变体与进程内镜像验证投影。`printMacroExpansion(of:attachedTo:level:)` 用同一套逐字段、逐成员的渲染把展开单独印成一块,`printMacroExpansionParts(of:attachedTo:)` 按 Xcode 放 attached macro 展开的位置拆成几块,供宿主做内联展开。它照宏自己的分层分两层(提案 [0095-observable-nested-expansion](../../Evolutions/0095-observable-nested-expansion.md)):展开 `@Observable` 得到每个被跟踪属性一块 `@Observation.ObservationTracked`(`.trackedPropertyAttribute`,放在折叠声明上方),加上闭合括号上方的成员块与下方的 conformance 块;属性块的 `nestedExpansions` 给出这个属性在块里的 UTF-8 范围与展开它的分块,也就是 accessor 块加存储的 `.trackedProperty`,放在折叠声明下方。两层的 `anchorKind` 都是那个折叠声明的区域。两者里被跟踪属性的 computed `x` 与 accessor 块都照宏的写法印 `@storageRestrictions(initializes: _x) init`、`get`、`set` 三行(`init` 那一行与别处的 accessor 块共用 `AccessorBlockKeywords.InitAccessorLine`,提案 [0094-init-accessor-recovery](../../Evolutions/0094-init-accessor-recovery.md)),不看镜像里还剩哪些 accessor(AppKit 剥光、SwiftUI 只剩 getter 的都有);`marksAttachedMacros` 把宏属性包进 `AnnotationRegion.Kind.attachedMacro(_:)` 的区域、把每个被跟踪属性折叠出的声明包进 `attachedMacroTrackedProperty(_:named:)` 的区域,配合 `marksNestedDefinitions`,最内层的 `DefinitionRegion` 指明是哪个类型的宏。diff 与 evolution 渲染器不走这条路,始终印展开。 -**`SwiftInterfaceBuilderExtraDataProvider`**:外部数据源的注入缝,纯生命周期钩子——`Sendable` + 一个默认为空的 `setup()`(提案 0015 之前它还继承 printer 的 resolver 协议,强迫所有 provider 都是类型名解析器)。「会不会回答 printer 查询」是正交能力:provider 按需另行声明 `SwiftPrinting` 的角色协议(`ModuleNameResolving` / `CImportedNameResolving` / `OpaqueTypeResolving`,均 refine 空标记协议 `TypeNameResolving`),`addExtraDataProvider(_:)` 用 `as? any TypeNameResolving` 命中才把它转发给 printer——所以一个 resolver 型 provider 一头挂在 builder 的 prepare 生命周期上,一头挂在打印热路径上,而纯 setup 型 provider(只预热缓存之类)也是合法形态。两个已知实现:`TypeIndexing.SwiftInterfaceBuilderTypeNameProvider`(`__C` 模块归属,跨模块,声明两个名字角色)和本模块的 `SwiftInterfaceBuilderOpaqueTypeProvider`(声明 `OpaqueTypeResolving`,见子系统 2)。 +**`SwiftInterfaceBuilderExtraDataProvider`**:外部数据源的注入缝,纯生命周期钩子——`Sendable` + 一个默认为空的 `setup()`(提案 0015 之前它还继承 printer 的 resolver 协议,强迫所有 provider 都是类型名解析器)。「会不会回答 printer 查询」是正交能力:provider 按需另行声明 `SwiftPrinting` 的角色协议(`ModuleNameResolving` / `CImportedNameResolving` / `MovedTypeModuleResolving` / `OpaqueTypeResolving`,均 refine 空标记协议 `TypeNameResolving`),`addExtraDataProvider(_:)` 用 `as? any TypeNameResolving` 命中才把它转发给 printer——所以一个 resolver 型 provider 一头挂在 builder 的 prepare 生命周期上,一头挂在打印热路径上,而纯 setup 型 provider(只预热缓存之类)也是合法形态。两个已知实现:`SwiftTypeNameResolution.SwiftInterfaceBuilderTypeNameProvider`(经 SDK 解析类型名,跨模块,声明三个名字角色:`__C` 模块归属与 Swift 名,以及被 SDK 搬过家的 Swift 类型现在的声明模块——见术语表 moved type;`SDKTypeNameResolutions` 决定开哪几样,只开搬家时 `setup()` 不生成任何模块接口)和本模块的 `SwiftInterfaceBuilderOpaqueTypeProvider`(声明 `OpaqueTypeResolving`,见子系统 2)。 **`SwiftInterfaceBuilderDependencies` + `DependencyPath`**:把「主 binary + 它的依赖镜像」凑成一组,按 reader 分特化——`MachOFile` 版从 `DependencyPath`(单个 Mach-O 路径 / dyld cache 路径 / 宿主系统 cache)按 install name 匹配装载,装载失败走 `renderingDegraded` 事件(默认无 handler 也有 os_log 地板);`MachOImage` 版直接按名字向 dyld 要。消费者是 CLI 的 `InterfaceCommand` 与 `TypeIndexing`(依赖过滤 + 惰性 ObjC 元数据索引都需要依赖镜像清单)。 @@ -104,7 +104,7 @@ N ≥ 2 版本渲染成**一份**并集接口,声明尾注生命周期注解 | 入口 | 路径 | |---|---| -| `swift-section interface` | `SwiftInterfaceBuilder`(+ `--resolve-c-module-names` 挂 TypeIndexing provider,opaque provider 只在 `--parse-opaque-return-type` 下挂,默认关) | +| `swift-section interface` | `SwiftInterfaceBuilder`(+ `--resolve-c-module-names` / `--resolve-moved-type-modules` 挂 `SwiftInterfaceBuilderTypeNameProvider`,两者同开时共用一个,opaque provider 只在 `--parse-opaque-return-type` 下挂,都默认关) | | `swift-section diff --interface` | `SwiftDiffableInterfaceBuilder` ×2 + `SwiftDiffableInterfaceRenderer` | | `swift-section evolution --interface` | `AnySwiftEvolutionInterfaceBuilder`,经 SwiftSectionKit 的 `ABIEvolutionRequest`(与 `--json`/`--summary-only` 互斥;`--emit-available` 打开 `@available` 属性,即 `Report.annotatedInterface(availabilityAttributes:)`:平台名从每个输入的 `LC_BUILD_VERSION` 推断,模拟器变体按对应的设备平台算,`--platform` 可以覆盖;推断不出或输入之间互相冲突时抛 `AvailabilityPlatformInferenceError`,命令行译成 usage 错误,不会悄悄地不发属性) | | `swift-section diff` / `snapshot` / `evolution`(数据路径) | `SwiftDiffableInterfaceBuilder.abiModule()/snapshot()` → SwiftDiffing | diff --git a/Documentations/Internal/Modules/SwiftLayout.md b/Documentations/Internal/Modules/SwiftLayout.md index 95a1f2660..fb1fb3292 100644 --- a/Documentations/Internal/Modules/SwiftLayout.md +++ b/Documentations/Internal/Modules/SwiftLayout.md @@ -77,7 +77,10 @@ libswiftCore 的 builtin 段还多一类记录:编译器 builtin 叶子类型 - **降级是产品的一部分,不是失败**。`FieldResolution.unknown(<原因>)` 带着可判读的原因枚举,渲染层会把它印成 `Field offset: unknown ()`。新增一种解不出来的情形时,加原因枚举,不要让它退化成静默的 0 或跳过。 - **实参永远赢过推断**。签名挖出来的 same-type 约束、类约束参数都只是无实参时的兜底;一旦有真实实参,用实参。 - **官方离线实现不是标准答案**。RemoteInspection 的 `TypeLowering.cpp` 在几处比本模块保守或直接错(spare bits 的 XI 不结构化推导、`unowned` 的 XI 声称继承引用的计数、packs 直接拒绝)。跟运行时对不上时以**活的 value witness table** 为准,不是以那份 C++ 为准。 +- **索引的键带 private discriminator**。类型、协议、builtin 记录、assocty witness 的键与查询一律经 `LayoutTypeNaming` 取名,它让 private 声明保留 mangling 里的判别符(`(Storage in _0F2B…)`):两边都从描述符 demangle(字段类型经 symbolic reference 指向描述符),要么都带要么都不带。不带时两个文件里同名的 private 类型共用一个键,后建的覆盖先建的,一个字段被按另一个类型布局,错的偏移还标成已计算(2026-11-29 代码库体检第 1 条)。剥过符号的镜像恢复不出判别符,同一镜像里仍重名的键记进 `ImageReference.ambiguousQualifiedTypeNames`,查询报 `.ambiguousTypeName`,不再任取一个。唯一的例外是按 ObjC 运行时名建的 `swiftClassInstanceStartsByQualifiedName`:运行时名总带判别符而剥过符号的描述符不一定带,那张表照旧用不带判别符的名字。 +- **畸形二进制只降级,不崩溃**。引擎读不可信的输入:字段偏移与 size 的加法带溢出检查、单个值不超过 `BasicLayout.maximumValueSize`(48 位地址空间),超出报 `.sizeOverflow`;类的父类链按描述符记录正在计算的类,关联类型 witness 递归不超过 64 层,绕回自己报 `.cyclicLayout`;enum 的逐 case 投影不超过 `EnumLayoutCalculator.maximumProjectedCaseCount`(65,536)个 case(2026-11-29 代码库体检第 7–10 条)。 - **跨模块偏移按「这一次具体部署」算**。resilient 类的字段偏移是拿依赖的那个实际二进制算出来的,不是抽象的 ABI 契约。 +- **嵌套展开树的类型名有两份,本模块只给事实**。`NestedFieldOffset.typeName` 是 `.default` 拼写,同时是防环的键和 dump 印的文字;`typeNode` 是替换过泛型实参的节点,interface 的打印器用自己的拼写印它(C 导入类型的 Swift 名、模块选择器、`any`、语法糖),和字段声明一致(提案 [0109-consistent-c-imported-type-spelling](../Evolutions/0109-consistent-c-imported-type-spelling.md))。本模块在打印层之下,拿不到打印器,所以不要在这里换 `typeName` 的拼写。 ## 相关文档 diff --git a/Documentations/Internal/Modules/SwiftObjCInterop.md b/Documentations/Internal/Modules/SwiftObjCInterop.md index 5b6c5065d..5361d0a26 100644 --- a/Documentations/Internal/Modules/SwiftObjCInterop.md +++ b/Documentations/Internal/Modules/SwiftObjCInterop.md @@ -38,12 +38,12 @@ ### 2:`@objc @implementation` 类 -SE-0436 的 `@objc @implementation` 类编出来是纯 ObjC class object,没有 Swift 的 nominal type descriptor 与 field descriptor。`ObjCImplementationClassIndex` 联合 `__objc_classlist` 与符号表认出它们,给出 `ObjCImplementationClassFacts`:证据分 definitive 与 inferred 两档,ivar 按偏移值与 `Wvd` 符号配对,还有方法表。见 [ObjCImplementationClassRecognition.md](../ObjCImplementationClassRecognition.md)。 +SE-0436 的 `@objc @implementation` 类编出来是纯 ObjC class object,没有 Swift 的 nominal type descriptor 与 field descriptor。`ObjCImplementationClassIndex` 联合 `__objc_classlist` 与符号表认出它们,给出 `ObjCImplementationClassFacts`:证据分 definitive 与 inferred 两档,ivar 按偏移值与 `Wvd` 符号配对,还有方法表。`Wvd` 被剥掉的存储属性由 `ObjCInstanceVariableSwiftType` 从 ivar 的 encoding 或 ObjC 属性还原 Swift 类型(提案 `objc-ivar-type-recovery`)。见 [ObjCImplementationClassRecognition.md](../ObjCImplementationClassRecognition.md)。 ### 3:ObjC 协议 - **Swift 里声明的 `@objc` 协议没有协议描述符**:只有一条 kind 为 `ObjCProtocol` 的 `__swift5_fieldmd` 记录和一个 ObjC `protocol_t`,两者按名字配对。记录上的 IsSwift 标志不是证据:Swift 给它引用的别的协议也发带这个标志的副本。`SwiftDeclaredObjCProtocolIndex` 做配对;`ObjCProtocolRecord` 读 `protocol_t`,方法表、属性表与扩展类型编码按下标读整张表(MachOObjCSection 的 `extendedMethodTypes(in:)` 只返回第一条);`ObjCProtocolRequirements` 把读到的记录变成 requirement。扩展类型编码按方法在四张表里的位置一一对应,读不出的表会让后面每个方法错配到别的方法的编码上,所以 `ObjCProtocolRecord.make` 逐个核对:擦掉类名、协议名与 block 签名后要与方法表的编码相同,有一个对不上就整组不用(体检第 8 条)。 -- **类对 ObjC 协议的遵循没有 conformance record**:`class_ro_t` 列出它(同一模块里 extension 声明的遵循也折进这里),只有给别的模块的类写的 category 才另外列出。`ObjCProtocolAdoptionIndex` 读这两处。 +- **类对 ObjC 协议的遵循没有 conformance record**:`class_ro_t` 列出它(同一模块里 extension 声明的遵循也折进这里),只有给别的模块的类写的 category 才另外列出。`ObjCProtocolAdoptionIndex` 读这两处。没有 Swift 代码进入的镜像(`objc_image_info` 的 flags 第 8–15 位为 0,即 objc4 的 `containsSwift()` 为假)一个 category 都不收:它的 category 全是 ObjC 代码写的。有 Swift 的镜像照旧收下每个带协议的 category,ObjC 代码写的也在内——链接器把同一个类的 category 合成一个,名字取第一个、协议取并集,按名字或协议表都分不出是谁写的。 - 只剩 selector 的 requirement 由 `ObjCImporterNaming` 起名,再用 `@objc(selector)` 钉住 selector。 见 [SwiftDeclaredObjCProtocols.md](../SwiftDeclaredObjCProtocols.md)。 @@ -60,7 +60,7 @@ SE-0436 的 `@objc @implementation` 类编出来是纯 ObjC class object,没 ### 5:命名规则与类型编码 -`ObjCImporterNaming`(词表在 `ObjCImporterVerbs`)移植自 Swift 仓库 `lib/Basic/StringExtras.cpp` 的 `omitNeedlessWords` 与 `lib/ClangImporter/ImportName.cpp`;`ObjCTypeEncoding` 解析 ObjC 协议记录里方法与属性的类型编码,包括 Swift 发出的扩展编码(`@"NSString"`、`@""`、block 签名)。这三个文件不读 Mach-O。导入命名按 selector 的冒号数与编码的参数一一配对,所以编码必须先过 `ObjCTypeEncodingParser.methodType(from:matchingArgumentsOf:)`:参数个数对不上的编码不导入,类成员与协议要求两条路径都走它(体检第 2 条:协议要求那条路径曾漏掉这一步,个数对不上时越界崩溃)。 +`ObjCImporterNaming`(词表在 `ObjCImporterVerbs`)移植自 Swift 仓库 `lib/Basic/StringExtras.cpp` 的 `omitNeedlessWords` 与 `lib/ClangImporter/ImportName.cpp`;`ObjCTypeEncoding` 解析 ObjC 协议记录里方法与属性的类型编码,包括 Swift 发出的扩展编码(`@"NSString"`、`@""`、block 签名)。这三个文件不读 Mach-O。导入命名按 selector 的冒号数与编码的参数一一配对,所以编码必须先过 `ObjCTypeEncodingParser.methodType(from:matchingArgumentsOf:)`:参数个数对不上的编码不导入,类成员与协议要求两条路径都走它(体检第 2 条:协议要求那条路径曾漏掉这一步,个数对不上时越界崩溃)。一个类型嵌在另一个里(指针的指向、数组的元素、block 的返回与参数)不超过 `ObjCTypeEncodingParser.maximumNestingDepth`(64)层,更深的编码读不出类型:解析与之后对结果的每次遍历都按层递归,一万个 `^` 曾让 512 KB 的线程栈溢出(2026-11-29 代码库体检第 13 条)。 为类与 category 的成员,`ObjCImporterNaming` 还有三条只在那里用到的规则:返回对象的类方法、selector 开头与类名末尾对得上时按工厂方法导入成初始化器(`ImportedName.Kind.factoryInitializer`,传 `factoryInitializerClassName`);属性名经 `importedPropertyName`,`BOOL` 属性取 getter 名,开头的缩写词改小写,再按属性的规则删减(不删本类型名);error 约定只认 selector 里名为 `error` 的那一段。 @@ -73,7 +73,7 @@ SE-0436 的 `@objc @implementation` 类编出来是纯 ObjC class object,没 - `ObjCImportedMemberNodes`:方法、属性、subscript 的 demangle 树,0079 的协议要求也经它建。 - `ObjCSwiftTypeCompatibility`:按名字把 ObjC 成员配给 Swift 成员时的类型核对(提案 [0096](../../Evolutions/0096-swift-first-imported-declarations.md))。只认明显对不上的两种:对象(`@`)对实现它的模块自己定义的 struct / enum,标量对类或 existential;别的模块的值类型可能桥接(`String`、`Data`、`UTType`),不判。它也是「同名的 Swift 属性是另一个声明」的证据——头文件标了 `NS_REFINED_FOR_SWIFT` 的属性,Swift 里叫 `__name`,原名留给一个纯 Swift 的属性。`ObjCMemberShape.removingRefinedForSwiftPrefix` 去掉这个 `__`(属性名、方法基名、初始化器第一个标签)再比 selector。 - `ObjCImplementationClassFacts.objcProperty(storedIn:swiftPropertyName:)`:存储属性对应的 ObjC 属性(`V`)。`-O` 下 setter 常被内联进 thunk、不留符号,可写与否、是否 `weak` 要看它的特性串,interface 不再把这样的属性打成 `let`。 -- `ObjCImportedTypes`:编码里的类型换成 Swift 的类型树(对象是 `T!`,`NSString` 这类桥接成值类型;`r*` 即 `const char *` 是 `UnsafePointer`,`*` 是 `UnsafeMutablePointer`;C 数组照 ClangImporter 导入成元组,单元素的是元素本身,超过 4,096 个元素的导入不了、指针指向它时是 `OpaquePointer`,嵌套数组展开超过 65,536 个元素也按导入不了处理);`ObjCBridgedStructures` 记哪些类导入成值类型,`@NSCopying` 据此判断。 +- `ObjCImportedTypes`:编码里的类型换成 Swift 的类型树(对象是 `T!`,`NSString` 这类桥接成值类型;另有两个入口给 `@objc @implementation` 的存储属性用——`triviallyRepresentedTypeNode` 按「原样表示」读完整的 ivar encoding,不桥接、`id` 是 `AnyObject`,`bridgedTypeNode` 按导入规则读 `?` 的 ivar 对应的 ObjC 属性类型,两者对 block、指向结构体的指针、位域等给不出确定类型的返回 `nil`;`ObjCInstanceVariableSwiftType.ambiguity` 记下 ObjC 一侧分不开的两种声明——编译器对 `weak` 与 `unowned(unsafe)` 都写 `W`、存储都写 `?`,只读的桥接值与只读的 `unowned(unsafe)` 类(ivar 只占一个指针时)也一样——打印端照旧印常见的读法,后面用注释写出另一种(2026-11-29 代码库体检第 2 条,更正提案 0112 的一条前提);`r*` 即 `const char *` 是 `UnsafePointer`,`*` 是 `UnsafeMutablePointer`;C 数组照 ClangImporter 导入成元组,单元素的是元素本身,超过 4,096 个元素的导入不了、指针指向它时是 `OpaquePointer`,嵌套数组展开超过 65,536 个元素也按导入不了处理);`ObjCBridgedStructures` 记哪些类导入成值类型,`@NSCopying` 据此判断。 ## 关键契约 diff --git a/Documentations/Internal/Modules/SwiftSectionKit.md b/Documentations/Internal/Modules/SwiftSectionKit.md index ed27ddca0..76853b465 100644 --- a/Documentations/Internal/Modules/SwiftSectionKit.md +++ b/Documentations/Internal/Modules/SwiftSectionKit.md @@ -67,6 +67,7 @@ SwiftSectionKit 是 `swift-section` 每个子命令的库版本:一个子命 - **请求是 `Equatable` 的值**,`run` 的依赖(输出端、环境)是参数而不是字段。包装层的测试靠这一点:解析 flag → `makeRequest()` → 与期望请求比较(`CommandRequestMappingTests`)。 - **库只报告,不退出**:`ABIDiffOutcome.hasBreakingChange` 等结论由包装层对照 `--fail-on-breaking` 决定是否 `throw ExitCode.failure`。`diff --interface` 只在 `includesBreakingChangeVerdict` 时才额外算一遍 change-list diff,和原来「只有 CI 闸门需要它」的取舍一致。 - **私有声明的源文件**(`emitsPrivateDeclarationSourceFiles`,提案 [0074-private-declaration-source-files](../../Evolutions/0074-private-declaration-source-files.md)):两个请求共用 `PrivateDeclarationSourceFileRecovery`,先对整个镜像批量反推一次,再把 index 交给 dumper(`DeclarationRenderConfiguration.privateDeclarationSourceFileProvider`)或打印器(`setPrivateDeclarationSourceFileProvider(_:)`)。`interface` 用 builder 自己的索引器,在 `prepare()` 之后装上。`dump` 本来不建索引器,打开时另建一个只为让 index 读名字,并且**让它活到 dump 结束**:索引器最后一次释放会回收它 `prepare()` 建的缓存,其中就有 dump 读每一行成员的符号索引,提前放掉的话 dump 后半段要重建一遍。关着时两条路径都不建 index、不多 `prepare()`。 +- **长类型拆行**(`multilineTypeFormatting`,提案 [0102-multiline-type-formatting](../../Evolutions/0102-multiline-type-formatting.md)):两个请求都只在出口调用一次 `MultilineTypeFormatting.format(_:)`——`InterfaceRequest.run` 在 `printRoot()` 之后、写文件或交给 output 之前,`DumpSession.dump` 在拿到一个顶层声明之后;打印器与 `DumperConfiguration` 都不知道这件事。dump 的头部注释块(`InterfaceHeaderBlock`)不经过它。`MultilineTypeFormatting` 来自 `SwiftDeclarationRendering`,本模块不重新导出它:`swift-section` 与 `SwiftSectionKitTests` 各自直接依赖那个模块。默认 `nil`,产物逐字节不变。测试在 `MultilineTypeFormattingRequestTests`:打开时的产物必须等于把关闭时的产物格式化一遍。 - **命令行拼写留在包装层**:模板名还是字面模板(`TransformerTemplateResolver`)、`--transformer-config` 的 JSON 文件、逗号分隔的 `--labels` / `--sections`、`--c-type-replacement` 的 `a=b`、demangle 的二十多个覆盖开关,都由包装层解释成库的值类型(`Transformer.SwiftConfiguration`、`[ObjCPrimitiveTypePattern: String]`、`DemangleOptions`…)再交给请求。代价见下一节的偏差 2。 ## 5. 与拆分前的行为差异(只有两类) diff --git a/Documentations/Internal/Modules/SwiftSymbols.md b/Documentations/Internal/Modules/SwiftSymbols.md index 02b41f4b0..f50973444 100644 --- a/Documentations/Internal/Modules/SwiftSymbols.md +++ b/Documentations/Internal/Modules/SwiftSymbols.md @@ -29,7 +29,7 @@ SwiftSymbols 是 **Swift 符号索引**层:在 MachOKitExtensions `MachOSymbol `SymbolLanguage.swift` 定义在本模块(`SymbolLanguage+Swift.swift`),不在 MachOKitExtensions:Swift 名字怎么认归本包管(MachOKitExtensions 提案 [split-symbol-language](https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions/blob/main/Documentations/Evolutions/0004-split-symbol-language.md))。 - **识别**:`SwiftSymbolNameRecognition.recognizes` 只看名字开头的字节——`$s` `_$s` `$S` `_$S` `$e` `_$e` `_T0` `@__swiftmacro_`,以及链接器去重名 `_symbolic `、`_default assoc type `。前缀集合必须与 swift-demangling 的 `isSwiftSymbol` 一致,`SymbolTableEquivalenceTests.swiftRecognitionMatchesDemanglingIsSwiftSymbol` 在真实符号表上钉住。 -- **注册**:C target `SwiftSymbolsRegistration` 里的 `__attribute__((constructor))` 在镜像加载时调用本模块用 `@c` 导出的 `swift_symbols_register_symbol_language`,向 `SymbolLanguageRegistry.shared` 登记 `.swift`。`SwiftSymbols` 依赖这个 C target,链接 `SwiftSymbols` 就带上了 constructor,调用方什么都不用做。Swift 自己没有加载时初始化:SE-0492 的 `@section` 写进 `__mod_init_func` 在 Swift 6.4.2 上链接失败,所以用 C target。 +- **注册**:C target `SwiftSymbolsRegistration` 里的 `__attribute__((constructor))` 在镜像加载时调用本模块用 `@c` 导出的 `swift_symbols_register_symbol_language`,向 `SymbolLanguageRegistry.shared` 登记 `.swift`。`SwiftSymbols` 依赖这个 C target。SwiftPM 与 Xcode 自带的包集成整块链接每个 target,constructor 总会带上;从静态归档链接时(Tuist 的静态 framework、静态库),链接器只拉被符号引用到的成员,而 constructor 是 `static` 的,所以这个 C 文件另外导出一个什么都不做的锚点 `swift_symbols_registration_anchor`,由 `SymbolLanguage+Swift.swift` 的注册函数调用:用到 Swift 索引、或带 `-ObjC` 的链接会拉进那个 Swift 文件,它对锚点的引用再把 C 文件连同 constructor 拉进来。调用方什么都不用做;`SwiftSymbolLanguageRegistrationTests.languageFileRefersToTheRegistrationAnchor` 钉住引用的两端。Swift 自己没有加载时初始化:SE-0492 的 `@section` 写进 `__mod_init_func` 在 Swift 6.4.2 上链接失败,所以用 C target。 - **效果**:注册之后,MachOKitExtensions 的 C/C++ 索引不再收 Swift 名字,只留它们的偏移,地址落在 Swift 函数里时 `closestSymbols` 答 `nil`。`SwiftSymbolLanguageRegistrationTests` 钉住这三件事。 ## 子系统 1:索引本体 diff --git a/Documentations/Internal/ObjCImplementationClassRecognition.md b/Documentations/Internal/ObjCImplementationClassRecognition.md index e1f73c32d..7f9f5bea7 100644 --- a/Documentations/Internal/ObjCImplementationClassRecognition.md +++ b/Documentations/Internal/ObjCImplementationClassRecognition.md @@ -33,7 +33,7 @@ SE-0436 的 `@objc @implementation extension` 让 ObjC 头文件里声明的类 ## 两个 join 是怎么做的 - **ivar ↔ `Wvd` 符号**:按**偏移值**。ivar_t 的 `offset` 字段指向的就是 `Wvd` 符号命名的那个全局变量,索引读出该全局变量的值(一个 word)与 `ivar.offset(in:)` 相等即配对。之所以不按名字:即时编译的 fixture 里头文件声明的 `title` 属性其 ivar name 字段是空指针;名字只作兜底。`Wvi`(间接字段偏移)不参与,`@implementation` 类没有 field offset vector,编译器也不会给它发 `Wvi`。符号里 `variable` 节点的名字有两种形状:普通属性是 `identifier`;`private` / `fileprivate` 属性和**每个 `lazy var` 的合成存储**(编译器总把它设为 private,不管属性本身写的什么访问级别)是 `privateDeclName`(鉴别符 + 名字)。第一版只认前者,这两类 ivar 在符号齐全的二进制里也拿不到类型,打出「Swift type not recoverable」注释,对应的成员还被打成 `{ get set }` 的计算属性(2026-09-29 修复)。 -- **存储属性 ↔ 成员定义**:按 Swift 属性名。`attachObjCImplementation(_:)` 用 `ObjCImplementationClassFacts.storageInstanceVariable(forPropertyNamed:)` 把 `VariableDefinition.objcImplementationStorage` 填上,打印器据此改打存储形态;没对上的 ivar 由 `unrepresentedObjCImplementationInstanceVariables` 单独渲染,有 `Wvd` 的打 `var name: Type`,没有的打一行诚实注释。`lazy var x` 的存储名是 `$__lazy_storage_$_x`,永远对不上属性自己的名字,所以查询先按原名找、找不到再找 `lazyPropertyName == x` 的 ivar。`lazyPropertyName` 读 Swift 名,`Wvd` 被剥掉后读 ObjC ivar 名,两者拼法相同(macOS 27.0 AppKit 的 `_NSTextFormattingViewController.campoTextSuggestionsViewController` 就是后一种:访问器导出,存储的 `Wvd` 是 local 符号、被剥掉了);只靠 ObjC 名连上的存储没有 Swift 名,所以「已有成员代表」的判断除按 Swift 名外还按对象身份。渲染规则照抄 Swift 类型自己的 lazy 字段:interface 打 `lazy var x: `,没有 getter 可连时打存储类型 `Optional<…>`;dump 与 `ClassDumper` 一样打 `lazy var x: <存储类型>`。 +- **存储属性 ↔ 成员定义**:按 Swift 属性名。`attachObjCImplementation(_:)` 用 `ObjCImplementationClassFacts.storageInstanceVariable(forPropertyNamed:)` 把 `VariableDefinition.objcImplementationStorage` 填上,打印器据此改打存储形态;没对上的 ivar 由 `unrepresentedObjCImplementationInstanceVariables` 单独渲染,有 `Wvd` 的打 `var name: Type`;没有的先问 ObjC 一侧(`ObjCInstanceVariableSwiftType`,提案 `objc-ivar-type-recovery`):encoding 完整的,Swift 类型就是这个 ObjC 类型本身(编译器只给能原样表示成 ObjC 的类型写完整 encoding);encoding 是 `?` 的,Swift 类型是它的 ObjC 属性 `T` 特性的桥接形态(`NSString` → `String`);`weak` 的存储让编译器对类也写 `?`,按 ObjC 属性读、不桥接。对象类型可空性未知写 `T!`,`readonly` 写 `let`,C 基本类型按打印配置的 `cTypeReplacements` 改写。都给不出的(空 encoding、block、指向结构体的指针等)才打一行诚实注释。dump 同样打出还原的类型,注释写明来自 encoding 还是 ObjC 属性。`lazy var x` 的存储名是 `$__lazy_storage_$_x`,永远对不上属性自己的名字,所以查询先按原名找、找不到再找 `lazyPropertyName == x` 的 ivar。`lazyPropertyName` 读 Swift 名,`Wvd` 被剥掉后读 ObjC ivar 名,两者拼法相同(macOS 27.0 AppKit 的 `_NSTextFormattingViewController.campoTextSuggestionsViewController` 就是后一种:访问器导出,存储的 `Wvd` 是 local 符号、被剥掉了);只靠 ObjC 名连上的存储没有 Swift 名,所以「已有成员代表」的判断除按 Swift 名外还按对象身份。渲染规则照抄 Swift 类型自己的 lazy 字段:interface 打 `lazy var x: `,没有 getter 可连时打存储类型 `Optional<…>`;dump 与 `ClassDumper` 一样打 `lazy var x: <存储类型>`。 ## 边界与已知限制 diff --git a/Documentations/Internal/ProjectEvolutionLog.md b/Documentations/Internal/ProjectEvolutionLog.md index 7a0572fef..2f15bd50a 100644 --- a/Documentations/Internal/ProjectEvolutionLog.md +++ b/Documentations/Internal/ProjectEvolutionLog.md @@ -1271,7 +1271,7 @@ [TaskReports/2026-09-03-self-contained-abi-layer.md](TaskReports/2026-09-03-self-contained-abi-layer.md)。 - **对应版本**:0.19.0(破坏性 API 变更,见 Changelog;0.18.0 写好后未发布,内容并入 0.19.0)。 -## 2026-09-03 大栈任务执行器接入与跨版本并行(提案 large-stack-executor-and-cross-version-parallelism;节号落地时取) +## 2026-09-03 大栈任务执行器接入与跨版本并行(提案 0019 large-stack-executor-and-cross-version-parallelism) - **时间段**:2026-09-03。 - **动机**:用户问「整个库都使用 async 环境是否可行」。调研结论:这个库的 async 是签名上的 async, @@ -1294,7 +1294,7 @@ --- -## 2026-09-06 vtable 槽归属改用 method descriptor 符号(提案 vtable-slot-attribution-via-method-descriptor-symbols;节号落地时取) +## 2026-09-06 vtable 槽归属改用 method descriptor 符号(提案 0020 vtable-slot-attribution-via-method-descriptor-symbols) - **时间段**:2026-09-06。 - **动机**:用户在 Hopper 里看 `SwiftUI.GraphHost`(iOS 18.5 simruntime 的 SwiftUICore)的 vtable, @@ -3063,9 +3063,9 @@ - **验证**:在 JHs-Mac-Studio-Ultra 上用 Xcode 26.6 跑,依赖走远端版本,fixture 照 CI 的参数编。全量 `swift test --skip IntegrationTests`:合并前 2,793 个测试、531 个套件全过;与远端 `next`(第 124、125 节)合并后重跑,2,796 个测试、532 个套件全过,原始退出码都是 0(多出的是第 124 节的测试,本次没有新增);`MachOSwiftSectionCoverageInvariantTests` 在内,`__Baseline__/` 与 allowlist 零改动,宏没有发出「成员已手写」的 warning。没跑渲染 A/B:生成的存储成员与改前逐字相同,只多了遵循。 - **对应版本**:0.25.0。发版说明不必写:宏只在本库内部使用,生成的存储成员不变;三个类型多出的 `Resolvable` 遵循是增量变化。 -## 2026-11-06 SwiftDeclaration 的目录分成公开模型与索引代码两块(节号落地时取) +## 2026-11-06 SwiftDeclaration 的目录分成公开模型与索引代码两块(提案 0114 swift-declaration-model-indexing-layout) -- **时间段**:2026-11-06,分支 `refactor/swift-declaration-layout`(worktree `.worktrees/MachOSwiftSection-SwiftDeclarationLayout`,基于 `next` d5368156)。提案 [draft-swift-declaration-model-indexing-layout](../Evolutions/draft-swift-declaration-model-indexing-layout.md)(轻量档)。 +- **时间段**:2026-11-06,分支 `refactor/swift-declaration-layout`(worktree `.worktrees/MachOSwiftSection-SwiftDeclarationLayout`,基于 `next` d5368156)。提案 [0114-swift-declaration-model-indexing-layout](../Evolutions/0114-swift-declaration-model-indexing-layout.md)(轻量档)。 - **动机**:0042 整理过这个模块之后,新增的 ObjC 相关文件都放进了 `Components/Definitions/`,那里攒到 25 个文件,声明本体、成员定义、索引扩展混在一起;`Components/` 这一层不区分任何东西;三个类型藏在别人的文件里。用户要求重新整理。 - **关键决策**: - **按可见性分两棵树**(用户在三个布局里选定):`Model/` 放公开模型,`Indexing/` 放全是 `package` / `internal` 的索引代码。沿用 0042 「`Members/` 是模型、`Building/` 是索引期机器」的分界,推到整个模块;九个 `TypeDefinition+…` 与三个 `ExtensionDefinition+…` 各进一个子目录。 @@ -3074,9 +3074,9 @@ - **验证**:在 JHs-Mac-Studio 上用默认工具链(Xcode 27.2)从空 scratch 编译库与全部测试 target(`swift build --build-tests`,本地兄弟依赖),原始退出码 0,SwiftDeclaration 没有新增警告。没跑测试和渲染 A/B:没有一行代码改变,源码扫描类测试按模块名取文件、不看目录层级。 - **对应版本**:0.25.0。发版说明不必写:模块的公开 API 与输出都不变。 -## 2026-11-06 SwiftDeclaration 的类型名按角色统一后缀(节号落地时取) +## 2026-11-06 SwiftDeclaration 的类型名按角色统一后缀(提案 0115 swift-declaration-type-naming) -- **时间段**:2026-11-06,接着上一节在同一分支 `refactor/swift-declaration-layout` 上做。提案 [draft-swift-declaration-type-naming](../Evolutions/draft-swift-declaration-type-naming.md)(轻量档)。 +- **时间段**:2026-11-06,接着上一节在同一分支 `refactor/swift-declaration-layout` 上做。提案 [0115-swift-declaration-type-naming](../Evolutions/0115-swift-declaration-type-naming.md)(轻量档)。 - **动机**:目录整理之后,用户指出这个模块的类型名不成套:`Indexing/Building/` 的六个命名空间用了四种起名法,`OverrideSymbolMatcher.swift` 里没有这个类型,「声明从哪来」一个叫 `Origin` 一个叫 `Source`,`AssociatedTypeWitnessProjection` 的「Projection」只此一处。 - **关键决策**: - **命名空间按角色取后缀**(用户选定):造新东西的叫 `…Builder`(`MemberDefinitionBuilder`、`StandInMemberSymbolBuilder`、`ObjCProtocolNameBuilder`),拿二进制里另一处的证据对到已建好的成员上的叫 `…Matcher`(`ThunkAttributeMatcher`、`ObjCMemberMatcher`、`OverrideSymbolMatcher`),补回丢掉的事实的叫 `…Recovery`(`WrappedPropertyRecovery`)。 @@ -3425,6 +3425,317 @@ - **关联文档**:[Changelogs/0.26.0.md](../../Changelogs/0.26.0.md)。 - **对应版本**:0.26.0。 +## 143. Tuist 开发 workspace + +- **时间段**:2026-11-20,五个仓库同名的分支 `feature/tuist-workspace`。在 JHs-Mac-Studio 上写,在 JHs-Mac-Studio-Ultra 上构建与测试。 +- **动机**:日常开发时第三方依赖(swift-dependencies 一族、swift-syntax、Capstone……)每次清空 DerivedData 都要重编。照 RuntimeViewer 的做法加一条只供开发用的 Tuist 路:第三方依赖走本机二进制缓存,本库与五个上游库从源码编,上游库可切换为本地检出。 +- **关键决策**: + - `Package.swift` 仍是唯一定义;Tuist 拒绝的两种测试形态(依赖可执行 target、依赖不属于任何 product 的 target)由清单末尾一段只在 `TUIST_MAPS_LOCAL_PACKAGE_TESTS=1` 时生效的适配块处理,MachOKitExtensions、MachOObjCSection、swift-demangling 加同一段,本地模式下六个包都带测试;`SwiftSectionCommandTests` 与 CLI 手写在 `Tuist/CommandLine/Project.swift`。 + - Tuist 的静态 framework 链接与 SwiftPM 不同:测试与 CLI 要 `-ObjC`,只有加载期 constructor 的 `SwiftSymbolsRegistration` 要整个 `-force_load`;这些名单由 `TuistScript.sh` 读清单与源码算出,不手抄。 + - 与 RuntimeViewer 的 Tuist 本地依赖模式共用一份占用记录,两边互斥。 +- **落地模块**:`TuistScript.sh`、`Tuist.swift`、`Workspace.swift`、`mise.toml`、`Tuist/`、`Package.swift` 末尾、`.gitignore`、原生 workspace 补齐三个成员;三个上游库的 `Package.swift`;RuntimeViewer 的 `TuistScript.sh`。 +- **文档**:提案 [0099-tuist-workspace](../Evolutions/0099-tuist-workspace.md);使用指南 [TuistDevelopment.md](TuistDevelopment.md);`AGENTS.md` 构建一节;术语表两条。 +- **验证**:Ultra,Xcode 27.2。远程模式的测试 scheme 与原生 `swift test --skip IntegrationTests` 逐 bundle 对照全部通过;本地模式全量 2,943 个通过;Tuist 编的 `swift-section` 与原生编的对 SymbolTestsCore 的 `dump`、`interface` 逐字节相同;清空 DerivedData 编 CLI 不走缓存 63 秒、走缓存 46 秒。四个清单在 Xcode 26.6 下也能解析。 +- **对应版本**:0.28.0;只影响开发,不进发版产物。 + +## 144. 静态链接也带上符号语言注册 + +- **时间段**:2026-11-20,`feature/registration-link-anchor`(本库与 MachOObjCSection 同名)。 +- **动机**:Swift 与 ObjC 两种符号语言由 C 文件里的 `static` 加载期 constructor 登记(第 141 节),文件里没有别的符号。SwiftPM 与 Xcode 自带的包集成整块链接 target,constructor 总会带上;从静态归档链接的使用方(Tuist 的静态 framework、静态库)只拉被引用的成员,`-ObjC` 也不拉它,注册表就是空的。本库的 Tuist workspace 当时靠脚本给它加 `-force_load` 绕过(第 143 节),RuntimeViewer 的 Tuist workspace 漏了,用链接探针实测证实;用户要求在库里根治。 +- **关键决策**:注册用的 C 文件另外导出一个什么都不做的锚点函数,由定义该语言、注册该语言的那个 Swift 文件在注册函数里调用。那个 Swift 文件定义了 extension,带 `-ObjC` 的链接一定拉进它;本库的 Swift 索引扫描每次都用它的识别规则,用到索引也会拉进它。它对锚点的引用再把 C 文件连同 constructor 拉进来。constructor 照旧负责在任何代码查询之前完成注册。没有改成显式注册(使用方调用一个函数):那要所有使用方都记得调用。 +- **落地模块**:`Sources/Symbols/SwiftSymbolsRegistration/`(锚点与头文件)、`Sources/Symbols/SwiftSymbols/SymbolLanguage+Swift.swift`;MachOObjCSection 的 `MachOObjCSectionC/symbol_language_registration.c` 与 `SymbolLanguage+ObjectiveC.swift`。本库 `TuistScript.sh` 对带 constructor 的 target 加 `-force_load` 的通用规则保留作保险。 +- **文档**:`Modules/SwiftSymbols.md` 注册一条、`TuistDevelopment.md` 已知的坑、`AGENTS.md` 的 MachOSymbols 一条(别删那个调用)。 +- **验证**:都在 JHs-Mac-Studio-Ultra 上,Xcode 27.2。 + - `SwiftSymbolLanguageRegistrationTests` 4 个通过,含新的 `languageFileRefersToTheRegistrationAnchor`:它钉住引用的两端,因为 SwiftPM 整块链接,单元测试看不到静态归档漏掉成员。MachOObjCSection 的 `ObjectiveCSymbolLanguageTests` 5 个通过。两个库的改动用 Xcode 26.6 也编得过。 + - 静态归档链接:用 `swift build` 编出的 11 个 SwiftSymbols 目标文件打成归档,只带 `-ObjC` 链接。注册文件带锚点时 constructor 被拉进来;换回改动前的注册文件,其余不变,constructor 不在。 + - RuntimeViewer 的 Tuist workspace 改动前没有这两个 constructor,它先在清单里对 15 个链到本库的 target 加了 `-force_load`。改后 App、插件、两个注入载荷、`runtime-viewer-cli` 与 10 个测试 bundle 里都有,见它 0053 的决策日志;它跟上本库与 MachOObjCSection 的 `next` 之后,那些 `-force_load` 可以去掉。 +- **对应版本**:0.28.0。 + +## 145. 夹具套件开头由 `@FixtureSuite` 宏生成 + +- **时间段**:2026-11-20,`feature/fixture-suite-macro`。在 JHs-Mac-Studio 上写,在 JHs-MacBook-Pro 上构建与测试(Ultra 当时负载过高,按规则分流)。 +- **动机**:`MachOSwiftSectionTests` 里 170 个夹具套件开头都手抄同样的 5 行(遵循 `FixtureSuite`、`testedTypeName`、`registeredTestMethodNames`)。被测类型名抄错一个字母,覆盖率守护就静默地对不上源码里的类型。 +- **关键决策**: + - 宏实现放进只给测试用的新宏 target `SwiftSectionTestingMacros`,声明放在 `SwiftSectionTestingSupport`;生产代码用的 `SwiftSectionMacros` 插件不带测试用的宏。 + - 宏与协议同名,照 Observation 的 `Observable` 先例。被测类型名与 baseline 默认从类名推出;5 个例外用参数写明,参数只收字面量,给变量就报错,不静默退回默认值。 + - `SuiteBehaviorScanner` 按源码读被测类型名,改为同时认宏的参数与类名词干;没有宏的类照旧读静态成员。 + - `CoroFunctionPointerTests` 自己编夹具、没有 baseline,保持手写。 + - 与 [0101-swift6-mode-and-upcoming-features](../Evolutions/0101-swift6-mode-and-upcoming-features.md) 同批落地:本分支先快进合入 `next`,Swift 6 那一支合在它之上。 +- **落地模块**:`Package.swift`(宏 target 与它的测试 target)、`Sources/TestSupport/SwiftSectionTestingMacros/`、`SwiftSectionTestingSupport` 的宏声明、`SwiftSectionFixtureSupport` 的 `SuiteBehaviorScanner`、`Tests/MachOSwiftSectionTests/Fixtures/**` 下的 170 个套件、`Tests/SwiftSectionTestingMacrosTests/`、扫描器的样例与测试。 +- **文档**:提案 [0100-fixture-suite-macro](../Evolutions/0100-fixture-suite-macro.md);[FixtureTestingAndContinuousIntegration.md](FixtureTestingAndContinuousIntegration.md)「套件头由 `@FixtureSuite` 生成」一节;`AGENTS.md` 添加夹具测试的一条。没有新术语。 +- **验证**:JHs-MacBook-Pro。 + - 宏的 6 个展开测试与扫描器的 9 个测试通过。 + - `swift test --skip IntegrationTests` 里覆盖率不变式通过;另有 150 组失败,在同一台机器、同一份夹具上切到 `next` 跑同一批逐条相同,是那台机器的环境(夹具按 CI 的 ad-hoc 签名重编、与 baseline 的产物不一致,没装 iOS 26.5 模拟器运行时),不是本次引入的。 + - 合并后的构建与全量测试在与 Swift 6 那一支合并后的结果上统一跑,结果见第 146 节。 +- **对应版本**:0.28.0;只影响测试,不进发版产物。 + +## 146. MachO 系列库统一 Swift 6 语言模式并开启三项 upcoming feature + +- **时间段**:2026-11-20,六个仓库同名的分支 `feature/swift6-mode-and-upcoming-features`。在 JHs-Mac-Studio 上写,在 JHs-Mac-Studio-Ultra 上构建、测试与收尾。 +- **动机**:MachOKit(fork)还停在 swift-tools-version 5.10、Swift 5 语言模式,其余五个包早已是 Swift 6 模式、严格并发按错误执行。用户要求把整个系列迁到 Swift 6,并量一量开启 Swift 7 默认特性的改动量。 +- **关键决策**: + - MachOKit 升到 tools 6.0 进 Swift 6 模式,切换后零错误。不用 6.2:fork 的 CI 用 Swift 6.0 读清单,编译器不认识的特性名会被忽略,CI 证实了这一点。 + - 六个包的每个 Swift target 开启 `ExistentialAny`、`MemberImportVisibility`、`InferIsolatedConformances`,由清单末尾的一个循环统一追加(本库复用清单里已有的常量)。`NonisolatedNonsendingByDefault`、`InternalImportsByDefault`、`ImmutableWeakCaptures`、`StrictMemorySafety` 量过后不做。 + - 源码与测试都交给 `swift package migrate --build-system native` 改。它写的 `internal import` 改回普通 import;Swift 6.4 写出的 `any P?` 改成 Swift 6.3 也认的 `(any P)?`;直接 import `Semantic` 的文件里,裸写的 `Error` 会被 `Semantic.Error` 遮住,改写成 `Swift.Error`。 + - 与 `@FixtureSuite` 宏(第 145 节)同批落地:宏先进 `next`,本支合在其上,宏的测试补了 `SwiftSyntaxBuilder` 的 import。MachOKitExtensions 落地前 rebase 到含 C++ 类索引的 `main`,那批代码补了两个 import 与一处 `any`。 +- **落地模块**:六个包的 `Package.swift`;MachOKit 的 49 个文件与其余五个包里约 900 处补 import 与 `any`;本库预修了 `migrate` 跑不起来的 4 处硬错误。 +- **文档**:提案 [0101-swift6-mode-and-upcoming-features](../Evolutions/0101-swift6-mode-and-upcoming-features.md);MachOKitExtensions 与 MachOObjCSection 的提案索引各一行 cross-repository。不配使用指南,没有新术语,`AGENTS.md` 不加条目:漏写 `any` 或漏 import,编译器当场报错。 +- **验证**:都在 JHs-Mac-Studio-Ultra 上。 + - 六个包用 Xcode 27.2 与 26.6 都编过,含全部测试目标。MachOKit 的 fork CI 在 Xcode 16.2 与 Linux Swift 6.0.3 上通过。 + - 测试:swift-semantic-string、swift-demangling、MachOKitExtensions 全过;MachOKit(跳过 `AotCachePrintTests`)只剩基线上同样失败的 5 个环境用例;MachOObjCSection 跳过读用户本机文件的 `MachOObjCSectionTests` 类后全过,那个类在基线上同样崩溃。 + - 本库:与第 145 节合并后,Xcode 26.6 下 `swift test --skip IntegrationTests` 555 个 suite、2,915 个测试全过。渲染 A/B(三条腿,基线 `next`)84 对逐字节一致,是在合并宏之前做的;宏只改测试,没有重跑。Tuist 工作区 `warm` 与 `build` 成功。 +- **对应版本**:0.28.0;各仓库随下一次正常发版带出。 + +## 147. 交叉引用索引存得下 `__text` 之前的函数 + +- **时间段**:2026-11-20,`fix/reference-index-functions-below-text`,在 JHs-Mac-Studio-Ultra 上写与验证。 +- **动机**:RuntimeViewer 在 iOS 27 真机上给 `Preferences` 预建交叉引用索引,`CodeReferenceIndex.Builder.add` 的断言「a reference outside the image's __text」每次都触发。原因是主可执行文件的符号表把 `__mh_execute_header`(Mach header 本身,地址 0x100000000)记在 `__text` 下,函数表把它当成一个函数起点,扫描把 header 连同 load commands 当作 `__text` 之前的一个函数来读(这是有意的,见 `FunctionStartOutsideTextTests`)。索引的偏移却从 `__text` 起点算,这个函数里只要扫出一条引用就存不下:Debug 构建触发断言,Release 构建把 -0x3440 截断成 0xFFFFCBC0 存进去,查询时还原出的函数地址差 4 GiB。与 slide 无关,离线读同一个文件也一样。2026-11-19 拆分分层时修过同一个根因(读指令时下溢),但只覆盖了整表那条路;索引早一个月加进来,没跟着改。 +- **关键决策**: + - 偏移改从镜像最低的函数起点算(函数表的起点有序,取第一个;没有起点或它不低于 `__text` 时仍是 `__text` 起点),断言照留:这样一来它恒成立。 + - header 被当作代码扫出的引用本身是假的,整表那条路也有。这次不改:要不要把 `__mh_execute_header` 排除出函数起点,是 MachOKitExtensions 的事,得先查清 macOS 缓存里另外那几个起点落在 `__text` 之外的镜像是怎么回事,用户决定以后再说。 +- **落地模块**:`CrossReferenceAnalyzer.referenceIndex(ofImageAt:reportingProgress:)`、`Models/CodeReferenceIndex.swift`(注释与断言文案)。 +- **文档**:[Modules/CrossReferenceAnalysis.md](Modules/CrossReferenceAnalysis.md) 的 `CodeReferenceIndex` 一段与测试清单。没有新术语,`AGENTS.md` 不加条目。 +- **验证**:都在 JHs-Mac-Studio-Ultra 上,Xcode 27.2。 + - 新测试 `FunctionStartOutsideTextTests.anIndexKeepsTheReferencesOfAFunctionBelowText`:编一个可执行文件,在 `__text` 前的填充区写一条 `bl`。修复前触发同一条断言,进程 SIGTRAP 退出;修复后通过,索引与整表逐键相同。 + - `CrossReferenceAnalysisTests` 整个目标 124 个测试,只有 3 个失败,原因是新 worktree 里没有 `SymbolTestsCore` 夹具;链上夹具后重跑这两个套件(5 个测试)通过。 + - 没跑全量,也没做渲染 A/B:只改了交叉引用索引存偏移的起点,不碰 demangle、打印、索引器与读取层。 +- **对应版本**:0.28.0。 + +## 148. 长类型按括号拆成多行(`MultilineTypeFormatting`) + +- **时间段**:2026-11-21,`feature/multiline-type-formatting`,在 JHs-Mac-Studio-Ultra 上写与验证。 +- **动机**:RuntimeViewer 里 SwiftUI 视图的 `typealias Body = SwiftUI.ModifiedContent<…>` 印成一行几千个字符,看不出泛型的层级;dump、interface 的长成员签名同样如此。社区工具 TypeAliasFormatter 能按括号排版,但只吃纯文本,丢掉着色、链接与 region。 +- **关键决策**: + - 规则由用户在澄清提问里选定:一行放得下的类型不动;放不下的类型(最外层泛型参数列表的 `>` 落在行宽之后)整个照 TypeAliasFormatter 的结构规则拆——多参数泛型每个参数一行,单参数泛型、元组、函数类型与参数列表、`[…]` 只在里面有拆开的部分时才拆。适用于所有类型位置。 + - 做成调用方在出口调用一次的纯格式化函数,不改打印器、不加打印配置:类型来自两套打印器,公开打印入口互相调用,嵌套定义契约只允许缩进随层级变化。 + - 行宽不计行首缩进,同一个声明在任何嵌套深度拆得一样,`marksNestedDefinitions` 的契约格式化后仍成立;插入的换行与缩进沿用相邻括号或逗号的 identifier,region 不会被切断。 + - 括号只在 `.standard` 组件里认,字符串、反引号、行注释、`->` 不算;括号不配对的行(dump 的 `< infix` 运算符)原样保留。`<…>` 里写着 `where`、`A: P` 或 `==` 的是泛型签名,不按参数拆——这条是对系统 SwiftUI 实测时发现后补的。 +- **落地模块**:`SwiftDeclarationRendering`(`MultilineTypeFormatting` 与三个 internal 扩展)、`SwiftSectionKit`(`InterfaceRequest` / `DumpRequest` 的 `multilineTypeFormatting`)、`swift-section`(`MultilineTypeOptionGroup`:`--multiline-types`、`--maximum-line-width`)、`Package.swift` 与 Tuist 命令行工程的依赖。 +- **文档**:提案 [0102-multiline-type-formatting](../Evolutions/0102-multiline-type-formatting.md);术语表新增 long type / multiline type formatting;`SwiftSectionKit.md`(中英两份)、[Modules/SwiftSectionKit.md](Modules/SwiftSectionKit.md)、agent 插件的 swift-section skill、`AGENTS.md` 的模块清单。不另写实现说明:规则与取舍都在提案和类型的文档注释里。 +- **验证**:都在 JHs-Mac-Studio-Ultra 上,Xcode 26.6。 + - 定向测试全过:`MultilineTypeFormattingTests`、`MultilineTypeFormattingPreservationTests`、`NestedDefinitionRegionContractTests`(含新变体,进程内与文件两种读取器)、`MultilineTypeFormattingRequestTests`、`DumpAndInterfaceRequestTests`、`MultilineTypesFlagTests`、`CommandRequestMappingTests`、`CommandLineStreamWriteScanTests`。 + - 没跑全量:机器负载高,两次开跑都停掉了,用户决定以定向测试交付。`swift test` 没法把进程限制在指定核数——`SWT_EXPERIMENTAL_MAXIMUM_PARALLELIZATION_WIDTH` 只限同时跑几个测试,测试内部建索引照样铺满全部核。功能默认关闭、打印器未改,关闭时的输出由构造保证不变;渲染 A/B 不适用。 + - 对系统 SwiftUI 实测(debug 构建的 CLI):`dump --sections types` 23.0 秒对 23.3 秒,65,207 行变 77,333 行;`interface` 124,716 行变 145,625 行,CPU 时间多约 4 秒(这一组与别的测试同时跑,墙钟不作数)。实测时发现并修掉了 dump 泛型签名被误拆的问题。 + - `swift-section` 实跑:`--multiline-types --maximum-line-width 60` 拆开 fixture 的长字段;只给宽度时退出码 64。`claude plugin validate` 两项通过;Codex 的 `validate_plugin.py` 本机没有,未跑。 +- **对应版本**:0.28.0。RuntimeViewer 的开关与调用是它自己的后续改动。 + +## 149. 跨引用测试的整份 cache 扫描限并发,Tuist 里扫描模块在 Debug 下开优化 + +- **时间段**:2026-11-21,`feature/cross-reference-test-scan-load`,在 JHs-Mac-Studio-Ultra 上写与验证。 +- **动机**:在 Tuist workspace 里跑 Debug 测试,xctest 长时间占满 28 核:`CrossReferenceAnalysisTests` 的 124 个测试要 841 秒,xctest 累计 CPU 约 234 分钟。采样定位到两个原因:四个测试辅助函数用不设上限的 `DispatchQueue.concurrentPerform` 扫描整份 dyld cache;`-Onone` 下扫描热路径的区间循环走未特化的 `IndexingIterator.next()`,每条指令查一次元组类型元数据,28 个线程争元数据缓存的同一把锁。 +- **关键决策**: + - 测试 target 新增 `ImageScanConcurrency`:全进程共用一个 `DispatchSemaphore` 名额(`max(2, 核心数 / 2)`),每次调用最多开名额那么多个工作线程,靠共享游标取下标。名额必须全进程共用:Swift Testing 并行跑套件,按调用限宽会叠加回满核。不许嵌套调用。四处扫描改走它,`ParallelScanSourceTests` 禁止这个 target 里再直接调 `concurrentPerform`,`AGENTS.md` 加了对应条目。 + - Debug 提速只改 Tuist 开发 workspace,不改 MachOKitExtensions 源码:`Tuist/Package.swift` 让 `MachOCodeReferences`、`ARM64InstructionDecoding` 在所有配置下用 `-O`。本包 `CrossReferenceAnalysis` 保持可调试;复测时它与 `ObjCCodeReferences` 已不占显著时间,不扩大名单。原生 workspace、`swift test` 与 CI 不变。 + - 开头约 35 秒仍满核:那是 Swift Testing 自己按核心数并行跑二十多个测试,不是这四处扫描。用户决定不限制测试运行器的并行度。 +- **落地模块**:`Tests/CrossReferenceAnalysisTests`(`ImageScanConcurrency`、`ImageScanConcurrencyTests`、`ParallelScanSourceTests`,四处调用点)、`Tuist/Package.swift`。 +- **文档**:提案 [0103-cross-reference-test-scan-load](../Evolutions/0103-cross-reference-test-scan-load.md);[FixtureTestingAndContinuousIntegration.md](FixtureTestingAndContinuousIntegration.md) 新增「整份 cache 扫描共用一份并发名额」,[TuistDevelopment.md](TuistDevelopment.md) 新增「扫描模块在 Debug 下也开优化」;`AGENTS.md` 的测试规则。没有新术语,不另写实现说明。 +- **验证**:都在 JHs-Mac-Studio-Ultra 上,Xcode 27.2,Tuist workspace 的 Debug 配置。 + - `-only-testing:CrossReferenceAnalysisTests`:841 秒降到约 91–93 秒,xctest 累计 CPU 约 14 030 秒降到约 829–843 秒(约 17 倍)。 + - `MachOSwiftSection Tests` 整个 scheme:3005 个通过、0 失败、7 个跳过,634 秒。`next` 上 `SwiftSectionTestingMacrosTests` 因 `Unable to resolve module dependency: 'SwiftSectionTestingMacros'` 编不过,测量与全量时临时套用了 `feature/shared-macho-testing-support` 里 `Package.swift` 的两行修复,没有提交。 + - 不涉及打印与读取层,渲染 A/B 不适用。 +- **对应版本**:0.28.0;只改测试与开发 workspace,不影响库的发布内容。 + +## 150. 测试支持的通用部分迁入 MachOKitExtensions + +- **时间段**:2026-11-20 至 2026-11-21,两个仓库同名分支 `feature/shared-macho-testing-support`;MachOKitExtensions 一侧随 3.2.0 发布。在 JHs-Mac-Studio-Ultra 上实现与测试。 +- **动机**:MachOKitExtensions 接过 Mach-O 层以后,两个包的测试各写一套辅助并在分叉(取本机 cache、选 slice、现编 dylib、归档 cache 路径、跨读取器写法、包装读取器)。按 0003 定下的归属,`MachO` 前缀的模块归 MachOKitExtensions。 +- **关键决策**: + - MachOKitExtensions 新增 `MachOFixtureSupport`(不依赖 Testing)与 `MachOTestingSupport`(依赖 Testing)两个 product;本包两个 support target 依赖并 re-export 它们,搬走的文件删除,SymbolTests 的名字、本包命名的 cache、按本包名字的 `ExclusiveImageAccess` 初始化作为 extension 留下。 + - `MachOSwiftSectionFixtureTests` 改为 `MachOFixtureTests` 的子类;测试基类仍是「继承基类拿到镜像」的写法,`@MainActor` 照旧。 + - 486 处跨读取器调用里 478 处改成成对传入、单个闭包的重载;41 处现编改用 `FixtureCompiler`,约 66 处选 slice 改用 `HostSlice`,27 处只读本机 cache 的地方改用 `FullDyldCache.cachedHost`。 + - `.print()` 的静默开关改成运行时环境变量 `MACHO_TESTING_SILENT=1`(CI 与 Tuist 的测试 scheme 都设了)。 + - Tuist:own-remote 的包也扫描 import Testing 的 target,给 MachOKitExtensions 的 `MachOTestingSupport` 补宏插件路径;清单末尾的适配段把依赖宏 target 的测试也拿掉(0100 带来的 `SwiftSectionTestingMacrosTests` 让 Tuist workspace 编不过)。 + - 同一批里 MachOKitExtensions 还换掉了全部 `NSLock`(改用 FrameworkToolbox 的 `Mutex`,因此不再支持 Linux),并把 `Sources/` 按层分组(它的提案 0007)。 +- **落地模块**:`Package.swift`、`Sources/TestSupport/`、`Tests/` 下约 180 个测试文件、`TuistScript.sh`、`Workspace.swift`、`.github/workflows/macOS.yml`。 +- **文档**:提案 [0104-shared-macho-testing-support](../Evolutions/0104-shared-macho-testing-support.md);[FixtureTestingAndContinuousIntegration.md](FixtureTestingAndContinuousIntegration.md)「测试支持的通用部分在 MachOKitExtensions」;[TuistDevelopment.md](TuistDevelopment.md);`AGENTS.md` 的测试一节与 `Sources/` 一节。没有新术语。 +- **验证**:Ultra,Xcode 27.2。`swift test --skip IntegrationTests` 每一部分后都是 2,914 个通过、退出码 0(改动前 2,916:删 4 个随代码搬走的测试,加 2 个);所有测试 target 与可执行文件都编过;`./TuistScript.sh test` 远程模式 `TEST SUCCEEDED`(2,953 个测试),编过 MachOKitExtensions 的 `MachOTestingSupport`;MachOKitExtensions 一侧全量测试与 TSTables、Espresso 普查通过。合进 `next` 前在合并了第 149 节的结果上重跑:`swift test --skip IntegrationTests` 2,971 个通过,`./TuistScript.sh test` 远程模式 3,003 个通过、0 失败、7 个跳过,退出码都是 0。 +- **对应版本**:0.28.0;依赖 MachOKitExtensions 3.2.0。 + +## 151. 类型索引独立成 swift-type-indexing 包,并接入 MachOObjCSection 与 RuntimeViewer + +- **时间段**:2026-11-23 至 2026-11-24,六个仓库:新仓库 swift-type-indexing(`main`,0.1.0、0.1.1),swift-apinotes fork(0.3.0),swift-semantic-string(0.7.0),MachOObjCSection(0.8.209),本仓库与 RuntimeViewer 的 `feature/swift-type-indexing-package`。在 JHs-Mac-Studio 上写、在 JHs-Mac-Studio-Ultra 上编译与测试。 +- **动机**:RuntimeViewer 把 UIKit 的桥接类型显示成 `__C.UICellConfigurationState`。二进制只记 ObjC 运行时名,改名只在 SDK 的 API notes 里;本仓库已有的 `TypeIndexing` RuntimeViewer 用不上,而且 API notes 的改名规则有误。 +- **关键决策**: + - `TypeIndexing` 整体搬进独立包 swift-type-indexing,模块名不变;新包不依赖本仓库与 MachOObjCSection,补私有类归属的那一层改为协议 `DeclaredTypeNameSource`,由 MachOObjCSection 的 `ObjCTypeIndexing` 实现。本仓库只留适配层 `SwiftTypeNameResolution`(`TypeDatabaseTypeNameResolver`、`SwiftInterfaceBuilderTypeNameProvider`)。 + - 搬家同时修两处:API notes 里只有 `SwiftPrivate` 的类型加 `__` 前缀、有 `SwiftName` 的直接用它;只装 Command Line Tools 时也找得到 sourcekitd。新增 `SDKPlatform.macCatalyst`,先搜 iOSSupport。 + - MachOObjCSection 按 API notes 在头文件里标 `NS_SWIFT_NAME` / `NS_REFINED_FOR_SWIFT`;验收时两个宏改用 Xcode 的宏色,为此 swift-semantic-string 加 `SemanticType.macro`(冻结编码 22)。`swift-section objc` 加同类开关。 + - 验收时发现 SourceKitService 涨到 80 GB:每个生成的模块接口从不 `editor.close`。swift-type-indexing 0.1.1 改为读完即关、同时最多 2 个,本仓库与 RuntimeViewer 的下限都抬到 0.1.1。 +- **落地模块**:`Package.swift`(删 `TypeIndexing` target 与其测试,加 swift-type-indexing)、`Sources/Output/SwiftTypeNameResolution/`、`Sources/Executables/swift-section/`(`interface` 与 `objc interface` 的开关)、`Sources/Commands/SwiftSectionKit/`。 +- **文档**:提案 [0105-swift-type-indexing-package](../Evolutions/0105-swift-type-indexing-package.md);实现说明搬到 swift-type-indexing 的 `Documentations/Internal/TypeIndexingPipeline.md`;[SupplementaryTypeMappings.md](../SupplementaryTypeMappings.md);术语表新增「type index(类型索引)」。 +- **验证**:实现时本仓库的相关测试与夹具测试通过,RuntimeViewer Core 与应用层整套测试在 Ultra 上跑过(红的都是已知基线或满载超时,单独重跑通过)。落地验证见提案决策日志最后一行。 +- **对应版本**:0.28.0;依赖 swift-type-indexing 0.1.1、MachOObjCSection 0.8.209、swift-semantic-string 0.7.0。 + +## 152. C 导入类型的名字统一成 Swift 名,并能切换回 C 名 + +- **时间段**:2026-11-24,本仓库与 RuntimeViewer 的 `feature/c-imported-type-name-spelling`,叠在第 151 节的分支上。在 JHs-Mac-Studio 上写、在 JHs-Mac-Studio-Ultra 上编译与测试。 +- **动机**:RuntimeViewer 显示 AttributeGraph 的 `AGWeakAttribute` 时,声明行是描述符给的 Swift 名 `AnyWeakAttribute`,扩展头与成员类型却是 mangled 的 `__C.AGWeakAttribute`。 +- **关键决策**: + - 新增 `CImportedTypeNameSpelling`(`.swiftName` 默认、`.cName`):Swift 名模式让声明、成员类型与扩展头一致——解析器找得到模块就带模块,本镜像描述符改过名的写裸名;C 名模式一律照 mangling 写,不问解析器。 + - 描述符的名字只在可信时采用(`CImportedTypeSwiftNameTable.trustsUserFacingName`):ABI 名以描述符名字结尾的不信,导入成成员的类型(描述符只存 `Key`)由此退回 C 名。 + - 扩展头一并修,只动根在 `__C` 的扩展,其余逐字节不变。 + - `marksCImportedTypeNames` 在名字上标出另一种写法(注释结构的一种 kind,分隔符用 `|`,因为 swift-semantic-string 不许 kind 里有控制字符),RuntimeViewer 据此在声明行尾画可点击的标签。 +- **落地模块**:`Sources/Output/SwiftPrinting/`(`CImportedTypeNameSpelling`、`CImportedTypeSwiftNameTable`、`AnnotationRegionKind+CImportedTypeName`、`SwiftDeclarationPrinter+Headers` 等)、`Sources/Executables/swift-section/`(`--c-imported-type-name-spelling`)、`Sources/Commands/SwiftSectionKit/`、`Tests/SwiftInterfaceTests/CImportedTypeNameSpellingTests.swift`(现场编译的桥接头 dylib)。 +- **文档**:提案 [0106-c-imported-type-name-spelling](../Evolutions/0106-c-imported-type-name-spelling.md);README 与 swift-section 插件 skill;术语表新增「C-imported type name spelling(C 导入类型名拼写)」,可信规则写在那里,不另写实现说明。 +- **验证**:相关测试 43 条全过;全量 22 个目标中只有 `IntegrationTests` 报读不到本机没有的文件(`Xcode-26.3.0.app`、iOS 18.5 模拟器运行时),与基线同类。落地验证见提案决策日志最后一行。 +- **对应版本**:0.28.0。 + +## 153. 被 SDK 搬过家的 Swift 类型,按现在声明它的模块打印 + +- **时间段**:2026-11-25,本仓库与 swift-type-indexing 的 `feature/moved-swift-type-modules`。在 JHs-Mac-Studio 上写(swift-type-indexing 在本机编译测试)、在 JHs-Mac-Studio-Ultra 上编译与测试本仓库(沙盒里带 swift-type-indexing 功能分支的拷贝)。 +- **动机**:`CGFloat` 在 SDK 里由 CoreFoundation 声明,二进制里却叫 `CoreGraphics.CGFloat`;macOS 15 起约 370 个 SwiftUI 类型搬进 SwiftUICore,二进制仍写 `SwiftUI.View`。原因是 `@_originallyDefinedIn` 让 mangling 永远用旧模块。interface 照 ABI 印出的名字能编过,但和 SDK 对不上。 +- **关键决策**: + - 搬家记录来自 SDK 的文本 `.swiftinterface`(扫描全部模块、只看第 0 列),不经 sourcekitd:sourcekitd 的接口不留属性,也只覆盖二进制直接链接的模块。 + - 是否改写看二进制编译所用的 SDK 版本,按平台取搬家版本(Catalyst 回退 iOS,visionOS 换算 iOS 版本),macOS 14 的 SwiftUI 不改。 + - 打印器新角色 `MovedTypeModuleResolving`,按最外层类型提问,嵌套类型、模块选择器与扩展头都跟着最外层;`__C` 永不参与。 + - 独立开关 `interface --resolve-moved-type-modules`,默认关闭(输出会随宿主 SDK 变化);与 `--resolve-c-module-names` 同开时共用一个 provider 与一个数据库(`SDKTypeNameResolutions`)。dump、diff、snapshot、evolution 不改。 +- **落地模块**:swift-type-indexing 的 `MovedTypeIndex`、`TypeDatabase.declaringModuleName(ofMovedTypeNamed:originallyDefinedIn:builtAgainst:)`;本仓库 `Sources/Output/SwiftPrinting/`(`MovedTypeModuleResolving`、`NodePrintable`、`TypeNodePrintable`、`SwiftDeclarationPrinter+Headers`)、`Sources/Output/SwiftTypeNameResolution/`(`TypeDatabaseMovedTypeModuleResolver`、`SDKTypeNameResolutions`)、`Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift`、`Sources/Executables/swift-section/Commands/InterfaceCommand.swift`。 +- **文档**:提案 [0107-moved-swift-type-modules](../Evolutions/0107-moved-swift-type-modules.md);术语表新增「moved type」;swift-type-indexing 的 `TypeIndexingPipeline.md` 新增「搬家记录」一节;插件 skill 与 `Modules/SwiftInterface.md`。 +- **验证**:Ultra(Xcode 26.6)全量 `swift test --skip IntegrationTests` 2969 个测试全过;TipKit 与 DeveloperToolsSupport 在 macOS 27.2 与 14.6 cache 上的前后对比见提案决策日志。 +- **对应版本**:0.28.0;依赖 swift-type-indexing 0.2.0(2026-11-25 发版)。 + +## 154. 私有 CF 类型按导出 `GetTypeID` 的镜像解析所属模块 + +- **时间段**:2026-11-25,本仓库的 `feature/private-cf-type-modules`。在 JHs-Mac-Studio 上写,在 JHs-Mac-Studio-Ultra 上编译、测试与对系统镜像做前后对照。 +- **动机**:`interface --resolve-c-module-names` 只认得 SDK 里有头文件的 C 导入类型;私有 CF 类型(`CGSVGDocumentRef`、`AGGraphRef`、`RIO…Ref`)在 0106 之后只印描述符给的裸名,看不出属于哪个框架。macOS 27.2 的 cache 里 Swift 用到 66 个 CF 类,20 个是私有的。 +- **关键决策**: + - 模块按「哪个镜像导出 `<名字>GetTypeID`」定:46 个公开 CF 类验证全对。只读根镜像与直接依赖。 + - 走 swift-type-indexing 现成的 `DeclaredTypeNameSource` 注册表,不另写打印器解析器;打印器、swift-type-indexing、CLI 参数都不改。 + - `TypeDatabase` 按镜像路径去重、静默丢掉第二个来源,所以一个依赖的 ObjC 名字与 CF 类型合成一个 `ImageDeclaredTypeNames`。 + - `GetTypeID` 只负责定位;「是不是 CF 类型」由根镜像的 foreign class 描述符(C 导入、从 C typedef 升格来的 class)决定,挡掉 `CFRef` 这类非类型名字与同名的 `swift_wrapper` typedef。 +- **落地模块**:`Sources/Output/SwiftTypeNameResolution/`(`CFDeclaredTypeNames`、`ImageDeclaredTypeNames`、`SwiftInterfaceBuilderTypeNameProvider.declaredTypeNameSources(root:dependencies:)` 与 `cfTypedefNames(referencedBy:)`)、`Sources/Executables/swift-section/Commands/InterfaceCommand.swift` 的帮助文字。 +- **文档**:提案 [0108-private-cf-type-modules](../Evolutions/0108-private-cf-type-modules.md);插件 skill 第 8 节;`AGENTS.md` 的 SwiftTypeNameResolution 一条。没有新术语,不另写使用指南或实现说明。 +- **验证**:Ultra(Xcode 26.6)全量 `swift test --skip IntegrationTests` 2978 个测试全过;两条回归测试(去重、foreign 描述符闸门)都先红后绿。macOS 27.2 系统镜像前后对照:SwiftUICore 300 行、AppKit 16 行、RealityIO 976 行变化,全是私有 CF 类型带上了模块,耗时测不出变化。 +- **对应版本**:0.28.0。RuntimeViewer 发版后接入(把 `ObjCDeclaredTypeNames` 换成 `ImageDeclaredTypeNames`)。 + +## 155. C 导入类型的拼写补齐:同名类型去掉 `__C`,布局注释跟着打印器的拼写 + +- **时间段**:2026-11-25,本仓库的 `feature/consistent-c-imported-type-spelling`,在 JHs-Mac-Studio-Ultra 上写、编译与测试。 +- **动机**:打 macOS 27.2 的 AttributeGraph(显示 C 导入类型、模块选择器、展开字段偏移)时,同一个类型写法混用:`struct AGDescriptionOption {` 的扩展头是 `extension __C::AGDescriptionOption`;`var base: AnyWeakAttribute` 下面的注释写 `identifier (__C.AGAttribute)`,也不带 `::`。 +- **关键决策**: + - 名字表收「没有 ABI 名」的描述符:编译器只在 Swift 名与 C 名不同时才写 ABI 名(IRGen `computeIdentity`),所以这样的描述符证明两个名字是同一个。只收直接位于 `__C` / `__C_Synthesized` 的、非相关实体的;import info 读不出来的不收。 + - 本镜像没有描述符的类型(只在签名里出现、没人要它的 metadata)照旧写 `__C::`。查别的镜像的描述符(`AGSubgraphRef` 在 SwiftUICore 里记作 `Subgraph`)另开提案。改了名但不可信的(`AGTreeValue` → `TreeValue`)不动。 + - 展开字段偏移树的行存类型节点,interface 打印器经自己的 `typeDemangleResolver` 印它,与字段声明同拼写(C 名开关、模块选择器、`any`、语法糖、私有类型不带判别符);dump 不打开开关,照旧 `.default`。离线与进程内两条后端一起改,进程内的全进程缓存行也带节点,渲染时不再 demangle。 +- **落地模块**:`Sources/Output/SwiftPrinting/`(`CImportedTypeSwiftNameTable.knownSwiftName(ofDescriptorNamed:importInfo:isDirectlyInImportedModule:)`、`SwiftDeclarationPrinter+Headers` 打开开关)、`Sources/Output/SwiftDeclarationRendering/`(`DeclarationRenderConfiguration.fieldLayoutTypeName(printedName:typeNode:)`、两条后端改成异步渲染、`NestedFieldOffsetLevel` 带节点)、`Sources/Analysis/SwiftLayout/NestedFieldOffsetTree.swift`(`NestedFieldOffset.typeNode`)、`swift-section interface --c-imported-type-name-spelling` 的帮助文字。 +- **文档**:提案 [0109-consistent-c-imported-type-spelling](../Evolutions/0109-consistent-c-imported-type-spelling.md);术语表「C-imported type name spelling」;插件 skill 第 8 节;SwiftLayout 模块文档的关键契约、[FieldLayoutRendererReaderSpecialization.md](FieldLayoutRendererReaderSpecialization.md)。 +- **顺带发现**:符号索引的建索引死锁(同一镜像 15 个以上并发建索引时占满大栈线程池),`next` 上就有,记在提案后续项,没在本分支修。 +- **验证**:Ultra(Xcode 26.6)全量 `swift test --skip IntegrationTests` 2997 个测试,只有已知的负载偶发 `BoundedConcurrentMapTests` 一条超时,单独重跑全过;每步的行为测试先红后绿。macOS 27.2 的 AttributeGraph 前后对照 `__C` 从 73 处降到 60 处;SwiftUICore 打开展开字段偏移的 interface 慢 4%(7.10 → 7.39 秒),进程内缓存多占约 2.1 MB([ReviewAdjudications](ReviewAdjudications.md) A91)。 +- **对应版本**:0.28.0。 + +## 156. IntegrationTests 的演进套件合并:Swift 与 ObjC 共用一套版本轴 + +- **时间段**:2026-11-26,本仓库的 `feature/unify-evolution-integration-suites`。在 JHs-Mac-Studio 上写,在 JHs-Mac-Studio-Ultra 上编译。 +- **动机**:IntegrationTests 的四套演进手检套件(Swift 报告、Swift 联合接口、ObjC 报告、ObjC 联合头文件)各自把同几条版本轴再定义一遍:SwiftUI 加 SwiftUICore 的两条轴各写了四次,51 份归档 cache 的清单挂在 Swift 接口套件上、别的套件去借它的类属性,ObjC 侧为了把 `__swift5_*` 换成 `__objc_*` 多出一层基类;四条管线又各把单镜像与镜像组写两遍。两个 Swift 侧 `DyldCacheTests` 的注释写着读 AppKit,实际读的是 SwiftUI。 +- **关键决策**: + - 一个套件实例为 Swift 与 ObjC 各存一条轴,按镜像带不带该语言的元数据筛版本,主镜像不带的版本不上这条轴。 + - 单镜像与镜像组仍走构建器的两个入口(`comparesImageGroups`):镜像组入口给版本描述写镜像名、不带 provenance,一律走它会改变输出。 + - 每种输出保留一对显式的一行测试,不用参数化测试:51 版归档轴一点就跑全部管线要几个小时。 + - 默认三版本轴上 Swift 一侧沿用实际读的 SwiftUI、ObjC 一侧沿用 AppKit,拆成两个套件,改正过时的注释。原有 43 个「轴 × 输出」组合与输出文件名不变,只改测试名。 +- **落地模块**:`Tests/IntegrationTests/Evolution/`(`EvolutionAxis.swift`、`EvolutionDumpTests.swift`、`EvolutionTests.swift`)与 `SwiftInterfaceTestSupport.swift` 的 `write(_:forImageGroup:)`;删去 `SwiftDiffing/ABIEvolutionTests.swift`、`SwiftInterface/SwiftEvolutionInterfaceBuilderTests.swift`、`ObjCDiffing/ObjCAPIEvolutionTests.swift`。 +- **文档**:提案 [0110-unify-evolution-integration-suites](../Evolutions/0110-unify-evolution-integration-suites.md);[ABIEvolutionDesign.md](ABIEvolutionDesign.md) 的集成套件一段。没有新术语,不另写使用指南或实现说明。 +- **验证**:只编译、没运行(IntegrationTests 不让 agent 跑):Ultra 上 Xcode 26.6 与 27.2 的 `swift build --build-tests` 都通过。改前改后的输出是否逐字一致,待维护者挑一条轴比对。 +- **对应版本**:0.28.0(只改测试目标)。 + +## 157. IntegrationTests 的 diff 与接口套件合并:三类手检输出共用一套骨架 + +- **时间段**:2026-11-26,本仓库的 `feature/unify-diff-and-interface-integration-suites`。在 JHs-Mac-Studio 上写,在 JHs-Mac-Studio-Ultra 上编译。 +- **动机**:0110 合并演进套件之后,单版本接口与两版本 diff 两类手检套件还各写各的。diff 自带三个「新旧两版」基类,读 cache 只开主文件,和演进套件、CLI 都不一样,`DyldCacheTests` 的注释写 SwiftUI、实际读 AppKit;接口套件为了开一个「只印导出声明」把整份配置抄了一遍,还用 `machO is MachOImage` 判读取器;两类都只出 Swift,AppKit 的 ObjC 部分只有演进套件看得到。 +- **关键决策**: + - 三类输出进同一个目录 `Tests/IntegrationTests/InspectionDumps/`,共用 `InspectionDumpTests`:输出目录、索引配置、计时、`DumpOutput` 与 `deliver`、泛型的 `preparedObjCIndexer`。 + - diff 与演进共用版本轴:diff 读轴上首尾两个版本的主镜像;cache 对改用 `MultiVersionDyldCacheImageTests`,整份打开;模拟器与 Xcode 两个两版基类搬进轴文件、各自给出轴;轴类型去掉 `Evolution` 前缀。 + - 单版本接口不走版本轴:它要读进程内的 `MachOImage`,而轴与演进构建器只收 `MachOFile`。 + - 每类一个输出种类枚举加一个 `dump` 入口。AppKit 的接口套件加整镜像的 ObjC 头文件(`objc dump` 的管线,四种注释全开),AppKit 的 diff 套件加 ObjC 变更列表与 JSON,Swift diff 报告加 JSON。套件类名保留(它们是维护者临时改读别的镜像的探针),测试名改成「种类 + 去向」;接口 14 个、diff 24 个,演进 43 个不变。 +- **落地模块**:`Tests/IntegrationTests/InspectionDumps/`(`InspectionDumpTests.swift`、`VersionAxis.swift`、`InterfaceDumpTests.swift`、`InterfaceTests.swift`、`DiffDumpTests.swift`、`DiffTests.swift`,以及从 `Evolution/` 移来的 `EvolutionDumpTests.swift`、`EvolutionTests.swift`);`Package.swift` 给 IntegrationTests 加 `ObjCDeclarationRendering`。删去 `SwiftInterface/SwiftInterfaceBuilderTests.swift`、`SwiftInterface/SwiftDiffableInterfaceBuilderTests.swift`,`SwiftInterface/SwiftInterfaceTestSupport.swift` 移成 `InspectionDumpTests.swift`。 +- **文档**:提案 [0111-unify-diff-and-interface-integration-suites](../Evolutions/0111-unify-diff-and-interface-integration-suites.md);[ABIEvolutionDesign.md](ABIEvolutionDesign.md) 的集成套件一段改了目录。没有新术语,不另写使用指南或实现说明。 +- **验证**:只编译、没运行(IntegrationTests 不让 agent 跑):Ultra 上 Xcode 26.6 与 27.2 的 `swift build --build-tests` 都通过,新文件没有警告。diff 的 cache 对改为整份打开,输出可能与改前不同;改前改后的比对待维护者做。维护者在接口套件里未提交的实验(读 AttributeGraph、显示 C 导入类型、类型名解析)落地前先单独提交,合并时按新结构处理,只留在历史里。 +- **对应版本**:0.28.0(只改测试目标)。 + +## 158. `@objc @implementation` 只剩 ivar 的存储属性按 ObjC 类型还原 Swift 类型 + +- **时间段**:2026-11-26,本仓库的 `feature/objc-ivar-type-recovery`。在 JHs-Mac-Studio 上写,在 JHs-Mac-Studio-Ultra 上编译和测试。 +- **动机**:RuntimeViewer 看 Mac Catalyst 的 UIKitCore,`_UISplitViewControllerAdaptiveLayoutTransition` 的 24 个存储属性在 Swift 接口里全是「Swift type not recoverable」注释,而 ObjC 头文件一侧已经显示出其中 12 个的类型。 +- **关键决策**: + - 按编译器写 ivar encoding 的规则(IRGen `buildIvar`)分流:完整 encoding 只写给能原样表示成 ObjC 的类型,所以就是 Swift 类型本身,不桥接、`id` 是 `AnyObject`;`?` 是桥接类型,读 ObjC 属性的 `T` 特性按导入规则还原,只认桥接表里的类与裸 `id`(`unowned` 的存储也写 `?`);`weak` 的存储对类也写 `?`,读属性、不桥接,写 `T?`;空 encoding 仍是注释。 + - 对象可空性未知写 `T!`,`readonly` 写 `let`;block、指向结构体的指针、位域、无名结构体还原不出。`NS_ENUM` 的 `q`、`^v`、`#` 之类的同码异型照导入规则打,与 ObjC 一侧一致。 + - C 基本类型可按 `SwiftDeclarationPrintConfiguration.cTypeReplacements` 改写(`double` → `CGFloat`),调用方用 `applyTransformers(_: Transformer.ObjCConfiguration)` 把 ObjC 一侧的 C Type Replacement 交进来;只换类型本身。 +- **落地模块**:`SwiftObjCInterop`(新增 `ObjCInstanceVariableSwiftType`,`ObjCImportedTypes` 加 `triviallyRepresentedTypeNode` / `bridgedTypeNode` / `Position.weakStorage`)、`SwiftPrinting`(还原的声明、`cTypeReplacements`,新依赖 `ObjCOutputTransformer`)、`SwiftDump`(ivar 行与来源注释);夹具 `ObjCImplementationFixture` 加 `AdaptiveTransitionWidget`。 +- **文档**:提案 [0112-objc-ivar-type-recovery](../Evolutions/0112-objc-ivar-type-recovery.md);[ObjCImplementationClassRecognition.md](ObjCImplementationClassRecognition.md) 与 [Modules/SwiftObjCInterop.md](Modules/SwiftObjCInterop.md) 补了还原规则。没有新术语,不另写使用指南。 +- **验证**:Ultra 上相关的五个套件全过;整套测试的失败全是构建槽位检出里缺 `SymbolTestsCore` fixture,没有别的原因。 +- **对应版本**:0.28.0。RuntimeViewer 抬依赖并把 ObjC 的 C 类型替换交给 Swift 打印之后,App 里才看得到 `CGFloat` 一类的替换。 + +## 159. IntegrationTests 手检套件按来源分,框架交给具名配置 + +- **时间段**:2026-11-26,本仓库的 `feature/source-based-inspection-dump-suites`。在 JHs-Mac-Studio 上写,在 JHs-Mac-Studio-Ultra 上编译。0111 的后续,按用户要求直接做、不写提案。 +- **动机**:0111 之后,手检套件的类型名还是很长(`EvolutionTestSuite.SwiftUIImageGroupArchivedDyldCacheTests`),而且按框架开套件:同一种版本来源,SwiftUI、AppKit、镜像组各一个类,测试在每个类里重写一遍。 +- **关键决策**: + - 套件只按版本或镜像的来源分,挂在三个短命名空间下:`Interface.SystemCache` / `ArchivedCache` / `File` / `InProcessImage` / `XcodeFile`,`Diff.SimulatorFiles` / `Caches` / `ArchivedCaches` / `XcodeFrameworks`,`Evolution.Caches` / `ArchivedCaches` / `SimulatorFiles`。不写限定某个框架的套件。 + - 读哪个框架交给具名配置:`CacheImagesConfiguration`(`.swiftUI`、`.swiftUICore`、`.appKit`、`.swiftUIGroup`、`.appKitGroup`;列多个镜像就是镜像组,不再单开套件)、`SimulatorFilePairConfiguration`(`.swiftUICore`、`.swiftUI`)、`XcodeFrameworkPairConfiguration`(`.dvtProductsUI`)。三个轴基类各读一个 `configuration` 类属性,原来的 `cacheImageName(s)`、`oldFileName` 一类属性删掉。接口套件的镜像本来就是基类的一个类属性,照旧。要看别的框架,加一份配置、把套件指过去。 + - 每个套件把这一类的输出各写一遍,Swift 与 ObjC 都写:接口 20 个、diff 24 个、演进 25 个测试;测试函数名与输出文件名不变。默认配置取覆盖面最广的:演进的两个 cache 套件读 SwiftUI 加 SwiftUICore,diff 与接口的 cache 套件读 AppKit。AppKit 的演进、SwiftUI 的模拟器 diff 不再默认跑,要看时改配置。 + - pack 门面那个测试改成取前三个版本、不足三个时打印一行说明;配置是镜像组时,它只印各版本的主镜像,不再与 `swiftInterfaceString` 逐字相同。 +- **落地模块**:`Tests/IntegrationTests/InspectionDumps/`:`InterfaceTests.swift`、`DiffTests.swift`、`EvolutionTests.swift`;原来的 `VersionAxis.swift` 按职责拆成五个文件——`VersionAxis.swift`(轴的值类型)、`VersionAxisDumpTests.swift`(协议与共享的 ObjC 快照)、`MultiVersionDyldCacheImageTests.swift`、`CrossVersionMachOFileTests.swift`、`CrossVersionXcodeFrameworkTests.swift`(每个轴基类与它的配置类型一个文件)。 +- **文档**:[ABIEvolutionDesign.md](ABIEvolutionDesign.md) 的集成套件一段改用新的套件与配置名。没有新术语,不另写使用指南或实现说明;提案 0111 是落地时的快照,不改。 +- **验证**:只编译、没运行(IntegrationTests 不让 agent 跑):Ultra 上 Xcode 26.6 与 27.2 的 `swift build --build-tests`。 +- **对应版本**:0.28.0(只改测试目标)。 + +## 160. 交叉引用召回补漏:按 Swift 类型查询、GOT 槽地址、selector 引用、ivar 读法与取函数地址 + +- **时间段**:2026-11-26,四个仓库的 `feature/cross-reference-recall-gaps`(MachOKitExtensions、MachOObjCSection、本仓库、RuntimeViewer)。在 JHs-Mac-Studio 上写,在 JHs-Mac-Studio-Ultra 上编译测试。提案 [0113](../Evolutions/0113-cross-reference-recall-gaps.md),愿景《[不依赖 IDA 的逆向](../Visions/ReverseEngineeringWithoutIDA.md)》第 1 阶段的补漏。 +- **动机**:0097 落地时没有做全面核对。按 2026-11-18 的方法(Finder 26.5.2 与 ControlCenter 26.7,120 个目标,独立生成的标准答案)补测,`swift-section refs` 0.25.0 找到 527 条代码引用里的 476 条(90.3%),IDA 一次查询 97.0%。 +- **关键决策**: + - CLI 加 `refs --type `(也收 `$s…Mn` / `$s…Ma` / `$s…N` 符号)与 `--type-image`,照 RuntimeViewer 按类型查引用的那条路;只收准确的 mangling,不收点分名字——mangling 会对重复的词做替换。 + - 核心层:`adrp; add` 或 `adr` 算出的地址落在引用槽(GOT、classref、cache 共用 GOT 池)或会话观察的槽(ivar 偏移变量、superref、selref)上时,就在这条指令上记,寄存器带「已记过」的位,之后零位移的载入不重记。前者补上优化 Swift 代码交给元数据访问器的类 GOT 槽,后者补上两条路径各算一个 ivar 地址、在载入处汇合的情况。 + - 取函数地址记成对函数的引用(`--function` 与调用层级因此穿过 block 与闭包);会话协议加 `leaveFunction()`。 + - ObjC 层:从 `__objc_selrefs` 载入、没用来发送的 selector 记成 `CodeReferenceTarget.selector`,归在 selector 的表键下;cache 里的镜像因构建器改写了 selref 载入而没有,记为后续项。 + - `__objc_superrefs` 的载入仍不算类引用(0097 的理由不变),是剩下的 13 条漏报。 + - 测量脚本收进 `Scripts/CrossReferenceRecall/`,从当次对话记录取回后按完整命名改写,复现核对通过。 +- **落地模块**:MachOKitExtensions 的 `MachOCodeReferences`(`ReferenceScanner`、`RegisterFile`、`CodeReferenceRecognition`);MachOObjCSection 的 `ObjCCodeReferences`;本仓库的 `CrossReferenceAnalysis`(`CodeReferenceTarget.selector`、`ReferenceCollector`、`CodeReferenceIndex`、符号化)、`SwiftSectionKit`(`CrossReferenceSubject.swiftType`)、`swift-section refs`;RuntimeViewer 的 `CrossReferenceQuery`(三处 switch,暂不显示 selector 引用)。 +- **文档**:[Modules/CrossReferenceAnalysis.md](Modules/CrossReferenceAnalysis.md)(引用种类、类引用、吞吐、测试锚点)、MachOKitExtensions 的 `MachOCodeReferences.md`、MachOObjCSection 的 `ObjCCodeReferences.md`、CLI 的 skill 与 README、愿景的复测段;术语表登记「selector 引用」。不另写使用指南或实现说明。 +- **验证**:同一组样本 514/527(97.5%),多报 0;吞吐(release,与三个仓库的 `next` 交替)整表慢 1.9%,两条调用者查询慢 1.9% 与 2.4%;三个库的全量测试与 RuntimeViewer 交叉引用模块,失败的几条在 `next` 上同样失败;本仓库合并时带进了 0112,在合并结果上重跑全量测试(跳过 IntegrationTests)全部通过。 +- **对应版本**:0.28.0(依赖 MachOKitExtensions 3.4.0、MachOObjCSection 0.10.102)。 + +## 2026-11-27 没有 Swift 的镜像不再把 category 打成遵循 + +- **时间段**:2026-11-27,`fix/objc-written-category-conformances`。在 JHs-Mac-Studio 上写,在 JHs-Mac-Studio-Ultra 上编译测试。 +- **动机**:RuntimeViewer 打开 OS X 10.9.5 的 AppKit(磁盘上的文件,没有任何 Swift),Swift 一栏列出 `__C.NSAttributedString`、`__C.NSFileVersion`、`__C.NSString`、`__C.NSURL` 四个 conformance。来源是 0079:`ObjCProtocolAdoptionIndex` 收下镜像里每个带协议的 category,当成 extension 别的模块的类时生成的,没区分 ObjC 代码写的。`dump` 的 `protocolConformances` 段、`interface` 的 `extension X: P {}` 与 RuntimeViewer 读的是同一份。 +- **关键决策**: + - 看 `objc_image_info`:flags 第 8–15 位为 0(objc4 的 `containsSwift()` 为假)就一个 category 都不收。两个读取器各加 `containsSwift()`;没有 `__objc_imageinfo` 时照旧全收。 + - 先试过按 category 名过滤(Swift 默认取模块名,同一个类第二个起加序号),没有采用:链接器把同一个类的 category 合成一个,名字取第一个、协议取并集,AppKit 27.2 的 `NSString (AppKit)` 带着 ObjC 头文件声明的 `NSPasteboardWriting`、`NSPasteboardReading`,SwiftUICore 的 `NSObject (CoreAX)` 名字是 ObjC 的却含 Swift 成员;描述符里的模块名又是 ABI 名(SwiftUICore 的是 `SwiftUI`),category 用的是真实名。用户定了先只修没有 Swift 的镜像,有 Swift 的镜像维持原样。 + - 同类排查:另外两处遍历 category 的(`ObjCClassMethodIndex` 的方法表、`ObjCImportedContainerIndex` 的 ObjC 导入声明)本来就该看全部 category,不动。 +- **落地模块**:SwiftObjCInterop(`ObjCImplementationClassReading.containsSwift()`、`ObjCImageInfo.containsSwift`、`ObjCProtocolAdoptionIndex`),SwiftSectionTestingSupport(`ObjCWrittenCategoriesFixture`)。 +- **文档**:[SwiftDeclaredObjCProtocols.md](SwiftDeclaredObjCProtocols.md)(数据来源、已知局限、验证)、[Modules/SwiftObjCInterop.md](Modules/SwiftObjCInterop.md)、CLI skill 的输出说明。 +- **验证**(JHs-Mac-Studio-Ultra,macOS 27.2.1,Xcode 27.2,本地依赖):`ObjCWrittenCategoryConformanceTests` 修复前没有 Swift 的镜像两条红(文件与进程内)、混编镜像两条绿,修复后四条全绿。全量 `swift test --skip IntegrationTests` 没有进程崩溃,1258 处失败全部是构建槽位里没有 SymbolTestsCore / SymbolTestsHelper 夹具(已知环境缺口);现编夹具的 ObjC 相关套件(`ObjCProtocolDefinitionIndexingTests`、`SwiftDeclaredObjCProtocol*`、`CustomObjCClassName*`、`ClassesWithoutClassObjects*`、`ObjCMemberDumpTests`)都通过。`interface` 修复前后对比(同机系统缓存,基线是只含测试提交的同一分支):BaseBoard、ViewBridge、FuseBoard、RunningBoardServices、FrontBoardServices 的 9、7、4、3、2 个空 `extension __C.X: P {}` 全部消失,别无差异;AppKit 与 SwiftUICore 输出逐字节相同。 +- **后续**:有 Swift 的镜像里分开 ObjC 代码写的 category 遵循,要逐个协议看实现其要求的方法是不是 Swift 的(符号或 thunk)。 +- **对应版本**:0.28.0。 + +## 2026-11-29 代码库体检的十二条修复 + +- **时间段**:2026-11-29,`fix/codebase-audit-2026-11-29`。在 JHs-Mac-Studio-Ultra 上写、编译、测试。体检报告 [CodebaseAudit20261129](Reviews/CodebaseAudits/CodebaseAudit20261129.md)。 +- **动机**:第二轮体检(改动集加轮转深审 `SwiftInspection`、`SwiftSpecialization`、`SwiftLayout`)确认十条严重 bug、四条待确认。用户批准全修,待确认的四条先写复现测试、能变红的才修。 +- **关键决策**: + - 第 1 条(同名 private 类型布局撞键)只在 `SwiftLayout` 内带上 private discriminator(`LayoutTypeNaming`),不改全局的 `NodeTypeNaming.nominalQualifiedName`:ObjC 运行时名总带判别符,剥过符号的描述符不一定带,全局换会让 ObjC 一侧的查找反而落空。恢复不出判别符时同一镜像里重名的键标为歧义(新失败原因 `.ambiguousTypeName`),不任取一个。 + - 第 2 条(`unowned` 印成 `weak`):编译器对 `weak` 与 `unowned(unsafe)` 都写 `W`、存储都写 `?`,二进制里分不开,照实标注另一种读法;有访问器符号、知道类型时按是否 `Optional` 分。顺带更正提案 0112 的一条前提。 + - 第 6–10 条(畸形二进制)在底层统一设上限:ABI 层的 `ContextDescriptorParentChain.maximumLength`(256)给六处父链循环共用,`GenericContext` 读父级时只读父级自己的参数;布局的加法带溢出检查(新失败原因 `.sizeOverflow`);类的父类链按描述符防环;关联类型 witness 递归限 64 层;enum 逐 case 投影限 65,536 个;`getEnumTagCounts` 照 C++ 的无符号回绕。 + - 第 12 条(新同步入口持锁 demangle)与第 14 条(锁内派发事件)造不出能变红的测试,按约定不修。 + - 测试支持新增 `CompiledFixtureCopies`(剥符号的拷贝、改写字节的拷贝),每份拷贝换一个新 `LC_UUID`:库的按镜像缓存按 UUID 认文件,拷贝与原库同 UUID 时并行测试会串用对方的索引(全量里实测撞上过)。 +- **落地模块**:`MachOSwiftSection`(`ContextDescriptorParentChain`、`MachOSwiftSectionError.parentChainTooLong`、`GenericContext`、`getEnumTagCounts`)、`SwiftInspection`(`NodeTypeNaming` 的判别符选项、`GenericParameterDepthLayout`、`EnumLayoutCalculator.maximumProjectedCaseCount`)、`SwiftLayout`(`LayoutTypeNaming`、`ImageReference` 的歧义名、`ImageUniverse`、`BasicLayout` 的溢出检查、解析器的两处防环)、`SwiftObjCInterop`(`ObjCInstanceVariableSwiftType.ambiguity`、`ObjCTypeEncodingParser.maximumNestingDepth`)、`CrossReferenceAnalysis`(文件模式认导入的运行时入口、槽目标、protocol 引用与 C 字符串的映射检查)、`SwiftSectionKit`(`symbolicate --in-image`)、`SwiftPrinting` 与 `SwiftDump`(ivar 的歧义注释、`unowned(unsafe)`)、`SwiftDeclaration` 与 `SwiftIndexing`(父链上限)、测试支持。 +- **文档**:[Modules/SwiftLayout.md](Modules/SwiftLayout.md)、[Modules/CrossReferenceAnalysis.md](Modules/CrossReferenceAnalysis.md)、[Modules/SwiftObjCInterop.md](Modules/SwiftObjCInterop.md)、提案 [0112](../Evolutions/0112-objc-ivar-type-recovery.md) 的决策日志、体检报告的「修复」一节。CLI 的参数与输出格式没变,skill 不用改;没有新术语。 +- **验证**(JHs-Mac-Studio-Ultra,macOS 27.2,Xcode 27.2,本地兄弟依赖):每条修复都先在只加了新测试的 `next` 上跑红(崩溃的六条是子进程 SIGBUS / SIGSEGV / SIGTRAP,其余是断言失败),修复后转绿。全量测试的对比见体检报告。这台机器上已没有 Xcode 26.6,fixture 与全量都用 Xcode 27.2 编,`MachOSwiftSectionTests` 的 195 处偏移不符在 `next` 上同样出现;CI 的 Xcode 26.6 结果要等推送后看。 +- **对应版本**:0.28.0。 + +## 161. 0.28.0 发版 + +- **时间段**:2026-12-01。在 JHs-Mac-Studio 上改、提交与发版,在 JHs-Mac-Studio-Ultra 上测试。 +- **动机**:0.26.0 之后攒下第 143–160 节与 11-27、11-29 两批修复;其中 0113 用到 MachOKitExtensions 与 MachOObjCSection 还没发版的接口,`next` 只能带本地兄弟依赖编译,下游的远程构建与 CI 都编不过。 +- **关键决策**: + - **① 发版顺序**:MachOKitExtensions 3.4.0 → MachOObjCSection 0.10.102 → 本库 0.28.0。MachOObjCSection 的 0.10.101 在 11-26 已打好 tag;把它的 `main` 快进过去后 `ci.yml` 红了六条 selector 引用测试。原因是那个仓库提交了 `Package.resolved`,钉着 MachOKitExtensions 3.3.0,而 manifest 的下限只写 3.0.0:这批识别要 3.4.0 才生效,配 3.3.0 编得过、只是悄悄认不出。在 Ultra 上对照证实(同一份代码配 3.3.0 红六处,配 3.4.0 全过)。用户决定把它的下限抬到 3.4.0、重新生成锁文件,发 0.10.102,本库的下限跟着到 0.10.102。 + - **② 版本号跳过 0.27.0**:插件版本在 `next` 上已经两次升到 0.28.0,`version-check.yml` 要求 CLI 与插件同号,插件版本又不能回退(已安装的用户只在版本号变大时更新)。 + - **③ MachOObjCSection 的范围改为 `"0.10.102" ..< "0.11.0"`**:fork 合入上游 0.10.0 之后从 0.10.100 起编号,原来的 `"0.8.209" ..< "0.9.0"` 会把新版本排除在外;下限在 0.10.100 之上,上游自己的 0.10.0 tag 也落在范围外。 + - **④ 发版前的检查用 Xcode 27.2**:三台机器里只有公司那台还装着 Xcode 26.6,而 MachOKitExtensions 这类大工程不在那台编;用户决定在 Ultra 上用 27.2 跑完全量即可,26.6 的结果看 MachOObjCSection 与本库的 CI。 + - **⑤ 提案取号**:11-06 落地、一直没编号的两份提案在发版前补为 0114、0115。 + - **⑥ 绕开 Swift 6.3 的优化器崩溃**:发版 PR 的 release CI(Xcode 26.6)在 IntegrationTests 里崩溃——优化器的 CopyPropagation 处理 `DiffDumpTests.dump(_:to:)` 为 `Diff.SimulatorFiles` 生成的特化版本时 signal 6。这段是 0111 在 11-26 加的,之后没人用 26.6 做过 release 编译。用户选择给它标 `@_optimize(none)`、靠 CI 验证,不在本机用 26.6 复现:它只是维护者的手检输出,不优化没有损失。下一轮同样崩在形状相同的 `EvolutionDumpTests.dump(_:to:)`(`Evolution.Caches` 的特化),于是把它和同形状、还没轮到的 `InterfaceDumpTests.dump(_:of:to:)` 一起标上。同一轮 debug 任务红的是已知的构建顺序竞争(`no such module 'swift_section'`),重跑即过。 +- **落地模块**:`Package.swift`(两个依赖的下限)、`Sources/Executables/swift-section/Version.swift`、`Changelogs/0.28.0.md`、`README.md` 的安装示例、本账本各节的「对应版本」。两个 `plugin.json` 已是 0.28.0,不用改。 +- **验证**(JHs-Mac-Studio-Ultra,macOS 27.2,Xcode 27.2,只走远端依赖、新 scratch):MachOKitExtensions 待发版的提交跑全量,只红 `ImagePointerSlotsTests` 一条(JavaScriptCore 的 35,667 个指针槽里有 4 个对不上),3.3.0 上同样红,是这台系统的环境问题。MachOObjCSection 0.10.102 的 `ci.yml`(Xcode 26.6)通过。本库在 0.10.101 上跑全量(跳过 IntegrationTests;0.10.102 只改了 manifest 与锁文件),只有 `MachOSwiftSectionTests` 一个测试包红,195 处偏移不符,即用 Xcode 27.2 编 fixture 的已知漂移;Xcode 26.6 的结果看发版 PR 的 CI。 +- **对应版本**:0.28.0。 + ## 维护约定 1. **每个非平凡批次结束时必须在本文追加/更新一节**(新工作弧新增一节;延续既有弧则在该节 diff --git a/Documentations/Internal/ProjectMap.md b/Documentations/Internal/ProjectMap.md index 0ad4844e8..46dc641ac 100644 --- a/Documentations/Internal/ProjectMap.md +++ b/Documentations/Internal/ProjectMap.md @@ -38,7 +38,7 @@ RuntimeViewer · MachOKitUI · swift-decompiler ───┘ └── swift-section CLI wrapper └─ SwiftSectionKit one request per subcommand (+ MachOObjCSection's ObjC* products for `objc`) ├─ SwiftDump the `dump` output - ├─ TypeIndexing `__C` type → module attribution (macOS only) + ├─ SwiftTypeNameResolution `__C` type → module + Swift name via swift-type-indexing (macOS only) └─ SwiftInterface orchestrator: single version / diff / evolution ├─ SwiftIndexing image → declaration model ├─ SwiftPrinting declaration model → Swift source (a peer of SwiftIndexing) diff --git a/Documentations/Internal/ReviewAdjudications.md b/Documentations/Internal/ReviewAdjudications.md index 4220fbbf6..4fad39ab6 100644 --- a/Documentations/Internal/ReviewAdjudications.md +++ b/Documentations/Internal/ReviewAdjudications.md @@ -1028,3 +1028,146 @@ - **既往修复**:无。 - **代码锚点**:`Sources/Executables/reader-benchmark/ReaderBenchmark.swift`;体检报告 [CodebaseAudit20261116](Reviews/CodebaseAudits/CodebaseAudit20261116.md)。 - **复审条件**:它被并进 `swift-section`,或开始输出诊断与进度信息。 + +--- + +## A86 — C 导入类型的名字表在锁内 demangle(提案 `consistent-c-imported-type-spelling` 的审查,归入 A61 第一处) + +- **裁决**:锁不改(2026-11-26)。本分支只把被 import info 排除的条目挪到 demangle 之前判定。 +- **发现**:`SwiftDeclarationPrinter.cImportedTypeSwiftNames()`(`Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift:129`)第一次用到时在 `@Mutex` 里建 `CImportedTypeSwiftNameTable`,每个收进表的描述符要 `SymbolicDemangler.demangleContext` 一次。本提案让没有 ABI 名的描述符也进表,持锁 demangle 的次数随之变多。 +- **复现 / 是否误报**:写法属实。结果不会错,只有「调用方在 512 KB 栈上、且另有线程在等这把锁」时多等;复现不出输出层面的问题。 +- **与 main 基线对比**:建表与锁来自提案 0106(`1e490500`,2026-11-24),main 上没有;本分支增加的是进表的条目数。 +- **为什么不修**:与 A61 第一处(打印器的另外两次一次性建表)同一种写法、同一个理由:建表只发生在打印入口里,入口已包 `LargeStackTaskExecution.run`,持锁期间不切线程。被相关实体、不可信改名排除的描述符现在先判定、不 demangle,持锁的工作只多出真正进表的那些。 +- **既往修复**:无。 +- **代码锚点**:`Sources/Output/SwiftPrinting/CImportedTypeSwiftNameTable.swift` 的 `init(typeContextDescriptors:in:)`。 +- **复审条件**:与 A61 相同;另外,有宿主在没包执行器的同步入口上第一次打印 C 导入类型。 + +--- + +## A87 — 同名 C 类型写裸名,会不会和同名的 Swift 类型混淆(提案 `consistent-c-imported-type-spelling` 的自审,**误报**) + +- **裁决**:不修(2026-11-26)。 +- **发现**:本镜像有描述符、Swift 名就是 C 名的 C 导入类型(`CMTime`、`CGRect`、`std` 这类 C++ 命名空间)现在写裸名;镜像里若另有同名的 Swift 类型,审查担心两者在声明、扩展头与布局注释里无法区分。 +- **复现 / 是否误报**:误报。Swift 类型的引用与扩展头一律带模块(`M.CMTime`、`M::CMTime`),C 类型现在是裸的 `CMTime`,两者照样分得开;声明行本来就不带模块,C 导入类型的声明在 0106 之前就是裸名。改了名的 C 类型(`AnyWeakAttribute`)从 0106 起就是这种写法。 +- **与 main 基线对比**:同名类型写裸名是本分支引入的;改名类型的同样写法来自 0106,main 上没有。 +- **为什么不修**:见上,没有实际的歧义。 +- **既往修复**:无。 +- **代码锚点**:`CImportedTypeSwiftNameTable.knownSwiftName(ofDescriptorNamed:importInfo:isDirectlyInImportedModule:)`。 +- **复审条件**:引用或扩展头里出现不带模块的 Swift 类型。 + +--- + +## A88 — interface 的布局注释行不带私有判别符、局部类型只写名字(提案 `consistent-c-imported-type-spelling` 的审查与自审,**有意设计**) + +- **裁决**:不修(2026-11-26)。 +- **发现**:展开字段偏移树的行改用 interface 打印器的拼写后,`M.(Foo in _ABC…)` 变成 `M.Foo`,局部类型只写自己的名字;同一个类型里两个字段分别是两个文件里同名的私有 `Foo` 时,注释行分不出哪棵子树属于哪个。 +- **复现 / 是否误报**:属实。 +- **与 main 基线对比**:本分支引入;main 上注释行按 `.default` 打印,带判别符。 +- **为什么不修**:这正是要的一致:这些行描述的字段声明(`let element: M.Foo`)本身也不带判别符,注释与声明写法相同才是这次改动的目的。要区分同名私有类型,看声明上方 `--emit-private-source-files` 印的源文件注释;dump 的注释行照旧带判别符。`SpecializedRuntimeTypeNameTests` 的期望随之改写,它要证明的「保留模块」不变。 +- **既往修复**:无。 +- **代码锚点**:`DeclarationRenderConfiguration.fieldLayoutTypeName(printedName:typeNode:)`。 +- **复审条件**:interface 的字段声明开始带判别符,或有宿主依赖注释行区分同名私有类型。 + +--- + +## A89 — 布局注释行的拼写失败时静默退回 `.default`(提案 `consistent-c-imported-type-spelling` 的自审,**不修**) + +- **裁决**:不修(2026-11-26)。 +- **发现**:`fieldLayoutTypeName(printedName:typeNode:)` 用 `try?` 调解析器,抛错或得到空串时退回 `.default` 拼写,不发事件、不打日志;那一行会是 `__C.AGAttribute`,旁边的行是 `AnyAttribute`。 +- **复现 / 是否误报**:机制属实,没有构造出会抛错的节点:interface 打印器的 `typeDemangleResolver` 只在打印器已释放时什么都不印。 +- **与 main 基线对比**:本分支引入。 +- **为什么不修**:退回的仍是正确的类型名,只是拼写不同;同一个类型在字段声明处由打印器自己印,出错会走它自己的报告路径。逐行打日志会在大框架上刷出几万行。 +- **既往修复**:无。 +- **代码锚点**:`Sources/Output/SwiftDeclarationRendering/DeclarationRenderConfiguration.swift` 的 `fieldLayoutTypeName(printedName:typeNode:)`。 +- **复审条件**:发现某类节点会让 interface 打印器抛错。 + +--- + +## A90 — 布局注释里来自依赖镜像的 C 类型按根镜像的名字表拼(提案 `consistent-c-imported-type-spelling` 的自审,**已知限制**) + +- **裁决**:不修,文档写明(2026-11-26)。 +- **发现**:展开树里某一行的类型来自依赖镜像时,打印器只认根镜像自己的描述符;依赖镜像带着那个 C 类型的描述符、根镜像没有时,这一行写 `__C.Bar`,而依赖镜像自己的 interface 写 `Bar`。 +- **复现 / 是否误报**:属实,按机制推断,没有专门造 fixture。 +- **与 main 基线对比**:main 上这一行永远是 `__C.Bar`,本分支没有让它变坏。 +- **为什么不修**:要从别的镜像的描述符取名字,正是另开提案的跨镜像查找(`AGSubgraphRef` 在 SwiftUICore 里记作 `Subgraph` 那条)要解决的事;插件 skill 第 8 节写明了这个限制。 +- **既往修复**:无。 +- **代码锚点**:`SwiftDeclarationPrinter.cImportedTypeSwiftNames()`。 +- **复审条件**:跨镜像查找的提案落地。 + +--- + +## A91 — 布局注释每行一次异步打印,进程内缓存每行多存一个节点(提案 `consistent-c-imported-type-spelling` 的自审,**实测后不修**) + +- **裁决**:不修(2026-11-26)。 +- **发现**:interface 的每一行展开字段偏移注释都经打印器的 `typeDemangleResolver` 印一次,没有跨行的结果缓存;进程内全进程缓存 `NestedFieldOffsetLevel` 的每一行多存一棵节点树,只有 `RuntimeFieldLayoutMemo.removeAll()` 能释放。 +- **复现 / 是否误报**:成本属实,实测都很小(JHs-Mac-Studio-Ultra,Xcode 26.6,release CLI 交替各跑 3 次):`swift-section interface --uses-system-dyld-shared-cache --cache-image-name SwiftUICore --module-selectors --emit-expanded-field-offsets` 从 7.10 秒到 7.39 秒(+4%,42,559 行注释,约每行 7 微秒);进程内把 SwiftUICore 每个非泛型类型的字段都展开一遍(34,755 行),渲染后的内存增量从 6.72 MB 到 8.85 MB(+2.1 MB)。 +- **与 main 基线对比**:本分支引入。 +- **为什么不修**:按 `.default` 文字做跨行缓存能省掉一部分打印,但收益只有那 4%;节点在建层时本来就算出来了,存下来避免渲染时重新 demangle(提案 0067 去掉的正是这部分成本)。 +- **既往修复**:无。 +- **代码锚点**:`DeclarationRenderConfiguration.fieldLayoutTypeName(printedName:typeNode:)`、`NestedFieldOffsetLevel.StructField.typeNode`。 +- **复审条件**:有宿主实测到这部分耗时或内存成为瓶颈(RuntimeViewer 建搜索语料时会把镜像的全部类型都展开一遍)。 + +--- + +## A92 — `@objc @implementation` 类的第 3 层成员配对在打印期现算,不记在定义上(2026-11-29 代码库体检,结构类,**有意设计**) + +- **裁决**:不修(2026-11-29,用户确认)。 +- **发现**:Swift 成员与 ObjC 成员只按名字配对的第 3 层(连同 `ObjCSwiftTypeCompatibility` 的类型比对与 `NS_REFINED_FOR_SWIFT` 判断)在 `ObjCImplementingSwiftMembers` 里打印时现算,五个打印入口各建一次(`SwiftDeclarationPrinter+ObjCImportedDefinitions.swift:64/81/116/141/260`),结果不回写定义;前两层由索引产出并记为 `evidence`。dump 与宿主因此拿不到这层配对。 +- **复现 / 是否误报**:结构属实,没有错误输出。 +- **与 main 基线对比**:`d7fc39b8`(2026-11-17)引入,已随 0.26.0 发布。 +- **为什么不修**:提案 [0096-swift-first-imported-declarations](../Evolutions/0096-swift-first-imported-declarations.md) 有意在打印时做:这层配对只服务于 ObjC 侧的 imported 声明,dump 与 Swift 侧的 interface 不受影响。它和「源码级事实在索引里算、新识别能力默认同时接 dump」的做法相左,下次动这块时值得重议,眼下没有消费者需要它。 +- **既往修复**:无。 +- **代码锚点**:`Sources/Output/SwiftPrinting/ObjCImplementingSwiftMembers.swift`;体检报告 [CodebaseAudit20261129](Reviews/CodebaseAudits/CodebaseAudit20261129.md)。 +- **复审条件**:dump 需要显示这层配对,或宿主要从声明模型读它。 + +--- + +## A93 — 交叉引用扫描在原始内存上手写 context descriptor 的 kind 掩码与名字指针(2026-11-29 代码库体检,结构类,**有意如此**) + +- **裁决**:不修(2026-11-29,用户确认)。 +- **发现**:`Sources/Analysis/CrossReferenceAnalysis/Scanning/SwiftTypeIndex.swift:240-251` 读 `flags & 0x1F` 判断 kind 是否在 16…31,再在 +8 处手算相对指针取名字,是 ABI 层之外的又一份布局知识;`ContextDescriptorFlags` 或名字指针的位置变了,这里不会跟着变。 +- **复现 / 是否误报**:写法属实,没有错误输出。 +- **与 main 基线对比**:`f1e9fcce`(2026-11-19)引入,已随 0.26.0 发布。 +- **为什么不修**:这是扫描热路径,读取必须经 `CrossReferenceMemory`(文件模式与进程内共用一套读取),ABI 模型的读取 API 走的是 `ReadingContext`,接不上;这两项布局自 Swift 5 起没变过。 +- **既往修复**:无。 +- **代码锚点**:`SwiftTypeIndex.swift` 的描述符识别;体检报告 [CodebaseAudit20261129](Reviews/CodebaseAudits/CodebaseAudit20261129.md)。 +- **复审条件**:`ContextDescriptorFlags` 的布局变化,或 ABI 层提供能经 `CrossReferenceMemory` 读的轻量入口。 + +--- + +## A94 — ObjC 协议记录与 `@objc @implementation` 类索引为 `MachOFile`、`MachOImage` 各写一份(2026-11-29 代码库体检,重复,**受上游 API 所迫**) + +- **裁决**:不修(2026-11-29,用户确认)。 +- **发现**:`Sources/Analysis/SwiftObjCInterop/ObjCProtocolRecord.swift:162-192` 与 `:202-232`、`ObjCImplementationClassIndex.swift:510-545` 与 `:675-710` 各约 30 行同形代码,一份给 `MachOFile`,一份给 `MachOImage`。 +- **复现 / 是否误报**:重复属实。 +- **与 main 基线对比**:main 上也有。 +- **为什么不修**:MachOObjCSection 的 `methods(in:)` 等读取 API 按具体读取器类型重载,返回值一边是可选值一边不是,方法实现一边是 offset、一边要 `resolveOffset(at:)`;本仓库单方面合并只能靠类型判断,正是 `CLAUDE.md` 禁止的强转。 +- **既往修复**:无。 +- **代码锚点**:上述两个文件;体检报告 [CodebaseAudit20261129](Reviews/CodebaseAudits/CodebaseAudit20261129.md)。 +- **复审条件**:MachOObjCSection 提供对两种读取器统一的泛型读取 API。 + +--- + +## A95 — `OSLogEventHandler` 直接用 `Logger(subsystem:category:)`(2026-11-29 代码库体检,规则类,**有意如此**) + +- **裁决**:不修(2026-11-29,用户确认)。 +- **发现**:全局指令与 `CLAUDE.md` 要求日志一律经 `@Loggable` + `#log`;`Sources/Declaration/SwiftIndexing/SwiftIndexEventsHandlers.swift:11` 直接构造 `Logger`。 +- **复现 / 是否误报**:写法属实,但规则管的是库自己打的日志,这里是给宿主用的事件 sink。 +- **与 main 基线对比**:main 上也有。 +- **为什么不修**:`OSLogEventHandler` 的 subsystem 与 category 是宿主运行时传进来的参数,`@Loggable` 只接受字面量,表达不了;`PrintFailureEventTests` 的 `configurableSinks` 有意放行它。 +- **既往修复**:无。 +- **代码锚点**:`SwiftIndexEventsHandlers.swift` 的 `OSLogEventHandler`;体检报告 [CodebaseAudit20261129](Reviews/CodebaseAudits/CodebaseAudit20261129.md)。 +- **复审条件**:FrameworkToolbox 的宏支持运行时 subsystem 与 category。 + +--- + +## A96 — `SpareBitAnalyzer.printAnalysis` 用 `print` 写 stdout(2026-11-29 代码库体检,规则类,**有意如此**) + +- **裁决**:不修(2026-11-29,用户确认)。 +- **发现**:`Sources/Analysis/SwiftInspection/SpareBitAnalyzer.swift:153-175` 是一个公开函数,用 `print` 往 stdout 打一张 spare bit 表。 +- **复现 / 是否误报**:写法属实,但它是调试接口,产物就是打出来的表,不是日志。 +- **与 main 基线对比**:`ae2d3a8d`(2026-02-02)引入,main 上也有。 +- **为什么不修**:库内没有调用方,只有 `Tests/IntegrationTests/SwiftInspection/MultiPayloadEnumTests.swift` 用它做手工检查;它已在 `PrintFailureEventTests.swift` 只减不增的名单上,新的 `print` 进不来。 +- **既往修复**:无。 +- **代码锚点**:`SpareBitAnalyzer.printAnalysis`;体检报告 [CodebaseAudit20261129](Reviews/CodebaseAudits/CodebaseAudit20261129.md)。 +- **复审条件**:库代码开始调用它,或它开始输出诊断信息。 diff --git a/Documentations/Internal/Reviews/CodebaseAudits/CodebaseAudit20261129.md b/Documentations/Internal/Reviews/CodebaseAudits/CodebaseAudit20261129.md new file mode 100644 index 000000000..79179d88b --- /dev/null +++ b/Documentations/Internal/Reviews/CodebaseAudits/CodebaseAudit20261129.md @@ -0,0 +1,332 @@ +# 代码库体检 2026-11-29 + +- **分支与提交**: `next` @ `947d5321`(工作树有 1 个未提交文件 `Tests/IntegrationTests/InspectionDumps/EvolutionTests.swift`,在不审的 `Tests/` 里,不影响本轮) +- **范围**: 改动集(自上次体检的 `1ba927ad` 起 265 个提交,`Sources` 与 `Plugins` 新增约 8,000 行、删除约 14,100 行;删除大多是 `Sources/MachO/*`、交叉引用的下两层、`TypeIndexing` 搬出仓库);轮转深审 `SwiftInspection`、`SwiftSpecialization`、`SwiftLayout`(上轮账本交接的三个,合计约 1.6 万行);全仓机械扫描 +- **降级**: 没有 `.swiftlint.yml`,没跑 lint;没装 `jscpd` / `pmd`,重复全靠人工判断 +- **对照已裁决清单**: finder 与复核共跳过 A54、A59、A61(其余入口)、A62、A70、A73、A82、A83、A85 等已裁决条目;A61 的复审条件被第 12 条触发 +- **流程**: 6 个 finder(改动集两个、轮转模块两个、结构、冗余)加 2 个复核,全部 medium effort;补漏与横向排查在主线程做 + +## 总评 + +窗口内最大的一批新代码——离线交叉引用(`refs` / `symbolicate` 与文件模式)、`@objc @implementation` 类的 ObjC 侧打印、ivar 类型恢复——各带出一两条结果错误,都不会崩溃,前三类已随 0.26.0 发布。轮转模块里最该先修的是第 1 条:`SwiftLayout` 用不带 private discriminator 的名字索引类型,同一模块两个文件里同名的 private 类型会互相顶替,算出错误的布局却标成已计算;issue #115 修过同一个根因在成员归属上的表现,布局这边一直没覆盖到。另有五条只在畸形二进制上触发的卡死或 trap,集中在「沿父链或递归走时不设上限」,其中父链那条在 ABI 层与索引器里有同形的循环,适合在底层统一加上限。和上一轮比,严重 bug 从 9 条变成 14 条(含 4 条待确认),但本轮多深审了三个从没整模块审过的模块;规则计数整体下降,几乎全是模块搬出仓库带来的,不是修掉的。 + +## 严重 bug + +### 1. 静态布局把同名的 private 类型当成同一个,算出错误的偏移与大小 + +- **位置**: `Sources/Analysis/SwiftLayout/ImageReference.swift:76-84`(建索引)、`Sources/Analysis/SwiftLayout/StaticTypeLayoutResolver.swift:504`(查询)、`Sources/Analysis/SwiftLayout/ImageUniverse.swift:246`(跨镜像合并) +- **判定**: CONFIRMED +- **失败场景**: 同一模块两个文件各有一个 `private struct Storage`,大小不同。类型索引的键是 `NodeTypeNaming.nominalQualifiedName`,它经 `declaredName`(`Sources/Analysis/SwiftInspection/NodeTypeNaming.swift:178-197`)只保留 `$` 开头的位置名,真正的 discriminator 落到 `node.identifier`,只剩本地名,于是两个类型撞到同一个键,后写的覆盖先写的。某个类型的字段 `var storage: Storage` 就按另一个文件的描述符算布局:它的大小、其后所有字段的偏移、整个类型的 size / stride 都错,而 interface 与 dump 的布局注释把它们标成已计算,而不是降级。 +- **能复现吗**: 能。fixture 里现成的 `Tests/Projects/SymbolTests/SymbolTestsCore/PrivateDoppelgangers.swift` 与 `PrivateDoppelgangersSecondFile.swift` 就是两个文件各一个同名 private struct,只因为两者恰好都是一个 `Int64`,基线看不出差别;把其中一个改成不同大小即可变红。 +- **新的还是旧的**: 旧的。按限定名建索引始于 `564ef6ee`(2026-06-21,静态字段偏移引擎),`7dffe26b`(2026-11-06)改成懒建与共享时沿用;`main` 与 0.26.0 都有。 +- **值不值得修**: 修。真实框架里同名 private 类型很常见(`Storage`、`Box`、`Key`),撞上就静默给出错误的偏移,而偏移注释是 interface 的卖点之一。 +- **以前修过吗**: 同一个根因修过一次:issue #115(dump 把不同文件里同名 private 类型的成员合在一起,2026-08-26 关闭)改为在成员归属上用接收节点的重载(`CLAUDE.md`「Resolving one type's members/info/attributes must use the node-taking overloads」)。那次没有覆盖 `SwiftLayout` 的类型索引;上轮体检第 5 条修的也是同一类(`SwiftClassWithoutClassObjectIndex` 把同名类登记成歧义),同样只修了那一处。 +- **同类实例**(未复核): 同一个键还用在 `StaticTypeLayoutResolver.swift:574` 的 memo、`EnumLayoutBridge.swift:70`、`ImageReference.swift:144-151` 的关联类型 witness 键、`ObjCClassIndex.swift:91/111` 的 `instanceStart`(同名 private 类拿到对方的 `instanceStart`);`SwiftLayout` 之外以 `nominalQualifiedName` 作键的还有 `ObjCProtocolAdoptionIndex.swift:167/258`、`ObjCProtocolWitnesses.swift:99`、`ClassDumper.swift:50/237`、`TypeDefinition+ObjCMembers.swift:29`、`SwiftDeclarationIndexer.swift:1074`,需要逐处判断是否会撞键。 + +### 2. `@objc @implementation` 类的 `unowned` 存储属性被印成 `weak var …?` 或 `let …: String!` + +- **位置**: `Sources/Analysis/SwiftObjCInterop/ObjCInstanceVariableSwiftType.swift:45-59`(按 `isWeak` 分支)、`Sources/Analysis/SwiftObjCInterop/ObjCImplementationClassFacts.swift:157`(`isWeak` 读属性特性里的 `W`) +- **判定**: CONFIRMED(finder 写的失败场景不对,复核改写为下面这样) +- **失败场景**: 剥过 field-offset 符号的镜像里,`unowned var label: NSString` 的 ObjC 属性特性带 `W`——编译器对 `weak` 与 `unowned` 一律写 `,W`(`swift/lib/IRGen/GenClass.cpp:2212-2214`,「Weak and Unowned properties are (weak)」)——于是走 `isWeak` 分支,印成 `weak var label: NSString?`,关键字与可选性都错。`unowned let label: NSString` 的特性只有 `R`,ivar 编码是 `?`,走桥接分支,印成 `let label: String!`,类型也错。 +- **能复现吗**: 能。在 `ObjCImplementationFixture` 一类的 fixture 里加一个 `unowned var` 与一个 `unowned let`,剥符号后看 interface。 +- **新的还是旧的**: 新的。`42d1c48a`(2026-11-26,ivar 类型恢复,提案 0112),上次体检以来出现;`main` 与 0.26.0 都没有。 +- **值不值得修**: 修。interface 把错误的声明当成事实输出,用到 `unowned` 的 `@objc @implementation` 类都会碰上。 +- **以前修过吗**: 没修过。提案 0112 决策日志(2026-11-26 那行)的前提是「`unowned` 属性的存储写 `?`、特性里没有 `W`」,与编译器源码不符:特性里有 `W`,所以 `unowned` 被当成 `weak`。修的时候顺带更正提案的这段记录。 + +### 3. `refs --type` 在剥过符号的独立文件上漏掉经 mangled name 实例化的类型引用 + +- **位置**: `Sources/Analysis/CrossReferenceAnalysis/Scanning/SwiftCodeReferenceRecognizer.swift:168-170`、`:245-248` +- **判定**: CONFIRMED +- **失败场景**: 文件模式分析一个剥过符号的 App 可执行文件,文件集里没有 libswiftCore。对 `swift_getTypeByMangledName…` 的调用经桩解析成 `.importedSymbol`,而 `role(of:)` 的 `.importedSymbol` 分支只认 `…Ma` 访问器;按形状认 helper 的那条路要求被调方解析成 `.function` 且在 `typeByMangledNameEntries` 里,同样认不出。结果是所有经 mangled name 实例化的类型引用都不报,输出为空,也没有任何提示。没剥符号时靠 helper 的名字(`:221-223`)还能认出。 +- **能复现吗**: 能。对一个剥过符号、内联了 `__swift_instantiateConcreteTypeFromMangledName` 的可执行文件跑 `refs --type`,对照没剥符号的同一产物。 +- **新的还是旧的**: 新的。文件模式由 `ce9cf93c`(2026-11-19)引入,这段识别在 `7c18fbb4`(2026-11-19)拆层时成形;上次体检以来出现,已随 0.26.0 发布、`main` 上也有。 +- **值不值得修**: 修。剥过符号的 App 正是离线分析最常见的输入,漏报是静默的。 +- **以前修过吗**: 没修过;按形状认 helper 的做法始于 `a5895b4c`(2026-10-17),当时只有进程内模式,被调方总能解析成函数。 + +### 4. `symbolicate` 把存着 protocol / method descriptor 的槽说成指向函数 + +- **位置**: `Sources/Analysis/CrossReferenceAnalysis/CrossReferenceAnalyzer+Symbolication.swift:139-152`(`slotTarget`) +- **判定**: CONFIRMED +- **失败场景**: 槽值落在任一镜像的 `__TEXT` 内、又不在 `descriptorsByRuntimeAddress` 里,就一律返回 `.function(location)`。protocol descriptor(`…Mp`)与 method descriptor(`…Tq`)都在 `__TEXT,__const`,`symbolicate` 一个存着它们的 GOT 槽,文本与 JSON 都说它指向一个函数。存着 struct metadata(`…VN`,在 `__DATA`)的槽只试 ObjC 类,没命中就报 `unrecognized`,而 `refs` 的扫描能把它认成这个类型。 +- **能复现吗**: 能。Swift 二进制里存 protocol descriptor 的 GOT 槽很常见,任取一个 `symbolicate` 即可。 +- **新的还是旧的**: 新的。`c9096554`(2026-11-19),已随 0.26.0 发布。 +- **值不值得修**: 修。`symbolicate` 的职责就是说清一个地址是什么,给出错误的种类比说「认不出」更糟。 +- **以前修过吗**: 没修过,功能是这个窗口新加的。 + +### 5. `symbolicate --in-image` 遇到同名镜像只看第一个 + +- **位置**: `Sources/Commands/SwiftSectionKit/CrossReferences/SymbolicateRequest.swift:28-31` +- **判定**: CONFIRMED +- **失败场景**: `imageIndices(named:)` 按 lastPathComponent 匹配,在 macOS 的 dyld cache 里 macOS 版与 Mac Catalyst 版的同名框架都会命中,请求直接取 `[0]`;`place(ofUnslid:inImageAt:)` 拿到指定镜像后不再看别的,地址不在它的段里就报 `.unmapped`。`symbolicate --in-image UIKitCore` 于是输出 macOS 版的路径加 `unmapped`。 +- **能复现吗**: 能,对 macOS cache 里任一同时有 `/System/iOSSupport` 版本的框架。 +- **新的还是旧的**: 新的。`7a3ee038`(2026-11-19),已随 0.26.0 发布。 +- **值不值得修**: 修,改动很小:像同文件 `ReferencesRequest.function(at:)` 那样把每个同名镜像都试一遍。 +- **以前修过吗**: 没修过;那行的注释承认会取第一个,理由是两者地址互不重叠,但没有在第一个落空时换下一个。 +- **同类实例**: `rg 'imageIndices\(named:'` 的另外三处(`ReferencesRequest.swift:89/387/475`)都用全部匹配结果,没有同样的问题。 + +### 只在畸形二进制上触发的五条(6–10) + +下面五条都要构造或损坏过的输入才会触发,正常编译器产不出来。库在宿主进程(RuntimeViewer)里读不可信的二进制,所以 trap 与卡死会带走宿主;上一轮同类的两条(畸形 export trie、超大 C 数组)用户都批准修了。建议修,优先级低于 1–5。 + +#### 6. context descriptor 的父链成环时取泛型深度卡死 + +- **位置**: `Sources/Analysis/SwiftInspection/GenericParameterDepthLayout.swift:151-161`、`:259-263` +- **判定**: CONFIRMED +- **失败场景**: parent 相对指针指回描述符自身(偏移 -4)或成环。两处 `while let` 都没有访问集也没有次数上限:非泛型时 CPU 空转卡死,泛型时每圈 append 一次,直到内存耗尽。dump、interface、specialize 取泛型深度都会走到。 +- **能复现吗**: 能,构造一个 parent 指向自己的描述符。 +- **新的还是旧的**: 旧的。`b72638f8`(2026-10-02,离线特化),`main` 与 0.26.0 都有。 +- **值不值得修**: 修,但应在底层统一修(见同类实例)。 +- **以前修过吗**: 没修过。`SymbolicDemangler` 走同一条链时一直限了 `recursionLimit: 50`(`SymbolicDemangler.swift:536`),其它走法没有跟上。 +- **同类实例**(未复核): 同形的无上限父链循环还有 `Sources/ABI/MachOSwiftSection/Models/Generic/GenericContext.swift:140`(每个泛型类型都会走)、`Sources/ABI/MachOSwiftSection/Models/ContextDescriptor/ContextDescriptorProtocol.swift:37`(`moduleContextDescriptor`)、`Sources/Declaration/SwiftDeclaration/Model/ExportStatus.swift:245`、`Sources/Declaration/SwiftIndexing/SwiftDeclarationIndexer.swift:549`、`:658`。更简单的形状是在 ABI 层给 context descriptor 提供一个带上限的父链序列,各处改用它。 + +#### 7. enum 的 empty case 数巨大时生成数十亿个 case 投影 + +- **位置**: `Sources/Analysis/SwiftInspection/EnumLayoutCalculator.swift:532`、`:668`(`:864`、`:883` 同理);调用方 `Sources/Output/SwiftDeclarationRendering/RuntimeFieldLayoutBackend.swift:715`、`Sources/Analysis/SwiftLayout/EnumLayoutBridge.swift:157/167/327` +- **判定**: CONFIRMED +- **失败场景**: `numEmptyCases` 是 `UInt32` 原样转成 `Int`,descriptor 写成 0xFFFFFFFF 时 `for i in 0 ..< numEmptyCases` 每圈 append 一个带字典的投影,约 43 亿项,内存耗尽。`multiPayloadEnumLayout` 只为求 size 也会生成全部 case。 +- **能复现吗**: 能,改写一个 enum descriptor 的 empty case 数。 +- **新的还是旧的**: 旧的。`81ebc002`(2025-12-28),`main` 与 0.26.0 都有。 +- **值不值得修**: 修;只求 size 的路径不该生成投影,注释用的投影设一个上限并标截断。 +- **以前修过吗**: 没修过。`RuntimeEnumCaseProjector` 有尺寸上限,这里没有。 +- **同类实例**(未复核): 公开函数 `getEnumTagCounts`(`Sources/ABI/MachOSwiftSection/Models/Type/Enum/EnumFunctions.swift:15-17`)在 payload 为 1–3 字节、`emptyCases` 接近 `UInt32.max` 时,`emptyCases + (casesPerTagBitValue - 1)` 溢出 trap;它目前只有基线生成器调用。 + +#### 8. 布局累加的加法溢出 trap + +- **位置**: `Sources/Analysis/SwiftLayout/BasicLayout.swift:72-73`、`Sources/Analysis/SwiftLayout/StaticLayoutCalculator.swift:447/464/483` +- **判定**: CONFIRMED +- **失败场景**: `fixedArrayLayout` 只检查 `stride × count` 的乘法(`StaticTypeLayoutResolver.swift:440`)。mangling 里 `InlineArray<9223372036854775807, Int8>` 的 stride 恰为 `Int.max`,乘法不溢出;它后面再跟一个字段时,`alignedOffset + fieldLayout.size`、`offsetAccumulator + fieldAlignmentMask` 是普通 `+`,算术溢出 trap。放进对齐为 8 的 tuple 或 enum 加 tag byte 同理。 +- **能复现吗**: 能,构造这样一个字段类型的 mangling。 +- **新的还是旧的**: 旧的。`564ef6ee`(2026-06-21),`main` 与 0.26.0 都有。 +- **值不值得修**: 修,改成带溢出检查的加法,溢出时降级。 +- **以前修过吗**: 没修过;乘法的检查当初就有,加法一直没有。 + +#### 9. 类的父类链递归没有守卫 + +- **位置**: `Sources/Analysis/SwiftLayout/StaticTypeLayoutResolver.swift:765-791`(`superclassStartLayout` → `computeClassLayout`),`StaticLayoutCalculator.swift:358` 也走这里 +- **判定**: CONFIRMED(畸形输入);经第 1 条撞键成环的那条路径是 PLAUSIBLE +- **失败场景**: 类不走 `memoizedNominalLayout` 的 in-progress 守卫,superclass 的符号引用指回自己时无限递归,栈溢出崩溃。合法源码在第 1 条的撞键下也可能拼出 `M.A` → `M.B` → `M.A` 的环,复核没能排出确定会撞上的写法。 +- **能复现吗**: 畸形输入能;撞键成环要造一个碰撞后互为父类的 fixture 才能证实。 +- **新的还是旧的**: 旧的。`ddbdd6f3`(2026-06-22),`main` 与 0.26.0 都有。 +- **值不值得修**: 修,加 in-progress 集合或深度上限;修第 1 条后撞键那条路自然消失。 +- **以前修过吗**: 没修过;值类型的递归早有 in-progress 守卫,类的父类链没接进去。 + +#### 10. 关联类型 witness 指回自己时无限递归 + +- **位置**: `Sources/Analysis/SwiftLayout/DependentMemberTypeBridge.swift:52-71` +- **判定**: CONFIRMED +- **失败场景**: `dependentMemberTypeLayout` 代换 witness 后直接递归回 `layout(forTypeNode:)`,这条路径上没有 memo、没有 in-progress 守卫、也没有跳数上限。`__swift5_assocty` 记录里 witness 写成指回自己的 `S.Element`(demangler 的 `Qa` 接受任意基类型)或两条记录互指,就无限递归、栈溢出。 +- **能复现吗**: 能,构造一条自指的关联类型记录。 +- **新的还是旧的**: 旧的。`605e873e`(2026-07-15),`main` 与 0.26.0 都有。 +- **值不值得修**: 修;同模块的 `projectingConcreteMembers` 已有 8 跳上限(`ImageUniverse+AssociatedTypeWitnessProjection.swift:96` 的 `maximumProjectionHops`),照用即可。 +- **以前修过吗**: 没修过。 + +### 待确认(PLAUSIBLE,后果是崩溃或卡死) + +#### 11. 进程内 `symbolicate` 读未映射的内存 + +- **位置**: `Sources/Analysis/CrossReferenceAnalysis/CrossReferenceAnalyzer+Symbolication.swift:135`、`:158-160` +- **判定**: PLAUSIBLE +- **失败场景**: `.protocolReference` 分支没确认已映射就 `memory.pointer(at: value &+ 8)`;`cString(atRuntimeAddress:)` 只确认了 1 个字节已映射就 `String(cString:)` 一直读到终止符。进程内的 `InProcessCrossReferenceMemory` 不做边界检查(MachOKitExtensions `InProcessCrossReferenceMemory.swift:15/30`),槽值为 0 时读的是地址 8,宿主崩溃。文件模式有区间检查,不受影响。 +- **能复现吗**: 机制成立,也违反 `CLAUDE.md`「Read a target's memory only after confirming it is mapped」。正常加载的镜像里 libobjc 修正过的 protorefs / selrefs 都有效,要畸形或半初始化的镜像才触发。还缺的证据:在进程内对一个手工写坏的 `__objc_protorefs` 槽调 `symbolication(of:inImageAt:)`。 +- **新的还是旧的**: 新的。`c9096554`(2026-11-19),已随 0.26.0 发布。 +- **值不值得修**: 建议修,改动小:读之前确认整段已映射,C 字符串设长度上限。 +- **以前修过吗**: 没修过。 + +#### 12. 新的公开同步入口 `objcMembersRefinedForSwift(in:)` 持锁 demangle,没包大栈执行器 + +- **位置**: `Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+ObjCImportedDefinitions.swift:61-62` +- **判定**: PLAUSIBLE +- **失败场景**: 这个入口直接调 `definition.index(in:)` 与各 extension 的 `index(in:)`,后者在 `DefinitionIndexing` 的锁里跑索引并 demangle(`ObjCImportedDefinitions+Indexing.swift:17-28`),之后在 `ObjCImplementingSwiftMembers` 里逐个 demangle,却没有包 `LargeStackTaskExecution.run` 或 `StackSafeExecutor.withLargeStack`。宿主在 512 KB 的协作线程上并发调用时,每次 demangle 都持锁跳到大栈线程等结果,线程池饱和后无限期卡住——`CLAUDE.md`「Never let a demangle or print hop while you hold a lock」描述的就是这个。 +- **能复现吗**: 机制成立。目前只有测试在调用;还缺的证据:在 512 KB 协作线程上并发调用,观察锁等待或卡死。 +- **新的还是旧的**: 新的。`d7fc39b8`(2026-11-17),已随 0.26.0 发布。 +- **值不值得修**: 修,代价很小(包一层执行器)。A61 与 A86 不修的前提是「所有入口都包了执行器」,这个新入口不满足,正好落在 A61 的复审条件里。 +- **以前修过吗**: 同类问题按 A61 处理过(入口统一包执行器);这次是新入口没跟上那条约定。 + +#### 13. ObjC 类型编码的解析递归不设深度上限 + +- **位置**: `Sources/Analysis/SwiftObjCInterop/ObjCTypeEncoding.swift:209-215`、`:232-240`;下游 `ObjCImportedTypes.bareTypeNode`、`flattenedElementCount`(`ObjCImportedTypes.swift:198-203`)、`ObjCEncodedType.withoutExtendedNames` +- **判定**: PLAUSIBLE +- **失败场景**: `readType` 遇到 `^`、`[` 与 block 签名就递归。`__objc_methtype` 或属性的 `T` 特性里放上万个 `^`(或层层嵌套的 `[1[1…`),在 512 KB 的协作线程上解析会栈溢出,宿主崩溃。 +- **能复现吗**: 正常编译器产不出这种编码。还缺的证据:喂一个含 10⁵ 个 `^` 的方法类型串。 +- **新的还是旧的**: 旧的。`ae6b78f0`(2026-10-28),`main` 与 0.26.0 都有。 +- **值不值得修**: 建议修,和上轮第 9 条一起看:上轮限了数组展开后的元素总数,没限嵌套深度。 +- **以前修过吗**: 上轮第 9 条修过同一个解析器的另一种畸形输入(超大 C 数组),没覆盖递归深度。 + +#### 14. `ConformanceProvider` 在锁内同步派发事件,宿主 handler 回调它会死锁 + +- **位置**: `Sources/Declaration/SwiftSpecialization/ConformanceProvider.swift:262-303` +- **判定**: PLAUSIBLE +- **失败场景**: `classHierarchy()` 持 `SubclassCache` 的非递归 `NSLock` 跑 `buildClassHierarchy`,其中某个类 `Class(descriptor:)` 物化失败时同步调 `eventDispatcher.dispatch(.renderingDegraded…)`,handler 在当前线程、锁内执行(`SwiftIndexEvents.swift:119/128-131`)。宿主的 handler 若回调同一个 provider(`subclasses(of:)` / `superclassLink(of:)`,例如收到降级事件后刷新候选列表),会在同一线程重入这把锁,死锁。 +- **能复现吗**: 机制成立;已知宿主里没见到这样回调的 handler。还缺的证据:在 handler 里调 provider,再配一个物化会失败的类。 +- **新的还是旧的**: 旧的。`c6d77bbb`(2026-08-09),`main` 与 0.26.0 都有。 +- **值不值得修**: 待确认;最省事的修法是先收集降级事件,出锁之后再派发。 +- **以前修过吗**: 没修过。 + +## 规则 + +### 新增违规(上次体检以来) + +| 规则 | 位置 | 说明 | +|------|------|------| +| `CLAUDE.md`「On a member's tree it rarely is [the intent]: a declaration's first child is its context …」 | `Sources/Output/SwiftPrinting/ObjCImplementingSwiftMembers.swift:297-302` | `moduleName(ofDemangledMember:)` 在成员整棵树上 `first(of: .extension)` / `first(of: .module)`;参数类型里嵌着 `(extension in M)` 的类型时模块取成 `M`。只在「ObjC 侧 `@`、Swift 侧值类型」时影响配对,输出影响是 PLAUSIBLE。`d7fc39b8`(2026-11-17) | +| 同上 | `Sources/Analysis/SwiftObjCInterop/ObjCSwiftTypeCompatibility.swift:62-71` | `root.first(of: .function)` 排在 `.allocator` 前面,局部类型的 `init` 先命中外层函数,拿外层函数的类型去比 ObjC 编码。`.function` 成员本身不受影响。`d7fc39b8` | +| `CLAUDE.md`「A CLI change updates the skill in the same batch — a new or renamed flag」 | `AgentPlugins/swift-section/skills/swift-section-cli/` | `refs --ivar`(`ReferencesCommand.swift:35`)与 `symbolicate --file`(`SymbolicateCommand.swift:15`)在 `SKILL.md` 与 `references/*.md` 里都没出现;另有一个值得写进 skill 的坑:`refs` 的文件是位置参数,`symbolicate` 却要 `--file`。`7a3ee038`(2026-11-19) | +| `CLAUDE.md`「Read a target's memory only after confirming it is mapped」 | `CrossReferenceAnalyzer+Symbolication.swift:135/158-160` | 即第 11 条。 | + +另外两条判为不违规:`Sources/Declaration/SwiftIndexing/SwiftIndexEventsHandlers.swift:11` 的 `Logger(`(`OSLogEventHandler` 的 subsystem 是运行时参数,`@Loggable` 表达不了,`PrintFailureEventTests` 的 `configurableSinks` 有意放行);`Plugins/RegenerateBaselinesPlugin/RegenerateBaselinesPlugin.swift:56/59` 的 `FileHandle.standard*.write(contentsOf:)`(会抛错的那个重载,不是会触发 ObjC 异常的 `write(_:)`,且插件不是库代码)。 + +### 存量计数 + +全仓(`Sources` 与 `Plugins`,不含生成文件)。本轮多数下降来自 `Sources/MachO/*`、交叉引用下两层与 `TypeIndexing` 搬出仓库,不是修掉的。 + +| 规则 | 模块分布(本轮) | 本轮 | 上轮 | 变化 | +|------|------|------|------|------| +| 不用 `print` 打日志 | SwiftInspection 12(全在 `SpareBitAnalyzer.printAnalysis`)、reader-benchmark 4(A85)、SwiftSectionFixtureSupport 4、SwiftDeclarationRendering 2(都是 `Node.print(using:)`,误报) | 22 | 27 | -5 | +| 不直接用 `os_log` / `Logger(` / `OSSignposter` | SwiftIndexing 1(判为不违规) | 1 | 1 | 0 | +| 不用 `FileHandle.standard*.write` | RegenerateBaselinesPlugin 2、注释 1 | 3 | 3 | 0 | +| 节点工厂调用数(信号) | SwiftThunkAnalysis 10、SwiftLayout 8、SwiftSpecialization 6、SwiftPrinting 4、SwiftDeclarationRendering 4、SwiftSymbols 2、SwiftDump 1、SwiftDeclaration 1 | 36 | 36 | 0 | +| 裸 `NodeReference(interning:`(信号) | SwiftSymbols 5、SwiftPrinting 1、SwiftInspection 1 | 7 | 7 | 0 | +| 单字母泛型参数(A82) | SwiftSectionTestingSupport 13、MachOSwiftSection 7、SwiftSectionFixtureSupport 6、Utilities 5、其余 11 | 42 | 86 | -44 | +| 单字母局部变量 | SwiftInspection 14、SwiftPrinting 7、其余 8 | 29 | 29 | 0 | +| 手写锁(信号) | SwiftThunkAnalysis 5、SwiftDeclarationRendering 5、CrossReferenceAnalysis 4、其余 14 | 28 | 43 | -15 | +| 废弃转发器 | SwiftDeclaration 5、SwiftInterface 2、其余 5 | 12 | 356 | -344(0.25.0 删掉了提案 0057 的转发器) | +| `"Swift.X"` 字面量(信号) | SwiftLayout 34、SwiftInterface 31、SwiftInspection 18 | 83 | 83 | 0 | +| 其余规则(读取器强转、`FullDyldCache.host`、`_mangledTypeName`、`first(of: .privateDeclName)`、裸 `NodeReference` 键、`Task {}`、注释工厂、内存压力、注释掉的日志、`#if false`) | — | 与上轮相同 | — | 0 | +| 新增:`hasPrefix("_Tt")` | 7 处,其中 6 处是协议名 `_TtP` 或过滤候选名;违规 1 处 `ObjCImporterNaming.swift:372`(`ae6b78f0`,2026-10-28,上轮窗口内就有),挡掉了 `$s…` 拼写的类名 | 7 | — | 新行 | +| 新增:裸 `SymbolIndexStore` | 1 处,`SymbolLanguage+Swift.swift:11` 的文档注释,说的正是 MachOKitExtensions 的 C / C++ store,不违规 | 1 | — | 新行 | +| 新增:`DispatchQueue.global(`(信号) | 1 处,`SwiftSymbolIndexStore.prepareWithProgress` 推进度流,调用方 `await` 流而不阻塞线程,不违规 | 1 | — | 新行 | + +## 代码异味与层次 + +### 交叉引用的查询换算写在命令层 + +- **位置**: `Sources/Commands/SwiftSectionKit/CrossReferences/ReferencesRequest.swift:276-500`(重点 `:306-318`、`:427-470`) +- **问题与代价**: 把查询对象换算成表键与候选镜像(`_OBJC_CLASS_$_` / `_OBJC_IVAR_$_` 前缀、`$s…Mn/Ma/N` 归一、类先查符号再回退各镜像的类列表)只写在 `refs` 的请求里,`CrossReferenceAnalyzer` 只给积木。RuntimeViewer 已经在 `RuntimeViewerCrossReferences/Analysis/CrossReferenceQuery.swift:191-357` 自己写了一份,规则一改两边分叉。 +- **更简单的形状**: 在 `CrossReferenceAnalyzer` 上提供一个接收查询对象的 `references(to:direction:among:)`,请求只做格式化。 +- **四问**: 确认;`7a3ee038`(2026-11-19),已在 `main`;第二个使用方已经出现,建议修;没处理过。 + +### 三份解码 `_TtP…` 协议运行时名的代码 + +- **位置**: `Sources/Analysis/SwiftLayout/ObjCProtocolIndex.swift:71-86`(手写解析),对照 `Sources/Analysis/SwiftObjCInterop/SwiftDeclaredObjCProtocolIndex.swift:275`(经 demangler)、`ObjCRuntimeNames.swift:37` +- **问题与代价**: 手写那份只认 `components.count == 2`,Punycode 与嵌套名都读不了;`ObjCProtocolIndex` 与 `ObjCClassIndex` 还各为 `MachOImage`、`MachOFile` 写了两遍构建函数。 +- **更简单的形状**: `SwiftLayout` 已依赖 `SwiftObjCInterop`(同文件 `:63` 就在用 `SwiftDeclaredObjCProtocolIndex`),改调 `qualifiedName(ofDefaultRuntimeName:)`;读取器经 `objcImplementationClassReader` 统一一次。注意合并会多认出 Punycode 与嵌套名,大概率是改进,但不是零变化。 +- **四问**: 确认;`5ee60d0d`(2026-07-16),`main` 上也有;收益中等;没处理过。 + +### 进程内与离线的嵌套特化各写一份 + +- **位置**: `Sources/Declaration/SwiftSpecialization/TypeDefinition+Specialization.swift:296-389` 对照 `:577-664`(`deriveNestedSpecializedTypeChildren` 与 `deriveNestedStaticallySpecializedTypeChildren`),`makeSpecializedDefinition` 与 `makeStaticallySpecializedDefinition` 也是一对 +- **问题与代价**: 约 90 行共享骨架,差别只在实参节点的传递和建特化定义用的函数;嵌套递归、深度上限、尽力而为的容错要改两处。 +- **更简单的形状**: 一份递归,把读取器相关的那一步作为闭包或协议传进来。 +- **四问**: 确认;`b72638f8`(2026-10-02),`main` 上也有;建议下次动特化时合并;没处理过。 + +### `GenericSpecializer` 一个类型管五件事 + +- **位置**: `Sources/Declaration/SwiftSpecialization/GenericSpecializer.swift`(2,147 行;`internalRuntimePreflight` 在 `:833-1034`,约 200 行) +- **问题与代价**: 请求构建、校验、运行时预检、执行、关联类型 witness 解析都在一个类型里,虽然按 extension 分了块。 +- **更简单的形状**: 按现有 MARK 拆成几个协作类型,先把预检的约束求值抽出去。 +- **四问**: 确认;2026-06 起逐步加长,`main` 上也有;收益中等、可排低优先;没处理过。 + +### 上轮的四条 + +`SwiftDeclarationPrinter` 三份成员排序、`SwiftDeclarationIndexer` 阶段函数过长(仍 1,606 行)、`SwiftSymbolIndexStore` 一个文件管太多事(1,778 行,变小只因 C / C++ 部分搬走)、`SwiftDeclaredObjCProtocolIndex` 一半存一半现算:都仍未处理。 + +## 重复代码 + +### enum 的 tag 数公式有三份 + +- **位置**: `Sources/Analysis/SwiftLayout/EnumLayoutBridge.swift:451-478`(`enumTagCounts`)、`Sources/Analysis/SwiftInspection/EnumLayoutCalculator.swift:24-50`(`getEnumTagCounts`)、`Sources/ABI/MachOSwiftSection/Models/Type/Enum/EnumFunctions.swift:8`(`UInt32` 版,见第 7 条的同类实例) +- **重复了什么**: 前两份逐行相同;运行时公式一改,静态与进程内的 enum 布局会分叉。 +- **该合并到哪里**: `SwiftLayout` 已 import `SwiftInspection`,直接调 `EnumLayoutCalculator.getEnumTagCounts`;第三份是公开 API,可改为转发到同一实现。 +- **四问**: 确认,合并后行为不变;`564ef6ee`(2026-06-21),`main` 上也有;建议合并;没处理过。 + +### 测试支持里的转发读取器抄了 MachOKitExtensions 的一份 + +- **位置**: `Sources/TestSupport/SwiftSectionTestingSupport/ForwardingMachOReader.swift:30-178`,对照 MachOKitExtensions `MachOFixtureSupport/ForwardingReader.swift:24-133` +- **重复了什么**: 约 150 行 `MachORepresentable` / `WithCache` 转发逐行相同,本仓库只多 `Readable` 与 `swift`。上游加接口,这里要跟着改。 +- **该合并到哪里**: 给上游的 `ForwardingReader` 加 `where Base: MachOSwiftSectionRepresentableWithCache` 的条件遵循,本包只补那两项(约 40 行)。 +- **四问**: 确认;`58820aa5` / `64a33363`(2026-11-18 / 21,搬家时留下),`main` 上也有前身;建议合并;文件头注释说的「`ForwardingReader` 不转发本包协议」用条件遵循就能解决。 + +### ivar 的关键字选择写了两份 + +- **位置**: `Sources/Output/SwiftDump/Dumper/ObjCImplementationClassDumper.swift:145-174`(及 `:190-194`)与 `Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+ObjCImplementation.swift:117-170`(及 `:153-157`) +- **重复了什么**: 按 facts 取 `recoveredSwiftType`,再在 `lazy var` / `var` / `weak var` / `let` 之间选关键字。第 2 条修的时候要改两处。 +- **该合并到哪里**: 关键字选择放进 `ObjCInstanceVariableSwiftType` 或 `SwiftDeclarationRendering` 共用;两边的类型打印方式与兜底文案不同,只合并关键字那段。 +- **四问**: 确认;`d84944a2` / `1ffe58b6`(2026-11-26),`main` 上没有;建议随第 2 条一起合并;没处理过。 + +### `GenericContext+Dump` 的两个函数几乎相同 + +- **位置**: `Sources/Output/SwiftDeclarationRendering/Extensions/GenericContext+Dump.swift:219-256` 与 `:331-369`(`dumpContent(in:builder:)` 与 `dumpProtocolContent(in:builder:)`),`:336` 还留着一行注释掉的旧调用 +- **重复了什么**: 约 35 行,只差两点:协议版走 `dumpProtocolMangledName`;`Error("SwiftDumpConformance")` 与 `Standard(...)` 不同(A70 判过的有意差异)。 +- **该合并到哪里**: 抽一个私有函数,把这两处差异作为参数。 +- **四问**: 确认;`fedbf876`(2025-08-21),`main` 上也有;收益中等;没处理过。 + +### 上轮的三条 + +ObjC 属性 getter / setter selector 推导两份、ObjC 协议要求的打印两份、「已 realize 的类先经 `class_rw_t` 再取 `class_ro_t`」(本仓库剩三份,第四份随交叉引用搬到了 MachOObjCSection):都仍未处理。 + +## 死代码 + +| 位置 | 判定依据 | 引入 | 建议 | +|------|---------|------|------| +| `SwiftSectionTestingSupportC` 整个 target 与 `Sources/TestSupport/SwiftSectionFixtureSupport/SwiftStdlibDemangle.swift` 的 `stdlib_demangleName` ×2、`stdlib_demangleNodeTree`(`package`) | target 只被这个文件引用,三个函数零调用方;头文件与 swift-demangling 的 `DemanglingTestingSupportC` 相同,`.cpp` 已开始分叉 | `8a67f679`(2026-02-12),`58820aa5` 改名 | 删;要用就依赖上游 | +| `Sources/Output/SwiftDump/Dumper/ExtensionDumper.swift` 整个文件:`ExtensionDumped`、`ExtensionDumper`、`GlobalDumper`(`package`,body 为空) | 除定义外零引用,下游也搜不到 | `d2f298e2`(2025-11-17) | 删 | +| `Sources/Declaration/SwiftDeclaration/Indexing/TypeDefinition/TypeDefinition+ThunkAttributes.swift:30/34`:`applyAttributeToFunction`、`applyAttributeToVariable`(internal) | 零调用方,也没有 `@testable` 用法;匹配逻辑早已移到 `ThunkAttributeMatcher` | `e565bfed`(2026-04-03) | 删 | +| `Sources/ABI/MachOSwiftSection/Extensions/String+.swift:3/8/12/21/25`:`countedString`、`stripProtocolDescriptorMangle`、`stripNominalTypeDescriptorMangle`、`stripProtocolMangleType`、`stripDuplicateProtocolMangleType`(internal) | 零引用;同文件 `insertManglePrefix`(`:16`)也没搜到引用,删时一并核对 | `968fb89e` / `cfde518c`(2025-05-08) | 删 | +| `Sources/Declaration/SwiftDeclaration/Extensions/FieldRecord+DemangledType.swift:12`:`demangledTypeName(in:)`(`package`) | 零调用;同文件的 `demangledTypeNode` 有人用 | `17d101e6`(2026-09-30) | 删 | +| `Sources/TestSupport/SwiftSectionFixtureSupport/DyldSharedCachePath+NamedCaches.swift:7-8`:`iOS_18_5`、`iOS_26_1`(`package`) | 只有定义;IntegrationTests 用的是另一个符号 `MachOFileName.iOS_18_5_Simulator_*` | `64a33363`(2026-11-21) | 删 | +| `Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/BaselineFixturePicker.swift:405/643/659`:`protocol_BaseProtocolTest`、`class_ObjCBridge`、`class_ObjCBridgeWithProto`(`package`) | 零调用,`CoverageAllowlistEntries.swift:327` 只在注释里提到;`:659` 的注释自称「为完整性保留」 | `21524a91`(2026-05-05) | 删或保留,看是否真要「完整性」 | +| public 废弃转发:`OpaqueTypeDescriptorProtocol.swift:14` `numUnderlyingTypeArugments`、`Sources/Analysis/SwiftLayout/ImageUniverse+DependencyClosure.swift:10` `LayoutDependencySearchPath` | 本仓库与已知下游(RuntimeViewer、MachOKitUI、swift-decompiler 等)都没有使用方;后者写着「Kept one release」,从 0.19.0 起已过 0.26.0 | `ca2a570c`(2026-09-18)、`e55978e0`(2026-06-21) | 下个 minor 版删 | + +都不涉及动态引用:复核搜了本仓库 `Sources`、`Tests`、`Plugins`、`Package.swift`、`Tuist`,以及下游 RuntimeViewer、MachOKitUI、swift-decompiler、REAgent、MachOViewer(排除 `.build` 与 `checkouts`)。其余 10 处 `@available(*, deprecated` 不建议现在删:`MetadataReader` 在 RuntimeViewer 的 `RuntimeSwiftInterfaceIndexer.swift:178` 还在用,另外 9 处是 2026-09 到 11 月刚加的改名转发。 + +上轮的四条(`FunctionNodePrinter.swift:106` `isReturnOptional`、`ImageReference.swift:200` `protocolClassConstraint(forQualifiedTypeName:)`、`MangledName.swift:116` `isContentsEqual(to:)`、`MetadataWrapper+Dump.swift:68` `dumpDebugDescription`)都仍未处理。 + +## 复核为 PLAUSIBLE、未达门槛的线索 + +后果不是崩溃、丢数据或安全问题,按门槛不列为发现;记在这里,供以后有证据时重新判断。 + +| 位置 | 机制 | 什么能证实它 | +|------|------|-------------| +| `Sources/Output/SwiftPrinting/ObjCImplementingSwiftMembers.swift:155-178` | 只按名字配对的第 3 步对 Swift 类那条路也生效,候选里包括非 `@objc`、索引没关联的成员 | 同一镜像里一个 ObjC category 给 Swift 类加 `-reload`,Swift 类有同名非 `@objc` 的 `func reload()`,看 `-reload` 是否从「no member of the Swift class answers to」的 extension 里消失 | +| `Sources/Analysis/SwiftObjCInterop/ObjCSwiftTypeCompatibility.swift:28-34` | 「ObjC 侧 `@`、Swift 侧是实现模块自己的值类型」判为明显不兼容;Foundation 自己定义了 `Date`、`DateComponents` 这类会桥接成对象的值类型 | 在 Foundation 里找一个 Swift 实现的类(如 `_NSSwiftCalendar` 的 `date(from:)`),确认它走到第 3 步并被拒 | +| `ObjCImplementingSwiftMembers.swift:297-302`、`ObjCSwiftTypeCompatibility.swift:62-71` | 规则一节的两条整树搜索对输出的实际影响 | 一个走到第 3 步、类型里嵌着 extension 类型的成员;函数里声明的 NSObject 子类的 `init` | +| `Sources/Analysis/SwiftLayout/StaticTypeLayoutResolver.swift:765-791` | 第 1 条撞键让两个类互为父类,触发第 9 条的无限递归 | 造一个撞键后 `M.A` ↔ `M.B` 互为父类的 fixture | + +## 建议不修(用户确认后登记进已裁决清单) + +用户已确认,五条依次登记为 [ReviewAdjudications](../../ReviewAdjudications.md) 的 A92–A96。 + +| 发现 | 理由 | 重新判断的条件 | +|------|------|---------------| +| `@objc @implementation` 类的第 3 层成员配对在打印期现算,不记在定义上(`ObjCImplementingSwiftMembers.swift:8-30`,入口在 `SwiftDeclarationPrinter+ObjCImportedDefinitions.swift:64/81/116/141/260`),dump 与宿主拿不到 | 提案 0096 第 28 行有意如此:配对只服务于 ObjC 侧的 imported 声明,dump 与 Swift 侧的 interface 不受影响。但它和「源码级事实在索引里算、新识别能力默认同时接 dump」的做法相左,值得在下次动这块时重议 | dump 需要显示这层配对,或宿主要从模型读它 | +| 交叉引用扫描在原始内存上手写 context descriptor 的 kind 掩码与名字指针(`Sources/Analysis/CrossReferenceAnalysis/Scanning/SwiftTypeIndex.swift:240-251`) | 扫描热路径,读取必须经 `CrossReferenceMemory`,不能走 ABI 模型的读取 API | `ContextDescriptorFlags` 的布局变化,或 ABI 层提供能经 `CrossReferenceMemory` 读的轻量入口 | +| `ObjCProtocolRecord.swift:162-192` 对 `:202-232`、`ObjCImplementationClassIndex.swift:510-545` 对 `:675-710` 为 `MachOFile`、`MachOImage` 各写一份 | MachOObjCSection 的 `methods(in:)` 等按具体类型重载,返回值是否可选、imp 是 offset 还是要 `resolveOffset(at:)` 都不同,本仓库单方面合不了 | 上游提供泛型的读取 API | +| `OSLogEventHandler` 直接用 `Logger(subsystem:category:)`(`SwiftIndexEventsHandlers.swift:11`) | subsystem 与 category 是宿主运行时传入的参数,`@Loggable` 只接受字面量;`PrintFailureEventTests` 的 `configurableSinks` 有意放行 | FrameworkToolbox 的宏支持运行时 subsystem | +| `SpareBitAnalyzer.printAnalysis` 用 `print` 写 stdout(`Sources/Analysis/SwiftInspection/SpareBitAnalyzer.swift:153-175`) | 公开的调试接口,产物就是打出来的表,库内没有调用方,只有 IntegrationTests 用;已在 `PrintFailureEventTests.swift:177` 只减不增的名单上 | 库代码开始调用它,或它输出诊断信息 | + +## 修复(2026-11-29 同日) + +体检报告写完后,用户批准修 1–10,以及 11–14 中能写出变红测试的。分支 `fix/codebase-audit-2026-11-29`。每条都先在只加了新测试的 `next` 上跑红(第 6、8、9、10、11、13 条是子进程崩溃:SIGBUS 栈溢出、SIGSEGV 读未映射内存、SIGTRAP 算术溢出;其余是断言失败),修复后转绿。 + +- **第 1 条**:`SwiftLayout` 新增 `LayoutTypeNaming`,类型、协议、builtin 记录、assocty witness 的键与查询都保留 private discriminator(`NodeTypeNaming.nominalQualifiedName(of:distinguishesPrivateDeclarations:)`,默认仍不保留);同一镜像里仍重名的键记进 `ImageReference.ambiguousQualifiedTypeNames`,查询报新的失败原因 `.ambiguousTypeName`。按 ObjC 运行时名建的 `instanceStart` 表不变(运行时名总带判别符,剥过符号的描述符不一定带)。测试 `SameNamedPrivateTypeLayoutTests`。 +- **第 2 条**:`ObjCInstanceVariableSwiftType.ambiguity` 记下 ObjC 一侧分不开的两种声明,interface 与 dump 照旧印常见的读法,后面注明 `or unowned(unsafe) …`;只读桥接类只在 ivar 占一个指针时才算有歧义;有访问器符号时按类型是否 `Optional` 在 `weak` 与 `unowned(unsafe)` 之间选。探针确认:`@implementation` 能对上头文件声明的只有 `unowned(unsafe)`,写 `unowned` 编译器报类型不符。fixture 加 `unretainedObserver`、`unretainedOwner`;测试在 `ObjCImplementationClassRecognitionTests`、`ObjCInstanceVariableSwiftTypeTests`。提案 0112 的决策日志补了更正。 +- **第 3 条**:调用点与「按形态认」的 helper 都认导入符号形式的 `swift_getTypeByMangledName…`(`SwiftRuntimeFunctions.nameRegister(ofTypeByMangledNameEntryNamed:)`)。测试 `StrippedStandaloneInstantiationTests`。 +- **第 4 条**:槽值在 `__TEXT` 里、不是类型描述符也不在函数里时报 `.unrecognized(address:)`;值类型元数据经与扫描共用的 `SwiftTypeIndex.descriptorLocation(ofValueMetadataAt:in:typeIndex:)` 报成它的类型。测试 `SlotSymbolicationTests` 的两条(GOT 槽里是另一个库 `__TEXT,__const` 里的常量;`Int` 的元数据)。 +- **第 5 条**:`SymbolicateRequest` 对同名的每个镜像都试,取映射着地址的那个。测试 `CrossReferenceRequestTests.symbolicateReadsAnAddressInTheSameNamedImageThatMapsIt`。 +- **第 6 条**:ABI 层新增 `ContextDescriptorParentChain.maximumLength`(256)与 `MachOSwiftSectionError.parentChainTooLong`;`GenericContext`、`moduleContextDescriptor`、`GenericParameterDepthLayout` 的两处、`ExportStatus`、索引器的两处父链循环都按它截断;`GenericContext` 读父级时只读父级自己的参数,不再为每个父级重走整条链。测试 `ParentChainCycleTests`。 +- **第 7 条**:`EnumLayoutCalculator.maximumProjectedCaseCount`(65,536)与 `canProjectCases(numPayloadCases:numEmptyCases:)`,三个调用方先问;同类实例 `getEnumTagCounts` 照 C++ 用回绕加法。测试在 `MalformedBinaryLayoutTests`。 +- **第 8 条**:`BasicLayout.compute` 与字段循环的加法带溢出检查,单个定长数组不超过 `BasicLayout.maximumValueSize`(2⁴⁸),超出报新的 `.sizeOverflow`。测试在 `MalformedBinaryLayoutTests`。 +- **第 9 条**:解析器按「镜像 + 描述符偏移」记下正在计算的类,父类链绕回报 `.cyclicLayout`;父类名重名时报 `.ambiguousTypeName`。测试在 `MalformedBinaryLayoutTests`。 +- **第 10 条**:关联类型 witness 的递归限 64 层。测试在 `MalformedBinaryLayoutTests`(把 `Circle` 的 witness 改成手写进镜像的 `Circle.Element`)。 +- **第 11 条**:protocol 引用读名字前确认 `value + 8` 已映射;C 字符串只读到映射的尽头、最多 4,096 字节,没有终止符不当字符串。测试 `SlotSymbolicationTests.aProtocolReferenceToNothingMappedReadsAsUnrecognized`(C 库里一个值为 `0x10` 的 `__objc_protorefs` 槽;没有 `__objc_imageinfo`,libobjc 不碰它)。 +- **第 13 条**:`ObjCTypeEncodingParser.maximumNestingDepth`(64),嵌套更深的编码读不出类型。测试 `ObjCTypeEncodingNestingTests`。 +- **规则一节的 skill 缺口**(2026-12-01 补):`references/cross-references.md` 补上 `refs --ivar` 与 `symbolicate --file` 的示例,并在「Things that will bite」里写明 `refs` 的文件是位置参数、`symbolicate` 的要用 `--file`。规则一节另外两条整树搜索与 `ObjCImporterNaming.swift:372` 的 `hasPrefix("_Tt")` 仍未处理。 +- **没修的**:第 12 条(新同步入口持锁 demangle)只有持锁的线程在跳到大栈,其余线程只是等锁,造不出确定的卡死,也观察不到入口内的跳转;第 14 条(锁内派发事件)要一个 `Class(descriptor:)` 失败、索引器却仍保留的类,再配一个回调 provider 的宿主 handler,没能在合理代价内构造。两条按约定不修,仍是待确认。 +- **测试支持**:`SwiftSectionFixtureSupport` 新增 `CompiledFixtureCopies`(剥符号的拷贝、改写字节的拷贝),每份拷贝换一个新 `LC_UUID`——库的按镜像缓存按 UUID 认文件,拷贝与原库同 UUID 时,全量里并行的两个测试串用了对方的类型索引。 +- **验证**:JHs-Mac-Studio-Ultra(macOS 27.2,Xcode 27.2,本地兄弟依赖:`next` 用到 MachOObjCSection 与 MachOKitExtensions 还没发版的接口)。这台机器上已没有 Xcode 26.6,fixture 只能用 27.2 编。新测试在只加了测试的 `next` 上全部变红、修复后全部转绿。全量 `swift test --skip IntegrationTests`:修复分支 3,052 个测试,只有 `MachOSwiftSectionTests` 一个测试包失败(195 处偏移不符,即用非 26.6 编 fixture 的已知漂移),同一份 fixture 下的 `next` 也是这 195 处,没有修复分支独有的失败。第一轮全量曾暴露两处测试自身的问题,已在本批修掉:拷贝与原库同 UUID 导致并行测试串用缓存(见上一条),以及缩写扫描抓到的 `lhs` / `rhs`。CI 的 Xcode 26.6 结果要等推送后看。 + +## 下一轮 + +- **轮转候选**(从未整模块深审,按行数与近期改动排):`MachOSwiftSection`(8,957,两轮都只看了改动集)、`SwiftDeclaration`(6,671)、`SwiftThunkAnalysis`(3,382)、`SwiftIndexing`(2,525),合计约 2.2 万行。之后是 `SwiftPrinting`(8,713)与 `SwiftDeclarationRendering`(7,360),它们这两轮的改动集已覆盖相当一部分。 +- **本轮没覆盖到的**:`SwiftPrinting`、`SwiftDeclarationRendering`、`SwiftSectionKit` 只审了改动集;测试支持(`Sources/TestSupport/*`)只做了结构与冗余,没找 bug;`SwiftTypeNameResolution` 的公开 `CFDeclaredTypeNames.init(machO:imagePath:)` 不做 foreign class 描述符确认,与 `CLAUDE.md` 的字面规则不一致,finder 认为那是给宿主的接口、库内只走受限的 init,没列为发现,下一轮可以确认一下设计意图。 +- 补漏(主线程)重看了 `SymbolicDemangler` 删掉的 80 行(全是 0.25.0 删的废弃转发)、`ObjCInstanceVariableSwiftType` 与属性配对、`--multiline-types` 的 flag 与请求默认值,没有新发现;横向排查补了第 1、5、6、7 条的同类实例。 diff --git a/Documentations/Internal/Reviews/CodebaseAudits/README.md b/Documentations/Internal/Reviews/CodebaseAudits/README.md index 196eea4f2..915299f27 100644 --- a/Documentations/Internal/Reviews/CodebaseAudits/README.md +++ b/Documentations/Internal/Reviews/CodebaseAudits/README.md @@ -4,80 +4,81 @@ ## 模块表 -「最近深审」写「从未(改动集审过 …)」的模块,只审过那一轮改动集里的改动与所在函数,没有整模块深审过;轮转时按「从未」对待。 +「最近深审」写「从未(改动集审过 …)」的模块,只审过那几轮改动集里的改动与所在函数,没有整模块深审过;轮转时按「从未」对待。「未结的严重问题」数的是最近一轮报告里确认与待确认、尚未修掉的严重 bug。 | 模块 | 路径 | 源码行数 | 最近深审 | 深审时的提交 | 未结的严重问题 | |------|------|---------|---------|-------------|---------------| -| CrossReferenceAnalysis | `Sources/Analysis/CrossReferenceAnalysis/` | 4,483 | 2026-11-16 | `1ba927ad` | 0 | -| ARM64InstructionDecoding | `Sources/Support/ARM64InstructionDecoding/` | 279 | 2026-11-16 | `1ba927ad` | 0 | -| SwiftObjCInterop | `Sources/Analysis/SwiftObjCInterop/` | 7,073 | 2026-11-16 | `1ba927ad` | 0 | -| SwiftThunkAnalysis | `Sources/Analysis/SwiftThunkAnalysis/` | 3,629 | 从未(改动集审过 2026-11-16) | — | 0 | -| SwiftInspection | `Sources/Analysis/SwiftInspection/` | 6,316 | 从未(改动集审过 2026-11-16) | — | 0 | -| SwiftLayout | `Sources/Analysis/SwiftLayout/` | 4,704 | 从未(改动集审过 2026-11-16) | — | 0 | -| SwiftDeclaration | `Sources/Declaration/SwiftDeclaration/` | 6,631 | 从未(改动集审过 2026-11-16) | — | 0 | -| SwiftIndexing | `Sources/Declaration/SwiftIndexing/` | 2,509 | 从未(改动集审过 2026-11-16) | — | 0 | -| SwiftSpecialization | `Sources/Declaration/SwiftSpecialization/` | 4,883 | 从未(改动集审过 2026-11-16) | — | 0 | -| SwiftPrivateDiscriminators | `Sources/Declaration/SwiftPrivateDiscriminators/` | 828(不含生成文件) | 从未(改动集审过 2026-11-16) | — | 0 | -| SwiftAttributeInference | `Sources/Declaration/SwiftAttributeInference/` | 191 | 从未 | — | — | -| TypeIndexing | `Sources/Declaration/TypeIndexing/` | 1,311 | 从未 | — | — | -| SwiftPrinting | `Sources/Output/SwiftPrinting/` | 7,543 | 从未(改动集审过 2026-11-16) | — | 0 | -| SwiftDeclarationRendering | `Sources/Output/SwiftDeclarationRendering/` | 6,580 | 从未(改动集审过 2026-11-16) | — | 0 | -| SwiftDump | `Sources/Output/SwiftDump/` | 3,323 | 从未(改动集审过 2026-11-16) | — | 0 | -| SwiftInterface | `Sources/Output/SwiftInterface/` | 4,065 | 从未(改动集审过 2026-11-16) | — | 0 | -| SwiftDiffing | `Sources/Output/SwiftDiffing/` | 3,698 | 从未(改动集审过 2026-11-16) | — | 0 | +| CrossReferenceAnalysis | `Sources/Analysis/CrossReferenceAnalysis/` | 2,967 | 2026-11-16(2026-11-29 又审了改动集) | `1ba927ad` | 0 | +| SwiftObjCInterop | `Sources/Analysis/SwiftObjCInterop/` | 7,574 | 2026-11-16(2026-11-29 又审了改动集) | `1ba927ad` | 0 | +| SwiftInspection | `Sources/Analysis/SwiftInspection/` | 6,256 | 2026-11-29 | `947d5321` | 0 | +| SwiftLayout | `Sources/Analysis/SwiftLayout/` | 4,717 | 2026-11-29 | `947d5321` | 0 | +| SwiftSpecialization | `Sources/Declaration/SwiftSpecialization/` | 4,886 | 2026-11-29 | `947d5321` | 1(待确认) | +| SwiftThunkAnalysis | `Sources/Analysis/SwiftThunkAnalysis/` | 3,382 | 从未(改动集审过 2026-11-16、2026-11-29) | — | 0 | +| SwiftDeclaration | `Sources/Declaration/SwiftDeclaration/` | 6,671 | 从未(改动集审过 2026-11-16、2026-11-29) | — | 0 | +| SwiftIndexing | `Sources/Declaration/SwiftIndexing/` | 2,525 | 从未(改动集审过 2026-11-16、2026-11-29) | — | 0 | +| SwiftPrivateDiscriminators | `Sources/Declaration/SwiftPrivateDiscriminators/` | 829(不含生成文件) | 从未(改动集审过 2026-11-16、2026-11-29) | — | 0 | +| SwiftAttributeInference | `Sources/Declaration/SwiftAttributeInference/` | 192 | 从未 | — | — | +| SwiftPrinting | `Sources/Output/SwiftPrinting/` | 8,713 | 从未(改动集审过 2026-11-16、2026-11-29) | — | 1(待确认) | +| SwiftDeclarationRendering | `Sources/Output/SwiftDeclarationRendering/` | 7,360 | 从未(改动集审过 2026-11-16、2026-11-29) | — | 0 | +| SwiftDump | `Sources/Output/SwiftDump/` | 3,343 | 从未(改动集审过 2026-11-16、2026-11-29) | — | 0 | +| SwiftInterface | `Sources/Output/SwiftInterface/` | 4,069 | 从未(改动集审过 2026-11-16、2026-11-29) | — | 0 | +| SwiftDiffing | `Sources/Output/SwiftDiffing/` | 3,701 | 从未(改动集审过 2026-11-16) | — | 0 | | SwiftOutputTransformer | `Sources/Output/SwiftOutputTransformer/` | 1,527 | 从未 | — | — | -| SwiftSectionKit | `Sources/Commands/SwiftSectionKit/` | 3,155 | 从未(改动集审过 2026-11-16) | — | 0 | -| swift-section | `Sources/Executables/swift-section/` | 2,242 | 从未(改动集审过 2026-11-16) | — | 0 | -| reader-benchmark | `Sources/Executables/reader-benchmark/` | 285 | 从未(改动集审过 2026-11-16) | — | 0 | +| SwiftTypeNameResolution | `Sources/Output/SwiftTypeNameResolution/` | 465 | 从未(改动集审过 2026-11-29,当时整个模块都是新增) | — | 0 | +| SwiftSectionKit | `Sources/Commands/SwiftSectionKit/` | 4,311 | 从未(改动集审过 2026-11-16、2026-11-29) | — | 0 | +| swift-section | `Sources/Executables/swift-section/` | 2,551 | 从未(改动集审过 2026-11-16、2026-11-29) | — | 0 | +| reader-benchmark | `Sources/Executables/reader-benchmark/` | 286 | 从未(改动集审过 2026-11-16) | — | 0 | | baseline-generator | `Sources/Executables/baseline-generator/` | 33 | 从未 | — | — | -| MachOSwiftSection | `Sources/ABI/MachOSwiftSection/` | 10,453 | 从未(改动集审过 2026-11-16) | — | 0 | -| MachOSwiftSectionC | `Sources/ABI/MachOSwiftSectionC/` | 588 | 从未 | — | — | -| MachOSymbols | `Sources/MachO/MachOSymbols/` | 3,207 | 从未(改动集审过 2026-11-16) | — | 0 | -| MachODependencies | `Sources/MachO/MachODependencies/` | 1,156 | 从未(改动集审过 2026-11-16) | — | 0 | -| MachOReading | `Sources/MachO/MachOReading/` | 1,416 | 从未(改动集审过 2026-11-16) | — | 0 | -| MachOResolving | `Sources/MachO/MachOResolving/` | 431 | 从未(改动集审过 2026-11-16) | — | 0 | -| MachOPointers | `Sources/MachO/MachOPointers/` | 809 | 从未 | — | — | -| MachOCaches | `Sources/MachO/MachOCaches/` | 675 | 从未 | — | — | -| MachOBase、MachOFoundation | `Sources/MachO/MachOBase/`、`Sources/MachO/MachOFoundation/` | 13 | 从未 | — | — | -| Utilities | `Sources/Support/Utilities/` | 507 | 从未(改动集审过 2026-11-16) | — | 0 | -| MachOMacros | `Sources/Support/MachOMacros/` | 452 | 从未(改动集审过 2026-11-16) | — | 0 | -| MachOFixtureSupport | `Sources/TestSupport/MachOFixtureSupport/` | 17,324 | 从未 | — | — | -| MachOTestingSupport | `Sources/TestSupport/MachOTestingSupport/` | 5,829 | 从未(改动集只做过结构与冗余审查 2026-11-16) | — | — | -| MachOTestingSupportC | `Sources/TestSupport/MachOTestingSupportC/` | 18 | 从未 | — | — | +| MachOSwiftSection | `Sources/ABI/MachOSwiftSection/` | 8,957 | 从未(改动集审过 2026-11-16、2026-11-29) | — | 0 | +| MachOSwiftSectionC | `Sources/ABI/MachOSwiftSectionC/` | 610 | 从未 | — | — | +| SwiftSymbols | `Sources/Symbols/SwiftSymbols/` | 2,519 | 从未(改动集审过 2026-11-29;前身 `MachOSymbols` 的改动集审过 2026-11-16) | — | 0 | +| SwiftSymbolsRegistration | `Sources/Symbols/SwiftSymbolsRegistration/` | 45 | 从未(改动集审过 2026-11-29) | — | 0 | +| Utilities | `Sources/Support/Utilities/` | 507 | 从未(改动集审过 2026-11-16、2026-11-29) | — | 0 | +| SwiftSectionMacros | `Sources/Support/SwiftSectionMacros/` | 452 | 从未(前身 `MachOMacros` 的改动集审过 2026-11-16) | — | 0 | +| SwiftSectionFixtureSupport | `Sources/TestSupport/SwiftSectionFixtureSupport/` | 16,881 | 从未(改动集只做过结构与冗余审查 2026-11-29) | — | — | +| SwiftSectionTestingSupport | `Sources/TestSupport/SwiftSectionTestingSupport/` | 5,496 | 从未(改动集只做过结构与冗余审查 2026-11-16、2026-11-29) | — | — | +| SwiftSectionTestingMacros | `Sources/TestSupport/SwiftSectionTestingMacros/` | 185 | 从未(改动集只做过结构与冗余审查 2026-11-29) | — | — | +| SwiftSectionTestingSupportC | `Sources/TestSupport/SwiftSectionTestingSupportC/` | 18 | 从未(2026-11-29 判为死代码,建议删) | — | — | | RegenerateBaselinesPlugin | `Plugins/RegenerateBaselinesPlugin/` | 81 | 从未 | — | — | +**已搬出仓库,不再轮转**(2026-11-16 到 11-29 之间):`MachOSymbols` 的 C / C++ 一半、`MachODependencies`、`MachOReading`、`MachOResolving`、`MachOPointers`、`MachOCaches`、`MachOBase`、`MachOFoundation`、`ARM64InstructionDecoding`,以及交叉引用的下两层,都去了 MachOKitExtensions(`ObjCCodeReferences` 去了 MachOObjCSection);`TypeIndexing` 去了 swift-type-indexing。它们的体检归各自的仓库。`MachOSymbols` 的 Swift 一半留下成了 `SwiftSymbols`;`MachOMacros`、`MachOFixtureSupport`、`MachOTestingSupport`、`MachOTestingSupportC` 改名为 `SwiftSection…`。 + **不审**: -- `Sources/Declaration/SwiftPrivateDiscriminators/PrivateDiscriminatorSourceFiles+KnownFileNames.swift`(`Scripts/GenerateKnownSwiftSourceFileNames.sh` 生成,2,027 行)。 -- `Tests/`(25 个测试目标,约 8.3 万行;含 `Tests/Projects/` 下的 fixture 源码,它们为了制造特定的二进制形态而刻意写得古怪):只作为核对发现时的证据读,不轮转深审。要纳入轮转,在这里改写并给它们加行。 -- `Scripts/`(A/B 验证用的 Python 脚本,不是构建目标)、`AgentPlugins/`(agent 插件的文档)、`Documentations/`。 +- `Sources/Declaration/SwiftPrivateDiscriminators/PrivateDiscriminatorSourceFiles+KnownFileNames.swift`(`Scripts/GenerateKnownSwiftSourceFileNames.sh` 生成)。 +- `Tests/`(含 `Tests/Projects/` 下的 fixture 源码,它们为了制造特定的二进制形态而刻意写得古怪):只作为核对发现时的证据读,不轮转深审。要纳入轮转,在这里改写并给它们加行。 +- `Scripts/`(A/B 验证用的 Python 脚本,不是构建目标)、`AgentPlugins/`(agent 插件的文档,只在规则检查里核对 flag 是否同步)、`Documentations/`。 +- 外部包(MachOKitExtensions、MachOObjCSection、swift-demangling、swift-type-indexing 等):只作为核对证据读。 ## 规则检查式 -在仓库根目录运行;全部带 `-g '*.swift' Sources Plugins`,并排除 `PrivateDiscriminatorSourceFiles+KnownFileNames.swift`(`| grep -v KnownFileNames | wc -l`)。计数包含注释与字符串里的命中,只用来看趋势;每条命中算不算违规由各轮报告判断。 +在仓库根目录运行;全部带 `-g '*.swift' Sources Plugins`,并排除 `PrivateDiscriminatorSourceFiles+KnownFileNames.swift`(`| grep -v KnownFileNames | wc -l`)。计数包含注释与字符串里的命中,只用来看趋势;每条命中算不算违规由各轮报告判断。2026-11-29 的多数下降来自模块搬出仓库,不是修掉的。 -| 规则 | 来源 | 检查式(`rg -nP`) | 2026-11-16 | -|------|------|--------|-----------| -| 不用 `print` 打日志 | 全局指令「编码风格」;项目 `CLAUDE.md`「writing a log statement」 | `'(?)'` | 86 | -| 不用单字母局部变量 | 全局指令「编码风格」 | `'\b(let\|var)\s+[a-z]\s*[=:]\|\bfor\s+(case\s+let\s+)?[a-z]\s+in\b'` | 29 | -| 不用 `FullDyldCache.host` | 项目 `CLAUDE.md`「MachODependencies」一段 | `'FullDyldCache\.host(?!\w)'` | 0 | -| 运行时 metatype 不裸用 `_mangledTypeName` | 项目 `CLAUDE.md`「touching the demangler…」 | `'_mangledTypeName\('` | 1 | -| 不用 `first(of: .privateDeclName)` 读鉴别符(信号) | 同上 | `'first\(of: \.privateDeclName\)'` | 2 | -| `NodeReference` 作键要用 `StructuralNodeReferenceKey`(信号) | 同上 | `'\[\s*NodeReference\s*:\|Set\|Dictionary)'` | 86 | 42 | +| 不用单字母局部变量 | 全局指令「编码风格」 | `'\b(let\|var)\s+[a-z]\s*[=:]\|\bfor\s+(case\s+let\s+)?[a-z]\s+in\b'` | 29 | 29 | +| 不用 `FullDyldCache.host` | 项目 `CLAUDE.md`「MachODependencies」一段 | `'FullDyldCache\.host(?!\w)'` | 0 | 0 | +| 运行时 metatype 不裸用 `_mangledTypeName` | 项目 `CLAUDE.md`「touching the demangler…」 | `'_mangledTypeName\('` | 1 | 1 | +| 不用 `first(of: .privateDeclName)` 读鉴别符(信号) | 同上 | `'first\(of: \.privateDeclName\)'` | 2 | 2 | +| `NodeReference` 作键要用 `StructuralNodeReferenceKey`(信号) | 同上 | `'\[\s*NodeReference\s*:\|Set\|Dictionary`。 +- 有 Swift 的镜像里,ObjC 代码写的 category 遵循照样打成 `extension X: P {}`。链接器(2026-11 实测 ld-27106)把同一个类的 category 合成一个,名字取第一个、协议取并集:AppKit 27.2 的 `NSString (AppKit)` 带着 `NSPasteboard.h` 里 ObjC 声明的 `NSPasteboardWriting`、`NSPasteboardReading`,SwiftUICore 的 `NSObject (CoreAX)` 名字是 ObjC 的,里面却有 Swift 实现的成员。所以按 category 名(Swift 默认取模块名,见 `GenClass.cpp` 的 `buildCategoryName`)过滤会多列也会漏列,没有采用。要分开只能逐个协议看实现它要求的方法是不是 Swift 的(符号或 thunk),尚未做。 - 实现者只在本镜像里找,不到别的镜像里找。 ## 验证 - `SwiftDeclaredObjCProtocolsFixture`(SwiftSectionTestingSupport)测试时现编两个镜像。kit 声明三个 `@objc` 协议(没改名、改成自身名字、改成别的名字);客户端声明六种形状的协议(编译器推导 selector、改成自身名字、改成别的名字、继承另一个、internal、嵌套在类型里)、在类声明与同模块 extension 里采纳它们的类、采纳 kit 协议的类、遵循继承 `NSCopying` 的 Swift 协议的类、extension `DateFormatter` 采纳协议(category),以及装着改名协议与嵌套协议存在类型的结构体;`.full`、关掉反射元数据、`strip -x` 三个变体。 +- `ObjCWrittenCategoriesFixture`(SwiftSectionTestingSupport)与 `ObjCWrittenCategoryConformanceTests`(SwiftIndexingTests):同一段 ObjC 代码(`NSString`、`NSDateFormatter` 的 category 采纳一个 ObjC 协议)单独编成一个镜像,以及和两个 extension `DateFormatter` 的 Swift 文件编进一个镜像。前者从文件与进程内读都不出 category 遵循;后者两个 Swift 协议都留着。 - `SwiftDeclaredObjCProtocolIndexTests`、`ObjCImporterNamingTests`、`ObjCProtocolRequirementBuilderTests`(SwiftObjCInteropTests):配对、退回路径、没认领的记录;命名规则对照真实 ClangImporter 的输出(含 DVTFoundation 的 selector);要求的种类、访问器、类成员与 optional。 - `ObjCProtocolDefinitionIndexingTests`(SwiftIndexingTests):文件、进程内、strip 后的文件三条路径的模型——要求的来源(selector 或实现者)、strip 后经 thunk 代码联结、继承的协议、默认实现、类与 category 的协议、跨镜像找回的改名协议、隐含协议的剔除。 - `SwiftDeclaredObjCProtocolInterfaceTests`(SwiftInterfaceTests)、`SwiftDeclaredObjCProtocolDumpTests`(SwiftDumpTests)、`SwiftDeclaredObjCProtocolRequestTests`(SwiftSectionKitTests):两种输出、两种 dump 排序、进程内与文件的 interface 一致。 diff --git a/Documentations/Internal/TuistDevelopment.md b/Documentations/Internal/TuistDevelopment.md new file mode 100644 index 000000000..e03841058 --- /dev/null +++ b/Documentations/Internal/TuistDevelopment.md @@ -0,0 +1,120 @@ +# 使用指南:Tuist 开发 workspace + +- **面向**: 在本仓库做日常开发、想让第三方依赖走二进制缓存的人;同时改本库和上游那几个库的人;改 `Package.swift` 的 target、依赖或测试的人(同步规则) +- **对应提案**: [0099-tuist-workspace](../Evolutions/0099-tuist-workspace.md) +- **最后更新**: 2026-11-21 + +`MachOSwiftSection-Tuist.xcworkspace` 是原生 `MachOSwiftSection.xcworkspace` 之外的第二条路,只供日常开发。它由 `./TuistScript.sh` 用 Tuist 生成:本库照常从源码编,可以跳转、可以编辑;原生 workspace 里放的五个上游库(MachOKit、MachOKitExtensions、MachOObjCSection、swift-demangling、swift-semantic-string)也从源码编;其余 27 个第三方包(swift-dependencies 一族、swift-collections、Capstone、swift-crypto、Yams……)预编进本机的 Tuist 二进制缓存,只编一次。 + +**`Package.swift` 仍是 target 与依赖的唯一定义。** Tuist 直接读它,把本库转换成 `MachOSwiftSection.xcodeproj`;手写的只有 Tuist 转换不了的那部分(`Tuist/CommandLine/Project.swift`,见下文)。 + +**发版、CI、`swift build` / `swift test` 和原生 workspace 都不走这里**,Tuist 这边出问题不影响它们。生成的工程文件都已忽略,不提交。 + +## 第一次使用 + +```bash +mise install # 装 mise.toml 钉的 Tuist(4.210.0,与 RuntimeViewer 相同) +./TuistScript.sh warm # 解析依赖 → 把第三方依赖编进缓存 → 生成 workspace +open MachOSwiftSection-Tuist.xcworkspace +``` + +- **锁文件**:脚本每次解析都从本检出根目录的 `Package.resolved`(`swift build` 与原生 workspace 解析出的那份,不提交)开始,所以 Tuist 用的是同样的版本。没有这个文件时 Tuist 解析各清单允许的最新版本,并提示一句;新 worktree 里可以先从集成检出拷一份过来。解析完与它不一致时会列出差异,多半是换了 Xcode:有些包按 Swift 版本选用不同的清单。 +- **Xcode**:脚本和 Tuist 都用 `DEVELOPER_DIR` 或 `xcode-select` 选中的那个,打开 workspace 也用同一个。二进制缓存按 Xcode 版本分开,换了 Xcode 要重新 `warm`。 +- **缓存省多少**:2026-11-20 在 Ultra(M3 Ultra 28 核,Xcode 27.2)上,清空 DerivedData 后编 `swift-section`(Debug),不走缓存 63 秒,走缓存 46 秒;`warm` 把 70 个第三方 target 编成 xcframework 用了 60 秒。省下的是第三方依赖那部分,本库与上游库照旧从源码编;核心少的机器上没有测过。 + +## 日常用法 + +| 要做的事 | 做法 | +|---|---| +| 编辑、构建、运行 CLI | scheme `swift-section` | +| 跑本库的测试 | scheme `MachOSwiftSection Tests`:`Package.swift` 里除 `IntegrationTests` 外的全部测试 target | +| 命令行构建 / 测试 | `./TuistScript.sh build`、`./TuistScript.sh test`,`--` 之后的参数原样交给 `xcodebuild`(例如 `-- -only-testing:SwiftDumpTests`) | +| 增删了源文件 | `./TuistScript.sh generate`(Tuist 转换包时按 glob 展开文件;只改已有文件不用) | +| 改了 `Package.swift`、换了根目录的 `Package.resolved` | `./TuistScript.sh generate`:脚本发现清单或种子锁文件变了,会先重新解析 | +| 第三方依赖升级、换了 Xcode | `./TuistScript.sh warm`(只重编变了的) | +| 同时改上游库 | `./TuistScript.sh generate --local-dependencies`,见下文 | +| 不再用这个 workspace,或要把本检出让给 RuntimeViewer 的本地模式 | `./TuistScript.sh release` | + +**别直接跑 `tuist generate` / `tuist install`。** 清单读的环境变量(哪些 target 留作源码、哪些测试进 scheme、要不要映射测试、本地模式的目录)都由脚本算好再传进去;直接跑 Tuist 拿不到它们,也没有下文的占用保护。 + +**生成出的工程只链接一套配置的缓存。** 默认按 Debug 生成;要在 Xcode 里编 Release,先 `./TuistScript.sh generate --configuration Release`,编完不带参数再 `generate` 回到 Debug。缓存也按配置分开预热(`warm --configuration Release`)。 + +**让测试少打输出**:同 CI 一样,在命令前加 `MACHO_SWIFT_SECTION_SILENT_TEST=1`(例如 `MACHO_SWIFT_SECTION_SILENT_TEST=1 ./TuistScript.sh test`)。它有两处效果:`Package.swift` 照旧给本库的测试 target 加编译条件 `SILENT_TEST`(手写的 `SwiftSectionCommandTests` 经脚本转成的 `TUIST_SILENT_TEST` 加);生成的每个测试 scheme 在 TestAction 的环境里设 `MACHO_TESTING_SILENT=1`(`Workspace.swift`),MachOKitExtensions 的 `MachOFixtureSupport` 在测试进程里读它,让测试里的 `.print()` 不出声——这个开关是运行时的环境变量,编译条件到不了 MachOKitExtensions 的模块。变量改了要重新 `generate`(`test`、`build` 每次都会先生成);在 Xcode 里直接跑这些 scheme 时,也是生成时的设置说了算。 + +## 用本地检出的上游库 + +同时改本库和上游库时,Tuist workspace 也能像原生 workspace 的本地依赖那样,直接编它们的本地检出,其余第三方依赖照旧走缓存: + +```bash +./TuistScript.sh generate --local-dependencies # 打开;之后不带参数的命令都沿用 +./TuistScript.sh generate --remote-dependencies # 回到锁文件钉住的版本(默认) +``` + +- **哪几个库、从哪取**:原生 workspace 的 `container:../<名字>` 成员,现在是上面五个;原生 workspace 加了库,这里自动跟上。默认从检出的上一级目录取,worktree 里就是 `.worktrees/` 下那组链接,所以编的是那组链接指向的检出(比如 `.worktrees/MachOKitExtensions` 指向 MachOKitExtensions 的主检出时,编的就是它当前所在的分支)。打开本地模式时设了 `TUIST_LOCAL_PACKAGE_CHECKOUTS`,就改从它指的目录取:每个库一个子目录,名字与库相同(SwiftPM 按目录名认包,经符号链接也一样按真实目录名认)。 +- **效果**:`Tuist/Package.swift` 按路径声明这几个库,顶替依赖图里所有按 URL 声明的同名包。它们从本地源码编,没提交的改动也算;改已有文件后在 Xcode 里直接编就生效。它们的编译警告照常显示。 +- **测试**:六个包的测试都进 workspace,每个包一个 scheme(`<包名> Tests`)。做到这一点要每个库的 `Package.swift` 末尾都有那段 `TUIST_MAPS_LOCAL_PACKAGE_TESTS` 适配块(见下一节);MachOKitExtensions、MachOObjCSection、swift-demangling 已经加了,MachOKit 与 swift-semantic-string 现在用不着。某个库的检出停在加块之前的提交、又有 Tuist 不接受的测试时,脚本会警告并点名那个库,这一次整个 workspace 都不带测试(Tuist 对按路径声明的包只能全映射或全不映射),生成照常进行。上游库自己的测试里有读写死路径的(MachOKit 的 `AotCachePrintTests`、`ArchiveFileTests`,MachOObjCSection 的 `MachOObjCSectionTests` 读 `/Users/JH/Downloads/iOS18.5-SwiftUI`),在没有这些文件的机器上照样失败,与 Tuist 无关。 +- **模式会记住**:记在 `Tuist/.local-dependencies`(已忽略),之后不带参数的命令都沿用;每条命令开头都打印当前用的是哪种依赖。两种模式各有一份依赖 checkout,切换后会先重新解析。 +- **写进库目录的文件**:Tuist 会在每个按路径声明的包目录里生成 `<包名>.xcodeproj/` 和 `Derived/`。脚本把这两项写进那个仓库的 `info/exclude`(只在本机,不提交),`git status` 里看不到;切回远程模式时删掉 `<包名>.xcodeproj/`,`Derived/` 留着。git 跟踪着 `<包名>.xcodeproj` 的库,脚本直接报错,不让 Tuist 覆盖。 + +## 与 RuntimeViewer 共用的占用记录 + +RuntimeViewer 的 Tuist workspace 在它的本地依赖模式下也往这几个检出里生成同名工程,其中也包括本库的检出;而本库的 Tuist workspace 每次都往本检出根目录生成 `MachOSwiftSection.xcodeproj`。两边的设置不同,谁后生成谁就让另一边的 workspace 坏掉,所以两个脚本生成之前都先「占用」检出: + +- 被占检出的 git 目录里写 `tuist-generated-project-owner`:占用者检出的路径、在占用者那里释放它的命令、生成进来的工程名。 +- 占用者在自己的 `Tuist/.claimed-checkouts`(已忽略)里列出手里的检出,列着才算有效;占用者已经不在或不再列着,记录就是陈旧的,直接接管。 +- 另一个检出占着时,命令报错并给出在那边要跑的释放命令:本库是 `./TuistScript.sh release`,RuntimeViewer 是 `./TuistScript.sh generate --remote-dependencies`。RuntimeViewer 旧版脚本写的 `runtimeviewer-tuist-local-dependencies` 记录也认。 +- **本库的检出在两种模式下都被自己占着**,本地模式下再加五个上游库。所以要让 RuntimeViewer 的本地模式用这个检出,先在这里 `./TuistScript.sh release`;反过来,RuntimeViewer 的本地模式占着这个检出时,这里的 `generate` 会报错,先在 RuntimeViewer 那边切回远程。 + +## 测试是怎么映射进来的 + +Tuist 把按路径声明的包的测试 target 一起转换(`PackageSettings` 的 `includeLocalPackageTestTargets`),但它拒绝几种 SwiftPM 接受的测试:依赖可执行 target 的(本库的 `SwiftSectionCommandTests`、MachOObjCSection 的 `ObjCSectionCommandTests`);依赖宏 target 的(本库的 `SwiftSectionTestingMacrosTests`:Tuist 把宏编成插件,`@testable import SwiftSectionTestingMacros` 找不到模块);和依赖一个不属于任何 product 的普通 target 的(本库的 `SwiftSectionFixtureSupport`、`SwiftSectionTestingSupport`,swift-demangling 的 `DemanglingTestingSupport`)。 + +- **适配块**:`Package.swift` 末尾那段代码只在 `TUIST_MAPS_LOCAL_PACKAGE_TESTS=1` 时生效——脚本解析依赖时设它——把依赖可执行 target 或宏 target 的测试拿掉(宏的展开测试因此只在 `swift test` 里跑),给依赖非 product target 的测试所依赖的 target 补一个 library product。平时这个变量不存在,块里什么都不做:`swift package dump-package` 的输出与没有这段代码时逐字节相同。规则是通用的,以后新加的这几种测试不用再改清单。三个上游库的清单末尾是同一段代码,改的时候四处一起改(2026-11-21 加「宏 target」一条时四处同步改了,三个上游库没有宏 target,对它们没有实际作用)。 +- **`SwiftSectionCommandTests` 手写在 `Tuist/CommandLine/Project.swift`**:它 `@testable import swift_section`,也就是可执行 target 自己的模块。那里把 CLI 的源码编成静态 framework `swift_section` 给它用,`swift-section` 工具再编一遍同样的源码,链接时不用绕开 `@main` 的入口。**CLI 的依赖列表是 Tuist 描述里唯一手抄的一份**:`Package.swift` 里 `swift-section` 加了依赖,这里也要加,否则编不过。MachOObjCSection 的 `ObjCSectionCommandTests` 不手写,留在 `swift test` 里跑。 +- **只被测试用到的外部依赖要在 `Tuist/Package.swift` 里声明**(现在只有 swift-snapshot-testing),否则 Tuist 报 `… depends on 'X', which is not a configured external dependency`。按 `Package.swift` 里的版本要求加上即可。 +- **`IntegrationTests`** 会被转换进来,但不进任何 scheme(`AGENTS.md`:维护者手工查看用的,不跑)。 + +## 存放位置 + +`/Volumes/DerivedData` 挂载时,全部放在 `/Volumes/DerivedData/MachOSwiftSection/Tuist/` 下;没挂载时放在仓库里(`Tuist/.build/`、`Tuist/.build-LocalDependencies/`、`DerivedData/Tuist/`,都已忽略)。`TUIST_SCRIPT_ROOT` 可以指定别处。 + +| 目录 | 内容 | +|---|---| +| `Cache/` | Tuist 的二进制缓存与清单缓存,所有检出共用(按内容寻址) | +| `Dependencies//` | 远程模式的依赖 checkout,每个检出一份;`-LocalDependencies` 后缀的是本地模式那份 | +| `WarmScratch//` | 预热时的临时构建目录,每次预热前清空 | +| `Work//` | `build` / `test` 的 DerivedData 与 `.xcresult`、各包解析后的清单(`Manifests/`)、上次解析依赖用的模式与清单(`InstalledDependencies`) | + +`` 是检出目录名加路径的短 hash,同名的两个 worktree 不会混用。想从头来:删掉 `Dependencies//` 与 `Work//InstalledDependencies` 后 `install`,删掉 `Cache/` 后 `warm`。 + +脚本的日志在仓库内的 `Products/Logs/Tuist/`(已忽略)。Tuist 命令的输出原样显示在终端,同时记进日志;`xcodebuild` 的输出只记进日志,失败时终端只显示错误摘要。`test` 结束时打印通过 / 失败 / 跳过的个数,`.xcresult` 的路径在日志开头。 + +**Agent 运行时**用 `TUIST_SCRIPT_ROOT=/Volumes/DerivedData/Agents.noindex//Tuist-MachOSwiftSection`。`install`、`generate`、`release` 不编译,可以直接跑;`warm`、`build`、`test` 要编译,经 `queued-build` 运行,在公司那台 Mac Studio 上按远程构建的规矩放到 Ultra 上跑。 + +## 已知的坑:清单里那些看着奇怪的写法 + +都是为了绕开 Tuist 4.210 的行为,改之前先看这里。 + +- **测试 scheme 关掉了 Main Thread Checker 与 Thread Performance Checker**(`Workspace.swift`,以及脚本生成后补的 `disablePerformanceAntipatternChecker`):后者往测试进程里插入 `libRPAC.dylib`,改写已加载镜像里的调用,`CrossReferenceAnalysisTests` 里拿进程内读到的 cache 镜像和同一镜像的文件比对的测试就看到一批指向 `libRPAC` 的调用而失败。关掉之后测试进程与 `swift test` 的一样。Tuist 4.210 只往 TestAction 写主线程检查那一项,另一项由脚本在生成后补上,所以别直接跑 `tuist generate`。 +- **工具 target 写明 `productName: "swift-section"`**:Tuist 会把 target 名里的 `-` 换成 `_`,不写的话编出来的可执行文件叫 `swift_section`。 +- **CLI 的部署版本是 macOS 12.0**(`Tuist/CommandLine/Project.swift`):Tuist 把 swift-argument-parser 编成它声明的最低版本 macOS 12,10.15 的 `swift-section` import 不了它。 +- **测试 target 的部署版本抬到 macOS 14.0**(`Tuist/Package.swift` 的 `testTargetSettings`):SwiftPM 给测试 target 的部署版本不低于 XCTest 与 Swift Testing 的要求(Xcode 26、27 都是 14.0),包声明的更低也一样;Tuist 照搬包声明的 10.15,`TypeIndexingTests` 于是找不到它测的 macOS 13 API。脚本把所有转换进来的测试 target(含 `IntegrationTests`,免得编整个 workspace 时它编不过)传进 `TUIST_TEST_TARGET_NAMES`。 +- **测试 target 与 `swift-section` 链接时带 `-ObjC`**(`Tuist/Package.swift` 的 `testTargetSettings`,`Tuist/CommandLine/Project.swift` 的 `linkFlags`):SwiftPM 把每个包 target 的目标文件整块链进去;Tuist 编的是静态 framework,链接器只拉被符号引用到的归档成员。没人点名的 protocol conformance 于是丢了,`as?` 静默失败:包装 `MachOImage` / `MachOFile` 的读取器(`MachOReaderWrapper`)两样都不像,`WrappedReaderSymbolTests` 与 `WrappedReaderDemanglingTests` 红了 4 条。Xcode 27 的链接器下 `-ObjC` 会拉进所有定义了 ObjC 类或分类、Swift 类型或 extension 的成员,与 RuntimeViewer 的 Tuist workspace 同一个做法。 +- **有加载期 constructor 的 target 被整个 `-force_load`**:`SwiftSymbolsRegistration` 的 constructor 把 Swift 注册成符号语言。它原先是那个 C 文件唯一的内容,又是 `static`,文件里没有全局符号,`-ObjC` 也拉不进来;不加的话 Swift 语言没注册,`SwiftSymbolsTests` 红 281 处,Tuist 编的 `swift-section` 也会把 Swift 符号当成 C。如今这个文件导出了锚点 `swift_symbols_registration_anchor`,`SymbolLanguage+Swift.swift` 调用它,带 `-ObjC` 的链接已经能把它拉进来(MachOObjCSection 的 `MachOObjCSectionC` 同样处理)。脚本仍然保留这条通用规则,作为保险:读清单时找出源码里有 `__attribute__((constructor))` 的 target,沿包内依赖算出哪些测试 target 与可执行 target 会链到它,传进 `TUIST_FORCE_LOADS`,这些链接对那个归档加 `-force_load`。 +- **导入了 Testing 的库 target 加上 TestingMacros 插件路径**(`Tuist/Package.swift` 的 `testingSupportSettings`):`SwiftSectionTestingSupport` 是普通的库 target,却用了 Swift Testing 的 `#require`。SwiftPM 给每个 target 都带上工具链的 TestingMacros 插件,Xcode 只给测试 target 带,于是报 `plugin for module 'TestingMacros' not found`。脚本读清单时找出源码里 `import Testing` 的库 target,传进 `TUIST_TESTING_SUPPORT_TARGET_NAMES`。上游库的也算,两种模式都扫:本地模式下扫它们的本地检出(比如 swift-demangling 的 `DemanglingTestingSupport`),远程模式下扫 Tuist 的依赖 checkout(记在 `Work//Manifests/packages.tsv`,角色 `own-remote`)——MachOKitExtensions 的 `MachOTestingSupport` 用了 `#expect`、`#require`,远程模式下它照样从源码编,只给本地检出补插件路径的话就编不过。 +- **手写的 target 设了 `SWIFT_PACKAGE_NAME = MachOSwiftSection`**(`Tuist/CommandLine/Project.swift`):`SwiftSectionCommandTests` 调用 SwiftSectionKit 的 `package` 方法,只有同一个包的模块看得见;Tuist 给它转换的 target 都设了这个值,手写的也要设。 +- **`CAPSTONE_HAS_AARCH64` 手动补上**:Tuist 丢掉只以 trait 为条件的设置;本库开了 swift-capstone 的 `AARCH64` trait,不补的话 Swift 包装编不过,C 库能编过但没有任何架构可用。 +- **警告还给按路径声明的包**:Tuist 对所有包都关掉警告,Xcode 只关远程包的;本库(本地模式下还有五个上游库)的 target 经 `TUIST_WARNING_TARGET_NAMES` 把警告要回来。 +- **预热要带 `--cache-profile development`**(脚本已经带上):`tuist cache warm` 不读 `Tuist.swift` 里的默认配置,不传就连本库与上游库也一起缓存。缓存例外按 target 名字匹配所有包,脚本读完清单会警告名字撞上的第三方 target。 +- **Tuist 会往 `PrecompiledLibraries/swift-syntax/` 里写 `swift-syntax.xcodeproj`、`Derived/` 与 `.build/`**:它也是按路径声明的包。都已忽略。 + +## 扫描模块在 Debug 下也开优化 + +`Tuist/Package.swift` 的 `optimizedScanSettings` 让 MachOKitExtensions 的 `MachOCodeReferences` 与 `ARM64InstructionDecoding` 在 Debug 配置下也用 `-O` 编译。这是 Tuist workspace 与原生 workspace、`swift test` 之间一处有意的差异,后两者不受影响。 + +- **为什么**:这两个模块是交叉引用扫描的热路径。`-Onone` 下,扫描里逐条指令、逐个寄存器的区间循环走 libswiftCore 里未特化的 `IndexingIterator.next()`,每走一步都要查一次元组类型元数据,几十个线程争同一把锁;2026-11-21 在 Ultra 上采样,工作线程近一半的时间花在这上面。 +- **效果**(同一台 Ultra,Debug,`-only-testing:CrossReferenceAnalysisTests`,连同测试里的扫描限并发一起改):这个 target 从 14 分钟降到约 1.5 分钟,xctest 累计 CPU 时间从约 234 分钟降到约 14 分钟。 +- **代价**:在 Tuist workspace 里对这两个模块打断点,看到的是优化后的代码,部分局部变量看不到。要调试它们时,从 `optimizedScanSettings` 的名单里临时拿掉再 `./TuistScript.sh generate`,调完放回去。本库自己的 `CrossReferenceAnalysis` 不在名单里,照常可调试。 +- **确认生效**:重新生成后,`/Dependencies//tuist-derived/Projects/MachOKitExtensions/MachOKitExtensions.xcodeproj` 里这两个 target 的 Debug 配置是 `SWIFT_OPTIMIZATION_LEVEL = "-O"`;构建日志里它们的编译命令带 `-O`。`base` 里的设置盖得过 Tuist 按配置写的 `-Onone`。 + +测试一侧的限并发见 [FixtureTestingAndContinuousIntegration.md](FixtureTestingAndContinuousIntegration.md) 的「整份 cache 扫描共用一份并发名额」;设计来历见提案 [0103-cross-reference-test-scan-load](../Evolutions/0103-cross-reference-test-scan-load.md)。 diff --git a/Documentations/Internal/TypeIndexingPipeline.md b/Documentations/Internal/TypeIndexingPipeline.md deleted file mode 100644 index abf3efb67..000000000 --- a/Documentations/Internal/TypeIndexingPipeline.md +++ /dev/null @@ -1,103 +0,0 @@ -# TypeIndexing:`__C` 模块归属索引管线实现说明 - -> 本文是 evolution 提案 [0009](../Evolutions/0009-type-indexing-revival.md)(TypeIndexing 重启)与 [0010](../Evolutions/0010-community-type-mapping-bundles.md)(补充映射包)的配套实现说明,面向维护者:记录实际落地的管线、与提案的差异、缓存布局与已知降级。 - -## 这个模块做什么 - -打印管线遇到 `__C` / `__ObjC` module 节点时(`NodePrintable.printModule`),会拿 sibling identifier 问 delegate 的 `moduleName(forTypeName:)`(带 `Ref` 后缀剥除回退)。`TypeIndexing` 提供唯一的 provider 实现 `SwiftInterfaceBuilderTypeNameProvider`:挂上它之后,`__C.NSString` 打印为 `Foundation.NSString`。CLI 入口是 `swift-section interface --resolve-c-module-names`(用户自备补充映射经 `--supplementary-apinotes` 追加);库入口是 `builder.addExtraDataProvider(SwiftInterfaceBuilderTypeNameProvider(machO:dependencies:supplementaryAPINotesURLs:))`(末参数带默认值)。 - -## 查询数据流(三源合并,优先级从高到低) - -``` -moduleName(forTypeName: "NSString") - 1. moduleNamesByTypeName ← Swift interface 类型名(低)+ APINotes C 名与 SwiftName 拼写 - (高,后写覆盖;SDK APINotes → 用户补充文件按传入序) - 2. objcModuleNamesByTypeName ← ObjC 元数据懒索引(最低,只补缺) - -swiftName(forCName: "CFStringRef", category:) ← identifier 重写(见下节) - 1. APINotes 改名表(按声明类别隔离;补充包条目同表、后写覆盖) - 2. CF `Ref` 剥除规则(剥后名必须存在于归属表;protocol 类别不适用) -``` - -## Identifier 重写:C 拼写 → Swift 拼写(用户指正驱动) - -module 名替换之外,`__C` 类型的 **identifier 本身**也可能是 Swift 里不存在的 C 拼写——首轮端到端输出的 `CoreFoundation.CFStringRef` 被用户指正:`CFStringRef` 是 C 侧 typedef 名,ClangImporter 剥 `Ref` 后缀桥接为原生 class `CFString`。落地为打印侧对 `swiftName(forCName:category:)` 的消费(该协议方法此前零消费者): - -- **只在 module 解析成功时重写**(`printModule` 返回是否命中),未解析的 `__C.CFStringRef` 绝不渲染成半吊子 `__C.CFString`。 -- **查询必须带声明类别**(`CImportedTypeNameCategory`,由 mangling 的 `Node.Kind` 映射:class / protocol / 值类型 / other)。这是第一版合并改名表当场踩出的回归:ObjC 的 class `NSObject` 与 protocol `NSObject` 同名,APINotes 只把 **protocol** 改名为 `NSObjectProtocol`——类别盲查让所有 class 继承行都被错写成 `NSObjectProtocol`(而 protocol 继承行反而是被修对的)。`APINotesIndex` 的改名表按 Classes / Protocols / 值类型(Tags + Enumerators + Typedefs)三张隔离,`.other`(typealias 等 mangling 不定类别的引用)查值类型表再查 class 表、**永不查 protocol 表**。 -- **CF `Ref` 剥除**是 APINotes miss 后的兜底规则:`Ref` 结尾且剥后名真实存在于归属表才重写(碰巧以 `Ref` 结尾的 ObjC 类不受影响),protocol 类别不适用(无 CF protocol 惯例)。 -- 归属表(`moduleNamesByCName`)不拆类别——同名实体同模块,归属无歧义。 -- **`Ref` 规则对整个 `objc_bridge`(`CF_BRIDGED_TYPE` / `CV_BRIDGED_TYPE` 等各框架宏别名)家族通用**,不是 CoreFoundation 专属——判据只是「剥后名存在于索引」。CG / CV / CM 探针实测(链 CoreGraphics + CoreVideo + libswiftCoreMedia 的 dylib):同一类型**两种 mangling 形态并存**——符号签名用 C typedef 名(`__C.CGContextRef`),字段元数据用剥后名(`__C.CGContext`)——分别由剥除规则与归属表直查覆盖(提案 0023 之后字段元数据也按描述符 import info 里的 ABI name 拼成 `__C.CGContextRef`,两种形态合一,只靠剥除规则),全部解析为 `CoreGraphics.CGContext` / `CoreVideo.CVBuffer` / `CoreMedia.CMFormatDescription`(`CVPixelBuffer` 在 mangling 层已归一为 `CVBuffer`,输出如实反映 ABI)。CoreMedia 仅以 `libswiftCoreMedia` overlay 形式出现在依赖里,`libswift` 前缀剥除使过滤命中其 SDK 模块——overlay-only 依赖场景成立。 - -- **Swift interface 类型名**:对二进制依赖命中的每个 SDK 模块,经 sourcekitd `editor.open.interface`(带 `key.enablesubstructure`)生成含 ObjC 导入声明的 Swift 视角 interface,`InterfaceTypeNameExtractor` 从结构树提取 fully-qualified 类型名。**不用 SwiftSyntax**(体积裁定,见提案 A′ 节);`.swiftinterface` 文件也不可用——它只含 Swift 声明,而本功能主要目标恰是 ObjC 导入类型。 -- **APINotes**:`.apinotes` 是编译器视角的权威归属记录,`APINotesIndex` 把**每个列出的实体**(含无 `SwiftName` 改名、含 `SwiftPrivate`)的 C 名注册到声明模块,后写覆盖 interface 名。双向改名表(`swiftName(forCName:)` / `cName(forSwiftName:)`)只收非 `SwiftPrivate` 的改名实体。 -- **ObjC 懒索引**:前两层 miss 才按依赖顺序逐 image 构造 MachOObjCSection `ObjCIndexing` 的 `ObjCInterfaceIndexer`、`prepare()`、并入 class / protocol / C struct / union 名 → image 模块名,命中即止。已索引 image 的结果缓存在 actor 内;索引失败的 image 记日志后丢弃不重试。依赖耗尽后 miss 只花一次字典探查。 - -## 补充映射:私有框架的外部知识入口(提案 0010) - -AttributeGraph 这类私有框架在 SDK 里没有任何模块(无头文件、无 swiftmodule、无 apinotes),三源全 miss;而 `AG_SWIFT_NAME(Graph)` 的改名在二进制里只剩消费方类型记录名字字段里的最后一截 `Graph`,所属模块与嵌套关系都不记录,完整的 `AttributeGraph.Graph` 原理上无法从二进制恢复。[提案 0010](../Evolutions/0010-community-type-mapping-bundles.md) 的补充映射就是这份外部知识的入口:映射用**标准 `.apinotes` 格式**表达(零新格式,直接进 `APINotesIndex` 既有管线,类别隔离天然携带),**全部由用户自备**——宿主经 provider 的 `supplementaryAPINotesURLs:`、CLI 经 `--supplementary-apinotes`(可重复,文件或目录)传入;库自身不内置任何映射(首版曾内置 SPM resource bundle,review 后按用户裁定移除:`Bundle.module` accessor 在 bundle 缺失时 fatalError,而 `build-executable-product.sh` 只分发裸二进制,分发出去一用就崩——纯用户自备把整个 resource 分发问题结构性消掉)。覆盖顺序:SDK APINotes → 用户文件按传入序,`APINotesIndex.register(files:)` 的后写覆盖即优先级实现。面向用户的公开指引见 [SupplementaryTypeMappings.md](../SupplementaryTypeMappings.md)。 - -**同一个 CF-bridged 类型有两种 mangling 形态**(AG probe 实测:手造 clang module 复刻 `objc_bridge` + `swift_name` 声明,5 处引用全解析为 `AttributeGraph.Graph` / `.Subgraph`;当时还有第三种,见第 3 条),各自的覆盖机制不同: - -1. **typedef 名**(`__C.AGGraphRef`,符号签名,typealias node → `.other` 类别):`Typedefs` 条目的改名表命中。 -2. **storage / tag 名**(`__C.AGGraphStorage`,字段元数据的 foreign **class** descriptor,`.objcClass` 类别):条目按 C 语义归 `Tags`(值类型表),所以 `.objcClass` 查询在 class 表 miss 后**回退值类型表**。安全性论证:C 的 tag namespace 与 ObjC class namespace 理论上可同名共存,但 class 表先查先赢,「改名只在 tag 侧、同名 ObjC class 又真被引用」无已知真实实例;protocol 表仍绝不回退(`NSObject` 隔离不动)。系统 dyld cache 的 SwiftUI 里实测存在孤立的 `AGGraphStorage` descriptor 名,即此形态。 -3. **导入名直出**(`__C.Graph`,已不再出现):消费方二进制 emit 的 foreign descriptor,名字字段记录的是 **swift_name 之后**的拼写,而且只是最后一截。提案 0023 之前描述符就按这个名字打印,`TypeDatabase` 的归属同步(`registerAttribution(fromAPINotesIndex:)`)因此把改名反查表(`cNamesBySwiftName`)里不带点的 SwiftName spelling 也登进归属表。0023 起描述符按 import info 里的 ABI name 打印(`__C.AGGraphRef`、`__C.NSDecimal`),走第 1、2 条。2026-10-01 用 macOS 27 的 SwiftUICore 实测 `dump`:0023 之前 `__C.Graph` / `__C.Subgraph` 共 107 行,之后为 0。那段登记却不能删:它排在 C 名登记之后,还决定着几个模块的 APINotes 都列出的 C 名归谁。Foundation 与 AppKit 的 APINotes 为了标注 category 方法也列了 `NSObject`,C 名登记是后加载的文件说了算;ObjectiveC 的条目把 `NSObject` 改名为它自己,这个 SwiftName spelling 最后登记,`NSObject` 才回到 ObjectiveC。2026-10-03 试删后,AppKit 的 `--resolve-c-module-names` 输出里 `ObjectiveC.NSObject` 108 行、`ObjectiveC.NSObjectProtocol` 22 行全部变成 `Foundation.…`,于是撤回,并用 `TypeDatabaseMergePriorityTests.renamingEntryKeepsItsModuleAgainstLaterListings` 钉住。 - -映射内容立场:**宁缺毋滥**——条目错了输出跟着错,公开指引要求每条改名都有头文件级一手证据(重建头文件声明或 OpenGraph 这类文档化项目)。 - -## 管线分层(每层一个类型,一文件) - -| 类型 | 职责 | 关键点 | -|---|---|---| -| `SDKPlatform` / `SDKSettings` | 平台 → SDK 路径、target triple、SDK 版本标识 | `SDKSettings.plist` 的 `Version` + `ProductBuildVersion` 组成缓存目录段 | -| `Subprocess` | `xcrun` / `xcode-select -p` 同步调用 | 非零退出码抛错,不再静默返回空串 | -| `SourceKitManager` | actor:sourcekitd 请求 + 响应转值类型 | dylib 路径从 active developer dir 派生(不再硬编码 `/Applications/Xcode.app`);substructure 在 actor 内转成 `InterfaceDeclarationNode` 值树;`importedModuleNames` 是行级 import 扫描 | -| `InterfaceDeclarationNode` | substructure 的值类型投影 | `other` 节点的子树在转换时即丢弃 | -| `InterfaceTypeNameExtractor` | 值树 → fully-qualified 类型名(纯函数) | extension 节点用被扩展类型名(可带点)作限定前缀、自身不入清单——旧 SwiftSyntax 解析器的 extension 嵌套键错误在此结构性消失 | -| `SDKIndexer` | SDK 文件发现(秒级,零 sourcekitd) | `.swiftmodule` 目录 `skipDescendants`;同名模块先到先得(search path 优先级) | -| `APINotesFile` / `APINotesIndex` | `.apinotes` 解析与三张名表 | 修复历史 bug:C 名 → Swift 名映射的 `moduleName` 字段曾被写成 swiftName;`register(files:)` 可追加(后写覆盖,补充包优先级的实现点) | -| `SupplementaryAPINotesLoader` | 用户自备补充映射的枚举与解析(提案 0010) | 路径可为文件或目录(目录取浅层 `.apinotes` 按文件名排序);解析失败逐文件记日志跳过;CLI 侧另有 stderr 预检警告 | -| `ModuleIndexCacheEntry` / `ModuleIndexCache` | per-module JSON 缓存 | 见下节 | -| `ModuleInterfaceIndexer` | 单模块管线:缓存 → 生成 → 提取 → 回写 | 单模块失败记日志返回 `nil`,不作废整轮索引;submodule interface 并入主模块条目(归属永远写顶层模块名);**任一 submodule 失败则本轮照常返回但不写缓存**(缓存无完整性标记,写了就把缺口固化到 SDK/generator 版本变化为止——review 发现 4);sourcekitd 调用经 `InterfaceGenerator` 闭包注入缝,缓存纪律可脱离 sourcekitd 单测 | -| `TypeDatabase` | actor:三源合并 + 懒索引 + 查询 | `register(moduleEntries:)` / `register(apiNotesIndex:)` / `register(supplementaryAPINotesFiles:)` / `register(dependencies:)` 四步公开为 package API,合并优先级因此可脱离 sourcekitd 单测;task group 结果按**完成序**到达,注册前经 `entriesInDiscoveryOrder` 重排回 SDK 发现序(后写覆盖 + 完成序 = 同名归属跨两次运行不确定——review 发现 7);`moduleName(forImagePath:)` 的扩展名剥除循环带不动点守卫(前导点名字如 `.hidden` 是剥除不动点,曾死循环——review 发现 5) | -| `SwiftInterfaceBuilderTypeNameProvider` | 对接 `SwiftInterfaceBuilder` 的 provider | 模块过滤 = 依赖 image 名集合(`TypeDatabase.moduleName(forImagePath:)`:剥全部扩展名 + `libswift` 前缀) | - -## 缓存布局 - -``` -~/Library/Application Support/MachOSwiftSection/SDKIndexer//-/.json -``` - -- 条目是**提取产物**(类型名清单 + submodule 名单),不存 interface 全文。 -- 按 SDK 精确构建分目录:Xcode 升级换目录,陈旧条目自然失效(历史实现只按 platform 分目录且要求全 SDK 索引完成的标记文件,升级后继续吃旧数据)。 -- `generatorVersion` 不匹配的条目按 miss 处理——提取行为变更时把 `ModuleIndexCacheEntry.currentGeneratorVersion` 加一。 -- 全部缓存 I/O 是 best-effort:读写失败记日志、走重新生成,不向上抛错。 - -## 性能形态 - -- SDK 扫描只做文件发现,秒级;sourcekitd 生成只对**依赖过滤命中的模块**进行(历史实现对全 SDK 数百模块逐个生成、过滤在其后,首次索引小时级——这是该 target 当年被禁用的直接原因)。 -- 首个未命中缓存的模块仍要付一次真实生成成本(大模块数秒到数十秒);同 SDK 下第二次起走缓存。 -- ObjC 懒索引把依赖 image 的解析成本压到「前两层查不到」的路径上;`ObjCInterfaceIndexer.prepare()` 解析全部成员 info,对单个大 framework 不算轻——若实测过重,未来方向是在 MachOObjCSection 加 name-only 快速路径。 - -## 降级行为(0005 事件化纪律的落点) - -TypeIndexing 内部拿不到 `SwiftIndexEvents` 的 dispatcher(provider 协议面只有 `setup()`),所以降级全部走 `@Loggable` + `#log` 地板(subsystem `com.machoswiftsection.typeindexing`):单模块 interface 生成失败、submodule 失败、`.apinotes` 解析失败、缓存读写失败、依赖 image ObjC 索引失败——都是「跳过该项 + 记日志」,绝不让一个模块的失败作废整个数据库。`setup()` 整体抛错(如 SDK 设置读不到)由 `SwiftInterfaceBuilder.prepare()` 的既有 `.renderingDegraded(source: .extraDataProvider)` 事件兜住。 - -## `@Loggable` 的形态约束(本模块特有的坑) - -TypeIndexing 的类型都标 `@available(macOS 13.0, *)`(包部署下限是 macOS 10.15)。`@Loggable` 的**直接类型形态**会展开自带 availability 标注的 static stored `logger`,在显式 `@available` 的类型里被 emit-module 拒绝("cannot be more available than enclosing scope",单 target 编译只是 warning,整包 emit-module 是 error)。因此本模块一律用 **protocol 形态**:不标 availability 的 `fileprivate protocol XxxLogging {}` + 标 `@available(macOS 13.0, *)` 的 conformance extension。泛型 `TypeDatabase` 本来就只能用 protocol 形态,非泛型类型在这里也被迫用它。 - -## 与提案的差异 - -- **swift-dependencies 未引入**:提案 E 节的依赖清单含 `Dependencies`(历史实现用 `@Dependency` 注入 `SourceKitManager`)。落地改为把 `TypeDatabase` 的三个 `register` 步骤公开为 package API,测试直接驱动合并逻辑,不需要依赖注入框架——少一个 target 依赖。 -- **兜底行级解析器未编写**:提案 A′ 允许 substructure 验证失败时退手写解析;scratchpad 探针实测 substructure 完整可用(ObjectiveC / CoreGraphics 两模块,节点带 kind + name + 嵌套 + extension),按提案「二选一定夺」条款只落主路。 -- **`MachOObjCSection` 下限抬到 0.8.105**:泛型(`ObjCMetadataSource`,支持 `MachOFile`)的 `ObjCInterfaceIndexer` 在 0.8.105 才有,0.8.104 的只接受 `MachOImage`。 -- **APINotes 归属注册比历史实现更宽**:历史实现只注册有 `SwiftName` 的实体;现在每个列出的实体(含 `SwiftPrivate`)都注册归属——`__C.X` 的 X 是 C 名,归属正确性与 Swift 侧可见性无关。改名表仍跳过 `SwiftPrivate`。 - -## 已知限制 - -- 整个 target 是 macOS-only(`#if os(macOS)` 全文件 + 依赖的 `.when(platforms: [.macOS])` 条件),且运行时要求 macOS 13+ 与本机 Xcode(sourcekitd)。 -- Identifier 重写只覆盖类型引用(`printType` 的 nominal 路径);成员级 SwiftName 改名(selector → Swift 方法名等)不在本案,另立提案。 -- 依赖 image 的模块名取自 image 文件名(`libobjc.A.dylib` → `libobjc`),与 Swift module 名在少数 dylib 上不一致;影响仅限私有类型归属的显示名。 -- CLI 的 provider 依赖集用 `.usesSystemDyldSharedCache`(被检查二进制的依赖按本机 dyld cache 解析);跨版本 / 跨平台二进制的依赖解析不在 CLI 默认路径覆盖内。 -- **声明模块完全不在依赖列表里时三层全 miss**:类型只出现在签名 / 元数据、二进制没有对该框架的任何符号引用时,链接器不会记 `LC_LOAD_DYLIB`(探针实测:只声明 `CGContext` 字段而不调 CG 函数,CoreGraphics 就不在依赖里),依赖过滤自然不会索引该模块,`__C.` 原样保留。真实二进制里用一个类型几乎必调它的函数(或至少链 overlay),所以实际影响很小;若将来遇到,可选增强是把过滤集合扩到依赖闭包(传递依赖)。用户自备的补充映射(提案 0010)不受此限:它不参与依赖过滤,条目覆盖到就能解析——SDK 里根本没有模块的私有框架(AttributeGraph)正是靠它。 diff --git a/Documentations/ObjCCommandLine.md b/Documentations/ObjCCommandLine.md index fd5222b51..3716228fb 100644 --- a/Documentations/ObjCCommandLine.md +++ b/Documentations/ObjCCommandLine.md @@ -33,6 +33,9 @@ swift-section objc interface # The same class, protocol or category as Swift imports it swift-section objc interface --swift +# The header with the NS_SWIFT_NAME / NS_REFINED_FOR_SWIFT the SDK's API notes give it +swift-section objc interface --mark-sdk-swift-names + # Freeze a binary's Objective-C API as a baseline snapshot (JSON) swift-section objc snapshot --label 26.0 -o baseline.json @@ -121,6 +124,28 @@ class NSColor: __C.NSObject, __C.NSAccessibilityColor, __C.CAAnimatableValue, __ - A Swift class goes by its runtime name (`_TtC6AppKit11SliderModel`), as for the header. Structs and unions have no Swift view. +## SDK Swift names (`interface --mark-sdk-swift-names`) + +A binary keeps no trace of `NS_SWIFT_NAME(...)` or `NS_REFINED_FOR_SWIFT`. With +`--mark-sdk-swift-names`, `interface` reads them back from the API notes of the binary's SDK in the +active developer directory and prints them as the header did: + +``` +$ swift-section objc interface PKDrawing --uses-system-dyld-shared-cache -n PencilKit --mark-sdk-swift-names +NS_SWIFT_NAME(PKDrawingReference) +@interface PKDrawing : NSObject +… +``` + +- The class's or protocol's own macros go on a line above `@interface` / `@protocol`; a member's go + ahead of its `;`, `NS_SWIFT_NAME(...)` first. A category prints its members' macros only, taken + from the API notes of the class it extends. +- Only these two macros: nullability and the other API notes attributes are not printed. +- The SDK is the one the binary's `LC_BUILD_VERSION` names: macOS and Mac Catalyst binaries need + Xcode or the Command Line Tools, others the matching SDK in Xcode. A binary no installed SDK covers + prints a warning and its plain interface. Needs macOS 13; ignored with `--swift`. +- Reads API notes only (about two seconds); no module interface is generated. + ## Ten generation switches All of them default to off: with none given, the output is the metadata as it stands, nothing diff --git a/Documentations/ObjCCommandLine_zh.md b/Documentations/ObjCCommandLine_zh.md index 2780ba95a..3c9e997f6 100644 --- a/Documentations/ObjCCommandLine_zh.md +++ b/Documentations/ObjCCommandLine_zh.md @@ -30,6 +30,9 @@ swift-section objc interface # 同一个类 / 协议 / 分类,打印成 Swift 导入它的样子 swift-section objc interface --swift +# 头文件里标出 SDK 的 API notes 给它的 NS_SWIFT_NAME / NS_REFINED_FOR_SWIFT +swift-section objc interface --mark-sdk-swift-names + # 把二进制的 Objective-C API 冻结成基线快照(JSON) swift-section objc snapshot --label 26.0 -o baseline.json @@ -103,6 +106,25 @@ class NSColor: __C.NSObject, __C.NSAccessibilityColor, __C.CAAnimatableValue, __ - Swift 类按运行时名指定(`_TtC6AppKit11SliderModel`),与头文件一样。struct 与 union 没有 Swift 视图。 +## SDK 的 Swift 命名(`interface --mark-sdk-swift-names`) + +二进制不留 `NS_SWIFT_NAME(...)` 与 `NS_REFINED_FOR_SWIFT` 的痕迹。加 `--mark-sdk-swift-names` 时,`interface` 从当前开发者目录 +里、这个二进制所属平台的 SDK 的 API notes 把它们读回来,照头文件的写法打出: + +``` +$ swift-section objc interface PKDrawing --uses-system-dyld-shared-cache -n PencilKit --mark-sdk-swift-names +NS_SWIFT_NAME(PKDrawingReference) +@interface PKDrawing : NSObject +… +``` + +- 类与协议本身的宏单独一行,在 `@interface` / `@protocol` 上面;成员的宏在分号前,`NS_SWIFT_NAME(...)` 在前。category + 只打成员的宏,取自它所扩展的类的 API notes。 +- 只打这两个宏,nullability 等其余 API notes 属性不打。 +- SDK 按二进制 `LC_BUILD_VERSION` 里的平台找:macOS 与 Mac Catalyst 的二进制有 Xcode 或 Command Line Tools 即可,其他平台要 + Xcode 里有对应 SDK。本机没有对应 SDK 时打一条警告,照常输出不带标注的头文件。要 macOS 13;与 `--swift` 同用时忽略。 +- 只读 API notes(约两秒),不生成模块接口。 + ## 十个生成开关 全部默认关闭:一个开关都不加时,输出就是元数据的原样,不删任何东西,也不加任何注释。 diff --git a/Documentations/README.md b/Documentations/README.md index be8fecfe5..1bb0eb18f 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -218,13 +218,30 @@ selects names using each access's offset and width. | [Evolutions/0096-swift-first-imported-declarations.md](Evolutions/0096-swift-first-imported-declarations.md) | **提案 0096(Implemented)**:Swift 实现的类,导入声明以 Swift 一侧为准——`@objc @implementation` 类改成与桥接 Swift 类同样的形状(类体是 Swift 一侧的成员,ObjC 方法表里没有 Swift 成员回答的放最后);系统框架里 thunk 被内联、符号被剥时,ObjC 成员改按名字配 Swift 成员(不再只限 override,认 `NS_REFINED_FOR_SWIFT` 的 `__` 前缀,类型明显对不上的不配);`@implementation` 存储属性的 `var` / `weak` 取自 ObjC 属性特性;判定哪些成员是 `NS_REFINED_FOR_SWIFT`,Swift 视图写出它的 `__` 声明,ObjC 头文件由 MachOObjCSection 打上这个宏、RuntimeViewer 接线。 | | [Evolutions/0097-offline-cross-references-and-symbolication.md](Evolutions/0097-offline-cross-references-and-symbolication.md) | **提案 0097(Implemented)**:交叉引用与地址符号化扩展到磁盘文件和归档 dyld cache——`CrossReferenceAnalyzer` 的 `init(dyldCache:)` / `init(machOFiles:)`、`symbolication(of:)`,CLI 的 `refs` 与 `symbolicate`;交叉引用拆成核心、ObjC、Swift 三层。 | | [Evolutions/0098-move-cross-reference-layers.md](Evolutions/0098-move-cross-reference-layers.md) | **提案 0098(Implemented)**:交叉引用的核心层与 ObjC 层迁出本库——`MachOCodeReferences`、`MachOAddressResolution`、`ARM64InstructionDecoding` 进 MachOKitExtensions 2.0.0,`ObjCCodeReferences` 进 MachOObjCSection 0.8.207,层间接口是 `@_spi(Internals)`,门面 `CrossReferenceAnalysis` 留在本库。 | -| [Glossary.md](Glossary.md) | **项目术语表**:sweep、腿(reader-split leg)、名字来源、detach、物化、permutation 二分、store-identity vs 结构相等、wrapper vs descriptor、桶、trailing objects、SymbolicDemangler(旧名 MetadataReader)、`_symbolic` 符号与被引用者、TypeImportInfo、缓存范围(cache scope)、读取接口的三种形式(context / Mach-O / pointer form)等本项目自造词与特定用法;跨项目通用术语在全局表(iCloud Global),不重复登记。提案与专题文档引入新术语时同批登记。 | +| [Evolutions/0100-fixture-suite-macro.md](Evolutions/0100-fixture-suite-macro.md) | **提案 0100(Implemented)**:attached 宏 `@FixtureSuite` 生成夹具测试套件的 `testedTypeName`、`registeredTestMethodNames` 与 `FixtureSuite` 遵循(170 个套件各省 3 行,没有 baseline 的 `CoroFunctionPointerTests` 保持手写),宏放新的 `SwiftSectionTestingMacros`,`SuiteBehaviorScanner` 改为也认宏的写法。 | +| [Evolutions/0101-swift6-mode-and-upcoming-features.md](Evolutions/0101-swift6-mode-and-upcoming-features.md) | **提案 0101(Implemented)**:MachO 系列库统一 Swift 6 语言模式并开启三项 upcoming feature——MachOKit(fork)从 tools 5.10 升到 6.0 进 Swift 6(实测零错误),六个包的每个 Swift target 用清单末尾的一个循环开启 `ExistentialAny`、`MemberImportVisibility`、`InferIsolatedConformances`;约 900 处补 import 与 `any`,含 `swift package migrate` 处理不了的 4 处硬错误与 `Semantic.Error` 遮蔽 `Swift.Error` 的坑;`NonisolatedNonsendingByDefault`、`InternalImportsByDefault`、`StrictMemorySafety` 量过后不做。跨仓库唯一提案。 | +| [Evolutions/0102-multiline-type-formatting.md](Evolutions/0102-multiline-type-formatting.md) | **提案 0102(Implemented)**:长类型拆行——新增 `MultilineTypeFormatting`(`SwiftDeclarationRendering`),把打印好的 `SemanticString` 里放不下的类型按括号拆成多行:放得下的类型不动,放不下的类型照 TypeAliasFormatter 的结构规则拆(多参数泛型每个参数一行,单参数泛型、元组、函数类型与参数列表只在里面有拆开的部分时才拆,`<…>` 里写着要求的泛型签名不按参数拆);行首缩进不计入宽度,嵌套定义契约不受影响;只加换行与缩进,semantic type、identifier 与 region 原样保留。`InterfaceRequest` / `DumpRequest` 加字段,`dump` / `interface` 加 `--multiline-types` 与 `--maximum-line-width`;默认关闭,打印器不改。RuntimeViewer 的「Break Long Types」由那边的提案接入。 | +| [Evolutions/0103-cross-reference-test-scan-load.md](Evolutions/0103-cross-reference-test-scan-load.md) | **提案 0103(Implemented)**:`CrossReferenceAnalysisTests` 的四处整份 dyld cache 扫描改走全进程共用的并发名额 `ImageScanConcurrency`(`max(2, 核心数 / 2)`),Swift Testing 并行跑套件时也不叠加回满核;Tuist 开发工作区里 `MachOCodeReferences`、`ARM64InstructionDecoding` 在 Debug 下也用 `-O` 编,去掉每条指令一次的运行时元数据查找。库 API、原生 workspace、`swift test` 与 CI 不变。 | +| [Evolutions/0104-shared-macho-testing-support.md](Evolutions/0104-shared-macho-testing-support.md) | **提案 0104(Implemented)**:测试支持里与 Swift 无关的部分(cache 路径、打开镜像与选 slice、现编 dylib、按镜像互斥的 trait、测试基类、闭包式跨读取器)搬到 MachOKitExtensions,发布为 `MachOFixtureSupport`(无 Testing)与 `MachOTestingSupport`(Testing)两个 product,两个包共用;本包夹具基类变成共享基类的子类,取本机 cache 统一为进程共用。跨仓库唯一提案。 | +| [Evolutions/0105-swift-type-indexing-package.md](Evolutions/0105-swift-type-indexing-package.md) | **提案 0105(Implemented,跨仓库)**:`TypeIndexing` 搬进独立包 swift-type-indexing(SDK 的模块接口与 API notes 索引,按 SDK 版本缓存),本仓库只留适配层 `SwiftTypeNameResolution`;同时修 API notes 改名规则与只装 Command Line Tools 时找不到 sourcekitd。MachOObjCSection 0.8.209 按 API notes 在头文件里标 `NS_SWIFT_NAME` / `NS_REFINED_FOR_SWIFT`(swift-semantic-string 0.7.0 的宏色),RuntimeViewer 把 `__C.X` 打印成模块限定的 Swift 名 | +| [Evolutions/0106-c-imported-type-name-spelling.md](Evolutions/0106-c-imported-type-name-spelling.md) | **提案 0106(Implemented,跨仓库,RuntimeViewer 参与)**:C 导入类型的名字统一成 Swift 名——声明、成员类型与扩展头一致写描述符给的 Swift 名(解析器找得到模块就带模块,否则写裸名),`CImportedTypeNameSpelling.cName` 一律写 mangled 的 C 名;ABI 名以描述符名字结尾的不信(导入成成员的类型退回 C 名)。`marksCImportedTypeNames` 在名字上标出另一种写法,RuntimeViewer 据此在声明行尾画可点击的标签、切换全局选项;`swift-section interface --c-imported-type-name-spelling` | +| [Evolutions/0107-moved-swift-type-modules.md](Evolutions/0107-moved-swift-type-modules.md) | **提案 0107(Implemented,跨仓库,swift-type-indexing 参与)**:被 SDK 用 `@_originallyDefinedIn` 搬过家的 Swift 类型(`CGFloat` 由 CoreFoundation 声明、mangling 仍是 CoreGraphics;macOS 15 起约 370 个 SwiftUI 类型搬进 SwiftUICore),interface 按现在声明它的模块打印——swift-type-indexing 扫描 SDK 文本 `.swiftinterface` 建搬家表,打印器多一个 `MovedTypeModuleResolving` 角色,`swift-section interface --resolve-moved-type-modules` 默认关闭,按二进制的 SDK 版本判断是否改写。 | +| [Evolutions/0108-private-cf-type-modules.md](Evolutions/0108-private-cf-type-modules.md) | **提案 0108(Implemented)**:私有 CF 类型在 `interface --resolve-c-module-names` 下查不到模块,只印描述符给的裸名(`CGSVGDocument`)。新增 swift-type-indexing `DeclaredTypeNameSource` 的实现 `CFDeclaredTypeNames`:从镜像导出的 `…GetTypeID` 列出它定义的 CF 类型(`_CGSVGDocumentGetTypeID` → `CGSVGDocumentRef`),provider 为根镜像和每个直接依赖登记,引用印成 `CoreSVG.CGSVGDocument`;打印器、swift-type-indexing 与 CLI 参数不改。macOS 27.2 cache 里 Swift 用到的 20 个私有 CF 类型能覆盖 15 个。 | +| [Evolutions/0109-consistent-c-imported-type-spelling.md](Evolutions/0109-consistent-c-imported-type-spelling.md) | **提案 0109(Implemented)**:C 导入类型的拼写补齐——0106 之后还剩两处混用:镜像里有描述符、Swift 名与 C 名相同的类型,声明写裸名而引用与扩展头写 `__C::`;展开字段偏移树的注释用固定的 `.default` 印类型名(C 名、点号限定、不带模块选择器与 `any`)。名字表收下没有 ABI 名的描述符(编译器只在两个名字不同时才写 ABI 名),引用改写裸名;interface 的布局注释经打印器自己的类型拼写印类型名,离线与进程内两条后端一起改,dump 不变。本镜像没有描述符的类型照旧写 `__C::`。 | +| [Evolutions/0110-unify-evolution-integration-suites.md](Evolutions/0110-unify-evolution-integration-suites.md) | **提案 0110(Implemented)**:IntegrationTests 的四套演进手检套件(Swift 报告、Swift 联合接口、ObjC 报告、ObjC 联合头文件)各自重复定义同几条版本轴、互相借用对方的类属性,每条管线又把单镜像与镜像组写两遍。合成一套:`Tests/IntegrationTests/Evolution/` 下版本轴只定义一次、按读的元数据(`__swift5_*` / `__objc_*`)筛版本,四条管线收进一个协议,21 个套件类变成 10 个轴套件,43 个「轴 × 输出」组合与输出文件名不变。 | +| [Evolutions/0111-unify-diff-and-interface-integration-suites.md](Evolutions/0111-unify-diff-and-interface-integration-suites.md) | **提案 0111(Implemented)**:IntegrationTests 的 diff 与单版本接口两类手检套件按 0110 的结构统一,三类输出(接口、diff、演进)进同一个目录 `Tests/IntegrationTests/InspectionDumps/`、共用一个公共协议;diff 改用演进的版本轴(cache 对因此整份打开,与 CLI 一致),每类一个「输出种类」枚举加一个 `dump` 入口;AppKit 的接口与 diff 套件多出 ObjC 头文件与 ObjC 变更列表。测试 20 个变 38 个,演进的 43 个不变。 | +| [Evolutions/0112-objc-ivar-type-recovery.md](Evolutions/0112-objc-ivar-type-recovery.md) | **提案 0112(Implemented)**:`@objc @implementation` 类的存储属性没了 `Wvd` 字段偏移符号时,interface 与 dump 不再只打「Swift type not recoverable」注释,而按 ObjC 一侧还原 Swift 类型:ivar 的完整 encoding 就是 Swift 类型本身(编译器只给能原样表示的类型写),`?` 的按 ObjC 属性 `T` 特性的桥接形态(只认桥接类与裸 `id`),`weak` 的读属性、不桥接;对象写 `T!`,`readonly` 写 `let`,C 基本类型按新的 `SwiftDeclarationPrintConfiguration.cTypeReplacements`(`applyTransformers(_: Transformer.ObjCConfiguration)`)改写,与 ObjC 头文件一侧一致;空 encoding 仍是注释。 | +| [Evolutions/0113-cross-reference-recall-gaps.md](Evolutions/0113-cross-reference-recall-gaps.md) | **提案 0113(Implemented)**:交叉引用召回补漏——2026-11-26 按 2026-11-18 的方法复测,`swift-section refs` 0.25.0 代码引用召回 90.3%(476/527),IDA 一次查询 97.0%;补四处缺口:CLI 加 `--type` 按 Swift 类型查询、取到 GOT 槽地址也算类引用、没被发送用掉的 selref 载入记成 selector 引用、一种 `adrp; add; ldrsw [xN]` 的 ivar 读法;第 5 步把取函数地址记成对函数的引用;测量脚本进 `Scripts/CrossReferenceRecall/` 作验收。跨 MachOKitExtensions、MachOObjCSection 与 RuntimeViewer | +| [Evolutions/0114-swift-declaration-model-indexing-layout.md](Evolutions/0114-swift-declaration-model-indexing-layout.md) | **提案 0114(Implemented)**:SwiftDeclaration 按可见性分成两棵目录树——`Model/` 放下游读的公开模型,`Indexing/` 放只在索引期运行的 `package` / `internal` 代码;只搬文件、原样剪切三个藏在别人文件里的类型,不改代码。2026-11-06 落地、随 0.25.0 发布,2026-12-01 补记编号 | +| [Evolutions/0115-swift-declaration-type-naming.md](Evolutions/0115-swift-declaration-type-naming.md) | **提案 0115(Implemented)**:SwiftDeclaration 索引期的命名空间按角色取后缀(`…Builder` 造新东西、`…Matcher` 把二进制里另一处的证据对到成员上、`…Recovery` 补回丢掉的事实),三个公开名字改成与模块其余部分一致的词(`ResolvedAssociatedTypeWitness`、`ConditionalCandidate`、`Origin`),旧名留废弃别名。2026-11-06 落地、随 0.25.0 发布,2026-12-01 补记编号 | +| [Glossary.md](Glossary.md) | **项目术语表**:sweep、腿(reader-split leg)、名字来源、detach、物化、permutation 二分、store-identity vs 结构相等、wrapper vs descriptor、桶、trailing objects、SymbolicDemangler(旧名 MetadataReader)、`_symbolic` 符号与被引用者、TypeImportInfo、C 导入类型名拼写(C-imported type name spelling)、类型索引(type index)、缓存范围(cache scope)、读取接口的三种形式(context / Mach-O / pointer form)等本项目自造词与特定用法;跨项目通用术语在全局表(iCloud Global),不重复登记。提案与专题文档引入新术语时同批登记。 | | [SymbolIndexStoreMemoryOptimization.md](Internal/SymbolIndexStoreMemoryOptimization.md) | **Swift 符号索引(今 `SwiftSymbolIndexStore`,原名 `SymbolIndexStore`)内存优化专题——读这批内存文档先读这篇**:三波优化各自解决什么、今天的存储模型长什么样、付出了哪些约束、实测收益全曲线(RuntimeViewer 五镜像稳态 842 → 262 MB)。 | | [SymbolicManglingSymbols.md](Internal/SymbolicManglingSymbols.md) | **`_symbolic` 符号**(提案 0050-symbolic-mangling-symbol-index 的实现说明):编译器为每条带 symbolic reference 的 mangled name 生成的去重符号,名字里按引用顺序写出每个被引用者的完整 mangling(含 private 鉴别符);Swift 符号索引(今 `SwiftSymbolIndexStore`)在已有扫描里收进一张独立的表,`SwiftInspection.SymbolicManglingIndex` 按顺序配对、按被引用位置建索引。被引用者会借用前面的 substitution,只能一起 demangle;私有鉴别符还原与 `SymbolicDemangler` 的对照测试是两个消费者;附 AppKit / SwiftUICore / SwiftUI 的数量与内存实测。 | | [DeclarationModelMemoryFootprint.md](Internal/DeclarationModelMemoryFootprint.md) | NodeStore 迁移后的声明模型内存足迹量测:`TypeDefinition` 1272 字节的逐属性构成(两份 `TypeContextWrapper` 占 74%)、`TypeContextWrapper` 按最大 case `Class` 定尺的原因、`parentContext` 是被当成永久字段的临时值、mini-store 增殖与 `MetadataReaderCache` 仍持 `Node` 树;含四项可回收估算(合计 ~8–10%)与「当前不建议实施、应先剖析其余 90%」的结论。 | | [NodeStoreMigrationOpenIssues.md](Internal/NodeStoreMigrationOpenIssues.md) | NodeStore 迁移的遗留问题台账:每条问题记录成因、影响面、修复位置与当前状态(已修 / 裁决不修 / 仍打开),闭环的条目保留成因备回溯。大部分条目已闭环或已终审;与 `Reviews/` 下两份审查记录冲突时以后者为准。 | | [SystemFrameworkRenderingVerification.md](Internal/SystemFrameworkRenderingVerification.md) | 系统框架渲染 A/B 验证流程(大重构必跑):两个检出对同一批真实输入(归档 dyld cache → 无则当前系统 cache、模拟器 runtime → 无则现有 runtime、当前系统 MachOImage)逐字节比对 dump+interface;入口脚本 `Scripts/run-rendering-ab-verification.py`,含回退规则、踩坑清单(`-p` 消歧、fat 二进制 `-a`、同 boot 会话、scratch 隔离)与 2026-08-03 基线运行记录。 | -| [TypeIndexingPipeline.md](Internal/TypeIndexingPipeline.md) | **`__C` 模块归属索引管线**(提案 0009 + 0010 的实现说明):`__C.NSString` → `Foundation.NSString` 的三源合并(SourceKit 生成 interface 的 substructure 提取(零 SwiftSyntax)→ APINotes 权威归属覆盖 → 依赖 image ObjC 元数据懒索引兜底)、补充映射包(私有框架外部知识入口,CF-bridged 类型三种 mangling 形态与各自覆盖机制)、按 SDK 精确构建分层的 per-module JSON 缓存、过滤前移的性能形态(历史全 SDK 生成为何小时级)、`@Loggable` 在 `@available` 类型上必须走 protocol 形态的坑、与提案的差异(swift-dependencies 未引入、兜底解析器未编写、MachOObjCSection 下限 0.8.105)。 | +| [TuistDevelopment.md](Internal/TuistDevelopment.md) | **使用指南:Tuist 开发 workspace**:`./TuistScript.sh` 生成的 `MachOSwiftSection-Tuist.xcworkspace`,第三方依赖走本机二进制缓存,`--local-dependencies` 改用五个上游库的本地检出;测试怎么映射进来(`Package.swift` 末尾的 `TUIST_MAPS_LOCAL_PACKAGE_TESTS` 块、手写的 `SwiftSectionCommandTests`)、与 RuntimeViewer 共用的占用记录、存放位置与 Tuist 4.210 的坑。提案 [0099-tuist-workspace](Evolutions/0099-tuist-workspace.md)。 | +| [TypeIndexingPipeline.md](https://github.com/MxIris-Reverse-Engineering/swift-type-indexing/blob/main/Documentations/Internal/TypeIndexingPipeline.md)(已移到 swift-type-indexing) | **`__C` 模块归属索引管线**(提案 0009 + 0010 的实现说明,随 `TypeIndexing` 一起搬到 swift-type-indexing,本仓库只剩适配层 `SwiftTypeNameResolution`):`__C.NSString` → `Foundation.NSString` 的三源合并(SourceKit 生成 interface 的 substructure 提取(零 SwiftSyntax)→ APINotes 权威归属覆盖 → 依赖 image ObjC 元数据懒索引兜底)、补充映射包(私有框架外部知识入口,CF-bridged 类型三种 mangling 形态与各自覆盖机制)、按 SDK 精确构建分层的 per-module JSON 缓存、过滤前移的性能形态(历史全 SDK 生成为何小时级)、`@Loggable` 在 `@available` 类型上必须走 protocol 形态的坑、与提案的差异(swift-dependencies 未引入、兜底解析器未编写、MachOObjCSection 下限 0.8.105)。 | | [EventBasedDegradationReporting.md](Internal/EventBasedDegradationReporting.md) | **降级上报走事件**(提案 0005 的实现说明):库代码不写进程流,落点由宿主装的 `Handler` 决定(GUI → os_log,CLI → stderr);`Dispatcher` 零 handler 时的 os_log 地板与它为何在 dispatcher 而非调用点、`unhandledFailureDescription` 为何是白名单式穷举 switch;四条走不通的近路(`@Loggable` 的 product 与部署下限双重限制 + 泛型类型不可用、`SwiftDeclarationRendering` 因依赖方向够不到事件类型、`Handler` 非 `Sendable` 导致改注入 `Dispatcher`、fd 重定向测试会挂死整轮 `swift test` 故改源码扫描);顺带修掉的 `ConsoleEventHandler` 写 stdout 与 diff 单侧 header 失败删两侧;以及 `FileHandle.write(_:)` 为何会 abort 宿主。 | | [PrivateTypeMemberAttribution.md](Internal/PrivateTypeMemberAttribution.md) | 同名私有类型的成员归属(issue #115 修复说明):成员索引的打印名 key 剥掉了私有判别符、不是单射,「解析单个类型的成员/信息/属性」必须走带 `node:` 的重载;当时踩坑的全部位置(dump 三个 dumper、deinit/destructor、thunk 属性、`typeInfoByName`)、刻意不改 key 格式的理由、fixture 的防优化手段与回归防线。 | | [References/](Internal/References/README.md) | **外部权威资料的中译**(与 `Internal/` 其余文档相反:不描述本库,而是本库赖以成立的外部事实)。目前是 Slava Pestov《Compiling Swift Generics》**全书 24 章中译**,译自 `swift-6.4.0-RELEASE` 的 `docs/Generics/`(Apache License 2.0 with Runtime Library Exception,每篇标明出处/原作者/许可/commit)。书讲「源码怎么编成二进制」,本库做反方向的事,故书里的编码规则即本库的解码依据:generic signature 与 requirement 的 canonical 顺序(Generic Signatures / Building Generic Signatures)、`⊗` 替换代数(Substitution Maps)、conformance 三形态与 witness table(Conformances / Conformance Paths)、existential 容器布局(Existential Types)、`some P` 的完整机制(Opaque Result Types)。译文正文忠于原著,仅在确有对应处以「译注」标出本库落点;该目录 README 是分部索引与阅读约定(术语、两套记法、图的降级、原书笔误的处理)。 | diff --git a/Documentations/SwiftSectionKit.md b/Documentations/SwiftSectionKit.md index b12aef191..ab1e8353c 100644 --- a/Documentations/SwiftSectionKit.md +++ b/Documentations/SwiftSectionKit.md @@ -64,6 +64,17 @@ if outcome.hasBreakingChange == true { Options that exclude each other are one enum rather than several flags: an `ABIDiffRequest.Report` is a change list, a summary, JSON or an annotated interface, never two at once. Where the command line has a flag that implies another (`--emit-expanded-field-offsets` implies field offsets), the request has one value covering both (`FieldOffsetComments.expanded`). +`DumpRequest` and `InterfaceRequest` take `multilineTypeFormatting: MultilineTypeFormatting?` (`--multiline-types` and `--maximum-line-width`). With it, a type that runs past the line width — a SwiftUI view's `Body` above all — is broken over several lines at its brackets before the product is handed over: the whole interface at once, the dump one declaration at a time. `MultilineTypeFormatting` lives in `SwiftDeclarationRendering`; import that module to make one. A host that prints declarations itself formats them the same way, by calling `format(_:)` on a finished print: + +```swift +import SwiftDeclarationRendering + +let formatting = MultilineTypeFormatting(maximumLineWidth: 100) +let interface = formatting.format(try await printer.printTypeDefinition(definition)) +``` + +Formatting only adds line breaks and indentation; text, semantic types, identifiers and every visibility, definition and annotation region stay as printed, and a nested definition taken out of a formatted parent reads as that definition printed and formatted on its own. + A binary is named by a `MachOSource` — a thin or fat file, an image inside a dyld shared cache file, or an image of the running system's cache. `refs` and `symbolicate` read machine code across many images, so they take a `CrossReferenceInput` instead: a set of files read together, a whole cache file, or the whole running system's cache, read from its files. Their results carry `CrossReferenceAnalysis` types (`CodeReference`, `AddressSymbolication`); import that module to inspect them. `snapshot`, `diff` and `evolution` take `SnapshotSource.path`, which may name a binary or a snapshot document; the file's first non-whitespace byte tells them apart, as on the command line. ## The output contract diff --git a/Documentations/SwiftSectionKit_zh.md b/Documentations/SwiftSectionKit_zh.md index 6a5905f1b..cc3049c7d 100644 --- a/Documentations/SwiftSectionKit_zh.md +++ b/Documentations/SwiftSectionKit_zh.md @@ -62,6 +62,17 @@ if outcome.hasBreakingChange == true { 互斥的选项是一个 enum 而不是几个开关:`ABIDiffRequest.Report` 只能是 change list、summary、JSON、annotated interface 之一,不会同时是两个。命令行上一个 flag 隐含另一个的(`--emit-expanded-field-offsets` 隐含字段偏移),请求里是一个值同时表达两者(`FieldOffsetComments.expanded`)。 +`DumpRequest` 与 `InterfaceRequest` 收 `multilineTypeFormatting: MultilineTypeFormatting?`(命令行的 `--multiline-types` 与 `--maximum-line-width`)。给了它,超过行宽的类型——首先是 SwiftUI 视图的 `Body`——在交出产物之前按括号拆成多行:interface 整份做一次,dump 每个声明做一次。`MultilineTypeFormatting` 在 `SwiftDeclarationRendering` 里,构造它要导入这个模块。自己打印声明的宿主用同样的办法,对打印完成的结果调用 `format(_:)`: + +```swift +import SwiftDeclarationRendering + +let formatting = MultilineTypeFormatting(maximumLineWidth: 100) +let interface = formatting.format(try await printer.printTypeDefinition(definition)) +``` + +格式化只加换行和缩进;文字、semantic type、identifier 以及各种 visibility / definition / annotation region 都和打印时一样,从格式化过的父定义里取出的嵌套定义,等于这个定义单独打印再格式化。 + 二进制用 `MachOSource` 指明:瘦或胖的文件、dyld shared cache 文件里的一个镜像、或运行系统 cache 里的一个镜像。`snapshot`、`diff`、`evolution` 收 `SnapshotSource.path`,它可以指向二进制,也可以指向 snapshot 文档;和命令行一样,按文件第一个非空白字节区分。 ## 输出端契约 diff --git a/Documentations/Visions/ReverseEngineeringWithoutIDA.md b/Documentations/Visions/ReverseEngineeringWithoutIDA.md index 3593fa4bc..1ef0a7822 100644 --- a/Documentations/Visions/ReverseEngineeringWithoutIDA.md +++ b/Documentations/Visions/ReverseEngineeringWithoutIDA.md @@ -1,8 +1,8 @@ # 愿景:不依赖 IDA 的逆向 - **状态**: Active -- **最后更新**: 2026-11-19 -- **相关提案**: [0097-offline-cross-references-and-symbolication](../Evolutions/0097-offline-cross-references-and-symbolication.md) +- **最后更新**: 2026-11-26 +- **相关提案**: [0097-offline-cross-references-and-symbolication](../Evolutions/0097-offline-cross-references-and-symbolication.md)、[0113-cross-reference-recall-gaps](../Evolutions/0113-cross-reference-recall-gaps.md)(召回补漏) 愿景**不做具体决定**,它划定一个方向的边界与取舍原则,让后续每个提案不必重新论证一遍。 具体怎么做写在各自的提案里。 @@ -135,6 +135,27 @@ (建库时间未计)。 - 没测到的:dyld shared cache 里的跨镜像引用。IDA 的弱点主要在这里(一个库只装得下几个镜像),而 Binary Ninja 的 MCP 又没法加载 cache 镜像,这一场景要用户在界面里手动加载后才能比。 + - **复测(2026-11-26):本方向的工具在同一组样本上,代码引用召回 90.3%(476/527);IDA 一次查询 97.0%、 + 两跳 99.4%。** + - 被测的是 `swift-section refs` 0.25.0(0097 之后交叉引用只有重构,行为与 `next` 相同),每个目标查一次。 + 标准答案与选目标的代码从 2026-11-18 那次的对话记录原样取回,复现出同一批 120 个目标;引用总数、目标列表与 + 当时逐项一致,IDA 一列按原规则重算仍是 97.0% / 99.4%,所以两次的数字可以直接比。 + - 分类别:导入函数(91)、内部 `bl`(70)、字符串(46)全中,与 IDA 持平;selector 发送 95/97(IDA 一次 + 92);ivar 31/32;ObjC 类引用 66/87(IDA 一次 76、两跳 84);Swift 元数据访问器 77/104(IDA 104)。 + 49 条数据引用按 0097 的非目标不做,记 0。多报 1 条,核对后是真引用。单次查询 0.1–0.3 秒,不用建库。 + - 漏掉的 51 条分五组:27 条是代码取了访问器的地址当函数指针用——分析器记成了 Swift 类型引用,但 CLI 没有 + 按类型查的入口;13 条是 `__objc_superrefs` 的载入,按设计不算类引用;8 条是 Swift 代码把 ObjC 类的 GOT + 槽地址交给编译器生成的元数据辅助函数(ControlCenter 里有 554 处这种调用);2 条是 selector 只当参数用 + (`respondsToSelector:`、返回 selector 的函数);1 条是 `adrp; add` 之后 `ldrsw [xN]` 读 ivar 偏移, + 原因待查。 + - 比 IDA 强的地方:页对齐的类对象、经 `ldr` 读 selref 的经典发送都一次查到。 + - 后四组缺口的修复是提案 + [0113-cross-reference-recall-gaps](../Evolutions/0113-cross-reference-recall-gaps.md),修完的目标是 + 514/527(97.5%),剩下的就是 `super` 的那 13 条。测量脚本随那份提案进仓库(`Scripts/CrossReferenceRecall/`), + 以后改交叉引用就拿它验收。 + - **补漏后(2026-11-26,同一组样本,那份提案的功能分支):514/527(97.5%),多报 0**,高于 IDA 一次查询的 + 97.0%;剩下的 13 条正是按设计不报的 `__objc_superrefs` 载入。selector 发送 97/97、ivar 32/32、Swift + 元数据访问器 104/104、类引用 74/87。单次查询中位 0.09–0.18 秒(release 构建)。 2. **两个解码器分工。** 扫描整个 cache 的热路径用手写的 `ARM64InstructionDecoding`;给人和 agent 读的反汇编 文本、需要完整操作数语义的地方(跳转表、寄存器追踪)用 swift-capstone。两者之间用对拍测试保持一致: 同一批函数两边解码,结果逐条比。swift-capstone 因此要加大维护——拿 `otool -tV` 整镜像对拍正确性(重点是 @@ -197,6 +218,7 @@ |------|------|------------------------| | [0097-offline-cross-references-and-symbolication](../Evolutions/0097-offline-cross-references-and-symbolication.md) | Implemented | 第 1 阶段:交叉引用与地址符号化扩展到磁盘文件和归档 cache,并接到 `swift-section` 与 RuntimeViewer 的 CLI / MCP;顺带把交叉引用按「我们选的方向」第 6 条拆成核心、ObjC、Swift 三层(真正迁出本库另写提案) | | [0098 move-cross-reference-layers](../Evolutions/0098-move-cross-reference-layers.md) | Accepted | 「我们选的方向」第 6 条:把 0097 拆出的核心层与地址解析、ARM64 解码搬进 MachOKitExtensions,ObjC 层搬进 MachOObjCSection,随本库 0.25.0 落地 | +| [0113-cross-reference-recall-gaps](../Evolutions/0113-cross-reference-recall-gaps.md) | Implemented | 第 1 阶段的补漏:按「我们选的方向」第 1 条的复测(2026-11-26,90.3% 对 IDA 97.0%)补上四处缺口——CLI 按 Swift 类型查询、取 GOT 槽地址的类引用、selector 引用、一种 ivar 读法,并把取函数地址记成对函数的引用;测量脚本进仓库作为第 7 条「标准答案」的验收工具 | --- diff --git a/MachOSwiftSection.xcworkspace/contents.xcworkspacedata b/MachOSwiftSection.xcworkspace/contents.xcworkspacedata index 13acd86af..c28ff3013 100644 --- a/MachOSwiftSection.xcworkspace/contents.xcworkspacedata +++ b/MachOSwiftSection.xcworkspace/contents.xcworkspacedata @@ -4,12 +4,21 @@ - + + + + + + diff --git a/MachOSwiftSection.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/MachOSwiftSection.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings index 08de0be8d..54782e32f 100644 --- a/MachOSwiftSection.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings +++ b/MachOSwiftSection.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -3,6 +3,6 @@ IDEWorkspaceSharedSettings_AutocreateContextsIfNeeded - + diff --git a/Package.swift b/Package.swift index c9bf092d0..4b5c357f0 100644 --- a/Package.swift +++ b/Package.swift @@ -102,10 +102,23 @@ var dependencies: [Package.Dependency] = [ .package(url: "https://github.com/pointfreeco/swift-dependencies", from: "1.9.4"), - // TypeIndexing (all its sources are `#if os(macOS)`; both products carry - // a macOS-only platform condition on the target dependency) - .package(url: "https://github.com/Mx-Iris/SourceKitD", from: "0.1.0"), - .package(url: "https://github.com/MxIris-DeveloperTool/swift-apinotes", from: "0.1.0"), + // The SDK index `SwiftTypeNameResolution` resolves `__C` types with, moved + // out of this package (proposal swift-type-indexing-package). Its sources + // are all `#if os(macOS)`, so targets depend on it with a macOS-only + // condition. 0.1.1 closes each module interface it generates once read: + // with 0.1.0, `--resolve-c-module-names` grew SourceKitService to tens of GB. + // 0.2.0 answers which module declares a Swift type the SDK moved + // (`@_originallyDefinedIn`), for `--resolve-moved-type-modules`. + .package( + local: .package( + path: "../swift-type-indexing", + isRelative: true, + ), + remote: .package( + url: "https://github.com/MxIris-Reverse-Engineering/swift-type-indexing", + from: "0.2.0", + ), + ), // CLI .package(url: "https://github.com/onevcat/Rainbow", from: "4.0.0"), @@ -175,7 +188,14 @@ extension Package.Dependency { // 3.0.0 leaves Swift symbol names to this package: `SwiftSymbols` // defines `SymbolLanguage.swift` and registers it when the image // loads (proposal split-symbol-language). - from: "3.0.0", + // 3.2.0 ships the test support this package builds on: the + // `MachOFixtureSupport` and `MachOTestingSupport` products. + // 3.4.0 reads a reference slot whose address is built as that + // slot, records the functions whose address code takes, and tells + // a recognition session where each function ends, which the + // cross-reference analysis builds on (proposal + // cross-reference-recall-gaps). + from: "3.4.0", ), ) @@ -223,7 +243,18 @@ extension Package.Dependency { // 0.8.208 defines `SymbolLanguage.objectiveC` and registers it when // its image loads, and takes MachOKitExtensions 3.0.0, which this // package requires (proposal split-symbol-language). - "0.8.208" ..< "0.9.0", + // 0.8.209 adds `ObjCTypeIndexing`, the bridge to swift-type-indexing + // `SwiftTypeNameResolution` hands dependency images through + // (proposal swift-type-indexing-package), and prints `NS_SWIFT_NAME` + // and `NS_REFINED_FOR_SWIFT` as macros. + // 0.10.101 merges upstream 0.10.0 and records the selectors code + // loads from `__objc_selrefs` but sends nothing with (proposal + // cross-reference-recall-gaps). The fork's releases above an + // upstream version start at its patch 100, so the range starts + // there and leaves out upstream's own 0.10.0 tag. 0.10.102 + // requires MachOKitExtensions 3.4.0, without which those selector + // references go missing. + "0.10.102" ..< "0.11.0", ), ) } @@ -262,8 +293,10 @@ extension Package.Dependency { url: "https://github.com/MxIris-Reverse-Engineering/swift-semantic-string", // 0.6.0 adds the annotation regions `marksCommentStructure` marks // every comment with; 0.5.0 added the definition regions - // `marksNestedDefinitions` wraps each nested definition in. - from: "0.6.0", + // `marksNestedDefinitions` wraps each nested definition in. 0.7.0 + // adds `SemanticType.macro`, which MachOObjCSection 0.8.209 prints + // two macros with (proposal swift-type-indexing-package). + from: "0.7.0", ), ) @@ -361,6 +394,19 @@ extension Target.Dependency { name: "MachOFoundation", package: "MachOKitExtensions", ) + // The Swift-free half of the test support, shared with + // MachOKitExtensions' own tests since its 3.2.0: fixture names, opening + // caches and images, slice picking, the fixture compiler + // (`MachOFixtureSupport`, no Testing), and the trait and base classes on + // top of it (`MachOTestingSupport`). + static let MachOFixtureSupport = Target.Dependency.product( + name: "MachOFixtureSupport", + package: "MachOKitExtensions", + ) + static let MachOTestingSupport = Target.Dependency.product( + name: "MachOTestingSupport", + package: "MachOKitExtensions", + ) static let MachOKitMain = Target.Dependency.product( name: "MachOKit", package: "MachOKit", @@ -409,6 +455,14 @@ extension Target.Dependency { name: "SwiftSyntaxBuilder", package: "swift-syntax", ) + static let SwiftSyntaxMacroExpansion = Target.Dependency.product( + name: "SwiftSyntaxMacroExpansion", + package: "swift-syntax", + ) + static let SwiftSyntaxMacrosGenericTestSupport = Target.Dependency.product( + name: "SwiftSyntaxMacrosGenericTestSupport", + package: "swift-syntax", + ) static let SwiftTUI = Target.Dependency.product( name: "SwiftTUI", package: "SwiftTUI", @@ -804,6 +858,10 @@ extension Target { .target(.SwiftDeclarationRendering), .target(.SwiftDeclaration), .target(.SwiftAttributeInference), + // `Transformer.CType.Pattern`, the keys of + // `SwiftDeclarationPrintConfiguration.cTypeReplacements`. + .product(.OutputTransformer), + .product(name: "ObjCOutputTransformer", package: "MachOObjCSection"), ], path: "Sources/Output/SwiftPrinting", ) @@ -860,23 +918,26 @@ extension Target { path: "Sources/Output/SwiftInterface", ) - /// Module-attribution index for `__C` types (evolution proposal 0009): - /// resolves `__C.NSString` to `Foundation.NSString` via SourceKit-generated - /// module interfaces (substructure, no SwiftSyntax), APINotes renames, and - /// a lazy ObjC-metadata index over the binary's dependencies. Every source - /// file is `#if os(macOS)`. - static let TypeIndexing = Target.target( - name: "TypeIndexing", + /// The printer's side of swift-type-indexing (proposal + /// swift-type-indexing-package): `TypeDatabaseTypeNameResolver` answers the + /// printer's `ModuleNameResolving` and `CImportedNameResolving` from a + /// `TypeDatabase`, so `__C.UICellConfigurationState` prints as + /// `UIKit.__UICellConfigurationState`; `SwiftInterfaceBuilderTypeNameProvider` + /// attaches one to a `SwiftInterfaceBuilder` for a binary and its + /// dependencies. Every source file is `#if os(macOS)`. + static let SwiftTypeNameResolution = Target.target( + name: "SwiftTypeNameResolution", dependencies: [ .target(.SwiftInterface), + .target(.SwiftPrinting), + .target(.MachOSwiftSection), .product(.MachOKit), - .product(name: "ObjCIndexing", package: "MachOObjCSection"), + .product(.MachOKitExtensions), .product(name: "ObjCMetadataSource", package: "MachOObjCSection"), - .product(name: "FoundationToolbox", package: "FrameworkToolbox"), - .product(name: "SourceKitD", package: "SourceKitD", condition: .when(platforms: [.macOS])), - .product(name: "APINotes", package: "swift-apinotes", condition: .when(platforms: [.macOS])), + .product(name: "ObjCTypeIndexing", package: "MachOObjCSection", condition: .when(platforms: [.macOS])), + .product(name: "TypeIndexing", package: "swift-type-indexing", condition: .when(platforms: [.macOS])), ], - path: "Sources/Declaration/TypeIndexing", + path: "Sources/Output/SwiftTypeNameResolution", ) // MARK: - Commands @@ -903,7 +964,11 @@ extension Target { .target(.SwiftDiffing), .target(.SwiftInterface), .target(.SwiftPrivateDiscriminators), - .target(.TypeIndexing), + .target(.SwiftTypeNameResolution), + // `APINotesFile`, which checks `--supplementary-apinotes` paths. + .product(name: "TypeIndexing", package: "swift-type-indexing", condition: .when(platforms: [.macOS])), + // `objc interface --mark-sdk-swift-names`. + .product(name: "ObjCTypeIndexing", package: "MachOObjCSection", condition: .when(platforms: [.macOS])), .target(.Utilities), // `refs` and `symbolicate`. .target(.CrossReferenceAnalysis), @@ -932,13 +997,15 @@ extension Target { .target(.SwiftSectionKit), // What the wrapper names itself while mapping its flags onto the // library's requests: `DependencySearchPath`, `DemangleOptions`, - // `Transformer.SwiftConfiguration`, `ConsoleEventHandler`, the - // ObjC generation options and C type presets. + // `Transformer.SwiftConfiguration`, `ConsoleEventHandler`, + // `MultilineTypeFormatting`, the ObjC generation options and C + // type presets. .product(.MachOFoundation), .target(.SwiftSymbols), .target(.SwiftDump), .target(.SwiftOutputTransformer), .target(.SwiftDeclaration), + .target(.SwiftDeclarationRendering), .target(.SwiftIndexing), .product(.Semantic), .product(.OutputTransformer), @@ -1015,16 +1082,33 @@ extension Target { path: "Sources/Support/SwiftSectionMacros", ) + /// The test support's macros: `@FixtureSuite`. Kept apart from + /// `SwiftSectionMacros`, so the plugin the production targets load + /// carries no test-only macro. + static let SwiftSectionTestingMacros = Target.macro( + name: "SwiftSectionTestingMacros", + dependencies: [ + .product(.SwiftSyntax), + .product(.SwiftSyntaxMacros), + .product(.SwiftCompilerPlugin), + .product(.SwiftSyntaxBuilder), + ], + path: "Sources/TestSupport/SwiftSectionTestingMacros", + ) + // MARK: - Testing /// Fixture-loading helpers, baseline generators, coverage scanners, and /// non-Testing-dependent code. Importable from non-test targets (e.g. /// `baseline-generator`) without dragging in `Testing.framework`. + /// Re-exports MachOKitExtensions' `MachOFixtureSupport`, which it adds + /// this package's fixture names and named caches to. static let SwiftSectionFixtureSupport = Target.target( name: "SwiftSectionFixtureSupport", dependencies: [ .product(.MachOKit), .product(.MachOFoundation), + .product(.MachOFixtureSupport), .target(.SwiftSymbols), .product(.MachOReading), .product(.MachOResolving), @@ -1044,8 +1128,11 @@ extension Target { swiftSettings: testSettings, ) - /// `swift-testing` base classes (`MachOFileTests`, `MachOImageTests`, - /// `DyldCacheTests`, `XcodeMachOFileTests`, `MachOSwiftSectionFixtureTests`). + /// `swift-testing` support: `MachOSwiftSectionFixtureTests` and the Swift + /// fixtures, on top of MachOKitExtensions' `MachOTestingSupport` (the + /// `MachOFileTests`, `MachOImageTests`, `DyldCacheTests`, + /// `XcodeMachOFileTests` and `MachOFixtureTests` base classes and + /// `ExclusiveImageAccess`), which it re-exports. /// Splitting this out from `SwiftSectionFixtureSupport` keeps `Testing.framework` /// out of the link line for non-test targets. static let SwiftSectionTestingSupport = Target.target( @@ -1058,12 +1145,14 @@ extension Target { .product(.MachOReading), .product(.MachOResolving), .target(.SwiftSectionFixtureSupport), + .product(.MachOTestingSupport), .target(.MachOSwiftSection), .target(.SwiftDeclaration), .target(.SwiftIndexing), .target(.SwiftPrinting), .target(.SwiftSpecialization), .target(.SwiftInterface), + .target(.SwiftSectionTestingMacros), .product(.Semantic), ], path: "Sources/TestSupport/SwiftSectionTestingSupport", @@ -1175,10 +1264,17 @@ extension Target { swiftSettings: testSettings, ) - static let TypeIndexingTests = Target.testTarget( - name: "TypeIndexingTests", + static let SwiftTypeNameResolutionTests = Target.testTarget( + name: "SwiftTypeNameResolutionTests", dependencies: [ - .target(.TypeIndexing), + .target(.SwiftTypeNameResolution), + .target(.SwiftPrinting), + // The provider's tests build a small library to read + // (proposal moved-swift-type-modules). + .target(.SwiftInterface), + .target(.SwiftSectionFixtureSupport), + .product(.MachOKit), + .product(name: "TypeIndexing", package: "swift-type-indexing", condition: .when(platforms: [.macOS])), ], swiftSettings: testSettings, ) @@ -1197,6 +1293,10 @@ extension Target { .target(.SwiftInterface), // The nested-definition contract with source-file comments on. .target(.SwiftPrivateDiscriminators), + // `Transformer.CType`, the C type replacements of a recovered + // `@objc @implementation` stored property's type. + .product(.OutputTransformer), + .product(name: "ObjCOutputTransformer", package: "MachOObjCSection"), .product(.MachOKitExtensions), .target(.SwiftSectionTestingSupport), .target(.SwiftSectionFixtureSupport), @@ -1325,6 +1425,9 @@ extension Target { name: "SwiftSectionKitTests", dependencies: [ .target(.SwiftSectionKit), + // `FixtureCompiler`, for a library that names a moved Swift type + // (proposal moved-swift-type-modules). + .target(.SwiftSectionFixtureSupport), .product(.MachOFoundation), .target(.SwiftSymbols), // `LocalTypeFixture` and `ExclusiveImageAccess`, for the source @@ -1333,6 +1436,9 @@ extension Target { .target(.SwiftDeclaration), .target(.SwiftDiffing), .target(.SwiftOutputTransformer), + // `MultilineTypeFormatting`, which the `dump` and `interface` + // requests take. + .target(.SwiftDeclarationRendering), // What `refs` and `symbolicate` return. .target(.CrossReferenceAnalysis), .product(.Semantic), @@ -1389,6 +1495,19 @@ extension Target { swiftSettings: testSettings, ) + static let SwiftSectionTestingMacrosTests = Target.testTarget( + name: "SwiftSectionTestingMacrosTests", + dependencies: [ + .target(.SwiftSectionTestingMacros), + .product(.SwiftSyntax), + .product(.SwiftSyntaxBuilder), + .product(.SwiftSyntaxMacros), + .product(.SwiftSyntaxMacroExpansion), + .product(.SwiftSyntaxMacrosGenericTestSupport), + ], + swiftSettings: testSettings, + ) + static let SwiftSectionTestingSupportTests = Target.testTarget( name: "SwiftSectionTestingSupportTests", dependencies: [ @@ -1423,13 +1542,16 @@ extension Target { .target(.SwiftPrinting), .target(.SwiftInterface), .target(.SwiftDiffing), - .target(.TypeIndexing), + .target(.SwiftTypeNameResolution), + .product(name: "TypeIndexing", package: "swift-type-indexing", condition: .when(platforms: [.macOS])), .target(.SwiftSectionTestingSupport), .target(.SwiftSectionFixtureSupport), .product(.MachOKit), .product(.MachOObjCSection), - // The ObjC API evolution dumps run the `swift-section objc - // evolution` pipeline on MachOObjCSection's own modules. + // The Objective-C inspection dumps run the `swift-section objc + // dump`, `objc diff` and `objc evolution` pipelines on + // MachOObjCSection's own modules. + .product(name: "ObjCDeclarationRendering", package: "MachOObjCSection"), .product(name: "ObjCDiffing", package: "MachOObjCSection"), .product(name: "ObjCIndexing", package: "MachOObjCSection"), .product(name: "ObjCInterface", package: "MachOObjCSection"), @@ -1469,7 +1591,7 @@ let package = Package( .library(.SwiftPrinting), .library(.SwiftSpecialization), .library(.SwiftInterface), - .library(.TypeIndexing), + .library(.SwiftTypeNameResolution), .library(.SwiftSectionKit), .executable(.swift_section), ], @@ -1497,9 +1619,10 @@ let package = Package( .SwiftPrinting, .SwiftSpecialization, .SwiftInterface, - .TypeIndexing, + .SwiftTypeNameResolution, .SwiftSectionKit, .SwiftSectionMacros, + .SwiftSectionTestingMacros, .SwiftSectionFixtureSupport, .SwiftSectionTestingSupport, .SwiftSectionTestingSupportC, @@ -1520,7 +1643,7 @@ let package = Package( .SwiftOutputTransformerTests, .SwiftLayoutTests, .SwiftDumpTests, - .TypeIndexingTests, + .SwiftTypeNameResolutionTests, .SwiftPrintingTests, .SwiftDeclarationRenderingTests, .SwiftThunkAnalysisTests, @@ -1533,6 +1656,7 @@ let package = Package( .SwiftPrivateDiscriminatorsTests, .SwiftSpecializationTests, .SwiftInterfaceTests, + .SwiftSectionTestingMacrosTests, .SwiftSectionTestingSupportTests, .IntegrationTests, ], @@ -1546,3 +1670,51 @@ extension SwiftSetting { static let nonisolatedNonsendingByDefault: Self = .enableUpcomingFeature("NonisolatedNonsendingByDefault") // SE-0461, Swift 6.2, SwiftPM 6.2+ static let immutableWeakCaptures: Self = .enableUpcomingFeature("ImmutableWeakCaptures") // SE-0481, Swift 6.2, SwiftPM 6.2+ } + +// MARK: - Upcoming features + +// Every Swift target adopts three upcoming features that Swift 7 turns on +// (proposal swift6-mode-and-upcoming-features, shared with the other MachO +// packages). The loop runs before the Tuist block so a target Tuist reshapes +// already carries them. The other three settings above stay unused: they +// change run-time behavior or every import, and were measured and declined. +let upcomingFeatureSettings: [SwiftSetting] = [ + .existentialAny, + .memberImportVisibility, + .inferIsolatedConformances, +] + +for target in package.targets where target.type != .system && target.type != .binary && target.type != .plugin { + target.swiftSettings = (target.swiftSettings ?? []) + upcomingFeatureSettings +} + +// MARK: - Tuist development workspace + +// MachOSwiftSection's Tuist development workspace (its Documentations/Internal/TuistDevelopment.md) +// maps this package's tests with Tuist, which rejects shapes SwiftPM accepts: a test that depends on +// an executable target or on a macro target (Tuist builds a macro as a plugin, so `@testable import` +// of it finds no module), and a test that depends on a target no product contains. Only while Tuist +// resolves the packages, with TUIST_MAPS_LOCAL_PACKAGE_TESTS=1, the first kinds are left out — the +// macro expansion tests then run under `swift test` only — and the last kind gets a library product +// of its own. Nothing changes without the variable. +if Context.environment["TUIST_MAPS_LOCAL_PACKAGE_TESTS"] == "1" { + let executableOrMacroTargetNames = Set(package.targets.filter { $0.type == .executable || $0.type == .macro }.map(\.name)) + func dependencyName(_ dependency: Target.Dependency) -> String? { + switch dependency { + case .targetItem(let name, _), .byNameItem(let name, _): + return name + default: + return nil + } + } + package.targets.removeAll { target in + target.type == .test && target.dependencies.contains { dependency in + dependencyName(dependency).map(executableOrMacroTargetNames.contains) ?? false + } + } + let productTargetNames = Set(package.products.flatMap { product in (product as? Product.Library)?.targets ?? [] }) + let testDependencyNames = Set(package.targets.filter { $0.type == .test }.flatMap { $0.dependencies.compactMap(dependencyName) }) + package.products += package.targets + .filter { target in target.type == .regular && testDependencyNames.contains(target.name) && !productTargetNames.contains(target.name) } + .map { target in Product.library(name: target.name, targets: [target.name]) } +} diff --git a/README.md b/README.md index 6e1e59e8c..83b82113e 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,7 @@ Add the package to your `Package.swift`: ```swift dependencies: [ - .package(url: "https://github.com/MxIris-Reverse-Engineering/MachOSwiftSection", from: "0.25.0"), + .package(url: "https://github.com/MxIris-Reverse-Engineering/MachOSwiftSection", from: "0.28.0"), ], targets: [ .target( @@ -73,7 +73,7 @@ Since 0.25.0 the Mach-O layer underneath — `MachOBase`, `MachOFoundation`, `Ma | `SwiftThunkAnalysis` | Reads a type stored behind a metadata accessor thunk (availability-conditional opaque types, noncopyable fields) by evaluating its ARM64 code instead of running it, and ties a class's ObjC method table to its Swift members. | | `CrossReferenceAnalysis` | What each function of a loaded arm64 image calls and references — functions, Objective-C classes, Swift types — read from its machine code. `MachOImage` only. | | `SwiftSpecialization` | Runtime specialization of generic types (`GenericSpecializer`). | -| `TypeIndexing` | Attributes `__C` types to their real module (`__C.NSString` → `Foundation.NSString`) through SDK module interfaces and APINotes. macOS only. | +| `SwiftTypeNameResolution` | Resolves `__C` types to their real module and Swift name (`__C.NSString` → `Foundation.NSString`, `__C.UICellConfigurationState` → `UIKit.__UICellConfigurationState`) through [swift-type-indexing](https://github.com/MxIris-Reverse-Engineering/swift-type-indexing), which reads the SDK's module interfaces and API notes. macOS only. | **Declarations and output** @@ -450,6 +450,17 @@ swift-section interface --resolve-c-module-names /path/to/binary # Frameworks with no SDK module (AttributeGraph, …) take user-provided APINotes swift-section interface --resolve-c-module-names --supplementary-apinotes AttributeGraph.apinotes /path/to/binary +# A Swift type the SDK moved to another module (@_originallyDefinedIn) mangles under its old one; +# print it as the SDK declares it (`CoreGraphics.CGFloat` → `CoreFoundation.CGFloat`, and for a +# binary built with the macOS 15 SDK or later `SwiftUI.View` → `SwiftUICore.View`). +# macOS only; reads the SDK's .swiftinterface files, no sourcekitd. +swift-section interface --resolve-moved-type-modules /path/to/binary + +# A C type the binary's own descriptors rename prints under its Swift name everywhere — +# declaration, member types, extension headers (`AnyWeakAttribute`, not `__C.AGWeakAttribute`). +# c-name prints every C-imported type as the binary mangles it instead. +swift-section interface --c-imported-type-name-spelling c-name /path/to/binary + # Experimental: spell opaque result types (`some View`) from their opaque type # descriptors; complex return types may fail to parse swift-section interface --parse-opaque-return-type /path/to/binary @@ -742,7 +753,7 @@ superclass chain, why pure-Swift classes' ivar records do not line up, and the r #### refs - Find Cross References -Who sends a selector, calls a function, or references a class, an instance variable or a string — across every image of a dyld shared cache (an archived one, another device's, or the running system's, read from its files) or across a set of Mach-O files read together, such as an app's executable and its frameworks. No disassembler and no process: the code is read from the files, through image stubs, the stub islands between a cache's images, and the selector and GOT stubs macOS 27 shares across a cache. Only the images that can reference the subject are scanned — the ones whose selector references, imports or linkage allow it. +Who sends a selector, calls a function or takes its address, or references a class, an instance variable, a string or a Swift type — across every image of a dyld shared cache (an archived one, another device's, or the running system's, read from its files) or across a set of Mach-O files read together, such as an app's executable and its frameworks. No disassembler and no process: the code is read from the files, through image stubs, the stub islands between a cache's images, and the selector and GOT stubs macOS 27 shares across a cache. Only the images that can reference the subject are scanned — the ones whose selector references, imports or linkage allow it. ```bash # Every send of a selector across a whole cache @@ -759,6 +770,10 @@ swift-section refs --symbol _objc_autoreleasePoolPush --uses-system-dyld-shared- # What one function references, in instruction order swift-section refs --function 0x18a403858 --callees --uses-system-dyld-shared-cache +# Every reference to a Swift type, by its mangling or a $s…Mn / $s…Ma / $s…N symbol of it; +# --type-image names the image of a type no image of a cache exports +swift-section refs --type 7SwiftUI4TextV --uses-system-dyld-shared-cache --in-image SwiftUICore + # An app's files; a fat file needs --architecture, as everywhere swift-section refs --string NSWindowDidBecomeKeyNotification \ Foo.app/Contents/MacOS/Foo Foo.app/Contents/Frameworks/Bar.framework/Bar -a arm64e diff --git a/Scripts/CrossReferenceRecall/README.md b/Scripts/CrossReferenceRecall/README.md new file mode 100644 index 000000000..5c5ff9b85 --- /dev/null +++ b/Scripts/CrossReferenceRecall/README.md @@ -0,0 +1,45 @@ +# Cross-reference recall benchmark + +Measures how many of the code references in two real Apple binaries `swift-section refs` finds, against a ground truth built without any of the tools measured, and puts the result next to IDA's on the same targets. It is the acceptance gate of evolution proposal [`cross-reference-recall-gaps`](../../Documentations/Evolutions/0113-cross-reference-recall-gaps.md), and the numbers are kept in the vision [Reverse engineering without IDA](../../Documentations/Visions/ReverseEngineeringWithoutIDA.md). + +## Samples + +| Binary | Path (default) | arm64e UUID | +|---|---|---| +| Finder 26.5.2 (mostly Objective-C) | `/Volumes/RE/Finder/26.5.2/Finder` | `1E2E81F7-9B9D-317A-A102-F55ADAF6A0A0` | +| ControlCenter 26.7 (mostly Swift) | `/Volumes/RE/ControlCenter/26.7/ControlCenter` | `5782ED6B-471B-3CAC-9258-93734B6009C3` | + +Override the paths with `CROSS_REFERENCE_RECALL_FINDER` and `CROSS_REFERENCE_RECALL_CONTROL_CENTER`; the slices must have these UUIDs, or the targets and the IDA baseline no longer apply. + +## Running + +```sh +SWIFT_SECTION=/path/to/swift-section Scripts/CrossReferenceRecall/run_all.sh +``` + +About 30 seconds. Everything is written to `CROSS_REFERENCE_RECALL_WORK` (default `/tmp/cross-reference-recall`). Needs `otool`, `dyld_info`, `lipo` and `dwarfdump` from the Xcode command-line tools, and the system `python3`. + +| Script | What it does | +|---|---| +| `prepare.sh` | Thins both binaries to arm64e and writes their `otool -tV`, section and `dyld_info -fixups` listings. | +| `ground_truth.py` | Builds the ground truth — `otool -tV` plus a linear `adrp` register tracker, the fixups, the relative method lists and `__swift5_types` — and picks the 120 targets, seeded, in the order the 2026-11-18 run did. | +| `verify_reproduction.py` | Checks the totals and target lists against that run's printed output; fails when they differ. | +| `query_swift_section.py` | Asks `$SWIFT_SECTION refs` once per target, as an agent would. | +| `score.py` | Scores with the 2026-11-18 rules and prints the table beside `ida-2026-11-18.txt`; every miss and extra goes to `swift-section.details.txt` with its disassembly line. | + +`ground_truth.py` is the 2026-11-18 run's code, recovered from that session's transcript and rewritten with full names; `verify_reproduction.py` is what shows the rewrite changed nothing. `ida-2026-11-18.txt` is that run's scoring output (`ida1` one query, `ida2` two hops; the `bn` rows are Binary Ninja through its MCP server). + +## Categories + +A selector sends · B Objective-C class references · C imported functions through stubs · D internal functions called with `bl` · E string literals · F instance variable offsets (Finder only) · G Swift metadata accessors, and functions only Swift tables point at (ControlCenter only) · H method implementations and function pointers. G-tableonly and H are data references, which `refs` does not report. + +## Results + +| Date | Tool | Code references found (of 527) | +|---|---|---| +| 2026-11-18 | IDA, one query / two hops | 97.0% / 99.4% | +| 2026-11-18 | Binary Ninja 6 through its MCP server | 67.6% | +| 2026-11-26 | `swift-section` 0.25.0 | 90.3% (476) | +| 2026-11-26 | `swift-section` with proposal `cross-reference-recall-gaps` | 97.5% (514), no extras | + +0.25.0's 51 misses: 27 Swift metadata accessors whose address is taken rather than called, 13 loads from `__objc_superrefs` (not class references by design), 8 class GOT slots whose address Swift code hands to the metadata helper, 2 selectors used as arguments, 1 instance variable offset whose address two paths build differently before one load. The proposal fixes all but the 13; with it the 13 are the only misses. diff --git a/Scripts/CrossReferenceRecall/ground_truth.py b/Scripts/CrossReferenceRecall/ground_truth.py new file mode 100644 index 000000000..ed0aa7159 --- /dev/null +++ b/Scripts/CrossReferenceRecall/ground_truth.py @@ -0,0 +1,403 @@ +"""Builds the independent ground truth of the cross-reference recall +benchmark and picks its targets, exactly as the 2026-11-18 IDA / Binary Ninja +benchmark did (see README.md): from `otool -tV`, a linear `adrp` register +tracker, `dyld_info -fixups`, the relative method lists and `__swift5_types` — +none of the tools measured. + +The order matters and is kept: a first ground truth with a 64-instruction +window between `adrp` and its use, the Finder targets picked from it, then +the final ground truth without the window, and the ControlCenter targets +picked from that. Both pickings are seeded, so the targets come out the same +every time; `verify_reproduction.py` checks that they do. + +Reads `.otool`, `.sections` and `.fixups` +(`prepare.sh`) from the work directory; writes `.ground-truth.json`, +`.pairs.json` and `.targets.json` there. +""" +import collections +import json +import os +import random +import re +import struct +import subprocess + +WORK = os.environ.get("CROSS_REFERENCE_RECALL_WORK", "/tmp/cross-reference-recall") + "/" +BINARIES = ("Finder", "ControlCenter") +INSTRUCTION_PATTERN = re.compile(r'^([0-9a-f]{16})\t(\S+)\t?([^;]*)') +ADD_PATTERN = re.compile(r'(\w+), (\w+), #(0x[0-9a-f]+|\d+)$') +MEMORY_PATTERN = re.compile(r'(\w+)(?:, (\w+))?, \[(\w+)(?:, #(-?0x[0-9a-f]+|-?\d+))?\]$') +NOT_WRITING_PREFIXES = ("st", "cmp", "cmn", "tst", "b", "cb", "tb", "ret", "pac", "aut", "brk", "fcmp", "prfm") +POINTER_SECTIONS = ("__got", "__auth_got", "__objc_superrefs", "__objc_classrefs") + + +def function_starts(binary_name): + output = subprocess.run(["dyld_info", "-function_starts", WORK + binary_name], capture_output=True, text=True).stdout + return [int(line.split()[0], 16) for line in output.splitlines()[2:] if line.strip().startswith("0x")] + + +def file_bytes_reader(binary_name): + """A reader of the bytes at a virtual address, through the segments' + file offsets.""" + file_bytes = open(WORK + binary_name, "rb").read() + load_commands = subprocess.run(["otool", "-l", WORK + binary_name], capture_output=True, text=True).stdout + segments = [] + current = {} + for line in load_commands.splitlines(): + tokens = line.split() + if not tokens: + continue + if tokens[0] == "cmd": + current = {"cmd": tokens[1]} + if tokens[0] in ("segname", "vmaddr", "vmsize", "fileoff", "filesize") and current.get("cmd") == "LC_SEGMENT_64" and tokens[0] not in current: + current[tokens[0]] = tokens[1] if tokens[0] == "segname" else int(tokens[1], 0) + if tokens[0] == "filesize": + segments.append(dict(current)) + + def read_bytes(address, count): + for segment in segments: + if segment["vmaddr"] <= address < segment["vmaddr"] + segment["filesize"]: + offset = segment["fileoff"] + address - segment["vmaddr"] + return file_bytes[offset:offset + count] + return None + + return read_bytes + + +def read_sections(binary_name): + sections = {} + for line in open(WORK + binary_name + ".sections"): + segment, section, address, size = line.split() + sections[section if section not in sections else segment + "," + section] = (int(address, 16), int(size, 16)) + return sections + + +def read_fixups(binary_name): + fixups = {} + for line in open(WORK + binary_name + ".fixups"): + tokens = line.split() + if len(tokens) >= 5 and tokens[2].startswith("0x"): + address = int(tokens[2], 16) + if tokens[3] in ("rebase", "auth-rebase"): + fixups[address] = ("r", int(tokens[4], 16)) + else: + fixups[address] = ("b", tokens[4]) + return fixups + + +def track_references(binary_name, window): + """Every address an instruction reaches: a branch target, an `adr`, or an + `adrp` page plus the immediate of an `add` or a load / store that uses + it — no further than `window` instructions apart when a window is given. + Also which `adrp` each such use pairs with.""" + starts = set(function_starts(binary_name)) + references = collections.defaultdict(list) + pairs = {} + registers = {} + instruction_number = 0 + for line in open(WORK + binary_name + ".otool"): + match = INSTRUCTION_PATTERN.match(line) + if not match: + continue + instruction_address = int(match.group(1), 16) + mnemonic = match.group(2) + operands = match.group(3).strip() + if instruction_address in starts: + registers = {} + instruction_number += 1 + if mnemonic == "adrp": + registers[operands.split(",", 1)[0].strip()] = (int(line.split(";")[1].strip(), 16), instruction_number, instruction_address) + continue + if mnemonic in ("bl", "b") and operands.startswith("0x"): + references[int(operands, 16)].append((instruction_address, "call" if mnemonic == "bl" else "jump")) + continue + if mnemonic == "adr": + register, immediate = [operand.strip() for operand in operands.split(",")] + references[instruction_address + int(immediate.lstrip("#"), 0)].append((instruction_address, "adr")) + registers.pop(register, None) + continue + add_match = ADD_PATTERN.match(operands) if mnemonic == "add" else None + if add_match: + destination, source, immediate = add_match.groups() + if source in registers and (window is None or instruction_number - registers[source][1] < window): + references[registers[source][0] + int(immediate, 0)].append((instruction_address, "add")) + pairs[instruction_address] = registers[source][2] + registers.pop(destination, None) + continue + memory_match = MEMORY_PATTERN.match(operands) + if memory_match and (mnemonic.startswith("ld") or mnemonic.startswith("st") or mnemonic == "prfm"): + destination, second_destination, base, immediate = memory_match.groups() + if base in registers and (window is None or instruction_number - registers[base][1] < window): + references[registers[base][0] + int(immediate or "0", 0)].append((instruction_address, mnemonic)) + pairs[instruction_address] = registers[base][2] + if mnemonic.startswith("ld"): + registers.pop(destination, None) + if second_destination: + registers.pop(second_destination, None) + continue + if operands and not mnemonic.startswith(NOT_WRITING_PREFIXES): + destination = operands.split(",")[0].strip() + registers.pop(destination, None) + if destination.startswith("w"): + registers.pop("x" + destination[1:], None) + return references, pairs + + +def objective_c_stubs(sections, fixups, read_bytes): + """Each `__objc_stubs` stub: its selector reference and selector.""" + def c_string(address): + bytes_read = read_bytes(address, 512) + return bytes_read.split(b"\0")[0].decode("utf8", "replace") if bytes_read else None + + stubs = {} + if "__objc_stubs" not in sections: + return stubs + start, size = sections["__objc_stubs"] + address = start + while address < start + size: + first_word, second_word = struct.unpack("> 29) & 3 + immediate_high = (first_word >> 5) & 0x7FFFF + immediate = (immediate_high << 2) | immediate_low + if immediate & (1 << 20): + immediate -= 1 << 21 + page = (address & ~0xFFF) + (immediate << 12) + offset = ((second_word >> 10) & 0xFFF) * 8 + selector_reference = page + offset + fixup = fixups.get(selector_reference) + selector = c_string(fixup[1]) if fixup and fixup[0] == "r" else None + stubs[address] = (selector_reference, selector) + address += 32 + return stubs + + +def save_ground_truth(binary_name, sections, stubs, references, fixups): + json.dump({ + "sections": sections, + "stubs": {str(key): value for key, value in stubs.items()}, + "references": {str(key): value for key, value in references.items()}, + "fixups": {str(key): value for key, value in fixups.items()}, + }, open(WORK + binary_name + ".ground-truth.json", "w")) + + +def load_ground_truth(binary_name): + ground_truth = json.load(open(WORK + binary_name + ".ground-truth.json")) + return ( + ground_truth["sections"], + {int(key): value for key, value in ground_truth["stubs"].items()}, + {int(key): value for key, value in ground_truth["references"].items()}, + {int(key): value for key, value in ground_truth["fixups"].items()}, + ) + + +def method_list_references(sections, read_bytes): + """Each method implementation's address, and the method list fields + that point at it: relative method lists, 12-byte entries.""" + method_lists_start, method_lists_size = sections["__objc_methlist"] + references = {} + lists = 0 + address = method_lists_start + while address < method_lists_start + method_lists_size - 8: + entry_size_and_flags, count = struct.unpack(" 5000: + print("bad method list", hex(address), hex(entry_size_and_flags), count) + break + lists += 1 + for index in range(count): + field = address + 8 + index * 12 + 8 + implementation = field + struct.unpack(" 0] + chosen = random.sample(candidates, 6) + random.sample(with_direct_loads, 2) + targets["A"] = [dict(stub=candidate[0], selector_reference=candidate[1], selector=candidate[2]) for candidate in chosen] + global_offset_table = section_range("__got") + authenticated_global_offset_table = section_range("__auth_got") + class_list = section_range("__objc_classlist") + external = [ + (address, value) for address, (kind, value) in fixups.items() + if (global_offset_table[0] <= address < global_offset_table[1] or authenticated_global_offset_table[0] <= address < authenticated_global_offset_table[1]) + and kind == "b" and "_OBJC_CLASS_$_" in value and 2 <= len(code_references(address)) <= 50 + ] + classes = [value for address, (kind, value) in fixups.items() if class_list[0] <= address < class_list[1] and kind == "r"] + own = [class_address for class_address in classes if 2 <= len(code_references(class_address)) <= 50] + targets["B"] = [dict(kind="ext", slot=address, symbol=value) for address, value in random.sample(external, 4)] + [dict(kind="own", class_address=class_address) for class_address in random.sample(own, 4)] + authenticated_stubs = section_range("__auth_stubs") + targets["C"] = random.sample([address for address in range(authenticated_stubs[0], authenticated_stubs[1], 16) if 2 <= len(code_references(address)) <= 50], 8) + starts = function_starts(binary_name) + start_set = set(starts) + targets["D"] = random.sample([start for start in starts if 2 <= len([instruction for instruction, kind in references.get(start, []) if kind == "call"]) <= 50], 8) + constant_strings = section_range("__cfstring") + c_strings = section_range("__cstring") + constant_string_targets = [address for address in range(constant_strings[0], constant_strings[1], 32) if 2 <= len(code_references(address)) <= 50] + c_string_targets = sorted(target for target in references if c_strings[0] <= target < c_strings[1] and 2 <= len(code_references(target)) <= 50) + targets["E"] = [dict(kind="cfstr", address=address) for address in random.sample(constant_string_targets, 4)] + [dict(kind="cstr", address=address) for address in random.sample(c_string_targets, 4)] + instance_variables = section_range("__objc_ivar") + targets["F"] = random.sample([address for address in range(instance_variables[0], instance_variables[1], 8) if 2 <= len(code_references(address)) <= 50], 8) + implementations, lists = method_list_references(sections, file_bytes_reader(binary_name)) + print("lists", lists, "imps", len(implementations)) + rebase_targets_in_text = {} + for fixup_address, (kind, value) in fixups.items(): + if kind == "r" and is_in_text(value): + rebase_targets_in_text.setdefault(value, []).append(fixup_address) + method_implementations = [start for start in implementations if start in start_set] + pointed_functions = [start for start in rebase_targets_in_text if start in start_set and start not in implementations] + print("H1", len(method_implementations), "H2", len(pointed_functions)) + targets["H"] = [dict(kind="imp", function=start) for start in random.sample(method_implementations, 4)] + [dict(kind="ptr", function=start) for start in random.sample(pointed_functions, 4)] + json.dump({ + "targets": targets, + "method_list_references": {str(key): value for key, value in implementations.items()}, + }, open(WORK + binary_name + ".targets.json", "w")) + + +def pick_control_center_targets(): + binary_name = "ControlCenter" + sections, stubs, references, fixups = load_ground_truth(binary_name) + read_bytes = file_bytes_reader(binary_name) + + def section_range(name): + start, size = sections[name] + return start, start + size + + text = section_range("__text") + + def is_in_text(address): + return text[0] <= address < text[1] + + def section_name(address): + for name, (start, size) in sections.items(): + if start <= address < start + size: + return name + return "?" + + def code_references(target): + return sorted(set(instruction for instruction, kind in references.get(target, []) if is_in_text(instruction))) + + random.seed(11) + targets = {} + candidates = [ + (stub_address, selector_reference, selector, len([instruction for instruction, kind in references.get(stub_address, []) if kind == "call" and is_in_text(instruction)]), len(code_references(selector_reference))) + for stub_address, (selector_reference, selector) in stubs.items() + ] + candidates = [candidate for candidate in candidates if 2 <= candidate[3] <= 50] + with_direct_loads = [candidate for candidate in candidates if candidate[4] > 0] + print("A", len(candidates), len(with_direct_loads)) + chosen = random.sample(candidates, 8 - min(2, len(with_direct_loads))) + random.sample(with_direct_loads, min(2, len(with_direct_loads))) + targets["A"] = [dict(stub=candidate[0], selector_reference=candidate[1], selector=candidate[2]) for candidate in chosen] + binds_by_symbol = collections.defaultdict(list) + rebases_by_target = collections.defaultdict(list) + for address, (kind, value) in fixups.items(): + if kind == "b": + binds_by_symbol[value.split("/")[-1].split()[0]].append(address) + else: + rebases_by_target[value].append(address) + external = [ + symbol for symbol, slots in binds_by_symbol.items() + if "_OBJC_CLASS_$_" in symbol and 2 <= sum(len(code_references(slot)) for slot in slots if section_name(slot) in POINTER_SECTIONS) <= 50 + ] + class_list = section_range("__objc_classlist") + classes = [value for address, (kind, value) in fixups.items() if class_list[0] <= address < class_list[1] and kind == "r"] + + def class_references(class_address): + return set(code_references(class_address)).union(*[set(code_references(slot)) for slot in rebases_by_target.get(class_address, []) if section_name(slot) in POINTER_SECTIONS]) + + own = [class_address for class_address in classes if 2 <= len(class_references(class_address)) <= 50] + print("B ext", len(external), "own", len(own), "of", len(classes)) + targets["B"] = [dict(kind="ext", symbol="x/" + symbol) for symbol in random.sample(external, 4)] + [dict(kind="own", class_address=class_address) for class_address in random.sample(own, min(4, len(own)))] + authenticated_stubs = section_range("__auth_stubs") + targets["C"] = random.sample([address for address in range(authenticated_stubs[0], authenticated_stubs[1], 16) if 2 <= len(code_references(address)) <= 50], 8) + starts = function_starts(binary_name) + start_set = set(starts) + types = section_range("__swift5_types") + accessors = {} + for address in range(types[0], types[1], 4): + descriptor = address + struct.unpack("= 1] + print("F", [(hex(address), len(code_references(address))) for address in targets["F"]]) + implementations, _ = method_list_references(sections, read_bytes) + rebase_targets_in_text = {} + for fixup_address, (kind, value) in fixups.items(): + if kind == "r" and is_in_text(value): + rebase_targets_in_text.setdefault(value, []).append(fixup_address) + method_implementations = [start for start in implementations if start in start_set] + # Functions referenced only from Swift metadata and witness tables: data, + # and no code. + table_only = [ + start for start, slots in rebase_targets_in_text.items() + if start in start_set and start not in implementations and not code_references(start) and all(section_name(slot) in ("__data", "__const") for slot in slots) + ] + pointed_functions = [start for start in rebase_targets_in_text if start in start_set and start not in implementations and start not in table_only] + print("H1", len(method_implementations), "H2", len(pointed_functions), "G2", len(table_only)) + targets["H"] = [dict(kind="imp", function=start) for start in random.sample(method_implementations, 4)] + [dict(kind="ptr", function=start) for start in random.sample(pointed_functions, 4)] + targets["G"] = [dict(category="G", kind="accessor", function=start) for start in random.sample(accessor_candidates, 8)] + [dict(category="G", kind="tableonly", function=start) for start in random.sample(table_only, 8)] + json.dump({ + "targets": targets, + "method_list_references": {str(key): value for key, value in implementations.items()}, + }, open(WORK + binary_name + ".targets.json", "w")) + + +def main(): + for binary_name in BINARIES: + read_bytes = file_bytes_reader(binary_name) + sections = read_sections(binary_name) + fixups = read_fixups(binary_name) + stubs = objective_c_stubs(sections, fixups, read_bytes) + references, _ = track_references(binary_name, window=64) + save_ground_truth(binary_name, sections, stubs, references, fixups) + print(binary_name, "stubs", len(stubs), "targets", len(references), "refs", sum(len(value) for value in references.values())) + pick_finder_targets() + for binary_name in BINARIES: + sections, stubs, first_references, fixups = load_ground_truth(binary_name) + references, pairs = track_references(binary_name, window=None) + save_ground_truth(binary_name, sections, stubs, references, fixups) + json.dump({str(key): value for key, value in pairs.items()}, open(WORK + binary_name + ".pairs.json", "w")) + print(binary_name, "refs old", sum(len(value) for value in first_references.values()), "new", sum(len(value) for value in references.values())) + pick_control_center_targets() + + +main() diff --git a/Scripts/CrossReferenceRecall/ida-2026-11-18.txt b/Scripts/CrossReferenceRecall/ida-2026-11-18.txt new file mode 100644 index 000000000..bf5ae684c --- /dev/null +++ b/Scripts/CrossReferenceRecall/ida-2026-11-18.txt @@ -0,0 +1,60 @@ +Finder A bn1 code 20/22 data 0/0 extra 0 {} internal 0 2hop 0 +Finder A bn2 code 22/22 data 0/0 extra 0 {} internal 0 2hop 0 +Finder A ida1 code 20/22 data 0/0 extra 0 {} internal 0 2hop 0 +Finder A ida2 code 22/22 data 0/0 extra 0 {} internal 0 2hop 0 +Finder B bn1 code 0/57 data 8/13 extra 0 {} internal 0 2hop 0 +Finder B bn2 code 57/57 data 8/13 extra 0 {} internal 0 2hop 0 +Finder B ida1 code 54/57 data 13/13 extra 0 {} internal 0 2hop 0 +Finder B ida2 code 54/57 data 13/13 extra 1 {'__objc_classlist': 1} internal 0 2hop 0 +Finder C bn1 code 58/58 data 0/0 extra 0 {} internal 0 2hop 0 +Finder C bn2 code 58/58 data 0/0 extra 0 {} internal 0 2hop 0 +Finder C ida1 code 58/58 data 0/0 extra 0 {} internal 0 2hop 0 +Finder C ida2 code 58/58 data 0/0 extra 0 {} internal 0 2hop 0 +Finder D bn1 code 27/28 data 0/0 extra 0 {} internal 226 2hop 0 +Finder D bn2 code 27/28 data 0/0 extra 0 {} internal 226 2hop 0 +Finder D ida1 code 28/28 data 0/0 extra 0 {} internal 2 2hop 0 +Finder D ida2 code 28/28 data 0/0 extra 0 {} internal 2 2hop 0 +Finder E bn1 code 0/28 data 2/2 extra 0 {} internal 0 2hop 0 +Finder E bn2 code 26/28 data 2/2 extra 0 {} internal 0 2hop 0 +Finder E ida1 code 28/28 data 2/2 extra 0 {} internal 0 2hop 0 +Finder E ida2 code 28/28 data 2/2 extra 0 {} internal 0 2hop 6 +Finder F bn1 code 0/32 data 8/8 extra 0 {} internal 0 2hop 0 +Finder F bn2 code 32/32 data 8/8 extra 0 {} internal 0 2hop 0 +Finder F ida1 code 32/32 data 8/8 extra 0 {} internal 0 2hop 0 +Finder F ida2 code 32/32 data 8/8 extra 0 {} internal 0 2hop 0 +Finder H bn1 code 0/0 data 4/8 extra 8 {'__objc_methname': 4, '__objc_selrefs': 4} internal 13 2hop 0 +Finder H bn2 code 0/0 data 4/8 extra 8 {'__objc_methname': 4, '__objc_selrefs': 4} internal 13 2hop 0 +Finder H ida1 code 0/0 data 8/8 extra 0 {} internal 0 2hop 0 +Finder H ida2 code 0/0 data 8/8 extra 0 {} internal 0 2hop 0 +ControlCenter A bn1 code 72/75 data 0/0 extra 0 {} internal 0 2hop 0 +ControlCenter A bn2 code 75/75 data 0/0 extra 0 {} internal 0 2hop 0 +ControlCenter A ida1 code 72/75 data 0/0 extra 0 {} internal 0 2hop 0 +ControlCenter A ida2 code 75/75 data 0/0 extra 0 {} internal 0 2hop 0 +ControlCenter B bn1 code 0/30 data 5/9 extra 0 {} internal 0 2hop 0 +ControlCenter B bn2 code 30/30 data 5/9 extra 0 {} internal 0 2hop 0 +ControlCenter B ida1 code 22/30 data 9/9 extra 2 {'text:ldr': 1, '?': 1} internal 0 2hop 0 +ControlCenter B ida2 code 30/30 data 9/9 extra 3 {'text:ldr': 1, '?': 2} internal 0 2hop 0 +ControlCenter C bn1 code 33/33 data 0/0 extra 0 {} internal 0 2hop 0 +ControlCenter C bn2 code 33/33 data 0/0 extra 0 {} internal 0 2hop 0 +ControlCenter C ida1 code 33/33 data 0/0 extra 0 {} internal 0 2hop 0 +ControlCenter C ida2 code 33/33 data 0/0 extra 0 {} internal 0 2hop 0 +ControlCenter D bn1 code 42/42 data 0/0 extra 0 {} internal 21 2hop 0 +ControlCenter D bn2 code 42/42 data 0/0 extra 0 {} internal 21 2hop 0 +ControlCenter D ida1 code 42/42 data 0/0 extra 1 {'__data': 1} internal 0 2hop 0 +ControlCenter D ida2 code 42/42 data 0/0 extra 1 {'__data': 1} internal 0 2hop 0 +ControlCenter E bn1 code 0/18 data 0/0 extra 0 {} internal 0 2hop 0 +ControlCenter E bn2 code 9/18 data 0/0 extra 0 {} internal 0 2hop 0 +ControlCenter E ida1 code 18/18 data 0/0 extra 0 {} internal 0 2hop 0 +ControlCenter E ida2 code 18/18 data 0/0 extra 0 {} internal 0 2hop 0 +ControlCenter G-accessor bn1 code 104/104 data 0/0 extra 5 {'text:adrp': 5} internal 3 2hop 0 +ControlCenter G-accessor bn2 code 104/104 data 0/0 extra 5 {'text:adrp': 5} internal 3 2hop 0 +ControlCenter G-accessor ida1 code 104/104 data 0/0 extra 8 {'__constg_swiftt': 8} internal 0 2hop 0 +ControlCenter G-accessor ida2 code 104/104 data 0/0 extra 8 {'__constg_swiftt': 8} internal 0 2hop 0 +ControlCenter G-tableonly bn1 code 0/0 data 11/11 extra 17 {'text:adrp': 17} internal 4 2hop 0 +ControlCenter G-tableonly bn2 code 0/0 data 11/11 extra 17 {'text:adrp': 17} internal 4 2hop 0 +ControlCenter G-tableonly ida1 code 0/0 data 11/11 extra 0 {} internal 0 2hop 0 +ControlCenter G-tableonly ida2 code 0/0 data 11/11 extra 0 {} internal 0 2hop 0 +ControlCenter H bn1 code 0/0 data 4/8 extra 8 {'__objc_methname': 4, '__objc_selrefs': 4} internal 7 2hop 0 +ControlCenter H bn2 code 0/0 data 4/8 extra 8 {'__objc_methname': 4, '__objc_selrefs': 4} internal 7 2hop 0 +ControlCenter H ida1 code 0/0 data 8/8 extra 0 {} internal 0 2hop 0 +ControlCenter H ida2 code 0/0 data 8/8 extra 0 {} internal 0 2hop 0 \ No newline at end of file diff --git a/Scripts/CrossReferenceRecall/prepare.sh b/Scripts/CrossReferenceRecall/prepare.sh new file mode 100644 index 000000000..5dd156c21 --- /dev/null +++ b/Scripts/CrossReferenceRecall/prepare.sh @@ -0,0 +1,26 @@ +#!/bin/zsh +# Thins the two samples to the arm64e slice both IDA databases hold, and +# writes the disassembly, load-command and fixup listings ground_truth.py +# reads. The samples are the ones the 2026-11-18 benchmark used. +set -euo pipefail +WORK=${CROSS_REFERENCE_RECALL_WORK:-/tmp/cross-reference-recall} +FINDER=${CROSS_REFERENCE_RECALL_FINDER:-/Volumes/RE/Finder/26.5.2/Finder} +CONTROL_CENTER=${CROSS_REFERENCE_RECALL_CONTROL_CENTER:-/Volumes/RE/ControlCenter/26.7/ControlCenter} +mkdir -p $WORK +cd $WORK + +# A sample already thinned to arm64e is taken as it is. +thin() { + if lipo -info $1 | grep -q '^Non-fat'; then cp $1 $2; else lipo -thin arm64e $1 -output $2; fi +} +thin $FINDER Finder +thin $CONTROL_CENTER ControlCenter +# 1E2E81F7-9B9D-317A-A102-F55ADAF6A0A0 and 5782ED6B-471B-3CAC-9258-93734B6009C3. +dwarfdump --uuid Finder ControlCenter + +for binary in Finder ControlCenter; do + otool -arch arm64e -tV $WORK/$binary > $binary.otool + otool -arch arm64e -l $WORK/$binary | awk '/sectname/{s=$2} /segname/{g=$2} /^ *addr /{a=$2} /^ *size /{if(s!=""){print g, s, a, $2; s=""}}' > $binary.sections + dyld_info -fixups $WORK/$binary > $binary.fixups + wc -l $binary.otool $binary.sections $binary.fixups +done diff --git a/Scripts/CrossReferenceRecall/query_swift_section.py b/Scripts/CrossReferenceRecall/query_swift_section.py new file mode 100644 index 000000000..e6730af2d --- /dev/null +++ b/Scripts/CrossReferenceRecall/query_swift_section.py @@ -0,0 +1,240 @@ +"""Asks `swift-section refs` about every target of the benchmark. + +The per-target ground truth is built exactly as the 2026-11-18 harness built +it for IDA and Binary Ninja; only the tool asked changes. Each target gets +one query, as an agent would ask it ("one_query"). An external class also +gets the by-symbol query the documentation tells callers to add +("with_symbol_query"); for every other target the two are the same. + +The binary asked is `$SWIFT_SECTION`, `swift-section` on the `PATH` when it +is unset. Writes `.swift-section.results.json`. +""" +import bisect +import collections +import json +import os +import struct +import subprocess +import time + +WORK = os.environ.get("CROSS_REFERENCE_RECALL_WORK", "/tmp/cross-reference-recall") + "/" +SWIFT_SECTION = os.environ.get("SWIFT_SECTION", "swift-section") +POINTER_SECTIONS = ("__got", "__auth_got", "__objc_superrefs", "__objc_classrefs") + + +def run_binary(binary_name): + ground_truth = json.load(open(WORK + binary_name + ".ground-truth.json")) + references_by_target = {int(key): value for key, value in ground_truth["references"].items()} + fixups = {int(key): value for key, value in ground_truth["fixups"].items()} + sections = ground_truth["sections"] + targets_document = json.load(open(WORK + binary_name + ".targets.json")) + targets = targets_document["targets"] + method_list_references = {int(key): value for key, value in targets_document.get("method_list_references", {}).items()} + + text_range = (sections["__text"][0], sections["__text"][0] + sections["__text"][1]) + + def is_in_text(address): + return text_range[0] <= address < text_range[1] + + def section_name(address): + for name, (start, size) in sections.items(): + if start <= address < start + size: + return name + return "?" + + def code_references(target_address): + return set(instruction for instruction, kind in references_by_target.get(target_address, []) if is_in_text(instruction)) + + rebases_by_target = collections.defaultdict(list) + binds_by_symbol = collections.defaultdict(list) + for slot_address, (fixup_kind, value) in fixups.items(): + if fixup_kind == "r": + rebases_by_target[value].append(slot_address) + else: + binds_by_symbol[value.split("/")[-1].split()[0]].append(slot_address) + + function_starts_output = subprocess.run(["dyld_info", "-function_starts", WORK + binary_name], capture_output=True, text=True).stdout + function_starts = sorted(int(line.split()[0], 16) for line in function_starts_output.splitlines()[2:] if line.strip().startswith("0x")) + + def function_end(function_start): + index = bisect.bisect_right(function_starts, function_start) + return function_starts[index] if index < len(function_starts) else text_range[1] + + file_bytes = open(WORK + binary_name, "rb").read() + + def read_bytes(address, count): + offset = address - 0x100000000 + return file_bytes[offset:offset + count] + + def stub_slot(stub_address): + words = struct.unpack("> 5) & 0x7FFFF) << 2) | ((words[0] >> 29) & 3) + if immediate & (1 << 20): + immediate -= 1 << 21 + return (stub_address & ~0xFFF) + (immediate << 12) + ((words[1] >> 10) & 0xFFF) + + # Names the queries need. Finder and ControlCenter keep no local symbols, so + # class and instance variable names are read from the Objective-C metadata. + def rebase_target(slot_address): + fixup = fixups.get(slot_address) + return fixup[1] if fixup and fixup[0] == "r" else None + + def read_c_string(address): + if address is None: + return None + raw = read_bytes(address, 4096).split(b"\0")[0] + try: + return raw.decode("utf-8") + except UnicodeDecodeError: + return None + + def class_read_only_data(class_address): + data_pointer = rebase_target(class_address + 32) + return data_pointer & ~7 if data_pointer is not None else None + + def class_runtime_name(class_address): + read_only_data = class_read_only_data(class_address) + return read_c_string(rebase_target(read_only_data + 24)) if read_only_data is not None else None + + def constant_string_characters(constant_string_address): + flags = struct.unpack(" ./run_all.sh +set -euo pipefail +SCRIPTS=${0:A:h} +export CROSS_REFERENCE_RECALL_WORK=${CROSS_REFERENCE_RECALL_WORK:-/tmp/cross-reference-recall} + +zsh $SCRIPTS/prepare.sh +python3 -I $SCRIPTS/ground_truth.py +python3 -I $SCRIPTS/verify_reproduction.py +python3 -I $SCRIPTS/query_swift_section.py +python3 -I $SCRIPTS/score.py diff --git a/Scripts/CrossReferenceRecall/score.py b/Scripts/CrossReferenceRecall/score.py new file mode 100644 index 000000000..2110ec8f8 --- /dev/null +++ b/Scripts/CrossReferenceRecall/score.py @@ -0,0 +1,141 @@ +"""Scores swift-section's answers with the 2026-11-18 scoring rules, puts +them next to that run's IDA rows (ida-2026-11-18.txt), and lists every miss +and extra with its disassembly line in `swift-section.details.txt`. + +A reference found counts when the tool's instruction is the ground truth's, +the `adrp` it pairs with, or up to 16 bytes after it; a hit inside the +target function itself, a data reference, or a reference through a +constant string to its characters is set aside rather than counted extra. +""" +import bisect +import collections +import json +import os +import re +import subprocess + +WORK = os.environ.get("CROSS_REFERENCE_RECALL_WORK", "/tmp/cross-reference-recall") + "/" +IDA_ROWS = os.path.join(os.path.dirname(os.path.abspath(__file__)), "ida-2026-11-18.txt") +TOOLS = ("one_query", "with_symbol_query") + +summary = {} +details = [] +for binary_name in ("Finder", "ControlCenter"): + results = json.load(open(WORK + binary_name + ".swift-section.results.json"))["results"] + ground_truth = json.load(open(WORK + binary_name + ".ground-truth.json")) + sections = ground_truth["sections"] + pairs = {int(key): value for key, value in json.load(open(WORK + binary_name + ".pairs.json")).items()} + mnemonics = {} + lines = {} + for line in open(WORK + binary_name + ".otool"): + parts = line.split("\t") + if len(parts) > 1 and len(parts[0]) == 16: + address = int(parts[0], 16) + mnemonics[address] = parts[1] + lines[address] = line.rstrip("\n") + text_range = (sections["__text"][0], sections["__text"][0] + sections["__text"][1]) + + def is_in_text(address): + return text_range[0] <= address < text_range[1] + + def section_name(address): + for name, (start, size) in sections.items(): + if start <= address < start + size: + return name + return "?" + + function_starts_output = subprocess.run(["dyld_info", "-function_starts", WORK + binary_name], capture_output=True, text=True).stdout + function_starts = sorted(int(line.split()[0], 16) for line in function_starts_output.splitlines()[2:] if line.strip().startswith("0x")) + + def function_end(function_start): + index = bisect.bisect_right(function_starts, function_start) + return function_starts[index] if index < len(function_starts) else text_range[1] + + counters = collections.defaultdict(collections.Counter) + extra_kinds = collections.defaultdict(collections.Counter) + for result in results: + category = result["category"] + ("-" + result["label"].split("@")[0] if result["category"] == "G" else "") + target = result["target"] + ground_truth_code = set(result["ground_truth_code"]) + ground_truth_data = set(result["ground_truth_data"]) + legitimate = set(result["legitimate"]) + if category in ("C", "D"): + ground_truth_data = set() + legitimate_addresses = set() + for address in legitimate: + legitimate_addresses.update({address, pairs.get(address, -1)}) + low, high = (target, function_end(target)) if (target and is_in_text(target)) else (0, 0) + for tool in TOOLS: + counter = counters[(category, tool)] + counter["targets"] += 1 + answer = set(result["tools"][tool] or []) + found = set() + data_found = set() + for site in sorted(answer): + hits = [expected for expected in ground_truth_code if site == expected or site == pairs.get(expected) or (is_in_text(site) and 0 < site - expected <= 16)] + if hits: + found |= set(hits) + counter["matched"] += 1 + continue + if low <= site < high: + counter["inside_target"] += 1 + continue + matched_data = [expected for expected in ground_truth_data if not is_in_text(site) and 0 <= expected - site < 32] + if matched_data: + data_found |= set(matched_data) + continue + if site in legitimate_addresses: + counter["through_constant_string"] += 1 + continue + kind = "text:" + mnemonics.get(site, "?") if is_in_text(site) else section_name(site) + extra_kinds[(category, tool)][kind] += 1 + counter["extra"] += 1 + if tool == "with_symbol_query": + details.append(("EXTRA", binary_name, category, result["label"], hex(site), lines.get(site, kind))) + counter["ground_truth_code"] += len(ground_truth_code) + counter["found"] += len(found) + counter["ground_truth_data"] += len(ground_truth_data) + counter["data_found"] += len(data_found) + if tool == "with_symbol_query": + for missed in sorted(ground_truth_code - found): + details.append(("MISS", binary_name, category, result["label"], hex(missed), lines.get(missed, "?"))) + summary[binary_name] = {"%s|%s" % key: counter for key, counter in counters.items()} + +# The 2026-11-18 IDA rows, e.g. "Finder A ida1 code 20/22 data 0/0 extra 0 ..." +ida_rows = {} +for line in open(IDA_ROWS): + match = re.match(r"(\w+) (\S+) (ida1|ida2) code (\d+)/(\d+) data (\d+)/(\d+) extra (\d+)", line) + if match: + binary_name, category, tool, found, total, data_found, data_total, extra = match.groups() + ida_rows[(binary_name, category, "one_query" if tool == "ida1" else "two_hops")] = tuple(int(value) for value in (found, total, data_found, data_total, extra)) + +print("binary category GT IDA-1 IDA-2 ours-1 ours-2 | data GT IDA ours | extras IDA-2 ours-2") +totals = collections.Counter() +for binary_name in ("Finder", "ControlCenter"): + for category in sorted({key.split("|")[0] for key in summary[binary_name]}): + one_query = summary[binary_name][category + "|one_query"] + with_symbol_query = summary[binary_name][category + "|with_symbol_query"] + ida_one_query = ida_rows.get((binary_name, category, "one_query")) + ida_two_hops = ida_rows.get((binary_name, category, "two_hops")) + if ida_one_query and ida_one_query[1] != one_query["ground_truth_code"]: + print(" GROUND TRUTH DIFFERS from 2026-11-18:", binary_name, category, ida_one_query[1], one_query["ground_truth_code"]) + print("%-14s %-14s %4d %5s %5s %6d %6d | %7d %3s %4d | %12s %6d" % ( + binary_name, category, one_query["ground_truth_code"], + ida_one_query[0] if ida_one_query else "-", ida_two_hops[0] if ida_two_hops else "-", + one_query["found"], with_symbol_query["found"], + one_query["ground_truth_data"], ida_two_hops[2] if ida_two_hops else "-", with_symbol_query["data_found"], + ida_two_hops[4] if ida_two_hops else "-", with_symbol_query["extra"])) + totals["ground_truth"] += one_query["ground_truth_code"] + totals["one_query"] += one_query["found"] + totals["with_symbol_query"] += with_symbol_query["found"] + totals["ida_one_query"] += ida_one_query[0] if ida_one_query else 0 + totals["ida_two_hops"] += ida_two_hops[0] if ida_two_hops else 0 +print() +print("code references %d: IDA one query %.1f%%, two hops %.1f%%; swift-section one query %.1f%%, with the by-symbol query %.1f%%" % ( + totals["ground_truth"], 100 * totals["ida_one_query"] / totals["ground_truth"], 100 * totals["ida_two_hops"] / totals["ground_truth"], + 100 * totals["one_query"] / totals["ground_truth"], 100 * totals["with_symbol_query"] / totals["ground_truth"])) + +with open(WORK + "swift-section.details.txt", "w") as details_file: + for entry in details: + details_file.write("\t".join(str(field) for field in entry) + "\n") +print("misses", sum(1 for entry in details if entry[0] == "MISS"), "extras", sum(1 for entry in details if entry[0] == "EXTRA"), "->", WORK + "swift-section.details.txt") diff --git a/Scripts/CrossReferenceRecall/verify_reproduction.py b/Scripts/CrossReferenceRecall/verify_reproduction.py new file mode 100644 index 000000000..3deaf1d71 --- /dev/null +++ b/Scripts/CrossReferenceRecall/verify_reproduction.py @@ -0,0 +1,52 @@ +"""Checks that ground_truth.py reproduced the 2026-11-18 run: the totals and +target lists below are copied from that run's printed output. Exits with 1 +when anything differs — the numbers would no longer compare with the IDA +baseline in ida-2026-11-18.txt.""" +import json +import os +import sys + +WORK = os.environ.get("CROSS_REFERENCE_RECALL_WORK", "/tmp/cross-reference-recall") + "/" + +expected_reference_totals = {"Finder": 511138, "ControlCenter": 359773} +expected_stub_counts = {"Finder": 8809, "ControlCenter": 1363} +expected_targets = { + "Finder": { + "C": [4303335148, 4303340684, 4303335740, 4303349948, 4303345276, 4303334844, 4303359708, 4303350588], + "D": [4296493604, 4297114024, 4302277612, 4302218044, 4301417104, 4295793096, 4301308772, 4301449572], + "F": [4307227568, 4307236272, 4307226952, 4307236864, 4307231160, 4307236592, 4307228448, 4307226664], + "first selectors": ["propertiesToUpdate", "fiDomain"], + }, + "ControlCenter": { + "C": [4301922220, 4301907948, 4301911132, 4301927564, 4301924412, 4301927388, 4301895132, 4301924860], + "D": [4295169504, 4301400024, 4295515008, 4295483488, 4295324396, 4296870092, 4297616600, 4295299536], + "F": [], + "first selectors": ["sfSymbolNameCase", "ssidData"], + }, +} + +failures = [] +for binary_name, expectation in expected_targets.items(): + ground_truth = json.load(open(WORK + binary_name + ".ground-truth.json")) + reference_total = sum(len(entries) for entries in ground_truth["references"].values()) + stub_count = len(ground_truth["stubs"]) + print(binary_name, "references", reference_total, "expected", expected_reference_totals[binary_name], "stubs", stub_count, "expected", expected_stub_counts[binary_name]) + if reference_total != expected_reference_totals[binary_name] or stub_count != expected_stub_counts[binary_name]: + failures.append(binary_name + " ground truth totals") + targets = json.load(open(WORK + binary_name + ".targets.json"))["targets"] + for category in ("C", "D", "F"): + matches = targets.get(category, []) == expectation[category] + print(binary_name, category, "matches" if matches else "DIFFERS") + if not matches: + failures.append(binary_name + " " + category) + first_selectors = [target["selector"] for target in targets["A"][:2]] + matches = first_selectors == expectation["first selectors"] + print(binary_name, "A", first_selectors, "matches" if matches else "DIFFERS") + if not matches: + failures.append(binary_name + " A") + print(binary_name, {category: len(entries) for category, entries in targets.items()}) + +if failures: + print("NOT REPRODUCED:", failures) + sys.exit(1) +print("reproduced") diff --git a/Sources/ABI/MachOSwiftSection/Extensions/String+.swift b/Sources/ABI/MachOSwiftSection/Extensions/String+.swift index 3bb6d0498..063423c65 100644 --- a/Sources/ABI/MachOSwiftSection/Extensions/String+.swift +++ b/Sources/ABI/MachOSwiftSection/Extensions/String+.swift @@ -1,3 +1,4 @@ +import Foundation extension String { var countedString: String { guard !isEmpty else { return "" } diff --git a/Sources/ABI/MachOSwiftSection/Models/ContextDescriptor/ContextDescriptorProtocol.swift b/Sources/ABI/MachOSwiftSection/Models/ContextDescriptor/ContextDescriptorProtocol.swift index 26e142791..b63ce6ffa 100644 --- a/Sources/ABI/MachOSwiftSection/Models/ContextDescriptor/ContextDescriptorProtocol.swift +++ b/Sources/ABI/MachOSwiftSection/Models/ContextDescriptor/ContextDescriptorProtocol.swift @@ -34,7 +34,12 @@ extension ContextDescriptorProtocol { return module } else { var parent: SymbolOrElement? = try parent(in: context) + var walkedParentCount = 0 while let currentParent = parent { + walkedParentCount += 1 + guard walkedParentCount <= ContextDescriptorParentChain.maximumLength else { + throw MachOSwiftSectionError.parentChainTooLong(contextDescriptorOffset: offset) + } if let module = currentParent.resolved?.contextDescriptor as? (any ModuleContextDescriptorProtocol) { return module } diff --git a/Sources/ABI/MachOSwiftSection/Models/Generic/GenericContext.swift b/Sources/ABI/MachOSwiftSection/Models/Generic/GenericContext.swift index e96794ec6..452cd8a06 100644 --- a/Sources/ABI/MachOSwiftSection/Models/Generic/GenericContext.swift +++ b/Sources/ABI/MachOSwiftSection/Models/Generic/GenericContext.swift @@ -120,6 +120,14 @@ public struct TargetGenericContext: ResolvableLocatableLayoutWrapper where Layout: MetadataLayout { associatedtype HeaderType: ResolvableLocatableLayoutWrapper = TypeMetadataHeader diff --git a/Sources/ABI/MachOSwiftSection/Models/Metadata/MetadataWrapper.swift b/Sources/ABI/MachOSwiftSection/Models/Metadata/MetadataWrapper.swift index 975181dd0..e3bb1b847 100644 --- a/Sources/ABI/MachOSwiftSection/Models/Metadata/MetadataWrapper.swift +++ b/Sources/ABI/MachOSwiftSection/Models/Metadata/MetadataWrapper.swift @@ -1,6 +1,7 @@ import Foundation import MachOBase import SwiftStdlibToolbox +import BinaryParseSupport @CaseCheckable(.public) @AssociatedValue(.public) diff --git a/Sources/ABI/MachOSwiftSection/Models/Type/Enum/EnumFunctions.swift b/Sources/ABI/MachOSwiftSection/Models/Type/Enum/EnumFunctions.swift index 630a6334c..fe197aee2 100644 --- a/Sources/ABI/MachOSwiftSection/Models/Type/Enum/EnumFunctions.swift +++ b/Sources/ABI/MachOSwiftSection/Models/Type/Enum/EnumFunctions.swift @@ -8,13 +8,17 @@ public struct EnumTagCounts { public func getEnumTagCounts(payloadSize: UInt64, emptyCases: UInt32, payloadCases: UInt32) -> EnumTagCounts { var numTags = payloadCases + // `unsigned` arithmetic, as `swift::getEnumTagCounts` (ABI/Enum.h) does + // it: it wraps. Trapping on it took a host down for case counts near + // `UInt32.max`, which only a malformed descriptor has (2026-11-29 + // codebase audit, finding 7). if emptyCases > 0 { if payloadSize >= 4 { - numTags += 1 + numTags &+= 1 } else { let bits = UInt32(payloadSize * 8) let casesPerTagBitValue: UInt32 = 1 << bits - numTags += ((emptyCases + (casesPerTagBitValue - 1)) >> bits) + numTags &+= ((emptyCases &+ (casesPerTagBitValue - 1)) >> bits) } } diff --git a/Sources/ABI/MachOSwiftSection/Protocols/TopLevelDescriptor.swift b/Sources/ABI/MachOSwiftSection/Protocols/TopLevelDescriptor.swift index d527463f0..f18e2bf66 100644 --- a/Sources/ABI/MachOSwiftSection/Protocols/TopLevelDescriptor.swift +++ b/Sources/ABI/MachOSwiftSection/Protocols/TopLevelDescriptor.swift @@ -1,3 +1,4 @@ +import BinaryParseSupport public protocol TopLevelDescriptor: ResolvableLocatableLayoutWrapper { var actualSize: Int { get } } diff --git a/Sources/ABI/MachOSwiftSection/Utils/ContextDescriptorParentChain.swift b/Sources/ABI/MachOSwiftSection/Utils/ContextDescriptorParentChain.swift new file mode 100644 index 000000000..a264cf06e --- /dev/null +++ b/Sources/ABI/MachOSwiftSection/Utils/ContextDescriptorParentChain.swift @@ -0,0 +1,12 @@ +/// How far up a context descriptor's parents a reader walks. +/// +/// A chain the compiler emits is a few contexts deep — the module, the +/// enclosing types and extensions, the anonymous contexts of the functions +/// declaring local types — and the demangler stops at 50 of its own. Only a +/// malformed binary has a longer one: a parent pointer leading back into the +/// chain, which a walk with no bound followed for ever, appending as it went +/// (2026-11-29 codebase audit, finding 6). A walk that reaches this many +/// parents stops and treats the descriptor as unreadable. +package enum ContextDescriptorParentChain { + package static let maximumLength = 256 +} diff --git a/Sources/ABI/MachOSwiftSection/Utils/MachOSwiftSectionError.swift b/Sources/ABI/MachOSwiftSection/Utils/MachOSwiftSectionError.swift index d85cbd4d6..d1a5b70e8 100644 --- a/Sources/ABI/MachOSwiftSection/Utils/MachOSwiftSectionError.swift +++ b/Sources/ABI/MachOSwiftSection/Utils/MachOSwiftSectionError.swift @@ -6,6 +6,10 @@ public enum MachOSwiftSectionError: LocalizedError, Sendable { case sectionNotFound(section: MachOSwiftSectionName, allSectionNames: [String]) case invalidSectionAlignment(section: MachOSwiftSectionName, align: Int) case unknownMetadataKind(rawValue: UInt) + /// The context descriptor at `contextDescriptorOffset` has more parents + /// than any compiler emits — `ContextDescriptorParentChain.maximumLength` + /// — which only a parent leading back into its own chain gives. + case parentChainTooLong(contextDescriptorOffset: Int) public var errorDescription: String? { switch self { @@ -15,6 +19,8 @@ public enum MachOSwiftSectionError: LocalizedError, Sendable { return "Invalid alignment for Swift section \(section.rawValue). Expected alignment is 4, but found \(align)." case .unknownMetadataKind(let rawValue): return "Unknown metadata kind: 0x\(String(rawValue, radix: 16)). MetadataWrapper cannot resolve metadata of an unrecognized kind." + case .parentChainTooLong(let contextDescriptorOffset): + return "The context descriptor at 0x\(String(contextDescriptorOffset, radix: 16)) has more than \(ContextDescriptorParentChain.maximumLength) parents: its parent chain leads back into itself." } } } diff --git a/Sources/ABI/MachOSwiftSectionC/include/MachOSwiftSectionC.h b/Sources/ABI/MachOSwiftSectionC/include/MachOSwiftSectionC.h new file mode 100644 index 000000000..e89c3e9fa --- /dev/null +++ b/Sources/ABI/MachOSwiftSectionC/include/MachOSwiftSectionC.h @@ -0,0 +1,22 @@ +// +// MachOSwiftSectionC.h +// MachOSwiftSectionC +// +// The module's umbrella header: every header in this directory, and a new +// one goes here too (MachOSwiftSectionCUmbrellaHeaderTests checks). +// +// Without it, SwiftPM and Tuist give the module the whole directory as its +// umbrella. A header added to the directory then changes no file a +// prebuilt module recorded, so Xcode keeps reusing the module built before +// it and Swift reports the new declarations as not in scope. Listing the +// header here edits this file, which rebuilds the module. +// + +#ifndef MACHO_SWIFT_SECTION_C_H +#define MACHO_SWIFT_SECTION_C_H + +#include "CallAccessor.h" +#include "Functions.h" +#include "ValueWitnessTable.h" + +#endif diff --git a/Sources/Analysis/CrossReferenceAnalysis/CrossReferenceAnalyzer+Symbolication.swift b/Sources/Analysis/CrossReferenceAnalysis/CrossReferenceAnalyzer+Symbolication.swift index 9b00fb673..6f4e5cc80 100644 --- a/Sources/Analysis/CrossReferenceAnalysis/CrossReferenceAnalyzer+Symbolication.swift +++ b/Sources/Analysis/CrossReferenceAnalysis/CrossReferenceAnalyzer+Symbolication.swift @@ -129,16 +129,28 @@ extension CrossReferenceAnalyzer { case .address(let value)?: switch kind { case .selectorReference: - if let selector = cString(atRuntimeAddress: value) { return .messageSend(selector: selector, receiver: .unknown) } + if let selector = cString(atRuntimeAddress: value) { return .selector(selector) } case .protocolReference: - // `protocol_t`: `isa`, then the name. - if let nameAddress = memory.pointer(at: value &+ 8), let name = cString(atRuntimeAddress: nameAddress) { return .cString(name) } + // `protocol_t`: `isa`, then the name. A slot of a malformed + // or half-initialized image may hold anything, and a read the + // process cannot make takes it down. + if isMapped(runtimeAddress: value &+ 8, length: 8), + let nameAddress = memory.pointer(at: value &+ 8), + let name = cString(atRuntimeAddress: nameAddress) { + return .cString(name) + } default: break } if let location = imageSet.location(ofRuntimeAddress: value) { if swiftTypeIndex(ofImageAt: location.imageIndex).describesType(descriptorAt: value) { return .swiftType(descriptor: location) } - return .function(location) + // `__TEXT` holds more than code: a protocol or method + // descriptor, a constant, a string — no function. + if function(containing: location) != nil { return .function(location) } + return .unrecognized(address: location.address) + } + if let descriptor = SwiftTypeIndex.descriptorLocation(ofValueMetadataAt: value, in: imageSet, typeIndex: swiftTypeIndex(ofImageAt:)) { + return .swiftType(descriptor: descriptor) } if let imageIndex = imageSet.imageIndex(containingDataAddress: value), let classObject = objectiveCClassIndex(ofImageAt: imageIndex).classObject(atRuntimeAddress: value) { @@ -155,8 +167,47 @@ extension CrossReferenceAnalyzer { ExportedFunctionNames.of(functionTable(ofImageAt: location.imageIndex)).namesByAddress[location.address] ?? [] } + /// The longest C string symbolication reads: a selector, a protocol's + /// name, a string literal's first characters. A longer run of non-zero + /// bytes is read up to here. + static let maximumCStringLength = 4096 + + /// The C string at the runtime `address`, read only as far as the + /// mapping holding it goes — at most `maximumCStringLength` bytes — and + /// `nil` when no terminator comes before that: a value of a malformed + /// slot is no string, and reading past what is mapped faults. private func cString(atRuntimeAddress address: UInt) -> String? { - guard address != 0, isMapped(runtimeAddress: address, length: 1), let characters = memory.typedPointer(to: CChar.self, at: address, length: 1) else { return nil } + guard address != 0, isMapped(runtimeAddress: address, length: 1) else { return nil } + let readableLength = mappedLength(fromRuntimeAddress: address, upTo: UInt(Self.maximumCStringLength)) + guard let characters = memory.typedPointer(to: CChar.self, at: address, length: Int(readableLength)) else { return nil } + guard strnlen(characters, Int(readableLength)) < Int(readableLength) else { return nil } return String(cString: characters) } + + /// How many bytes from the runtime `address` on are mapped, up to + /// `maximumLength`; at least the one byte the caller confirmed. + private func mappedLength(fromRuntimeAddress address: UInt, upTo maximumLength: UInt) -> UInt { + var mappedLength: UInt = 1 + var unmappedLength: UInt? + while mappedLength < maximumLength { + let candidateLength = min(mappedLength * 2, maximumLength) + guard isMapped(runtimeAddress: address, length: candidateLength) else { + unmappedLength = candidateLength + break + } + mappedLength = candidateLength + } + // The mapping ends between the two: find where. + if var upperLength = unmappedLength { + while upperLength - mappedLength > 1 { + let middleLength = mappedLength + (upperLength - mappedLength) / 2 + if isMapped(runtimeAddress: address, length: middleLength) { + mappedLength = middleLength + } else { + upperLength = middleLength + } + } + } + return mappedLength + } } diff --git a/Sources/Analysis/CrossReferenceAnalysis/CrossReferenceAnalyzer.swift b/Sources/Analysis/CrossReferenceAnalysis/CrossReferenceAnalyzer.swift index 4c0968ebf..1a9b2ad92 100644 --- a/Sources/Analysis/CrossReferenceAnalysis/CrossReferenceAnalyzer.swift +++ b/Sources/Analysis/CrossReferenceAnalysis/CrossReferenceAnalyzer.swift @@ -2,6 +2,7 @@ import Foundation import MachOKit @_spi(Internals) import MachOCodeReferences @_spi(Internals) import ObjCCodeReferences +import MachOKitExtensions /// Reads what each function of an image references, from its arm64 /// machine code, inside the current process. @@ -254,7 +255,12 @@ public final class CrossReferenceAnalyzer: @unchecked Sendable { reportingProgress reportProgress: ((_ scannedFunctionCount: Int, _ functionCount: Int) -> Bool)? ) -> CodeReferenceIndex? { let table = functionTable(ofImageAt: imageIndex) - var builder = CodeReferenceIndex.Builder(imageIndex: imageIndex, codeStart: table.textStart) + // A start of `__text` may lie below the section — a main executable's + // symbol table files `__mh_execute_header`, the Mach header itself, + // there — and the scan reads that function too. The starts are + // sorted, so the first is the lowest address a reference can name. + let codeStart = min(table.textStart, table.starts.first ?? table.textStart) + var builder = CodeReferenceIndex.Builder(imageIndex: imageIndex, codeStart: codeStart) let functionCount = table.starts.count var isStopped = false _ = scan(table) { scanner, collector in @@ -384,7 +390,7 @@ public final class CrossReferenceAnalyzer: @unchecked Sendable { ) -> [CodeReference] { let collector = ReferenceCollector(keeping: keys, matching: query) let sessions: [any CodeReferenceRecognitionSession] = [ - objectiveC.makeSession(table: table, recording: collector, findsClassReferences: collector.findsTypeReferences), + objectiveC.makeSession(table: table, recording: collector, findsClassReferences: collector.findsTypeReferences, findsSelectorReferences: collector.findsSelectorReferences), swift.makeSession(table: table, recording: collector, findsTypeReferences: collector.findsTypeReferences), ] var scanner = ReferenceScanner( @@ -394,7 +400,8 @@ public final class CrossReferenceAnalyzer: @unchecked Sendable { recording: collector, followsBranches: followsBranches, recordsStringReferences: collector.findsStrings(whenWholeImage: recordsStringReferences), - recordsImportedSymbolReferences: collector.findsImportedSymbolReferences + recordsImportedSymbolReferences: collector.findsImportedSymbolReferences, + recordsFunctionAddressReferences: collector.findsFunctionAddressReferences ) body(&scanner, collector) return collector.references @@ -505,8 +512,23 @@ final class ReferenceCollector: ObjCCodeReferenceRecording, SwiftCodeReferenceRe self.findsImportedSymbolReferences = keptKeys.map { keys in keys.contains { if case .importedSymbol = $0 { true } else { false } } } ?? true + self.findsSelectorReferences = keptKeys.map { keys in + keys.contains { if case .selector = $0 { true } else { false } } + } ?? true + self.findsFunctionAddressReferences = keptKeys.map { keys in + keys.contains { if case .function = $0 { true } else { false } } + } ?? true } + /// Whether the selectors code loads but sends nothing with are recorded: + /// for a whole image, or for a query for a selector. + let findsSelectorReferences: Bool + + /// Whether the addresses code builds of a function's start are recorded + /// as references to the function: for a whole image, or for a query for + /// a function's callers. + let findsFunctionAddressReferences: Bool + /// Whether loads from slots that bind to another image's symbol are /// recorded: for a whole image, or for a query for an imported name. let findsImportedSymbolReferences: Bool @@ -524,13 +546,16 @@ final class ReferenceCollector: ObjCCodeReferenceRecording, SwiftCodeReferenceRe } private func keep(_ target: CodeReferenceTarget, at site: ScanSite, isRuntimeHelperCall: Bool = false) { - if let keptKeys { - let isFiled = if let key = target.tableKey { keptKeys.contains(key) } else { false } - guard isFiled || swiftTypeQuery?.matches(target) == true else { return } - } + guard isKept(target) else { return } references.append(CodeReference(function: site.function, instructionAddress: site.instructionAddress, kind: site.kind, target: target, route: site.route, isRuntimeHelperCall: isRuntimeHelperCall)) } + private func isKept(_ target: CodeReferenceTarget) -> Bool { + guard let keptKeys else { return true } + let isFiled = if let key = target.tableKey { keptKeys.contains(key) } else { false } + return isFiled || swiftTypeQuery?.matches(target) == true + } + func recordCall(to target: ResolvedCallTarget, targetAddress: UInt64, at site: ScanSite, isRuntimeHelperCall: Bool) { switch target { case .function(let location): @@ -562,6 +587,25 @@ final class ReferenceCollector: ObjCCodeReferenceRecording, SwiftCodeReferenceRe keep(.objectiveCInstanceVariable(className: className, name: name), at: site) } + /// Recorded when the scan leaves the function that loads the selector, + /// after the function's later references: put back in instruction order, + /// which a function's references are listed in. + func recordSelectorReference(selector: String, at site: ScanSite) { + let target = CodeReferenceTarget.selector(selector) + guard isKept(target) else { return } + var insertionIndex = references.endIndex + while insertionIndex > references.startIndex, + references[insertionIndex - 1].function == site.function, + references[insertionIndex - 1].instructionAddress > site.instructionAddress { + insertionIndex -= 1 + } + references.insert(CodeReference(function: site.function, instructionAddress: site.instructionAddress, kind: site.kind, target: target, route: site.route, isRuntimeHelperCall: false), at: insertionIndex) + } + + func recordFunctionAddressReference(to function: CodeLocation, at site: ScanSite) { + keep(.function(function), at: site) + } + func recordString(_ string: StringLiteralReference, at site: ScanSite) { switch string { case .cString(let characters): diff --git a/Sources/Analysis/CrossReferenceAnalysis/Models/CodeReference.swift b/Sources/Analysis/CrossReferenceAnalysis/Models/CodeReference.swift index b3f134dac..aee7e6bd4 100644 --- a/Sources/Analysis/CrossReferenceAnalysis/Models/CodeReference.swift +++ b/Sources/Analysis/CrossReferenceAnalysis/Models/CodeReference.swift @@ -41,6 +41,13 @@ public enum CodeReferenceTarget: Hashable, Sendable { /// (`_OBJC_IVAR_$_.`): the class that declares it, by /// its runtime name, and the variable's name. case objectiveCInstanceVariable(className: String, name: String) + /// A selector the code loads but sends no message with: it hands the + /// selector on — to `respondsToSelector:` or `performSelector:`, as a + /// return value, as a control's action. Filed under the same table key as + /// the selector's sends. Found only where code loads the selector from + /// the image's `__objc_selrefs`: a dyld shared cache's builder rewrites + /// those loads into the selector string's address. + case selector(String) /// A C string literal whose address the code takes, by its characters. /// Recorded only when string references are: see /// ``CrossReferenceAnalyzer/recordsStringReferences``. diff --git a/Sources/Analysis/CrossReferenceAnalysis/Models/CodeReferenceIndex.swift b/Sources/Analysis/CrossReferenceAnalysis/Models/CodeReferenceIndex.swift index 551343d81..505e58cd5 100644 --- a/Sources/Analysis/CrossReferenceAnalysis/Models/CodeReferenceIndex.swift +++ b/Sources/Analysis/CrossReferenceAnalysis/Models/CodeReferenceIndex.swift @@ -5,7 +5,9 @@ import Foundation /// One image's references, filed by what they reference and stored small /// enough for a host to keep for every image it has open: a name is stored /// once however many references carry it, and the referencing function and -/// instruction as 32-bit offsets into the image's `__text`. +/// instruction as 32-bit offsets from the image's lowest function start — +/// the start of `__text`, or below it where the symbol table puts a function +/// there, as a main executable's does with `__mh_execute_header`. /// /// It holds what a query for callers or for a type's references reads — /// calls and tail calls, sends, imported names, class, instance variable and @@ -41,6 +43,7 @@ public struct CodeReferenceIndex: Sendable { case importedSymbol(name: String) case messageSend(selector: String) case superMessageSend(selector: String) + case selector(String) case objectiveCClass(name: String, location: CodeLocation) case swiftType(descriptor: CodeLocation) case swiftTypeName(SwiftTypeName) @@ -63,7 +66,8 @@ public struct CodeReferenceIndex: Sendable { /// names included. public let approximateByteCount: Int - /// Where the offsets count from: the start of the image's `__text`. + /// Where the offsets count from: the image's lowest function start, which + /// is the start of its `__text` unless a function lies below it. private let codeStart: UInt64 /// Every group's entries, one group after another, each in scan order. private let entries: [Entry] @@ -158,6 +162,8 @@ public struct CodeReferenceIndex: Sendable { return .messageSend(selector: selector, receiver: receiver) case .superMessageSend(let selector): return .superMessageSend(selector: selector, className: className) + case .selector(let selector): + return .selector(selector) case .objectiveCClass(let name, let location): return .objectiveCClass(name: name, location: location) case .swiftType(let descriptor): @@ -225,6 +231,8 @@ public struct CodeReferenceIndex: Sendable { case .superMessageSend(let selector, let superclassName): target = .superMessageSend(selector: selector) className = superclassName + case .selector(let selector): + target = .selector(selector) case .objectiveCClass(let name, let location): target = .objectiveCClass(name: name, location: location) case .swiftType(let descriptor): @@ -249,7 +257,7 @@ public struct CodeReferenceIndex: Sendable { } assert( reference.function.address >= codeStart && reference.instructionAddress >= codeStart && reference.instructionAddress - codeStart <= UInt64(UInt32.max), - "a reference outside the image's __text" + "a reference below the image's lowest function start, or 4 GiB beyond it" ) var classNamePosition: UInt32 = 0 if let className { @@ -284,7 +292,7 @@ public struct CodeReferenceIndex: Sendable { keyedTargets[.function(location), default: []].append(target) case .importedSymbol(let name): keyedTargets[.importedSymbol(name), default: []].append(target) - case .messageSend(let selector), .superMessageSend(let selector): + case .messageSend(let selector), .superMessageSend(let selector), .selector(let selector): keyedTargets[.selector(selector), default: []].append(target) case .objectiveCClass(let name, _): keyedTargets[.objectiveCClass(name), default: []].append(target) @@ -357,7 +365,7 @@ public struct CodeReferenceIndex: Sendable { private static func heapByteCount(of target: Target) -> Int { switch target { - case .importedSymbol(let name), .messageSend(let name), .superMessageSend(let name), .objectiveCClass(let name, _), .cString(let name), .constantString(let name): + case .importedSymbol(let name), .messageSend(let name), .superMessageSend(let name), .selector(let name), .objectiveCClass(let name, _), .cString(let name), .constantString(let name): return heapByteCount(of: name) case .objectiveCInstanceVariable(let className, let name): return heapByteCount(of: className) + heapByteCount(of: name) diff --git a/Sources/Analysis/CrossReferenceAnalysis/Models/CodeReferenceTable.swift b/Sources/Analysis/CrossReferenceAnalysis/Models/CodeReferenceTable.swift index 7b3cab311..6bcc1de81 100644 --- a/Sources/Analysis/CrossReferenceAnalysis/Models/CodeReferenceTable.swift +++ b/Sources/Analysis/CrossReferenceAnalysis/Models/CodeReferenceTable.swift @@ -74,7 +74,7 @@ extension CodeReferenceTarget { switch self { case .function(let location): return .function(location) - case .messageSend(let selector, _), .superMessageSend(let selector, _): + case .messageSend(let selector, _), .superMessageSend(let selector, _), .selector(let selector): return .selector(selector) case .importedSymbol(let name): return .importedSymbol(name) diff --git a/Sources/Analysis/CrossReferenceAnalysis/Scanning/SwiftCodeReferenceRecognizer.swift b/Sources/Analysis/CrossReferenceAnalysis/Scanning/SwiftCodeReferenceRecognizer.swift index b171081aa..6b21035b7 100644 --- a/Sources/Analysis/CrossReferenceAnalysis/Scanning/SwiftCodeReferenceRecognizer.swift +++ b/Sources/Analysis/CrossReferenceAnalysis/Scanning/SwiftCodeReferenceRecognizer.swift @@ -26,11 +26,20 @@ struct SwiftRuntimeFunctions: Sendable { mutating func consider(_ name: UnsafePointer, at location: CodeLocation) { if Self.returnsItsClassArgument(name) { classReturningFunctions.insert(location) - } else if strncmp(name, "_swift_getTypeByMangledNameIn", 29) == 0 { - typeByMangledNameEntries[location] = strstr(name, "InMetadataState") == nil ? 0 : 1 + } else if let nameRegister = Self.nameRegister(ofTypeByMangledNameEntryNamed: name) { + typeByMangledNameEntries[location] = nameRegister } } + /// The register the runtime entry point `name` takes a mangled name in, + /// when it is one that instantiates a type from it; `nil` for any other + /// name. A standalone file's set holds no libswiftCore, and reaches the + /// entry points as imported symbols by these names. + static func nameRegister(ofTypeByMangledNameEntryNamed name: UnsafePointer) -> Int? { + guard strncmp(name, "_swift_getTypeByMangledNameIn", 29) == 0 else { return nil } + return strstr(name, "InMetadataState") == nil ? 0 : 1 + } + static func returnsItsClassArgument(_ name: UnsafePointer) -> Bool { strcmp(name, "_swift_getInitializedObjCClass") == 0 } @@ -167,7 +176,13 @@ final class SwiftCodeReferenceRecognitionSession: CodeReferenceRecognitionSessio if findsTypeReferences { plan.typeFunction = typeFunction(at: location) } case .importedSymbol(let name): plan.returnsItsClassArgument = SwiftRuntimeFunctions.returnsItsClassArgument(name) - if findsTypeReferences, let accessorSymbol = Self.accessorSymbol(name) { plan.typeFunction = .accessorSymbol(accessorSymbol) } + if findsTypeReferences { + if let accessorSymbol = Self.accessorSymbol(name) { + plan.typeFunction = .accessorSymbol(accessorSymbol) + } else if let nameRegister = SwiftRuntimeFunctions.nameRegister(ofTypeByMangledNameEntryNamed: name) { + plan.typeFunction = .runtimeEntry(nameRegister: nameRegister) + } + } case .registerSettingTrampoline, .unrecognized: return nil } @@ -243,10 +258,17 @@ final class SwiftCodeReferenceRecognitionSession: CodeReferenceRecognitionSessio if let load = ARM64InstructionWord.load(word), load.base == 1, load.displacement == 0 { readsRecord = true } else if let callee = ARM64InstructionWord.callTarget(word, at: instructionAddress) ?? ARM64InstructionWord.branchTarget(word, at: instructionAddress), - callee < start || callee >= end, - case .function(let calleeLocation) = resolver.resolve(callee), - recognizer.runtimeFunctions.typeByMangledNameEntries[calleeLocation] != nil { - callsRuntime = true + callee < start || callee >= end { + // The runtime's function, or — in a set of standalone files, + // which holds no libswiftCore — the symbol its stub imports. + switch resolver.resolve(callee) { + case .function(let calleeLocation) where recognizer.runtimeFunctions.typeByMangledNameEntries[calleeLocation] != nil: + callsRuntime = true + case .importedSymbol(let name) where SwiftRuntimeFunctions.nameRegister(ofTypeByMangledNameEntryNamed: name) != nil: + callsRuntime = true + default: + break + } } } return callsRuntime ? .instantiationHelper(takesRecord: readsRecord) : nil @@ -304,13 +326,7 @@ final class SwiftCodeReferenceRecognitionSession: CodeReferenceRecognitionSessio /// metadata is its Objective-C class object, which the Objective-C layer /// recognizes first. private func valueMetadataDescriptor(atRuntimeAddress address: UInt) -> CodeLocation? { - guard address != 0, images.isMapped(runtimeAddress: address, length: 16), let kind = images.memory.load(UInt64.self, at: address) else { return nil } - // MetadataKind: struct 0x200, enum 0x201, optional 0x202, foreign - // class 0x203, foreign reference type 0x204. - guard kind >= 0x200, kind <= 0x204, let descriptor = images.memory.pointer(at: address &+ 8) else { return nil } - guard let imageIndex = images.imageIndex(containingRuntimeAddress: descriptor) else { return nil } - let index = typeIndex(ofImageAt: imageIndex) - return index.describesType(descriptorAt: descriptor) ? index.location(ofRuntimeAddress: descriptor) : nil + SwiftTypeIndex.descriptorLocation(ofValueMetadataAt: address, in: images, typeIndex: typeIndex(ofImageAt:)) } /// The type indexes this scan asked for, kept here so that a lookup does diff --git a/Sources/Analysis/CrossReferenceAnalysis/Scanning/SwiftTypeIndex.swift b/Sources/Analysis/CrossReferenceAnalysis/Scanning/SwiftTypeIndex.swift index 2827841e6..40519e717 100644 --- a/Sources/Analysis/CrossReferenceAnalysis/Scanning/SwiftTypeIndex.swift +++ b/Sources/Analysis/CrossReferenceAnalysis/Scanning/SwiftTypeIndex.swift @@ -66,6 +66,23 @@ final class SwiftTypeIndex: @unchecked Sendable { descriptorsByRuntimeAddress[address] != nil } + /// The descriptor of the type whose metadata lies at the runtime + /// `address`: a struct, an enum, an optional or an imported type, whose + /// metadata holds its kind first and its descriptor next. A Swift + /// class's metadata is its Objective-C class object, which the + /// Objective-C layer recognizes. `typeIndex` gives the index of the image + /// the descriptor lies in. The scan and the symbolication read a slot + /// holding metadata alike. + static func descriptorLocation(ofValueMetadataAt address: UInt, in images: CodeImageSet, typeIndex: (Int) -> SwiftTypeIndex) -> CodeLocation? { + guard address != 0, images.isMapped(runtimeAddress: address, length: 16), let kind = images.memory.load(UInt64.self, at: address) else { return nil } + // MetadataKind: struct 0x200, enum 0x201, optional 0x202, foreign + // class 0x203, foreign reference type 0x204. + guard kind >= 0x200, kind <= 0x204, let descriptor = images.memory.pointer(at: address &+ 8) else { return nil } + guard let imageIndex = images.imageIndex(containingRuntimeAddress: descriptor) else { return nil } + let index = typeIndex(imageIndex) + return index.describesType(descriptorAt: descriptor) ? index.location(ofRuntimeAddress: descriptor) : nil + } + /// The runtime address of the metadata accessor of the type whose /// descriptor lies at the runtime `descriptor`. func accessorAddress(ofDescriptorAt descriptor: UInt) -> UInt? { diff --git a/Sources/Analysis/SwiftInspection/EnumLayoutCalculator.swift b/Sources/Analysis/SwiftInspection/EnumLayoutCalculator.swift index 2ba2a7b8c..be6717d38 100644 --- a/Sources/Analysis/SwiftInspection/EnumLayoutCalculator.swift +++ b/Sources/Analysis/SwiftInspection/EnumLayoutCalculator.swift @@ -53,6 +53,23 @@ public enum EnumLayoutCalculator { /// every extra-inhabitant count saturates to. public static let maximumExtraInhabitantCount = 0x7FFF_FFFF + /// The most cases a layout is projected for, one ``EnumCaseProjection`` + /// each: far more than any Swift enum declares. A descriptor claiming + /// more is malformed — 4,294,967,295 empty cases had every one built and + /// kept, until the process ran out of memory (2026-11-29 codebase audit, + /// finding 7). Ask ``canProjectCases(numPayloadCases:numEmptyCases:)`` + /// before calculating. + public static let maximumProjectedCaseCount = 1 << 16 + + /// Whether an enum of `numPayloadCases` payload and `numEmptyCases` + /// empty cases is one a layout is projected for: neither count negative, + /// and together at most ``maximumProjectedCaseCount``. + public static func canProjectCases(numPayloadCases: Int, numEmptyCases: Int) -> Bool { + numPayloadCases >= 0 && numEmptyCases >= 0 + && numPayloadCases <= maximumProjectedCaseCount + && numEmptyCases <= maximumProjectedCaseCount - numPayloadCases + } + /// The extra-inhabitant count of a native heap-object reference /// (`Builtin.NativeObject` — what an `indirect` enum case stores) on /// 64-bit Darwin: `swift_getHeapObjectExtraInhabitantCount()` returns diff --git a/Sources/Analysis/SwiftInspection/GenericParameterDepthLayout.swift b/Sources/Analysis/SwiftInspection/GenericParameterDepthLayout.swift index b628cb65d..9833de6b9 100644 --- a/Sources/Analysis/SwiftInspection/GenericParameterDepthLayout.swift +++ b/Sources/Analysis/SwiftInspection/GenericParameterDepthLayout.swift @@ -148,7 +148,12 @@ extension GenericParameterDepthLayout { private static func genericAncestorsOutermostFirst(of descriptor: some ContextDescriptorProtocol, in context: some ReadingContext) -> [ContextDescriptorWrapper] { var ancestorsInnermostFirst: [ContextDescriptorWrapper] = [] var parent = (try? descriptor.parent(in: context))?.flatMap(\.resolved) + var walkedParentCount = 0 while let currentParent = parent { + walkedParentCount += 1 + // A chain no compiler emits leads back into itself: no ancestors, + // so every level counts as one depth. + guard walkedParentCount <= ContextDescriptorParentChain.maximumLength else { return [] } switch currentParent { case .type, .extension: if currentParent.contextDescriptor.layout.flags.isGeneric { @@ -259,7 +264,8 @@ extension GenericParameterDepthLayout { do { var parentReference = try descriptor.parent(in: context) while let currentReference = parentReference { - guard let parent = currentReference.resolved else { return nil } + // A chain no compiler emits leads back into itself. + guard ancestors.count < ContextDescriptorParentChain.maximumLength, let parent = currentReference.resolved else { return nil } ancestors.append(parent) parentReference = try parent.parent(in: context) } diff --git a/Sources/Analysis/SwiftInspection/NodeTypeNaming.swift b/Sources/Analysis/SwiftInspection/NodeTypeNaming.swift index ceb5b511e..8cd083b0c 100644 --- a/Sources/Analysis/SwiftInspection/NodeTypeNaming.swift +++ b/Sources/Analysis/SwiftInspection/NodeTypeNaming.swift @@ -49,10 +49,22 @@ package enum NodeTypeNaming { } /// The fully-qualified name of a (possibly wrapped) nominal type node, or - /// `nil` if the node is not nominal. + /// `nil` if the node is not nominal. A private declaration is named by + /// its local name alone. package static func nominalQualifiedName(of node: Node) -> String? { + nominalQualifiedName(of: node, distinguishesPrivateDeclarations: false) + } + + /// `nominalQualifiedName(of:)`, keeping — when + /// `distinguishesPrivateDeclarations` — the discriminator a private + /// declaration's mangling carries (`(Storage in _0F2B…)`), so that two + /// files' same-named private types get two names. Turn it on only where + /// both sides of a lookup demangle descriptors: a class's runtime name + /// spells the discriminator where a stripped image's descriptor no + /// longer can. + package static func nominalQualifiedName(of node: Node, distinguishesPrivateDeclarations: Bool) -> String? { guard let nominal = unwrappedNominal(of: node) else { return nil } - return qualifiedName(ofNominal: nominal) + return qualifiedName(ofNominal: nominal, distinguishesPrivateDeclarations: distinguishesPrivateDeclarations) } /// The fully-qualified name of a protocol reference node (`.protocol`), @@ -61,15 +73,28 @@ package enum NodeTypeNaming { /// protocol up from an existential's component list, sharing the same /// `qualifiedName(ofNominal:)` formatting as the type side so the two agree. package static func protocolQualifiedName(of node: Node) -> String? { + protocolQualifiedName(of: node, distinguishesPrivateDeclarations: false) + } + + /// `protocolQualifiedName(of:)`, keeping a private protocol's + /// discriminator when `distinguishesPrivateDeclarations`. + package static func protocolQualifiedName(of node: Node, distinguishesPrivateDeclarations: Bool) -> String? { let unwrapped = (node.kind == .type ? node.firstChild : node) ?? node guard unwrapped.kind == .protocol else { return nil } - return qualifiedName(ofNominal: unwrapped) + return qualifiedName(ofNominal: unwrapped, distinguishesPrivateDeclarations: distinguishesPrivateDeclarations) } /// The fully-qualified name of a declared nominal-or-protocol node. Lets the /// per-image index treat a protocol context the same way as a type context. package static func declaredQualifiedName(of node: Node) -> String? { - nominalQualifiedName(of: node) ?? protocolQualifiedName(of: node) + declaredQualifiedName(of: node, distinguishesPrivateDeclarations: false) + } + + /// `declaredQualifiedName(of:)`, keeping a private declaration's + /// discriminator when `distinguishesPrivateDeclarations`. + package static func declaredQualifiedName(of node: Node, distinguishesPrivateDeclarations: Bool) -> String? { + nominalQualifiedName(of: node, distinguishesPrivateDeclarations: distinguishesPrivateDeclarations) + ?? protocolQualifiedName(of: node, distinguishesPrivateDeclarations: distinguishesPrivateDeclarations) } /// The bare name of an Objective-C class node (a `.class` whose module is @@ -152,8 +177,8 @@ package enum NodeTypeNaming { return (try? demangleAsNodeTransient(String(mangledName)))?.first(of: .class) } - private static func qualifiedName(ofNominal node: Node) -> String? { - guard let identifier = declaredName(of: node) else { return nil } + private static func qualifiedName(ofNominal node: Node, distinguishesPrivateDeclarations: Bool) -> String? { + guard let identifier = declaredName(of: node, distinguishesPrivateDeclarations: distinguishesPrivateDeclarations) else { return nil } guard let context = node.firstChild else { return identifier } if node.children.at(1)?.kind == .localDeclName { // A type declared in a function or closure body, keyed under that @@ -163,7 +188,7 @@ package enum NodeTypeNaming { // (evolution proposal `local-type-context-names`). return context.print(using: .interfaceTypeBuilderOnly) + "." + identifier } - if let contextName = contextQualifiedName(of: context) { + if let contextName = contextQualifiedName(of: context, distinguishesPrivateDeclarations: distinguishesPrivateDeclarations) { return contextName + "." + identifier } return identifier @@ -175,7 +200,7 @@ package enum NodeTypeNaming { /// back to the first identifier it finds in the tree, which for a /// `relatedEntityDeclName` is the entity tag — and every synthesized /// error struct shares the tag `e`, so keying on it would collide. - private static func declaredName(of node: Node) -> String? { + private static func declaredName(of node: Node, distinguishesPrivateDeclarations: Bool) -> String? { if let nameNode = node.children.at(1), nameNode.kind == .relatedEntityDeclName { guard let entityTag = nameNode.children.first?.text, let entityName = nameNode.children.at(1)?.text else { return nil } return "related decl '\(entityTag)' for \(entityName)" @@ -193,19 +218,24 @@ package enum NodeTypeNaming { // its address is what keeps it apart from the others of its name. return "(\(localName) in \(discriminator))" } + if distinguishesPrivateDeclarations, let nameNode = node.children.at(1), nameNode.kind == .privateDeclName, + let discriminator = nameNode.children.first?.text, + let localName = nameNode.children.at(1)?.text { + return "(\(localName) in \(discriminator))" + } return node.identifier } - private static func contextQualifiedName(of node: Node) -> String? { + private static func contextQualifiedName(of node: Node, distinguishesPrivateDeclarations: Bool) -> String? { switch node.kind { case .module: return node.text case .structure, .enum, .class, .typeAlias: - return qualifiedName(ofNominal: node) + return qualifiedName(ofNominal: node, distinguishesPrivateDeclarations: distinguishesPrivateDeclarations) case .type: // A `.type`-wrapped context (as appears inside a bound-generic // parent's first child): unwrap and recurse. - return node.firstChild.flatMap(contextQualifiedName) + return node.firstChild.flatMap { contextQualifiedName(of: $0, distinguishesPrivateDeclarations: distinguishesPrivateDeclarations) } case .boundGenericStructure, .boundGenericEnum, .boundGenericClass: // A nested type whose enclosing type is a *specialized* generic // (e.g. the `Environment` in `Environment.Content`) @@ -214,11 +244,11 @@ package enum NodeTypeNaming { // names the nested type's own descriptor — by unwrapping to the // underlying nominal. Without this the parent chain is lost and the // nested type degrades to a bare, unresolvable identifier. - return unwrappedNominal(of: node).flatMap(contextQualifiedName) + return unwrappedNominal(of: node).flatMap { contextQualifiedName(of: $0, distinguishesPrivateDeclarations: distinguishesPrivateDeclarations) } case .extension: // `.extension` children are [module, extendedType, ...]; the // nesting context is the extended type. - return node.children.at(1).flatMap(contextQualifiedName) + return node.children.at(1).flatMap { contextQualifiedName(of: $0, distinguishesPrivateDeclarations: distinguishesPrivateDeclarations) } default: return node.text } diff --git a/Sources/Analysis/SwiftInspection/RuntimeMetadataTypeBuilder.swift b/Sources/Analysis/SwiftInspection/RuntimeMetadataTypeBuilder.swift index 0ebf5f25c..cbc250754 100644 --- a/Sources/Analysis/SwiftInspection/RuntimeMetadataTypeBuilder.swift +++ b/Sources/Analysis/SwiftInspection/RuntimeMetadataTypeBuilder.swift @@ -1116,7 +1116,7 @@ public struct RuntimeMetadataTypeBuilder: TypeBuilder { "Swift.PartialRangeFrom": PartialRangeFrom.self, "Swift.PartialRangeUpTo": PartialRangeUpTo.self, "Swift.PartialRangeThrough": PartialRangeThrough.self, - "Swift.Result": Result.self, + "Swift.Result": Result.self, "Swift.Unmanaged": Unmanaged.self, "Swift.UnsafePointer": UnsafePointer.self, "Swift.UnsafeMutablePointer": UnsafeMutablePointer.self, diff --git a/Sources/Analysis/SwiftInspection/SymbolicDemangler.swift b/Sources/Analysis/SwiftInspection/SymbolicDemangler.swift index 456e88be1..83f022e3f 100644 --- a/Sources/Analysis/SwiftInspection/SymbolicDemangler.swift +++ b/Sources/Analysis/SwiftInspection/SymbolicDemangler.swift @@ -641,7 +641,7 @@ extension SymbolicDemangler { // It contributes a discriminator only when it wraps a private // type; otherwise it is skipped, and a type inside demangles as if // it were internal. - if let lookupContext = readingContext as? SymbolLookupContext, + if let lookupContext = readingContext as? (any SymbolLookupContext), let privateDeclNameIdentifier = lookupContext.privateDiscriminatorIdentifier(forAnonymousContextAt: context.contextDescriptor.offset) { if let parentDemangling { return Node.createTransient(kind: .anonymousContext, children: [privateDeclNameIdentifier, parentDemangling]) @@ -746,7 +746,7 @@ extension SymbolicDemangler { let symbolNode = try demangle(for: mangledName, kind: .symbol, in: readingContext) return symbolNode.kind == .global ? symbolNode.children.first : symbolNode } - guard let lookupContext = readingContext as? SymbolLookupContext else { return nil } + guard let lookupContext = readingContext as? (any SymbolLookupContext) else { return nil } return lookupContext.anonymousContextName(forAnonymousContextAt: anonymousContext.offset) } @@ -764,7 +764,7 @@ extension SymbolicDemangler { private static func positionNameOfUnnamedLocalType(inside parent: SymbolOrElement?, in readingContext: some ReadingContext) throws -> String? { guard case .element(.anonymous(let anonymousContext))? = parent, isAnonymousContext(try anonymousContext.parent(in: readingContext)), - let lookupContext = readingContext as? SymbolLookupContext + let lookupContext = readingContext as? (any SymbolLookupContext) else { return nil } return lookupContext.positionName(forAnonymousContextAt: anonymousContext.offset) } diff --git a/Sources/Analysis/SwiftLayout/BasicLayout.swift b/Sources/Analysis/SwiftLayout/BasicLayout.swift index eb3e56a4b..05438787f 100644 --- a/Sources/Analysis/SwiftLayout/BasicLayout.swift +++ b/Sources/Analysis/SwiftLayout/BasicLayout.swift @@ -54,11 +54,16 @@ public enum BasicLayout { /// rounded up to the field's alignment, the accumulator then advances by /// the field's **size** (not stride), and trailing padding lands only in /// `stride`, never in `size`. + /// + /// Throws ``LayoutSizeOverflow`` when an offset or the size does not fit + /// an `Int`: no binary holds such a type, but a malformed one can name + /// it (`InlineArray<9223372036854775807, Int8>` followed by a field), + /// and the arithmetic trapped (2026-11-29 codebase audit, finding 8). public static func compute( startOffset: Int, startAlignmentMask: Int, fieldLayouts: [StaticTypeLayout] - ) -> AggregateLayout { + ) throws(LayoutSizeOverflow) -> AggregateLayout { var offsetAccumulator = startOffset var alignmentMask = startAlignmentMask var isBitwiseTakable = true @@ -70,9 +75,9 @@ public enum BasicLayout { for fieldLayout in fieldLayouts { let fieldAlignmentMask = fieldLayout.alignmentMask - let alignedOffset = (offsetAccumulator + fieldAlignmentMask) & ~fieldAlignmentMask + let alignedOffset = try alignedUp(offsetAccumulator, toAlignmentMask: fieldAlignmentMask) fieldOffsets.append(alignedOffset) - offsetAccumulator = alignedOffset + fieldLayout.size + offsetAccumulator = try adding(alignedOffset, fieldLayout.size) alignmentMask = max(alignmentMask, fieldAlignmentMask) isBitwiseTakable = isBitwiseTakable && fieldLayout.isBitwiseTakable isBitwiseBorrowable = isBitwiseBorrowable && fieldLayout.isBitwiseBorrowable @@ -83,7 +88,7 @@ public enum BasicLayout { } let size = offsetAccumulator - let stride = max(1, (size + alignmentMask) & ~alignmentMask) + let stride = max(1, try alignedUp(size, toAlignmentMask: alignmentMask)) return AggregateLayout( fieldOffsets: fieldOffsets, @@ -97,3 +102,29 @@ public enum BasicLayout { ) } } + +/// An offset or a size of a layout that does not fit an `Int`: a type no +/// binary can hold, which only a malformed one names. +public struct LayoutSizeOverflow: Error, Sendable, Hashable { + public init() {} +} + +extension BasicLayout { + /// The most bytes one value may take: what a 48-bit address space holds. + /// A layout past it is a malformed binary's, and kept below it, the + /// sums of a few of them stay far from `Int.max`. + public static let maximumValueSize = 1 << 48 + + /// `augend + addend`, or ``LayoutSizeOverflow`` when it does not fit. + static func adding(_ augend: Int, _ addend: Int) throws(LayoutSizeOverflow) -> Int { + let (sum, didOverflow) = augend.addingReportingOverflow(addend) + guard !didOverflow else { throw LayoutSizeOverflow() } + return sum + } + + /// `offset` rounded up to a multiple of `alignmentMask + 1`, or + /// ``LayoutSizeOverflow`` when that does not fit. + static func alignedUp(_ offset: Int, toAlignmentMask alignmentMask: Int) throws(LayoutSizeOverflow) -> Int { + try adding(offset, alignmentMask) & ~alignmentMask + } +} diff --git a/Sources/Analysis/SwiftLayout/BuiltinTypeLayoutIndex.swift b/Sources/Analysis/SwiftLayout/BuiltinTypeLayoutIndex.swift index 7b933dad0..6786bdef1 100644 --- a/Sources/Analysis/SwiftLayout/BuiltinTypeLayoutIndex.swift +++ b/Sources/Analysis/SwiftLayout/BuiltinTypeLayoutIndex.swift @@ -75,7 +75,7 @@ public struct BuiltinTypeLayoutIndex: Sendable { // generic-argument-free name the resolver looks types up by. if let demangledNode, Self.isConcreteBoundGenericReference(demangledNode) { continue } let typeName: String - if let demangledNode, let nominalQualifiedName = NodeTypeNaming.nominalQualifiedName(of: demangledNode) { + if let demangledNode, let nominalQualifiedName = LayoutTypeNaming.nominalQualifiedName(of: demangledNode) { typeName = nominalQualifiedName } else if let demangledNode, let builtinTypeName = Self.builtinTypeName(of: demangledNode) { typeName = builtinTypeName diff --git a/Sources/Analysis/SwiftLayout/ClassBoundGenericParameterAnalysis.swift b/Sources/Analysis/SwiftLayout/ClassBoundGenericParameterAnalysis.swift index 908cb80f2..c439e61cf 100644 --- a/Sources/Analysis/SwiftLayout/ClassBoundGenericParameterAnalysis.swift +++ b/Sources/Analysis/SwiftLayout/ClassBoundGenericParameterAnalysis.swift @@ -1,6 +1,7 @@ import MachOSwiftSection @_spi(Internals) import SwiftInspection import Demangling +import BinaryParseSupport /// The layout facts a generic type descriptor's requirement signature yields /// **without any instantiation argument** — what the signature alone pins about @@ -176,7 +177,7 @@ enum ClassBoundGenericParameterAnalysis { guard let symbolNode = try? SymbolicDemangler.demangleType(for: symbol, in: image.machO.context), let protocolNode = symbolNode.kind == .protocol ? symbolNode : symbolNode.first(of: .protocol), - let qualifiedProtocolName = NodeTypeNaming.protocolQualifiedName(of: protocolNode) + let qualifiedProtocolName = LayoutTypeNaming.protocolQualifiedName(of: protocolNode) else { return false } switch imageUniverse.resolveProtocol(byQualifiedTypeName: qualifiedProtocolName) { case .swift(let classConstraint): diff --git a/Sources/Analysis/SwiftLayout/DependentMemberTypeBridge.swift b/Sources/Analysis/SwiftLayout/DependentMemberTypeBridge.swift index 4e4de29d9..54c602c92 100644 --- a/Sources/Analysis/SwiftLayout/DependentMemberTypeBridge.swift +++ b/Sources/Analysis/SwiftLayout/DependentMemberTypeBridge.swift @@ -31,7 +31,7 @@ extension StaticTypeLayoutResolver { if unwrappedBase.kind == .dependentGenericParamType || unwrappedBase.kind == .dependentMemberType { throw LayoutResolutionError.unknown(.genericParameterUnsubstituted) } - guard let conformingName = NodeTypeNaming.nominalQualifiedName(of: baseTypeNode) else { + guard let conformingName = LayoutTypeNaming.nominalQualifiedName(of: baseTypeNode) else { throw LayoutResolutionError.unknown(.demangleFailure) } @@ -40,7 +40,7 @@ extension StaticTypeLayoutResolver { guard let associatedTypeName = associatedTypeReference.firstChild?.text, let protocolReferenceNode = associatedTypeReference.children.at(1), - let protocolName = NodeTypeNaming.protocolQualifiedName(of: protocolReferenceNode) + let protocolName = LayoutTypeNaming.protocolQualifiedName(of: protocolReferenceNode) else { throw LayoutResolutionError.unknown(.demangleFailure) } @@ -68,6 +68,11 @@ extension StaticTypeLayoutResolver { // from the concrete base instantiation before resolving. let baseEnvironment = GenericArgumentEnvironment.make(forInstantiatedTypeNode: baseTypeNode) let substitutedWitnessNode = baseEnvironment.substituting(in: witnessNode) + guard dependentMemberTypeDepth < Self.maximumDependentMemberTypeDepth else { + throw LayoutResolutionError.unknown(.cyclicLayout) + } + dependentMemberTypeDepth += 1 + defer { dependentMemberTypeDepth -= 1 } return try layout(forTypeNode: substitutedWitnessNode, in: witness.image) } } diff --git a/Sources/Analysis/SwiftLayout/EnumLayoutBridge.swift b/Sources/Analysis/SwiftLayout/EnumLayoutBridge.swift index c359da890..a0c6a4b45 100644 --- a/Sources/Analysis/SwiftLayout/EnumLayoutBridge.swift +++ b/Sources/Analysis/SwiftLayout/EnumLayoutBridge.swift @@ -10,7 +10,7 @@ import Demangling /// `__swift5_builtin` whole-type descriptor is available. extension StaticTypeLayoutResolver { func enumLayout(forNode node: Node, in originImage: ImageReference) throws -> StaticTypeLayout { - guard let qualifiedTypeName = NodeTypeNaming.nominalQualifiedName(of: node) else { + guard let qualifiedTypeName = LayoutTypeNaming.nominalQualifiedName(of: node) else { throw LayoutResolutionError.unknown(.demangleFailure) } // `Optional` is a single-payload enum whose descriptor lives in the @@ -49,7 +49,7 @@ extension StaticTypeLayoutResolver { } let compute: () throws -> StaticTypeLayout = { guard let resolved = self.imageUniverse.resolveType(byQualifiedTypeName: qualifiedTypeName) else { - throw LayoutResolutionError.unknown(.typeDescriptorNotFound(qualifiedTypeName: qualifiedTypeName)) + throw LayoutResolutionError.unknown(self.imageUniverse.unresolvedTypeReason(forQualifiedTypeName: qualifiedTypeName)) } guard let enumDescriptor = resolved.descriptor.enum else { throw LayoutResolutionError.unknown(.unsupportedTypeKind(nodeKindName: "non-enum:\(qualifiedTypeName)")) @@ -124,6 +124,10 @@ extension StaticTypeLayoutResolver { ) throws -> StaticTypeLayout { let payloadCaseCount = descriptor.numberOfPayloadCases let emptyCaseCount = descriptor.numberOfEmptyCases + // The size comes from a projection of every case. + guard EnumLayoutCalculator.canProjectCases(numPayloadCases: payloadCaseCount, numEmptyCases: emptyCaseCount) else { + throw LayoutResolutionError.unknown(.unsupportedTypeKind(nodeKindName: "enum declaring \(payloadCaseCount) payload and \(emptyCaseCount) empty cases")) + } let payloadArea = try multiPayloadArea(of: descriptor, in: image, environment: environment) let payloadSize = payloadArea.size let payloadAlignmentMask = payloadArea.alignmentMask @@ -131,7 +135,7 @@ extension StaticTypeLayoutResolver { let isBitwiseBorrowable = payloadArea.isBitwiseBorrowable let isAddressableForDependencies = payloadArea.isAddressableForDependencies - let qualifiedTypeName = NodeTypeNaming.nominalQualifiedName(of: node) + let qualifiedTypeName = LayoutTypeNaming.nominalQualifiedName(of: node) let result: EnumLayoutCalculator.LayoutResult if // Spare bits apply exactly when the compiler recorded a spare-bit @@ -237,7 +241,7 @@ extension StaticTypeLayoutResolver { guard let mangledTypeName = try? descriptor.mangledTypeName(in: image.machO.context), let node = try? SymbolicDemangler.demangleType(for: mangledTypeName, in: image.machO.context), - NodeTypeNaming.nominalQualifiedName(of: node) == qualifiedTypeName + LayoutTypeNaming.nominalQualifiedName(of: node) == qualifiedTypeName else { continue } return descriptor } @@ -318,7 +322,7 @@ extension StaticTypeLayoutResolver { ) let payloadCaseCount = descriptor.numberOfPayloadCases let emptyCaseCount = descriptor.numberOfEmptyCases - guard payloadCaseCount > 0 else { return nil } + guard payloadCaseCount > 0, EnumLayoutCalculator.canProjectCases(numPayloadCases: payloadCaseCount, numEmptyCases: emptyCaseCount) else { return nil } let node = try SymbolicDemangler.demangleContext(for: .type(.enum(descriptor)), in: image.machO.context) let layoutResult: EnumLayoutCalculator.LayoutResult @@ -336,7 +340,7 @@ extension StaticTypeLayoutResolver { // `__swift5_mpenum` mask exists exactly for statically-fixed // enums (argument-independent when generic), so record // presence — not genericity — picks the strategy. - let qualifiedTypeName = NodeTypeNaming.nominalQualifiedName(of: node), + let qualifiedTypeName = LayoutTypeNaming.nominalQualifiedName(of: node), let multiPayloadDescriptor = multiPayloadEnumDescriptor(forQualifiedTypeName: qualifiedTypeName, in: image), multiPayloadDescriptor.usesPayloadSpareBits { diff --git a/Sources/Analysis/SwiftLayout/ExistentialLayoutBridge.swift b/Sources/Analysis/SwiftLayout/ExistentialLayoutBridge.swift index bc47d44f6..e718c7b0d 100644 --- a/Sources/Analysis/SwiftLayout/ExistentialLayoutBridge.swift +++ b/Sources/Analysis/SwiftLayout/ExistentialLayoutBridge.swift @@ -108,7 +108,7 @@ extension StaticTypeLayoutResolver { // `Error` appearing inside a composition is an ordinary witness table. if !structurallyClassBound, protocolNodes.count == 1, - NodeTypeNaming.protocolQualifiedName(of: protocolNodes[0]) == errorProtocolName { + LayoutTypeNaming.protocolQualifiedName(of: protocolNodes[0]) == errorProtocolName { return ExistentialComposition(witnessTableCount: 0, isClassBound: false, isError: true) } @@ -123,7 +123,7 @@ extension StaticTypeLayoutResolver { isClassBound = true continue } - guard let qualifiedName = NodeTypeNaming.protocolQualifiedName(of: protocolNode) else { + guard let qualifiedName = LayoutTypeNaming.protocolQualifiedName(of: protocolNode) else { throw LayoutResolutionError.unknown(.demangleFailure) } switch imageUniverse.resolveProtocol(byQualifiedTypeName: qualifiedName) { diff --git a/Sources/Analysis/SwiftLayout/ImageReference.swift b/Sources/Analysis/SwiftLayout/ImageReference.swift index 7aa8d8ec7..72d55a68f 100644 --- a/Sources/Analysis/SwiftLayout/ImageReference.swift +++ b/Sources/Analysis/SwiftLayout/ImageReference.swift @@ -23,7 +23,7 @@ public final class ImageReference() - private let typeDescriptorsSlot = LazilyBuiltIndex<[String: TypeContextDescriptorWrapper]>() + private let typeDescriptorsSlot = LazilyBuiltIndex() private let protocolClassConstraintsSlot = LazilyBuiltIndex<[String: ProtocolClassConstraint]>() private let objCClassInstanceSizesSlot = LazilyBuiltIndex<[String: (instanceSize: Int, alignmentMask: Int)]>() private let associatedTypeWitnessRecordsSlot = LazilyBuiltIndex<[String: AssociatedTypeRecord]>() @@ -71,21 +71,56 @@ public final class ImageReference { + typeDescriptorIndex.ambiguousQualifiedNames + } + + private var typeDescriptorIndex: TypeDescriptorIndex { typeDescriptorsSlot.index { - var typeIndex: [String: TypeContextDescriptorWrapper] = [:] + var typeIndex = TypeDescriptorIndex() for contextDescriptor in (try? Self.contextDescriptorsOrEmpty(in: machO)) ?? [] { guard let typeDescriptor = contextDescriptor.typeContextDescriptorWrapper, let contextNode = try? SymbolicDemangler.demangleContext(for: contextDescriptor, in: machO.context), - let qualifiedTypeName = NodeTypeNaming.nominalQualifiedName(of: contextNode) + let qualifiedTypeName = LayoutTypeNaming.nominalQualifiedName(of: contextNode) else { continue } - typeIndex[qualifiedTypeName] = typeDescriptor + typeIndex.insert(typeDescriptor, named: qualifiedTypeName) } return typeIndex } } + /// The image's type descriptors by name, and the names that do not tell + /// two of them apart. + private struct TypeDescriptorIndex { + var descriptorsByQualifiedName: [String: TypeContextDescriptorWrapper] = [:] + var ambiguousQualifiedNames: Set = [] + + mutating func insert(_ descriptor: TypeContextDescriptorWrapper, named qualifiedTypeName: String) { + guard !ambiguousQualifiedNames.contains(qualifiedTypeName) else { return } + if let existing = descriptorsByQualifiedName[qualifiedTypeName] { + guard existing.asContextDescriptorWrapper.contextDescriptor.offset != descriptor.asContextDescriptorWrapper.contextDescriptor.offset else { return } + descriptorsByQualifiedName[qualifiedTypeName] = nil + ambiguousQualifiedNames.insert(qualifiedTypeName) + } else { + descriptorsByQualifiedName[qualifiedTypeName] = descriptor + } + } + } + /// Exposed (package-internal) so `ImageUniverse` can merge each image's /// protocol class-constraint index into the closure-wide global index. /// @@ -100,7 +135,7 @@ public final class ImageReference /// so the root and earlier dependencies shadow later ones. private var typeIndex: [String: (image: ImageReference, descriptor: TypeContextDescriptorWrapper)] = [:] + /// The names an image folded so far gives two of its type descriptors + /// (`ImageReference.ambiguousQualifiedTypeNames`) and no earlier image + /// defines: a lookup of one resolves to neither, and reads no further + /// image for it — the types are private to the image that has both. + private var ambiguousTypeNames: Set = [] + /// Closure-wide protocol class-constraint index, grown with the same /// root-first / first-writer-wins policy as `typeIndex`. private var protocolIndex: [String: (image: ImageReference, constraint: ProtocolClassConstraint)] = [:] @@ -143,10 +149,19 @@ public final class ImageUniverse byQualifiedTypeName qualifiedTypeName: String ) -> (image: ImageReference, descriptor: TypeContextDescriptorWrapper)? { if let resolved = typeIndex[qualifiedTypeName] { return resolved } - while typeIndex[qualifiedTypeName] == nil, foldNextImage(into: .types) {} + while typeIndex[qualifiedTypeName] == nil, !ambiguousTypeNames.contains(qualifiedTypeName), foldNextImage(into: .types) {} return typeIndex[qualifiedTypeName] } + /// Why ``resolveType(byQualifiedTypeName:)`` resolved `qualifiedTypeName` + /// to nothing: no image in the closure defines it, or one image defines + /// two types the name does not tell apart. + func unresolvedTypeReason(forQualifiedTypeName qualifiedTypeName: String) -> LayoutUnknownReason { + ambiguousTypeNames.contains(qualifiedTypeName) + ? .ambiguousTypeName(qualifiedTypeName: qualifiedTypeName) + : .typeDescriptorNotFound(qualifiedTypeName: qualifiedTypeName) + } + /// What a protocol name resolves to: a Swift protocol descriptor, or only /// an Objective-C protocol record. enum ResolvedProtocol: Equatable { @@ -243,9 +258,12 @@ public final class ImageUniverse guard let image = image(atResolutionPosition: foldedImageCount) else { return true } switch kind { case .types: - for (qualifiedTypeName, descriptor) in image.typeDescriptorsByQualifiedName where typeIndex[qualifiedTypeName] == nil { + for (qualifiedTypeName, descriptor) in image.typeDescriptorsByQualifiedName where typeIndex[qualifiedTypeName] == nil && !ambiguousTypeNames.contains(qualifiedTypeName) { typeIndex[qualifiedTypeName] = (image, descriptor) } + for qualifiedTypeName in image.ambiguousQualifiedTypeNames where typeIndex[qualifiedTypeName] == nil { + ambiguousTypeNames.insert(qualifiedTypeName) + } case .protocols: for (qualifiedTypeName, classConstraint) in image.protocolClassConstraintsByQualifiedName where protocolIndex[qualifiedTypeName] == nil { protocolIndex[qualifiedTypeName] = (image, classConstraint) diff --git a/Sources/Analysis/SwiftLayout/LayoutResolutionError.swift b/Sources/Analysis/SwiftLayout/LayoutResolutionError.swift index 3fe13d9c2..ccbcfb5ef 100644 --- a/Sources/Analysis/SwiftLayout/LayoutResolutionError.swift +++ b/Sources/Analysis/SwiftLayout/LayoutResolutionError.swift @@ -20,6 +20,10 @@ public enum LayoutUnknownReason: Sendable, Hashable { /// The demangled type resolved to a fully-qualified name that has no /// descriptor in the current image scope. case typeDescriptorNotFound(qualifiedTypeName: String) + /// Two type descriptors of one image demangle to this name, and nothing + /// tells which one a field means: same-named private types of two files + /// whose discriminators the image no longer carries. + case ambiguousTypeName(qualifiedTypeName: String) /// A generic parameter was encountered with no substitution available /// (generic substitution is a later phase). case genericParameterUnsubstituted @@ -36,6 +40,34 @@ public enum LayoutUnknownReason: Sendable, Hashable { /// per-field offset is derivable; only the builtin whole-type layout is /// authoritative. case foreignTypeFieldOffsetsUnavailable + /// An offset or the size does not fit an `Int`, or a value takes more + /// than an address space holds (`BasicLayout.maximumValueSize`): only a + /// malformed binary names such a type. + case sizeOverflow +} + +extension LayoutResolutionError { + /// The overflow as the per-field reason every layout path reports. + init(_ overflow: LayoutSizeOverflow) { + self = .unknown(.sizeOverflow) + } +} + +extension BasicLayout { + /// ``compute(startOffset:startAlignmentMask:fieldLayouts:)``, an + /// overflow reported as the unknown layout the resolver's callers + /// degrade a field to. + static func computeOrUnknown( + startOffset: Int, + startAlignmentMask: Int, + fieldLayouts: [StaticTypeLayout] + ) throws(LayoutResolutionError) -> AggregateLayout { + do { + return try compute(startOffset: startOffset, startAlignmentMask: startAlignmentMask, fieldLayouts: fieldLayouts) + } catch { + throw LayoutResolutionError(error) + } + } } /// Internal error thrown while resolving a layout; caught at the aggregate diff --git a/Sources/Analysis/SwiftLayout/LayoutTypeNaming.swift b/Sources/Analysis/SwiftLayout/LayoutTypeNaming.swift new file mode 100644 index 000000000..c02838b04 --- /dev/null +++ b/Sources/Analysis/SwiftLayout/LayoutTypeNaming.swift @@ -0,0 +1,33 @@ +@_spi(Internals) import Demangling +import SwiftInspection + +/// The names the layout engine keys its type, protocol, builtin-layout and +/// associated-type witness indexes on, and looks them up by. +/// +/// `NodeTypeNaming`'s, with one difference: a private declaration keeps its +/// discriminator (`(Storage in _0F2B…)`). Every key and every lookup here +/// is demangled from a descriptor — a field type names a type of its own +/// image through a symbolic reference to the descriptor — so both sides +/// carry the discriminator or both lack it. Without it, two files' +/// same-named private types shared one key, and a field of one was laid out +/// as the other. Where neither side can recover the discriminator (a +/// stripped image), the two still share a name; the type index marks it +/// ambiguous rather than pick one (`ImageReference.ambiguousQualifiedTypeNames`). +/// +/// The one index not keyed here is the Objective-C class list's +/// (`ImageReference.swiftClassInstanceStartsByQualifiedName`): a class's +/// runtime name always spells its discriminator, so it keys on the plain +/// name the descriptor side can always produce. +enum LayoutTypeNaming { + static func nominalQualifiedName(of node: Node) -> String? { + NodeTypeNaming.nominalQualifiedName(of: node, distinguishesPrivateDeclarations: true) + } + + static func protocolQualifiedName(of node: Node) -> String? { + NodeTypeNaming.protocolQualifiedName(of: node, distinguishesPrivateDeclarations: true) + } + + static func declaredQualifiedName(of node: Node) -> String? { + NodeTypeNaming.declaredQualifiedName(of: node, distinguishesPrivateDeclarations: true) + } +} diff --git a/Sources/Analysis/SwiftLayout/NestedFieldOffsetTree.swift b/Sources/Analysis/SwiftLayout/NestedFieldOffsetTree.swift index b5977de1b..8a2c7765d 100644 --- a/Sources/Analysis/SwiftLayout/NestedFieldOffsetTree.swift +++ b/Sources/Analysis/SwiftLayout/NestedFieldOffsetTree.swift @@ -15,8 +15,18 @@ import Demangling public struct NestedFieldOffset: Sendable { /// The stored property's (or enum payload's) name. public let fieldName: String - /// The field type's printable name (e.g. `Swift.Int`, `MyModule.Box`). + /// The field type's printable name (e.g. `Swift.Int`, `MyModule.Box`), + /// printed from ``typeNode`` with the fixed `.default` options. It is the + /// walk's cycle key, and what a host that does not spell types itself + /// prints (the dump). public let typeName: String + /// The field type's node, with the enclosing type's generic arguments + /// substituted — what ``typeName`` was printed from. A printer spells it + /// the way it spells its declarations' types: the C-imported type name + /// spelling, module selectors, `any` (evolution proposal + /// `consistent-c-imported-type-spelling`). `nil` when the field's type + /// did not demangle, or for a node built by hand. + public let typeNode: Node? /// The field's absolute byte offset from the start of the outermost type. public let offset: Int /// The field's value size, excluding trailing alignment padding. Available @@ -27,9 +37,10 @@ public struct NestedFieldOffset: Sendable { /// reference, or an aggregate the engine could not expand). public let children: [NestedFieldOffset] - public init(fieldName: String, typeName: String, offset: Int, children: [NestedFieldOffset], byteWidth: Int? = nil) { + public init(fieldName: String, typeName: String, offset: Int, children: [NestedFieldOffset], byteWidth: Int? = nil, typeNode: Node? = nil) { self.fieldName = fieldName self.typeName = typeName + self.typeNode = typeNode self.offset = offset self.children = children self.byteWidth = byteWidth @@ -141,7 +152,7 @@ extension StaticLayoutCalculator { private func cImportedTypeAliasCategory(of node: Node) -> NodeTypeNaming.NominalCategory? { guard node.kind == .typeAlias, - let qualifiedTypeName = NodeTypeNaming.nominalQualifiedName(of: node), + let qualifiedTypeName = LayoutTypeNaming.nominalQualifiedName(of: node), let resolved = imageUniverse.resolveType(byQualifiedTypeName: qualifiedTypeName) else { return nil } switch resolved.descriptor { @@ -160,7 +171,7 @@ extension StaticLayoutCalculator { hasUnconditionalStorage: Bool ) -> [NestedFieldOffset] { guard - let qualifiedTypeName = NodeTypeNaming.nominalQualifiedName(of: node), + let qualifiedTypeName = LayoutTypeNaming.nominalQualifiedName(of: node), let resolved = imageUniverse.resolveType(byQualifiedTypeName: qualifiedTypeName), let structDescriptor = resolved.descriptor.struct else { return [] } @@ -203,7 +214,7 @@ extension StaticLayoutCalculator { enclosingTypeNames: Set ) -> [NestedFieldOffset] { guard - let qualifiedTypeName = NodeTypeNaming.nominalQualifiedName(of: node), + let qualifiedTypeName = LayoutTypeNaming.nominalQualifiedName(of: node), let resolved = imageUniverse.resolveType(byQualifiedTypeName: qualifiedTypeName), let enumDescriptor = resolved.descriptor.enum, enumDescriptor.hasPayloadCases, @@ -277,6 +288,6 @@ extension StaticLayoutCalculator { hasUnconditionalStorage: byteWidth != nil ) } ?? []) : [] - return NestedFieldOffset(fieldName: fieldName, typeName: typeName, offset: absoluteOffset, children: children, byteWidth: byteWidth) + return NestedFieldOffset(fieldName: fieldName, typeName: typeName, offset: absoluteOffset, children: children, byteWidth: byteWidth, typeNode: fieldTypeNode) } } diff --git a/Sources/Analysis/SwiftLayout/StaticLayoutCalculator.swift b/Sources/Analysis/SwiftLayout/StaticLayoutCalculator.swift index 859e4f255..3e21fd9a5 100644 --- a/Sources/Analysis/SwiftLayout/StaticLayoutCalculator.swift +++ b/Sources/Analysis/SwiftLayout/StaticLayoutCalculator.swift @@ -70,11 +70,11 @@ public struct StaticLayoutCalculator.rawLayoutStorage(likeTypeLayout: resolvedLayout) : resolvedLayout let fieldAlignmentMask = fieldLayout.alignmentMask - let alignedOffset = (offsetAccumulator + fieldAlignmentMask) & ~fieldAlignmentMask + // An offset past `Int.max` is a malformed binary's: the field + // reads as unknown instead of trapping. + let alignedOffset: Int + let nextOffset: Int + do { + alignedOffset = try BasicLayout.alignedUp(offsetAccumulator, toAlignmentMask: fieldAlignmentMask) + nextOffset = try BasicLayout.adding(alignedOffset, fieldLayout.size) + } catch { + throw LayoutResolutionError(error) + } // A zero-sized field occupies no storage, and the // compiler-emitted field-offset vector reports 0 for it (IRGen // `ElementLayout::completeEmpty` zeroes the reported @@ -461,7 +470,7 @@ public struct StaticLayoutCalculator private var memoizationCache: [String: StaticTypeLayout] = [:] private var inProgressKeys: Set = [] + /// The classes whose layouts are being computed, each by the image and + /// offset of its descriptor: a class's layout is no memoized value + /// layout, so the value guard above never saw it, and a superclass chain + /// leading back into itself — a malformed binary's — recursed until the + /// stack ran out (2026-11-29 codebase audit, finding 9). + private var inProgressClassDescriptors: Set = [] + + private struct ClassDescriptorIdentity: Hashable { + let image: ObjectIdentifier + let descriptorOffset: Int + } + + /// How many associated-type witnesses deep the layout being computed is + /// (`dependentMemberTypeLayout(forNode:in:)`). A witness naming another + /// conformance's associated type goes one deeper; one naming itself — a + /// malformed `__swift5_assocty` record's `S.Element` — went on until the + /// stack ran out (2026-11-29 codebase audit, finding 10). + var dependentMemberTypeDepth = 0 + + /// Deeper than any chain of witnesses a compiler emits. + static var maximumDependentMemberTypeDepth: Int { 64 } init(imageUniverse: ImageUniverse) { self.imageUniverse = imageUniverse @@ -180,7 +202,7 @@ final class StaticTypeLayoutResolver) throws -> StaticTypeLayout { - guard let qualifiedTypeName = NodeTypeNaming.nominalQualifiedName(of: node) else { + guard let qualifiedTypeName = LayoutTypeNaming.nominalQualifiedName(of: node) else { throw LayoutResolutionError.unknown(.demangleFailure) } if let builtinLayout = originImage.builtinLayoutIndex.layout(forTypeName: qualifiedTypeName) { @@ -201,11 +223,11 @@ final class StaticTypeLayoutResolver (image: ImageReference, descriptor: TypeContextDescriptorWrapper) { - guard let qualifiedTypeName = NodeTypeNaming.nominalQualifiedName(of: node) else { + guard let qualifiedTypeName = LayoutTypeNaming.nominalQualifiedName(of: node) else { throw LayoutResolutionError.unknown(.demangleFailure) } guard let resolved = imageUniverse.resolveType(byQualifiedTypeName: qualifiedTypeName) else { - throw LayoutResolutionError.unknown(.typeDescriptorNotFound(qualifiedTypeName: qualifiedTypeName)) + throw LayoutResolutionError.unknown(imageUniverse.unresolvedTypeReason(forQualifiedTypeName: qualifiedTypeName)) } return resolved } @@ -313,7 +335,7 @@ final class StaticTypeLayoutResolver) throws -> StaticTypeLayout { - guard let qualifiedTypeName = NodeTypeNaming.nominalQualifiedName(of: node) else { + guard let qualifiedTypeName = LayoutTypeNaming.nominalQualifiedName(of: node) else { throw LayoutResolutionError.unknown(.demangleFailure) } // A frozen stdlib type whose layout is argument-independent (Array, @@ -544,7 +571,7 @@ final class StaticTypeLayoutResolver StaticTypeLayout = { guard let resolved = self.imageUniverse.resolveType(byQualifiedTypeName: qualifiedTypeName) else { - throw LayoutResolutionError.unknown(.typeDescriptorNotFound(qualifiedTypeName: qualifiedTypeName)) + throw LayoutResolutionError.unknown(self.imageUniverse.unresolvedTypeReason(forQualifiedTypeName: qualifiedTypeName)) } guard let structDescriptor = resolved.descriptor.struct else { throw LayoutResolutionError.unknown(.unsupportedTypeKind(nodeKindName: "non-struct:\(qualifiedTypeName)")) @@ -646,7 +673,7 @@ final class StaticTypeLayoutResolver, environment: GenericArgumentEnvironment = .empty ) throws -> AggregateLayout { + let classIdentity = ClassDescriptorIdentity(image: ObjectIdentifier(image), descriptorOffset: descriptor.offset) + guard !inProgressClassDescriptors.contains(classIdentity) else { + throw LayoutResolutionError.unknown(.cyclicLayout) + } + inProgressClassDescriptors.insert(classIdentity) + defer { inProgressClassDescriptors.remove(classIdentity) } // Class-bound parameters lay out as one object reference even without // a substitution — applied before the superclass computation so // `class Sub: Base` resolves its start. @@ -673,7 +706,7 @@ final class StaticTypeLayoutResolver (any ObjCImplementationClassReading, ObjCClass64)? + /// Whether Swift code went into the image, as its `objc_image_info` + /// says (``ObjCImageInfo/containsSwift``); `nil` when the image has no + /// `__objc_imageinfo`. + func containsSwift() -> Bool? func instanceMethods(of category: ObjCCategory64) -> [RawObjCMethod] func classMethods(of category: ObjCCategory64) -> [RawObjCMethod] func protocolSelectors(of category: ObjCCategory64) -> RawObjCProtocolSelectors @@ -428,6 +432,15 @@ protocol ObjCImplementationClassReading: MachORepresentableWithCache, Readable { func objcProtocolRecords() -> [ObjCProtocolRecord] } +extension ObjCImageInfo { + /// objc4's `objc_image_info::containsSwift()`: the Swift compiler records + /// its ABI version in bits 8–15 of the flags of the image info it emits, + /// the linker keeps it in the image's, and clang leaves those bits clear. + var containsSwift: Bool { + layout.flags & 0xff00 != 0 + } +} + extension MachOFile: ObjCImplementationClassReading { func objcImplementationClassObjects() -> [ObjCClass64]? { objc.classes64 @@ -526,6 +539,10 @@ extension MachOFile: ObjCImplementationClassReading { objc.categories64 } + func containsSwift() -> Bool? { + objc.imageInfo.map(\.containsSwift) + } + /// The reader names a class bound in from another image for chained /// fixups and `LC_DYLD_INFO` opcodes alike. func targetClassName(of category: ObjCCategory64) -> String? { @@ -686,6 +703,10 @@ extension MachOImage: ObjCImplementationClassReading { objc.categories64 } + func containsSwift() -> Bool? { + objc.imageInfo.map(\.containsSwift) + } + func targetClassName(of category: ObjCCategory64) -> String? { category.className(in: self) } diff --git a/Sources/Analysis/SwiftObjCInterop/ObjCImportedTypes.swift b/Sources/Analysis/SwiftObjCInterop/ObjCImportedTypes.swift index bd7ee698c..270103940 100644 --- a/Sources/Analysis/SwiftObjCInterop/ObjCImportedTypes.swift +++ b/Sources/Analysis/SwiftObjCInterop/ObjCImportedTypes.swift @@ -20,6 +20,20 @@ package struct ObjCImportedTypes case closureComponent /// A result the error convention proves non-nil. case nonOptional + /// A `weak` property: `T?`, as `weak` requires an optional. + case weakStorage + } + + /// How an Objective-C type maps to a Swift one. + private enum Mapping { + /// As the importer imports a declaration: Foundation's bridged + /// classes become their Swift value types and `id` is `Any`. + case imported + /// As the Swift type behind an `@objc @implementation` ivar's complete + /// encoding, which the compiler only writes for a type Objective-C + /// represents as it is (evolution proposal `objc-ivar-type-recovery`): + /// no class is bridged and `id` is `AnyObject`. + case triviallyRepresented } /// The image the names are resolved in: a Swift class or protocol is @@ -32,15 +46,72 @@ package struct ObjCImportedTypes /// A `Type` node for `type` in `position`. package func typeNode(_ type: ObjCEncodedType, position: Position) -> Node { - let base = Self.type(bareTypeNode(type)) + typeNode(type, position: position, mapping: .imported) + } + + /// The Swift type of an `@objc @implementation` stored property whose + /// ivar carries the complete encoding `type` (evolution proposal + /// `objc-ivar-type-recovery`): the compiler writes one only for a type + /// Objective-C represents as it is, so `NSString` stays `NSString` and + /// `id` is `AnyObject`. `nil` for a type the encoding does not + /// determine: a block, whose signature no ivar encoding carries, a + /// pointer to a structure (a CF type reads the same), a bit field, an + /// unnamed structure, an array the importer cannot represent, or one the + /// reader does not know. + package func triviallyRepresentedTypeNode(_ type: ObjCEncodedType, position: Position) -> Node? { + guard Self.determinesStoredPropertyType(type) else { return nil } + return typeNode(type, position: position, mapping: .triviallyRepresented) + } + + /// The Swift type of an `@objc @implementation` stored property whose + /// ivar the compiler marked `?` — a type bridged to a separate + /// Objective-C one — read off the `T` attribute of the Objective-C + /// property synthesized on it (evolution proposal + /// `objc-ivar-type-recovery`): the type the importer gives that + /// Objective-C type, `NSString` as `String`, `NSArray` as `[Any]` (the + /// attribute names no element type), `id` as `Any`. The `?` proves the + /// Swift type is no class Objective-C has, so only a class the importer + /// bridges and a bare `id` qualify; anything else — a class imported as + /// itself, which an `unowned` property's storage also marks `?`, a + /// Foundation class bridged to a value type the table does not list — + /// returns `nil`. + package func bridgedTypeNode(_ type: ObjCEncodedType, position: Position) -> Node? { + guard case .object(let className, let protocolNames) = type, protocolNames.isEmpty else { return nil } + if let className, !ObjCBridgedStructures.importsAsNonClassType(className) { return nil } + return typeNode(type, position: position, mapping: .imported) + } + + private func typeNode(_ type: ObjCEncodedType, position: Position, mapping: Mapping) -> Node { + let base = Self.type(bareTypeNode(type, mapping: mapping)) guard Self.isNullable(type) else { return base } switch position { case .topLevel: return Self.implicitlyUnwrapped(base) - case .closureComponent: return Self.optional(base) + case .closureComponent, .weakStorage: return Self.optional(base) case .nonOptional: return base } } + /// Whether `type` names one Swift type a stored property can have. A + /// pointer does only to `void` or a scalar: the importer gives a pointer + /// to an object, a pointer or a structure a type of its own + /// (`AutoreleasingUnsafeMutablePointer`, an optional pointee, a CF class). + private static func determinesStoredPropertyType(_ type: ObjCEncodedType) -> Bool { + switch type { + case .void, .block, .bitField, .unknown: false + case .structure(let name), .union(let name): name != nil + case .array(_, let element): flattenedElementCount(of: type) != nil && determinesStoredPropertyType(element) + case .pointer(let pointee, _): pointee == .void || isScalar(pointee) + default: true + } + } + + private static func isScalar(_ type: ObjCEncodedType) -> Bool { + switch type { + case .bool, .character, .unsignedCharacter, .short, .unsignedShort, .int, .unsignedInt, .long, .unsignedLong, .longLong, .unsignedLongLong, .float, .double, .longDouble: true + default: false + } + } + /// `instancetype`, of unknown nullability, as an initializer's result: /// `Self!`. package static var initializerResultTypeNode: Node { @@ -59,7 +130,7 @@ package struct ObjCImportedTypes } /// The type itself, unwrapped: what a `Type` node holds. - private func bareTypeNode(_ type: ObjCEncodedType) -> Node { + private func bareTypeNode(_ type: ObjCEncodedType, mapping: Mapping = .imported) -> Node { switch type { case .void: return Node.createTransient(kind: .tuple) case .bool: return Self.swiftStructure("Bool") @@ -76,7 +147,7 @@ package struct ObjCImportedTypes case .characterString(let isConst): return Self.boundGenericStructure(Self.swiftStructure(isConst ? "UnsafePointer" : "UnsafeMutablePointer"), arguments: [Self.swiftStructure("Int8")]) case .selector: return Self.structure(module: "ObjectiveC", name: "Selector") case .objectClass: return Node.createTransient(kind: .typeAlias, children: [Self.module("Swift"), Node.createTransient(kind: .identifier, text: "AnyClass")]) - case .object(let className, let protocolNames): return objectNode(className: className, protocolNames: protocolNames) + case .object(let className, let protocolNames): return objectNode(className: className, protocolNames: protocolNames, mapping: mapping) case .block(let signature): guard let signature else { return Self.anyNode } return Node.createTransient(kind: .functionType, children: [ @@ -92,7 +163,7 @@ package struct ObjCImportedTypes // ClangImporter imports a pointer to what it cannot represent as // `OpaquePointer`. case .array where Self.flattenedElementCount(of: pointee) == nil: return Self.swiftStructure("OpaquePointer") - default: return Self.boundGenericStructure(Self.swiftStructure(isConst ? "UnsafePointer" : "UnsafeMutablePointer"), arguments: [bareTypeNode(pointee)]) + default: return Self.boundGenericStructure(Self.swiftStructure(isConst ? "UnsafePointer" : "UnsafeMutablePointer"), arguments: [bareTypeNode(pointee, mapping: mapping)]) } case .structure(let name), .union(let name): guard let name else { return Self.swiftStructure("OpaquePointer") } @@ -101,9 +172,9 @@ package struct ObjCImportedTypes // A C array imports as a tuple of its elements, a single element // as the element itself; one it cannot represent, as nothing. guard Self.flattenedElementCount(of: type) != nil else { return Self.anyNode } - if count == 1 { return bareTypeNode(element) } + if count == 1 { return bareTypeNode(element, mapping: mapping) } return Node.createTransient(kind: .tuple, children: (0 ..< count).map { _ in - Node.createTransient(kind: .tupleElement, child: Self.type(bareTypeNode(element))) + Node.createTransient(kind: .tupleElement, child: Self.type(bareTypeNode(element, mapping: mapping))) }) case .bitField, .unknown: return Self.anyNode @@ -132,9 +203,14 @@ package struct ObjCImportedTypes return flattenedCount } - private func objectNode(className: String?, protocolNames: [String]) -> Node { + private func objectNode(className: String?, protocolNames: [String], mapping: Mapping) -> Node { let protocols = protocolNames.map { Self.type(ObjCRuntimeNames.protocolNode(forRuntimeName: $0, in: machO)) } guard let className else { + // A bare `id` a Swift type represents as it is is `AnyObject`; + // the importer gives `Any`. + if mapping == .triviallyRepresented, protocols.isEmpty { + return Node.createTransient(kind: .protocolListWithAnyObject, child: Node.createTransient(kind: .protocolList, child: Node.createTransient(kind: .typeList))) + } // `id`, `id

`, `id`. return Node.createTransient(kind: .protocolList, child: Node.createTransient(kind: .typeList, children: protocols)) } @@ -145,6 +221,10 @@ package struct ObjCImportedTypes Self.type(ObjCRuntimeNames.classNode(forRuntimeName: className, in: machO)), ]) } + // A class a Swift type represents as it is is that class. + if mapping == .triviallyRepresented { + return ObjCRuntimeNames.classNode(forRuntimeName: className, in: machO) + } if let bridged = ObjCBridgedStructures.structuresByClassName[className] { return Self.structure(module: bridged.module, name: bridged.name) } diff --git a/Sources/Analysis/SwiftObjCInterop/ObjCInstanceVariableSwiftType.swift b/Sources/Analysis/SwiftObjCInterop/ObjCInstanceVariableSwiftType.swift new file mode 100644 index 000000000..ae91bfc53 --- /dev/null +++ b/Sources/Analysis/SwiftObjCInterop/ObjCInstanceVariableSwiftType.swift @@ -0,0 +1,137 @@ +import MachOSwiftSection +@_spi(Internals) import Demangling + +/// The Swift type of an `@objc @implementation` stored property, read off +/// the Objective-C side once the image no longer carries the property's +/// field-offset symbol (evolution proposal `objc-ivar-type-recovery`). +/// +/// The compiler writes a stored property's ivar encoding in one of three +/// ways (`buildIvar` in IRGen's `GenClass.cpp`): empty when the property is +/// not `@objc`; `?` when its type is bridged to a separate Objective-C type; +/// and otherwise the property type's own encoding — which it only writes for +/// a type Objective-C represents as it is (`isTriviallyRepresentableIn`), so +/// that Objective-C type IS the Swift type. A `?` ivar's Swift type is the +/// bridged form of the Objective-C property synthesized on it, whose `T` +/// attribute the same function encodes. Neither says whether an object is +/// optional, so a type that can be `nil` reads `T!`, as ClangImporter spells +/// an unannotated declaration — `T?` for a `weak` property, which must be +/// optional. +package struct ObjCInstanceVariableSwiftType { + /// Where the type was read. + package enum Source: Sendable, Hashable { + /// The ivar's own type encoding. + case instanceVariableEncoding + /// The `T` attribute of the Objective-C property synthesized on the + /// ivar, for an ivar the compiler marked `?`. + case objcProperty + } + + /// The property's `Type` node, its unknown nullability spelled. + package let typeNode: Node + package let source: Source + /// The Objective-C type the Swift type was read from, which tells a + /// printer when the type is a C primitive it may spell otherwise. + package let encodedType: ObjCEncodedType + /// The Objective-C property offers no setter. + package let isReadOnly: Bool + /// The Objective-C property is `weak` — or `unowned(unsafe)`: the + /// compiler marks both `W` (`ambiguity`). + package let isWeak: Bool + /// What the Objective-C side leaves open, and nothing else in the binary + /// settles: the declaration prints the common reading, and says what + /// else it may be. + package let ambiguity: Ambiguity? + + /// Two declarations the compiler gives the same Objective-C property and + /// ivar (`GenClass.cpp`, 2026-11-29 codebase audit, finding 2). + /// + /// The other reading is `unowned(unsafe)`: what a header's + /// `unsafe_unretained` (or `assign`) class property imports as, and so + /// the one an `@implementation` body must declare. A plain `unowned` does + /// not match any header property. + package enum Ambiguity: Sendable, Hashable { + /// `W` marks a `weak` and an `unowned(unsafe)` property alike, and + /// both store their class under a `?` ivar. Read as the common + /// `weak`, an `unowned(unsafe) var label: NSString` printed as `weak + /// var label: NSString?`. + case weakOrUnownedUnsafe + /// A `?` ivar under a read-only class property: a bridged value + /// (`let label: String`), or the class held `unowned(unsafe)` — its + /// storage is marked `?` too, and a read-only property carries no + /// `W`. Read as the common bridging, an `unowned(unsafe) let label: + /// NSString` printed as `let label: String!`. `className` is the + /// class, `nil` for `id`. + case bridgedValueOrUnownedUnsafeClass(className: String?) + } + + /// The type of `instanceVariable`, given the Objective-C property + /// synthesized on it (`ObjCImplementationClassFacts.objcProperty(storedIn:swiftPropertyName:)`); + /// `nil` when the Objective-C side does not say. + package init?(instanceVariable: ObjCImplementationClassFacts.InstanceVariable, objcProperty: ObjCImplementationClassFacts.Property?, in machO: some MachOSwiftSectionRepresentableWithCache) { + let importedTypes = ObjCImportedTypes(machO: machO) + let isWeak = objcProperty?.isWeak ?? false + let encodedType: ObjCEncodedType + let typeNode: Node + // An empty encoding: the property is not `@objc`, and nothing in the + // binary says what its type is. + guard instanceVariable.isObjCVisible else { return nil } + if instanceVariable.typeEncoding == "?" { + // Bridged: the Objective-C property says to what. A `weak` + // property's storage is marked `?` whatever its class, and + // `weak` holds only a class, which no bridging changes. + guard let objcProperty, + let propertyType = ObjCTypeEncodingParser.propertyType(fromAttributes: objcProperty.attributes), + let propertyTypeNode = isWeak + ? importedTypes.triviallyRepresentedTypeNode(propertyType, position: .weakStorage) + : importedTypes.bridgedTypeNode(propertyType, position: .topLevel) + else { return nil } + encodedType = propertyType + typeNode = propertyTypeNode + self.source = .objcProperty + } else { + guard let instanceVariableType = ObjCTypeEncodingParser.type(from: instanceVariable.typeEncoding), + let instanceVariableTypeNode = importedTypes.triviallyRepresentedTypeNode(instanceVariableType, position: isWeak ? .weakStorage : .topLevel) + else { return nil } + encodedType = instanceVariableType + typeNode = instanceVariableTypeNode + self.source = .instanceVariableEncoding + } + self.typeNode = typeNode + self.encodedType = encodedType + self.isReadOnly = objcProperty?.isReadOnly ?? false + self.isWeak = isWeak + if isWeak { + self.ambiguity = .weakOrUnownedUnsafe + } else if source == .objcProperty, isReadOnly, instanceVariable.size == MemoryLayout.size, + case .object(let className, let protocolNames) = encodedType, protocolNames.isEmpty { + // `unowned(unsafe)` storage is one pointer: a bridged value that + // takes more (`String`, `Any`) is no such property. + self.ambiguity = .bridgedValueOrUnownedUnsafeClass(className: className) + } else { + self.ambiguity = nil + } + } + + /// What a comment beside the declaration printed for the property `name` + /// says the Objective-C side reads the same as — `or unowned(unsafe) var + /// label: NSObject: …` — so that dump and interface word it alike. `nil` + /// when nothing is left open. + package func alternativeDeclarationNote(named name: String) -> String? { + let alternativeDeclaration: String + switch ambiguity { + case .weakOrUnownedUnsafe: + alternativeDeclaration = "unowned(unsafe) var \(name): \(Self.className(of: encodedType))" + case .bridgedValueOrUnownedUnsafeClass(let className): + alternativeDeclaration = "unowned(unsafe) let \(name): \(className ?? "AnyObject")" + case nil: + return nil + } + return "or \(alternativeDeclaration): the Objective-C property reads the same for both" + } + + /// The class an object encoding names, `AnyObject` for `id`. + private static func className(of encodedType: ObjCEncodedType) -> String { + guard case .object(let className?, _) = encodedType else { return "AnyObject" } + return className + } +} diff --git a/Sources/Analysis/SwiftObjCInterop/ObjCProtocolAdoptionIndex.swift b/Sources/Analysis/SwiftObjCInterop/ObjCProtocolAdoptionIndex.swift index ea8895205..3c1bdcfb6 100644 --- a/Sources/Analysis/SwiftObjCInterop/ObjCProtocolAdoptionIndex.swift +++ b/Sources/Analysis/SwiftObjCInterop/ObjCProtocolAdoptionIndex.swift @@ -55,6 +55,13 @@ package struct ObjCCategoryProtocolAdoption: Sendable, Hashable { /// ancestry targets the class's stub, whose name the reader cannot read, /// and is missed. /// +/// An image no Swift code went into lists no category: its categories are +/// all Objective-C code's. An image Swift went into lists every category +/// that names a protocol, Objective-C code's among them — the linker merges +/// the categories of one class into one, named after the first, with the +/// protocols of all, so neither the name nor the list says whose a protocol +/// is. +/// /// Built once per image, lazily, and evicted with the other ObjC-side /// per-image state. package final class ObjCProtocolAdoptionIndex: @unchecked Sendable { @@ -166,8 +173,12 @@ package final class ObjCProtocolAdoptionIndex: @unchecked Sendable { qualifiedNamesByClass[swiftClass.name] = swiftClass.qualifiedName } + // Only an image Swift code went into can hold an extension of + // Swift's: OS X 10.9's AppKit, all Objective-C, printed four of its + // categories as conformance extensions. An image without + // `__objc_imageinfo` says nothing either way and keeps them all. var categories: [(offset: Int, classRuntimeName: String, protocolRuntimeNames: [String])] = [] - for category in machO.objcCategories() ?? [] { + for category in machO.containsSwift() == false ? [] : machO.objcCategories() ?? [] { guard let targetClassName = machO.targetClassName(of: category), !targetClassName.isEmpty else { continue } let protocolNames = machO.protocolNames(of: category) if !protocolNames.isEmpty { diff --git a/Sources/Analysis/SwiftObjCInterop/ObjCTypeEncoding.swift b/Sources/Analysis/SwiftObjCInterop/ObjCTypeEncoding.swift index 2ee3a1da8..c2f0cb6ce 100644 --- a/Sources/Analysis/SwiftObjCInterop/ObjCTypeEncoding.swift +++ b/Sources/Analysis/SwiftObjCInterop/ObjCTypeEncoding.swift @@ -130,9 +130,18 @@ package enum ObjCTypeEncodingParser { return type } + /// How deep one type nests in another — a pointer's pointee, an array's + /// element, a block's result and parameters — before the encoding reads + /// as none. Far deeper than any declaration spells; an encoding nesting + /// further is a malformed binary's, and each level is a frame of the + /// reader and of every reading of its result: ten thousand `^`s ran a + /// 512 KB thread out of stack (2026-11-29 codebase audit, finding 13). + package static let maximumNestingDepth = 64 + private struct Reader { private let characters: [Character] private var position = 0 + private var nestingDepth = 0 init(_ text: String) { self.characters = Array(text) @@ -207,12 +216,12 @@ package enum ObjCTypeEncodingParser { case "?": return .unknown case "@": return readObject() case "^": - guard let pointee = readType() else { return nil } + guard let pointee = readNestedType() else { return nil } return .pointer(pointee, isConst: isConst) case "{": return readAggregate(closing: "}").map { .structure(name: $0) } case "(": return readAggregate(closing: ")").map { .union(name: $0) } case "[": - guard let count = readNumber(), let element = readType(), peek == "]" else { return nil } + guard let count = readNumber(), let element = readNestedType(), peek == "]" else { return nil } position += 1 return .array(count: count, element: element) case "b": @@ -223,6 +232,15 @@ package enum ObjCTypeEncodingParser { } } + /// A type nested in the one being read, or `nil` past + /// ``ObjCTypeEncodingParser/maximumNestingDepth``. + private mutating func readNestedType() -> ObjCEncodedType? { + guard nestingDepth < ObjCTypeEncodingParser.maximumNestingDepth else { return nil } + nestingDepth += 1 + defer { nestingDepth -= 1 } + return readType() + } + private mutating func readObject() -> ObjCEncodedType? { if peek == "?" { position += 1 @@ -231,13 +249,13 @@ package enum ObjCTypeEncodingParser { // The block's own encoding: its result, the block literal, // then its parameters. The compilers write no offsets here; // any are skipped all the same. - guard let returnType = readType() else { return nil } + guard let returnType = readNestedType() else { return nil } skipOffset() - guard readType() != nil else { return nil } + guard readNestedType() != nil else { return nil } skipOffset() var parameterTypes: [ObjCEncodedType] = [] while let character = peek, character != ">" { - guard let parameterType = readType() else { return nil } + guard let parameterType = readNestedType() else { return nil } skipOffset() parameterTypes.append(parameterType) } diff --git a/Sources/Analysis/SwiftThunkAnalysis/ObjCMembers/ObjCMembers.swift b/Sources/Analysis/SwiftThunkAnalysis/ObjCMembers/ObjCMembers.swift index fa78e9509..0a39a706b 100644 --- a/Sources/Analysis/SwiftThunkAnalysis/ObjCMembers/ObjCMembers.swift +++ b/Sources/Analysis/SwiftThunkAnalysis/ObjCMembers/ObjCMembers.swift @@ -6,6 +6,7 @@ import MachOKitExtensions @_spi(Internals) import SwiftSymbols @_spi(Internals) import SwiftInspection import SwiftObjCInterop +import MachOResolving /// The public face of the ObjC member recovery (evolution proposals /// `objc-ancestor-override-recovery` and `objc-member-selector-recovery`): diff --git a/Sources/Analysis/SwiftThunkAnalysis/ObjCMembers/ObjCMethodThunkReferences.swift b/Sources/Analysis/SwiftThunkAnalysis/ObjCMembers/ObjCMethodThunkReferences.swift index c741862eb..94e771913 100644 --- a/Sources/Analysis/SwiftThunkAnalysis/ObjCMembers/ObjCMethodThunkReferences.swift +++ b/Sources/Analysis/SwiftThunkAnalysis/ObjCMembers/ObjCMethodThunkReferences.swift @@ -3,6 +3,8 @@ import MachOKit @_spi(Internals) import MachOAddressResolution import MachOKitExtensions @_spi(Internals) import SwiftSymbols +import MachOReading +import MachOResolving /// What an ObjC method's IMP references (evolution proposal /// `objc-ancestor-override-recovery`): the addresses its code calls, diff --git a/Sources/Commands/SwiftSectionKit/CrossReferences/CrossReferenceFormatting.swift b/Sources/Commands/SwiftSectionKit/CrossReferences/CrossReferenceFormatting.swift index 2521db514..5bcd1e775 100644 --- a/Sources/Commands/SwiftSectionKit/CrossReferences/CrossReferenceFormatting.swift +++ b/Sources/Commands/SwiftSectionKit/CrossReferences/CrossReferenceFormatting.swift @@ -190,6 +190,8 @@ final class CrossReferenceTargetNaming { return .object(["objectiveCClass": .object(members)]) case .objectiveCInstanceVariable(let className, let name): return .object(["instanceVariable": .object(["class": .string(className), "name": .string(name)])]) + case .selector(let selector): + return .object(["selector": .string(selector)]) case .cString(let characters): return .object(["cString": .string(characters)]) case .constantString(let characters): @@ -230,6 +232,8 @@ final class CrossReferenceTargetNaming { return "class \(name) (\(CrossReferenceFormatting.imageName(ofPath: imagePath(of: location))))" case .objectiveCInstanceVariable(let className, let name): return "ivar \(className).\(name)" + case .selector(let selector): + return "selector \(selector)" case .cString(let characters): return "C string \(CrossReferenceFormatting.quoted(characters))" case .constantString(let characters): diff --git a/Sources/Commands/SwiftSectionKit/CrossReferences/CrossReferenceInput.swift b/Sources/Commands/SwiftSectionKit/CrossReferences/CrossReferenceInput.swift index 7b350a793..8404a4085 100644 --- a/Sources/Commands/SwiftSectionKit/CrossReferences/CrossReferenceInput.swift +++ b/Sources/Commands/SwiftSectionKit/CrossReferences/CrossReferenceInput.swift @@ -32,6 +32,13 @@ public enum CrossReferenceRequestError: Error, LocalizedError, Sendable, Equatab case symbolIsNoFunction(name: String) /// No analyzed image defines or imports a class of this name. case classNotFound(name: String) + /// No analyzed image — or none of the one named — defines a Swift type + /// with this mangling. + case swiftTypeNotFound(mangling: String) + /// A dyld shared cache's images export no descriptor of a Swift type + /// with this mangling: the image that defines it must be named, since + /// working out every image's type keys takes minutes. + case swiftTypeNeedsImage(mangling: String) /// No function of the image the address was looked up in holds it. case noFunction(address: UInt64) /// Several of the files hold a function at the address; the image must @@ -54,6 +61,10 @@ public enum CrossReferenceRequestError: Error, LocalizedError, Sendable, Equatab "The symbol '\(name)' does not name the start of a function." case .classNotFound(let name): "No analyzed image defines or imports an Objective-C class named '\(name)'." + case .swiftTypeNotFound(let mangling): + "No analyzed image defines a Swift type whose mangling is '\(mangling)'." + case .swiftTypeNeedsImage(let mangling): + "No image of the dyld shared cache exports a descriptor of '\(mangling)'; name the image that defines it." case .noFunction(let address): "No function holds the address \(CrossReferenceFormatting.hexadecimal(address))." case .ambiguousFunction(let address, let imagePaths): diff --git a/Sources/Commands/SwiftSectionKit/CrossReferences/ReferencesRequest.swift b/Sources/Commands/SwiftSectionKit/CrossReferences/ReferencesRequest.swift index 445981e22..65a886f33 100644 --- a/Sources/Commands/SwiftSectionKit/CrossReferences/ReferencesRequest.swift +++ b/Sources/Commands/SwiftSectionKit/CrossReferences/ReferencesRequest.swift @@ -22,6 +22,12 @@ public enum CrossReferenceSubject: Sendable, Hashable { case instanceVariable(className: String, name: String) /// A C string or constant `CFString` literal with these characters. case string(String) + /// A Swift struct, enum or class by its mangling — `7SwiftUI4TextV` — or + /// by a `$s…Mn`, `$s…Ma` or `$s…N` symbol of it (its descriptor, its + /// metadata accessor, its metadata), defined in the image `imageName` + /// names, or in whichever image exports its descriptor. A Swift class is + /// also referenced as the Objective-C class it is. + case swiftType(String, imageName: String?) } /// Which way `refs` follows a function. @@ -40,8 +46,9 @@ public enum CrossReferenceOutputFormat: Sendable, Hashable { } /// `swift-section refs`: the code that references a selector, a symbol, a -/// class, a function, an instance variable or a string — or, for a function, -/// what it references — across a dyld shared cache or a set of files. +/// class, a function, an instance variable, a string or a Swift type — or, +/// for a function, what it references — across a dyld shared cache or a set +/// of files. /// /// The images that can reference the subject are found first, from their /// symbol tables, selector references and linkage; only those are scanned, @@ -91,6 +98,9 @@ public struct ReferencesRequest: Sendable, Equatable { case .callers(let keys, let candidates): references = await Self.references(to: keys, inImagesAt: candidates, analyzer: analyzer).filter(query.acceptsReference) scannedImageCount = candidates.count + case .swiftTypes(let identities, let candidates): + references = await Self.references(toSwiftTypes: identities, inImagesAt: candidates, analyzer: analyzer) + scannedImageCount = candidates.count } let referenceCount = references.count let referencingImageCount = Set(references.map(\.function.imageIndex)).count @@ -151,6 +161,32 @@ public struct ReferencesRequest: Sendable, Equatable { } } + /// The references to any of `identities` in each candidate image, + /// concurrently, in candidate order. A type defined by two variants of a + /// framework has an identity each; a reference matching both is listed + /// once. + private static func references(toSwiftTypes identities: [SwiftTypeIdentity], inImagesAt candidates: [Int], analyzer: CrossReferenceAnalyzer) async -> [CodeReference] { + await withCheckedContinuation { continuation in + scanQueue.async { + let results = ImageResults(count: candidates.count) + DispatchQueue.concurrentPerform(iterations: candidates.count) { position in + var seen = Set() + var references: [CodeReference] = [] + for identity in identities { + for reference in analyzer.references(toSwiftType: identity, inImageAt: candidates[position]) where seen.insert(reference).inserted { + references.append(reference) + } + } + if identities.count > 1 { + references.sort { ($0.instructionAddress, $0.function.address) < ($1.instructionAddress, $1.function.address) } + } + results.store(references, at: position) + } + continuation.resume(returning: results.joined()) + } + } + } + /// One slot an image, each written by one iteration alone. private final class ImageResults: @unchecked Sendable { private var slots: [[CodeReference]] @@ -241,6 +277,10 @@ private struct ResolvedQuery { enum Search { case callers(keys: Set, candidates: [Int]) case callees(CodeFunction) + /// A Swift type's references, matched by the analyzer's type query + /// rather than by table keys: they are filed by descriptor, and a + /// mangled name may spell the type. + case swiftTypes([SwiftTypeIdentity], candidates: [Int]) } var search: Search @@ -309,7 +349,59 @@ private struct ResolvedQuery { // Any image can hold the literal; none is ruled out. search = .callers(keys: [.cString(characters), .constantString(characters)], candidates: scope) jsonDescription = ["string": .string(characters)] + case .swiftType(let spelling, let imageName): + let mangling = Self.swiftTypeMangling(spelledAs: spelling) + let identities = try Self.swiftTypeIdentities(mangling: mangling, imageName: imageName, input: input, analyzer: analyzer) + var candidates = Set() + for identity in identities { + candidates.formUnion(analyzer.imageIndices(referencingSwiftType: identity, among: scope)) + } + search = .swiftTypes(identities, candidates: candidates.sorted()) + jsonDescription = ["swiftType": .string(mangling)] + } + } + + /// The nominal mangling `spelling` names: itself, or — for a symbol, + /// `$s` first and `_` before it optionally — the symbol without its + /// prefix and its descriptor (`Mn`), accessor (`Ma`) or metadata (`N`) + /// suffix. A mangling on its own ends with its kind (`V`, `C`, `O`, `a` + /// for a C type), never with one of those suffixes. + static func swiftTypeMangling(spelledAs spelling: String) -> String { + var mangling = Substring(spelling) + if mangling.hasPrefix("_") { mangling = mangling.dropFirst() } + guard mangling.hasPrefix("$s") else { return spelling } + mangling = mangling.dropFirst(2) + for suffix in ["Mn", "Ma", "N"] where mangling.hasSuffix(suffix) && mangling.count > suffix.count { + return String(mangling.dropLast(suffix.count)) + } + return String(mangling) + } + + /// The Swift types with `mangling`: in the image `imageName` names, or + /// wherever a `$s…Mn` symbol puts the descriptor, or — for a set of + /// files, which are few — in whichever file defines one. + private static func swiftTypeIdentities(mangling: String, imageName: String?, input: CrossReferenceInput, analyzer: CrossReferenceAnalyzer) throws -> [SwiftTypeIdentity] { + let allImages = 0 ..< analyzer.imageCount + let descriptors: [CodeLocation] + if let imageName { + descriptors = try analyzer.imageIndices(named: [imageName]).flatMap { analyzer.swiftTypeDescriptorLocations(withKey: mangling, inImageAt: $0) } + } else { + let exported = analyzer.locations(ofSymbolNamed: "_$s" + mangling + "Mn", among: allImages) + if !exported.isEmpty { + descriptors = exported + } else if case .files = input { + descriptors = allImages.flatMap { analyzer.swiftTypeDescriptorLocations(withKey: mangling, inImageAt: $0) } + } else { + throw CrossReferenceRequestError.swiftTypeNeedsImage(mangling: mangling) + } + } + var identities: [SwiftTypeIdentity] = [] + for descriptor in descriptors { + guard let identity = analyzer.swiftTypeIdentity(ofDescriptorAt: descriptor), !identities.contains(identity) else { continue } + identities.append(identity) } + guard !identities.isEmpty else { throw CrossReferenceRequestError.swiftTypeNotFound(mangling: mangling) } + return identities } private init(search: Search, acceptsReference: @escaping (CodeReference) -> Bool, jsonDescription: [String: CrossReferenceJSONValue]) { diff --git a/Sources/Commands/SwiftSectionKit/CrossReferences/SymbolicateRequest.swift b/Sources/Commands/SwiftSectionKit/CrossReferences/SymbolicateRequest.swift index 4eec7bc6d..2f566a498 100644 --- a/Sources/Commands/SwiftSectionKit/CrossReferences/SymbolicateRequest.swift +++ b/Sources/Commands/SwiftSectionKit/CrossReferences/SymbolicateRequest.swift @@ -25,12 +25,20 @@ public struct SymbolicateRequest: Sendable, Equatable { @discardableResult public func run(output: some SwiftSectionOutput) async throws -> [AddressSymbolication] { let analyzer = try input.makeAnalyzer() - let imageIndex = try imageName.map { name -> Int in - // A name two images answer to — the macOS and the Mac Catalyst - // variant — means the first; their addresses are apart. - try analyzer.imageIndices(named: [name])[0] + // A name two images answer to — the macOS and the Mac Catalyst + // variant of a cache's framework — means whichever maps the address: + // their addresses are apart. Only when none does is it the first's. + let imageIndices = try imageName.map { try analyzer.imageIndices(named: [$0]) } + let symbolications = addresses.map { address -> AddressSymbolication in + guard let imageIndices else { return analyzer.symbolication(of: address, inImageAt: nil) } + var firstSymbolication: AddressSymbolication? + for imageIndex in imageIndices { + let symbolication = analyzer.symbolication(of: address, inImageAt: imageIndex) + if symbolication.meaning != .unmapped { return symbolication } + firstSymbolication = firstSymbolication ?? symbolication + } + return firstSymbolication ?? analyzer.symbolication(of: address, inImageAt: nil) } - let symbolications = addresses.map { analyzer.symbolication(of: $0, inImageAt: imageIndex) } let naming = CrossReferenceTargetNaming(analyzer: analyzer) switch format { case .text: diff --git a/Sources/Commands/SwiftSectionKit/ObjC/ObjCAPIRequests.swift b/Sources/Commands/SwiftSectionKit/ObjC/ObjCAPIRequests.swift index a2046d3d1..efe57ce8b 100644 --- a/Sources/Commands/SwiftSectionKit/ObjC/ObjCAPIRequests.swift +++ b/Sources/Commands/SwiftSectionKit/ObjC/ObjCAPIRequests.swift @@ -5,6 +5,8 @@ import ObjCIndexing import ObjCInterface import ObjCMetadataSource import SwiftIndexing +import MachOKitExtensions +import Semantic /// `swift-section objc snapshot`: index a binary's ObjC API and persist it as a /// baseline document — or relabel an existing document. @@ -290,7 +292,7 @@ public struct ObjCAPIEvolutionRequest: Sendable, Equatable { /// found no one platform to spell the availability macros for. Naming the /// platform with ``ObjCAPIEvolutionRequest/AvailabilityAttributes/platform(_:)`` /// avoids both. -public enum ObjCAvailabilityPlatformInferenceError: Error, LocalizedError, Sendable, Equatable { +public enum ObjCAvailabilityPlatformInferenceError: Swift.Error, LocalizedError, Sendable, Equatable { /// The binary at `path` has no `LC_BUILD_VERSION`, or names a platform /// the availability macros have no name for, such as bridgeOS. case noPlatform(path: String) diff --git a/Sources/Commands/SwiftSectionKit/ObjC/ObjCInterfaceRequest.swift b/Sources/Commands/SwiftSectionKit/ObjC/ObjCInterfaceRequest.swift index 7e19229b7..dbb334db3 100644 --- a/Sources/Commands/SwiftSectionKit/ObjC/ObjCInterfaceRequest.swift +++ b/Sources/Commands/SwiftSectionKit/ObjC/ObjCInterfaceRequest.swift @@ -33,6 +33,13 @@ public struct ObjCInterfaceRequest: Sendable, Equatable { /// proposal `objc-imported-declarations`). Classes, categories and /// protocols only; the header options do not apply. public var printsSwiftImport: Bool + /// Mark the `NS_SWIFT_NAME(...)` / `NS_REFINED_FOR_SWIFT` the API notes of + /// the binary's SDK give a class, protocol or category and its members, + /// read from the active developer directory (proposal + /// swift-type-indexing-package). macOS 13 and later; a binary no + /// installed SDK covers prints a warning and its plain interface. Ignored + /// with `printsSwiftImport`. + public var marksSDKSwiftNames: Bool public init( declarationName: String, @@ -43,7 +50,8 @@ public struct ObjCInterfaceRequest: Sendable, Equatable { ivarOffsetComment: Transformer.ObjCIvarOffset? = nil, reportsIndexingProgress: Bool = false, destination: ProductDestination = .output, - printsSwiftImport: Bool = false + printsSwiftImport: Bool = false, + marksSDKSwiftNames: Bool = false ) { self.declarationName = declarationName self.kind = kind @@ -54,6 +62,7 @@ public struct ObjCInterfaceRequest: Sendable, Equatable { self.reportsIndexingProgress = reportsIndexingProgress self.destination = destination self.printsSwiftImport = printsSwiftImport + self.marksSDKSwiftNames = marksSDKSwiftNames } public func run(output: some SwiftSectionOutput) async throws { @@ -70,11 +79,14 @@ public struct ObjCInterfaceRequest: Sendable, Equatable { output: output ) + let swiftImportNotesForKind = await sdkSwiftImportNotesProvider(for: session.machOFile, output: output) + // Searched in declaration-kind order rather than by guessing from the // spelling: `Foo(Bar)` is unambiguous, but a bare name could be a // class, a protocol or a struct. for candidateKind in kind.map({ [$0] }) ?? ObjCDeclarationKind.allCases { - guard let interface = session.interface(of: candidateKind, named: declarationName) else { continue } + let swiftImportNotes = await swiftImportNotesForKind?(candidateKind) ?? ObjCSwiftImportNotes() + guard let interface = session.interface(of: candidateKind, named: declarationName, swiftImportNotes: swiftImportNotes) else { continue } switch destination { case .file(let path): try interface.string.write(to: URL(fileURLWithPath: path), atomically: true, encoding: .utf8) @@ -87,6 +99,24 @@ public struct ObjCInterfaceRequest: Sendable, Equatable { throw ObjCDeclarationLookupError.declarationNotFound(declarationName) } + /// What gives the notes of a declaration kind when `marksSDKSwiftNames` + /// is on and the binary's SDK is readable; `nil` otherwise. + private func sdkSwiftImportNotesProvider(for machOFile: MachOFile, output: some SwiftSectionOutput) async -> (@Sendable (ObjCDeclarationKind) async -> ObjCSwiftImportNotes)? { + guard marksSDKSwiftNames else { return nil } + #if os(macOS) + guard #available(macOS 13.0, *) else { + output.report(SwiftSectionDiagnostic(severity: .warning, message: "warning: --mark-sdk-swift-names needs macOS 13 or later; printing without the SDK's Swift names")) + return nil + } + guard let notesSource = await SDKSwiftImportNotesSource.make(for: machOFile, output: output) else { return nil } + let declarationName = declarationName + return { candidateKind in await notesSource.notes(for: candidateKind, named: declarationName) } + #else + output.report(SwiftSectionDiagnostic(severity: .warning, message: "warning: --mark-sdk-swift-names needs macOS; printing without the SDK's Swift names")) + return nil + #endif + } + /// The Swift side: the image's declaration index, which pairs a class or /// category Swift implements with its Swift definitions. private func runPrintingSwiftImport(output: some SwiftSectionOutput) async throws { diff --git a/Sources/Commands/SwiftSectionKit/ObjC/ObjCInterfaceSession.swift b/Sources/Commands/SwiftSectionKit/ObjC/ObjCInterfaceSession.swift index 8fd58a93d..4722d90af 100644 --- a/Sources/Commands/SwiftSectionKit/ObjC/ObjCInterfaceSession.swift +++ b/Sources/Commands/SwiftSectionKit/ObjC/ObjCInterfaceSession.swift @@ -85,28 +85,34 @@ struct ObjCInterfaceSession { // MARK: - Rendering - func interface(of kind: ObjCDeclarationKind, named name: String) -> SemanticString? { + /// The declaration of `kind` named `name`, with `swiftImportNotes` printed + /// as their macros on a class, protocol or category (structs and unions + /// take none). + func interface(of kind: ObjCDeclarationKind, named name: String, swiftImportNotes: ObjCSwiftImportNotes = ObjCSwiftImportNotes()) -> SemanticString? { switch kind { case .classes: builder.classInterface( named: name, options: options, cTypeReplacements: cTypeReplacements, - ivarOffsetCommentBuilder: ivarOffsetCommentBuilder + ivarOffsetCommentBuilder: ivarOffsetCommentBuilder, + swiftImportNotes: swiftImportNotes ) case .protocols: builder.protocolInterface( named: name, options: options, cTypeReplacements: cTypeReplacements, - ivarOffsetCommentBuilder: ivarOffsetCommentBuilder + ivarOffsetCommentBuilder: ivarOffsetCommentBuilder, + swiftImportNotes: swiftImportNotes ) case .categories: builder.categoryInterface( uniqueName: name, options: options, cTypeReplacements: cTypeReplacements, - ivarOffsetCommentBuilder: ivarOffsetCommentBuilder + ivarOffsetCommentBuilder: ivarOffsetCommentBuilder, + swiftImportNotes: swiftImportNotes ) case .structs: builder.structInterface( diff --git a/Sources/Commands/SwiftSectionKit/ObjC/SDKSwiftImportNotesSource.swift b/Sources/Commands/SwiftSectionKit/ObjC/SDKSwiftImportNotesSource.swift new file mode 100644 index 000000000..fca87e271 --- /dev/null +++ b/Sources/Commands/SwiftSectionKit/ObjC/SDKSwiftImportNotesSource.swift @@ -0,0 +1,61 @@ +#if os(macOS) + +import MachOKit +import MachOKitExtensions +import ObjCDeclarationRendering +import ObjCTypeIndexing +import SwiftTypeNameResolution +import TypeIndexing + +/// The notes `objc interface --mark-sdk-swift-names` prints: what the API +/// notes of the binary's SDK say about how Swift imports a class or protocol +/// and its members, read from the active developer directory. API notes only: +/// no module interface is generated, so no sourcekitd work runs. +@available(macOS 13.0, *) +struct SDKSwiftImportNotesSource: Sendable { + let typeDatabase: TypeDatabase + + /// The source for `machOFile`'s SDK, or `nil` after a warning when the + /// binary names no platform an SDK covers, or this Mac has no SDK for it. + static func make(for machOFile: MachOFile, output: some SwiftSectionOutput) async -> SDKSwiftImportNotesSource? { + guard + let buildPlatform = machOFile.loadCommands.buildVersionCommand?.platform, + let platform = SDKPlatform(buildPlatform) + else { + output.report(SwiftSectionDiagnostic(severity: .warning, message: "warning: --mark-sdk-swift-names: the binary names no platform an SDK covers; printing it without the SDK's Swift names")) + return nil + } + let availability = TypeIndexingAvailability.availability(for: platform) + guard availability.isAvailable else { + output.report(SwiftSectionDiagnostic(severity: .warning, message: "warning: --mark-sdk-swift-names: the active developer directory has no \(platform.rawValue) SDK; printing without the SDK's Swift names")) + return nil + } + let typeDatabase = TypeDatabase(platform: platform) + do { + try await typeDatabase.index(dependencies: [], moduleFilter: { _ in false }) + } catch { + output.report(SwiftSectionDiagnostic(severity: .warning, message: "warning: --mark-sdk-swift-names: reading the \(platform.rawValue) SDK failed (\(error)); printing without the SDK's Swift names")) + return nil + } + return SDKSwiftImportNotesSource(typeDatabase: typeDatabase) + } + + /// The notes for the declaration of `kind` named `name`. A category takes + /// the notes of the class it extends — API notes list category methods + /// under the class — and the builder leaves out the class's own note. + func notes(for kind: ObjCDeclarationKind, named name: String) async -> ObjCSwiftImportNotes { + switch kind { + case .classes: + return await ObjCSwiftImportNotes(apiNotesForClassNamed: name, in: typeDatabase) + case .protocols: + return await ObjCSwiftImportNotes(apiNotesForProtocolNamed: name, in: typeDatabase) + case .categories: + let className = name.split(separator: "(", maxSplits: 1).first.map(String.init) ?? name + return await ObjCSwiftImportNotes(apiNotesForClassNamed: className, in: typeDatabase) + case .structs, .unions: + return ObjCSwiftImportNotes() + } + } +} + +#endif diff --git a/Sources/Commands/SwiftSectionKit/Swift/ABIDiffRequest.swift b/Sources/Commands/SwiftSectionKit/Swift/ABIDiffRequest.swift index c377c9a0b..c9bec9161 100644 --- a/Sources/Commands/SwiftSectionKit/Swift/ABIDiffRequest.swift +++ b/Sources/Commands/SwiftSectionKit/Swift/ABIDiffRequest.swift @@ -5,6 +5,7 @@ import SwiftDiffing import SwiftIndexing import SwiftInterface import Utilities +import Semantic /// `swift-section diff`: compare the Swift ABI of two binaries, or of a binary /// and a persisted baseline. diff --git a/Sources/Commands/SwiftSectionKit/Swift/ABIEvolutionRequest.swift b/Sources/Commands/SwiftSectionKit/Swift/ABIEvolutionRequest.swift index d940fa745..d02fb0a61 100644 --- a/Sources/Commands/SwiftSectionKit/Swift/ABIEvolutionRequest.swift +++ b/Sources/Commands/SwiftSectionKit/Swift/ABIEvolutionRequest.swift @@ -5,6 +5,7 @@ import SwiftDiffing import SwiftIndexing import SwiftInterface import Utilities +import Semantic /// `swift-section evolution`: track the Swift ABI of one module across an /// ordered series of versions. @@ -176,7 +177,7 @@ public struct ABIEvolutionRequest: Sendable, Equatable { /// Why ``ABIEvolutionRequest/AvailabilityAttributes/inferredPlatform`` found /// no one platform to spell the attributes for. Naming the platform with /// ``ABIEvolutionRequest/AvailabilityAttributes/platform(_:)`` avoids both. -public enum AvailabilityPlatformInferenceError: Error, LocalizedError, Sendable, Equatable { +public enum AvailabilityPlatformInferenceError: Swift.Error, LocalizedError, Sendable, Equatable { /// The binary at `path` has no `LC_BUILD_VERSION`, or names a platform /// `@available` has no spelling for, such as DriverKit. case noPlatform(path: String) diff --git a/Sources/Commands/SwiftSectionKit/Swift/DumpRequest.swift b/Sources/Commands/SwiftSectionKit/Swift/DumpRequest.swift index 5a37dd137..7ec11c22c 100644 --- a/Sources/Commands/SwiftSectionKit/Swift/DumpRequest.swift +++ b/Sources/Commands/SwiftSectionKit/Swift/DumpRequest.swift @@ -97,6 +97,10 @@ public struct DumpRequest: Sendable, Equatable { /// A leading header comment: generator, image path, UUID, architecture, /// library-evolution detection, unrecoverable-facts notes. public var emitsHeader: Bool + /// Lays a type that runs past the line width out over several lines, at + /// its brackets, in each declaration (evolution proposal + /// `multiline-type-formatting`). `nil` prints every type on one line. + public var multilineTypeFormatting: MultilineTypeFormatting? /// The comment templates. `nil` keeps the built-in rendering; a module the /// configuration enables also turns its comment kind on. public var commentTransformers: Transformer.SwiftConfiguration? @@ -117,6 +121,7 @@ public struct DumpRequest: Sendable, Equatable { emitsExportStatus: Bool = false, emitsPrivateDeclarationSourceFiles: Bool = false, emitsHeader: Bool = false, + multilineTypeFormatting: MultilineTypeFormatting? = nil, commentTransformers: Transformer.SwiftConfiguration? = nil, destination: ProductDestination = .output ) { @@ -134,6 +139,7 @@ public struct DumpRequest: Sendable, Equatable { self.emitsExportStatus = emitsExportStatus self.emitsPrivateDeclarationSourceFiles = emitsPrivateDeclarationSourceFiles self.emitsHeader = emitsHeader + self.multilineTypeFormatting = multilineTypeFormatting self.commentTransformers = commentTransformers self.destination = destination } @@ -144,7 +150,7 @@ public struct DumpRequest: Sendable, Equatable { public func run(output: some SwiftSectionOutput, environment: SwiftSectionEnvironment) async throws { try await withAccessorThunkResolver(searchPaths: dependencySearchPaths) { let machOFile = try source.load() - let session = DumpSession(output: output, destination: destination) + let session = DumpSession(output: output, destination: destination, multilineTypeFormatting: multilineTypeFormatting) try await dump(machOFile, into: session, environment: environment) try session.finish() } @@ -500,11 +506,13 @@ private enum DumpTopLevelContext { private final class DumpSession { let output: Output let destination: ProductDestination + let multilineTypeFormatting: MultilineTypeFormatting? private var dumpedText = "" - init(output: Output, destination: ProductDestination) { + init(output: Output, destination: ProductDestination, multilineTypeFormatting: MultilineTypeFormatting?) { self.output = output self.destination = destination + self.multilineTypeFormatting = multilineTypeFormatting } /// Dumps one top-level declaration and hands it to the output with what it @@ -513,7 +521,8 @@ private final class DumpSession { func dump(_ topLevelContext: DumpTopLevelContext, using configuration: DumperConfiguration, in machOFile: MachOFile) async throws { let dumpedDeclaration: SemanticString do { - dumpedDeclaration = try await topLevelContext.dump(using: configuration, in: machOFile) + let printedDeclaration = try await topLevelContext.dump(using: configuration, in: machOFile) + dumpedDeclaration = multilineTypeFormatting?.format(printedDeclaration) ?? printedDeclaration } catch { reportError(error) return diff --git a/Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift b/Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift index e52a62377..63d4ddccc 100644 --- a/Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift +++ b/Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift @@ -11,6 +11,8 @@ import OutputTransformer import SwiftOutputTransformer #if os(macOS) import TypeIndexing +import SwiftTypeNameResolution +import Semantic #endif /// `swift-section interface`: generate a `.swiftinterface` from a binary. @@ -37,6 +39,13 @@ public struct InterfaceRequest: Sendable, Equatable { /// Experimental: may fail to parse complex return types. public var parsesOpaqueReturnTypes: Bool public var cModuleNameResolution: CModuleNameResolution + /// Whether a Swift type the SDK moved between modules + /// (`@_originallyDefinedIn`) prints under the module that declares it + /// now (`CoreGraphics.CGFloat` → `CoreFoundation.CGFloat`), for the SDK + /// version the binary was built with. Reads the SDK's textual module + /// interfaces; needs Xcode or the Command Line Tools, not sourcekitd, and + /// is macOS only (evolution proposal `moved-swift-type-modules`). + public var resolvesMovedTypeModules: Bool public var fieldOffsetComments: FieldOffsetComments public var emitsMemberAddresses: Bool /// For class methods, computed properties and non-final stored @@ -73,6 +82,12 @@ public struct InterfaceRequest: Sendable, Equatable { /// `any P.Type`), as the compiler writes a `.swiftinterface`. On by /// default. public var usesExistentialAny: Bool + /// How the types a mangling places in `__C` spell their names: the name + /// Swift code uses (`AnyWeakAttribute`, from the image's own descriptors, + /// under the module `cModuleNameResolution` finds), or the C name every + /// mangled reference carries (`__C.AGWeakAttribute`). Swift names by + /// default (evolution proposal `c-imported-type-name-spelling`). + public var cImportedTypeNameSpelling: CImportedTypeNameSpelling /// What an attached macro generated, as the binary has it: an /// `@Observable` class's registrar, the storage and computed properties of /// its tracked properties, the generated methods and conformance. Off by @@ -87,6 +102,10 @@ public struct InterfaceRequest: Sendable, Equatable { /// A leading header comment: generator, image path, UUID, architecture, /// library-evolution detection, unrecoverable-facts notes. public var emitsHeader: Bool + /// Lays a type that runs past the line width out over several lines, at + /// its brackets (evolution proposal `multiline-type-formatting`). `nil` + /// prints every type on one line. + public var multilineTypeFormatting: MultilineTypeFormatting? public var commentTransformers: Transformer.SwiftConfiguration? public var destination: ProductDestination @@ -96,6 +115,7 @@ public struct InterfaceRequest: Sendable, Equatable { showsCImportedTypes: Bool = false, parsesOpaqueReturnTypes: Bool = false, cModuleNameResolution: CModuleNameResolution = .disabled, + resolvesMovedTypeModules: Bool = false, fieldOffsetComments: FieldOffsetComments = .none, emitsMemberAddresses: Bool = false, emitsVTableOffsets: Bool = false, @@ -108,9 +128,11 @@ public struct InterfaceRequest: Sendable, Equatable { infersObjCOverridesFromSelectorNames: Bool = false, usesModuleSelectors: Bool = false, usesExistentialAny: Bool = true, + cImportedTypeNameSpelling: CImportedTypeNameSpelling = .swiftName, expandsMacros: Bool = false, protocolRequirementPlacement: ProtocolRequirementPlacement = .protocolWhereClause, emitsHeader: Bool = false, + multilineTypeFormatting: MultilineTypeFormatting? = nil, commentTransformers: Transformer.SwiftConfiguration? = nil, destination: ProductDestination = .output ) { @@ -119,6 +141,7 @@ public struct InterfaceRequest: Sendable, Equatable { self.showsCImportedTypes = showsCImportedTypes self.parsesOpaqueReturnTypes = parsesOpaqueReturnTypes self.cModuleNameResolution = cModuleNameResolution + self.resolvesMovedTypeModules = resolvesMovedTypeModules self.fieldOffsetComments = fieldOffsetComments self.emitsMemberAddresses = emitsMemberAddresses self.emitsVTableOffsets = emitsVTableOffsets @@ -131,9 +154,11 @@ public struct InterfaceRequest: Sendable, Equatable { self.infersObjCOverridesFromSelectorNames = infersObjCOverridesFromSelectorNames self.usesModuleSelectors = usesModuleSelectors self.usesExistentialAny = usesExistentialAny + self.cImportedTypeNameSpelling = cImportedTypeNameSpelling self.expandsMacros = expandsMacros self.protocolRequirementPlacement = protocolRequirementPlacement self.emitsHeader = emitsHeader + self.multilineTypeFormatting = multilineTypeFormatting self.commentTransformers = commentTransformers self.destination = destination } @@ -170,6 +195,7 @@ public struct InterfaceRequest: Sendable, Equatable { printConfiguration.infersObjCOverridesFromSelectorNames = infersObjCOverridesFromSelectorNames printConfiguration.usesModuleSelectors = usesModuleSelectors printConfiguration.usesExistentialAny = usesExistentialAny + printConfiguration.cImportedTypeNameSpelling = cImportedTypeNameSpelling printConfiguration.expandsMacros = expandsMacros printConfiguration.protocolRequirementPlacement = protocolRequirementPlacement @@ -204,8 +230,13 @@ public struct InterfaceRequest: Sendable, Equatable { builder.addExtraDataProvider(SwiftInterfaceBuilderOpaqueTypeProvider(machO: machOFile)) } - if case .enabled(let supplementaryAPINotesPaths) = cModuleNameResolution { - addTypeNameProvider(to: builder, machOFile: machOFile, supplementaryAPINotesPaths: supplementaryAPINotesPaths, output: output) + let cImportedSupplementaryAPINotesPaths: [String]? = if case .enabled(let supplementaryAPINotesPaths) = cModuleNameResolution { + supplementaryAPINotesPaths + } else { + nil + } + if cImportedSupplementaryAPINotesPaths != nil || resolvesMovedTypeModules { + addTypeNameProvider(to: builder, machOFile: machOFile, cImportedSupplementaryAPINotesPaths: cImportedSupplementaryAPINotesPaths, output: output) } if !emitsHeader { @@ -221,7 +252,8 @@ public struct InterfaceRequest: Sendable, Equatable { output.reportProgress("Building Swift interface...") - let interfaceString = try await builder.printRoot() + let printedInterface = try await builder.printRoot() + let interfaceString = multilineTypeFormatting?.format(printedInterface) ?? printedInterface output.reportProgress("Swift interface built successfully.") @@ -234,30 +266,50 @@ public struct InterfaceRequest: Sendable, Equatable { } } + /// Attaches the SDK type-name provider: `__C` resolution when + /// `cImportedSupplementaryAPINotesPaths` is non-nil, moved-type + /// resolution when `resolvesMovedTypeModules` is set — one provider and + /// one SDK database for both. private func addTypeNameProvider( to builder: SwiftInterfaceBuilder, machOFile: MachOFile, - supplementaryAPINotesPaths: [String], + cImportedSupplementaryAPINotesPaths: [String]?, output: some SwiftSectionOutput ) { + let flagNames = [ + cImportedSupplementaryAPINotesPaths != nil ? "--resolve-c-module-names" : nil, + resolvesMovedTypeModules ? "--resolve-moved-type-modules" : nil, + ].compactMap(\.self).joined(separator: " and ") #if os(macOS) guard #available(macOS 13.0, *) else { - output.reportWarning("warning: --resolve-c-module-names requires macOS 13 or later") + output.reportWarning("warning: \(flagNames) requires macOS 13 or later") return } + var resolutions: SDKTypeNameResolutions = [] + if cImportedSupplementaryAPINotesPaths != nil { + resolutions.insert(.cImportedModules) + } + if resolvesMovedTypeModules { + resolutions.insert(.movedTypeModules) + } + let supplementaryAPINotesPaths = cImportedSupplementaryAPINotesPaths ?? [] + // Only `__C` resolution reads the dependency images; moved types come + // from the SDK alone. let providerDependencies = SwiftInterfaceBuilderDependencies( machO: machOFile, - searchPaths: [.systemDyldSharedCache], + searchPaths: cImportedSupplementaryAPINotesPaths != nil ? [.systemDyldSharedCache] : [], eventHandlers: output.indexEventHandlers(forInputLabeled: nil) ) - // Dependency resolution against the HOST dyld cache matches install - // names exactly, then bare names; a non-macOS binary's paths mostly - // miss both, which silently guts the SDK-interface source. Said - // aloud, misses named, instead of degrading quietly. - if providerDependencies.dependencies.isEmpty { - output.reportWarning("warning: --resolve-c-module-names resolved no dependency images against this host (non-macOS binary?); attribution will be limited to SDK APINotes and supplementary files") - } else if !providerDependencies.unresolvedLoadNames.isEmpty { - output.reportWarning("warning: --resolve-c-module-names could not resolve \(providerDependencies.unresolvedLoadNames.count) dependency image(s) against this host; their types will not be attributed: \(providerDependencies.unresolvedLoadNames.joined(separator: ", "))") + if cImportedSupplementaryAPINotesPaths != nil { + // Dependency resolution against the HOST dyld cache matches + // install names exactly, then bare names; a non-macOS binary's + // paths mostly miss both, which silently guts the SDK-interface + // source. Said aloud, misses named, instead of degrading quietly. + if providerDependencies.dependencies.isEmpty { + output.reportWarning("warning: --resolve-c-module-names resolved no dependency images against this host (non-macOS binary?); attribution will be limited to SDK APINotes and supplementary files") + } else if !providerDependencies.unresolvedLoadNames.isEmpty { + output.reportWarning("warning: --resolve-c-module-names could not resolve \(providerDependencies.unresolvedLoadNames.count) dependency image(s) against this host; their types will not be attributed: \(providerDependencies.unresolvedLoadNames.joined(separator: ", "))") + } } // A bad supplementary path is otherwise only os_log'd by the library // floor; a mistyped path or a broken YAML deserves the same warning @@ -278,13 +330,13 @@ public struct InterfaceRequest: Sendable, Equatable { } } let supplementaryAPINotesURLs = supplementaryAPINotesPaths.map { URL(fileURLWithPath: $0) } - if let typeNameProvider = SwiftInterfaceBuilderTypeNameProvider(machO: machOFile, dependencies: providerDependencies, supplementaryAPINotesURLs: supplementaryAPINotesURLs) { + if let typeNameProvider = SwiftInterfaceBuilderTypeNameProvider(machO: machOFile, dependencies: providerDependencies, resolutions: resolutions, supplementaryAPINotesURLs: supplementaryAPINotesURLs) { builder.addExtraDataProvider(typeNameProvider) } else { - output.reportWarning("warning: --resolve-c-module-names ignored: the binary carries no build-version command mapping to a known SDK platform") + output.reportWarning("warning: \(flagNames) ignored: the binary carries no build-version command mapping to a known SDK platform") } #else - output.reportWarning("warning: --resolve-c-module-names is only available on macOS") + output.reportWarning("warning: \(flagNames) is only available on macOS") #endif } } diff --git a/Sources/Declaration/SwiftAttributeInference/TypeAttributeInferrer.swift b/Sources/Declaration/SwiftAttributeInference/TypeAttributeInferrer.swift index 39488eea1..c0daa65df 100644 --- a/Sources/Declaration/SwiftAttributeInference/TypeAttributeInferrer.swift +++ b/Sources/Declaration/SwiftAttributeInference/TypeAttributeInferrer.swift @@ -1,6 +1,7 @@ import SwiftDeclaration import MachOSwiftSection import Demangling +import SwiftObjCInterop /// Infers type-level Swift attributes by analyzing a `TypeDefinition`'s members and metadata flags. /// diff --git a/Sources/Declaration/SwiftDeclaration/Events/SwiftIndexEvents.swift b/Sources/Declaration/SwiftDeclaration/Events/SwiftIndexEvents.swift index 7466339be..0748eff76 100644 --- a/Sources/Declaration/SwiftDeclaration/Events/SwiftIndexEvents.swift +++ b/Sources/Declaration/SwiftDeclaration/Events/SwiftIndexEvents.swift @@ -90,15 +90,15 @@ public enum SwiftIndexEvents { @Loggable(.private, subsystem: "com.machoswiftsection.swift-declaration", category: "SwiftIndexEvents.unhandled") public final class Dispatcher: Sendable { @Mutex - private var handlers: [Handler] = [] + private var handlers: [any Handler] = [] public init() {} - public func addHandler(_ handler: Handler) { + public func addHandler(_ handler: any Handler) { handlers.append(handler) } - public func addHandlers(_ newHandlers: [Handler]) { + public func addHandlers(_ newHandlers: [any Handler]) { handlers.append(contentsOf: newHandlers) } diff --git a/Sources/Declaration/SwiftDeclaration/Extensions/DemanglingNode+StoredVariable.swift b/Sources/Declaration/SwiftDeclaration/Extensions/DemanglingNode+StoredVariable.swift index ffcbf2ebe..3073d4bf6 100644 --- a/Sources/Declaration/SwiftDeclaration/Extensions/DemanglingNode+StoredVariable.swift +++ b/Sources/Declaration/SwiftDeclaration/Extensions/DemanglingNode+StoredVariable.swift @@ -1,4 +1,5 @@ import Demangling +import SwiftSymbols extension DemanglingNode where Self: Sequence { var isStoredVariable: Bool { diff --git a/Sources/Declaration/SwiftDeclaration/Extensions/FieldRecord+DemangledType.swift b/Sources/Declaration/SwiftDeclaration/Extensions/FieldRecord+DemangledType.swift index 6e6ab7a99..a0539fe7f 100644 --- a/Sources/Declaration/SwiftDeclaration/Extensions/FieldRecord+DemangledType.swift +++ b/Sources/Declaration/SwiftDeclaration/Extensions/FieldRecord+DemangledType.swift @@ -3,6 +3,7 @@ import MachOSwiftSection @_spi(Internals) import SwiftSymbols @_spi(Internals) import SwiftInspection import Semantic +import SwiftDeclarationRendering extension FieldRecord { package func demangledTypeNode(in context: some ReadingContext) throws -> Node { try SymbolicDemangler.demangleType(for: mangledTypeName(in: context), in: context) diff --git a/Sources/Declaration/SwiftDeclaration/Indexing/Building/MemberSymbolBucketing.swift b/Sources/Declaration/SwiftDeclaration/Indexing/Building/MemberSymbolBucketing.swift index 5aed201e9..4746d1b02 100644 --- a/Sources/Declaration/SwiftDeclaration/Indexing/Building/MemberSymbolBucketing.swift +++ b/Sources/Declaration/SwiftDeclaration/Indexing/Building/MemberSymbolBucketing.swift @@ -1,5 +1,6 @@ @_spi(Internals) import SwiftSymbols import OrderedCollections +import Demangling extension Definition { func addSymbol(_ symbol: MemberSymbol, memberSymbolsByKind: inout OrderedDictionary, inExtension: Bool) { diff --git a/Sources/Declaration/SwiftDeclaration/Indexing/Building/ObjCMemberMatcher.swift b/Sources/Declaration/SwiftDeclaration/Indexing/Building/ObjCMemberMatcher.swift index 8d32cfdb9..16431a356 100644 --- a/Sources/Declaration/SwiftDeclaration/Indexing/Building/ObjCMemberMatcher.swift +++ b/Sources/Declaration/SwiftDeclaration/Indexing/Building/ObjCMemberMatcher.swift @@ -2,6 +2,7 @@ import Demangling import SwiftInspection import SwiftObjCInterop import SwiftThunkAnalysis +import SwiftSymbols /// Joins an `ObjCMemberTable` — the class's ObjC method table tied to its /// Swift members — onto already-built member definitions (evolution diff --git a/Sources/Declaration/SwiftDeclaration/Indexing/Building/StandInMemberSymbolBuilder.swift b/Sources/Declaration/SwiftDeclaration/Indexing/Building/StandInMemberSymbolBuilder.swift index e61087c92..378021943 100644 --- a/Sources/Declaration/SwiftDeclaration/Indexing/Building/StandInMemberSymbolBuilder.swift +++ b/Sources/Declaration/SwiftDeclaration/Indexing/Building/StandInMemberSymbolBuilder.swift @@ -2,6 +2,7 @@ import MachOSwiftSection import OrderedCollections @_spi(Internals) import SwiftSymbols +import Foundation /// Member symbols that stand in for an implementation symbol the image does /// not have. diff --git a/Sources/Declaration/SwiftDeclaration/Indexing/ExtensionDefinition/ExtensionDefinition+Indexing.swift b/Sources/Declaration/SwiftDeclaration/Indexing/ExtensionDefinition/ExtensionDefinition+Indexing.swift index 355edf5fa..c20b8e924 100644 --- a/Sources/Declaration/SwiftDeclaration/Indexing/ExtensionDefinition/ExtensionDefinition+Indexing.swift +++ b/Sources/Declaration/SwiftDeclaration/Indexing/ExtensionDefinition/ExtensionDefinition+Indexing.swift @@ -3,6 +3,7 @@ import MachOSwiftSection import OrderedCollections @_spi(Internals) import SwiftSymbols @_spi(Internals) import SwiftInspection +import BinaryParseSupport extension ExtensionDefinition: OnceIndexedDefinition { /// Resolves a conformance's resilient witnesses to members. Idempotent, diff --git a/Sources/Declaration/SwiftDeclaration/Indexing/TypeDefinition/TypeDefinition+ClassDispatch.swift b/Sources/Declaration/SwiftDeclaration/Indexing/TypeDefinition/TypeDefinition+ClassDispatch.swift index 981c08663..62bae730a 100644 --- a/Sources/Declaration/SwiftDeclaration/Indexing/TypeDefinition/TypeDefinition+ClassDispatch.swift +++ b/Sources/Declaration/SwiftDeclaration/Indexing/TypeDefinition/TypeDefinition+ClassDispatch.swift @@ -4,6 +4,7 @@ import OrderedCollections import SwiftDeclarationRendering @_spi(Internals) import SwiftSymbols @_spi(Internals) import SwiftInspection +import BinaryParseSupport extension TypeDefinition { /// The dynamic-dispatch lookups this type's vtable and override tables diff --git a/Sources/Declaration/SwiftDeclaration/Indexing/TypeDefinition/TypeDefinition+Indexing.swift b/Sources/Declaration/SwiftDeclaration/Indexing/TypeDefinition/TypeDefinition+Indexing.swift index 77ed82a56..c10c69dd1 100644 --- a/Sources/Declaration/SwiftDeclaration/Indexing/TypeDefinition/TypeDefinition+Indexing.swift +++ b/Sources/Declaration/SwiftDeclaration/Indexing/TypeDefinition/TypeDefinition+Indexing.swift @@ -7,6 +7,7 @@ import SwiftThunkAnalysis @_spi(Internals) import SwiftSymbols @_spi(Internals) import SwiftInspection import SwiftObjCInterop +import BinaryParseSupport extension TypeDefinition: OnceIndexedDefinition { /// Fills the definition from the image: fields, members, the facts that diff --git a/Sources/Declaration/SwiftDeclaration/Model/ExportStatus.swift b/Sources/Declaration/SwiftDeclaration/Model/ExportStatus.swift index e07d3f769..943ebe8c5 100644 --- a/Sources/Declaration/SwiftDeclaration/Model/ExportStatus.swift +++ b/Sources/Declaration/SwiftDeclaration/Model/ExportStatus.swift @@ -242,7 +242,11 @@ extension ExportStatus { in machO: some MachOSwiftSectionRepresentableWithCache ) -> Bool { var parent = try? descriptor.parent(in: machO.context) + var walkedParentCount = 0 while let parentDescriptor = parent?.resolved { + // A chain no compiler emits leads back into itself. + walkedParentCount += 1 + guard walkedParentCount <= ContextDescriptorParentChain.maximumLength else { return false } if parentDescriptor.isAnonymous { return true } diff --git a/Sources/Declaration/SwiftDeclaration/Model/Members/OrderedMember.swift b/Sources/Declaration/SwiftDeclaration/Model/Members/OrderedMember.swift index 036afcd85..d1d54d1ff 100644 --- a/Sources/Declaration/SwiftDeclaration/Model/Members/OrderedMember.swift +++ b/Sources/Declaration/SwiftDeclaration/Model/Members/OrderedMember.swift @@ -1,4 +1,5 @@ import MachOSwiftSection +import SwiftSymbols public enum OrderedMember: Sendable { case allocator(FunctionDefinition) diff --git a/Sources/Declaration/SwiftDeclaration/Model/Members/ResolvedObjCMemberFacts.swift b/Sources/Declaration/SwiftDeclaration/Model/Members/ResolvedObjCMemberFacts.swift index 364e26d89..7659d17d9 100644 --- a/Sources/Declaration/SwiftDeclaration/Model/Members/ResolvedObjCMemberFacts.swift +++ b/Sources/Declaration/SwiftDeclaration/Model/Members/ResolvedObjCMemberFacts.swift @@ -1,5 +1,6 @@ import SwiftInspection import SwiftObjCInterop +import MachOSwiftSection /// A member's ObjC-derived source facts, resolved against one consumer's /// verdict on NAME-only evidence (evolution proposal diff --git a/Sources/Declaration/SwiftIndexing/SwiftDeclarationIndexer+ObjCImportedDefinitions.swift b/Sources/Declaration/SwiftIndexing/SwiftDeclarationIndexer+ObjCImportedDefinitions.swift index 603a12a44..70b676d9e 100644 --- a/Sources/Declaration/SwiftIndexing/SwiftDeclarationIndexer+ObjCImportedDefinitions.swift +++ b/Sources/Declaration/SwiftIndexing/SwiftDeclarationIndexer+ObjCImportedDefinitions.swift @@ -5,6 +5,7 @@ import MachOSwiftSection @_spi(Internals) import SwiftInspection import SwiftObjCInterop import SwiftDeclaration +import OrderedCollections /// The image's Objective-C classes, categories and protocols as Swift imports /// them (evolution proposal `objc-imported-declarations`). A definition is diff --git a/Sources/Declaration/SwiftIndexing/SwiftDeclarationIndexer.swift b/Sources/Declaration/SwiftIndexing/SwiftDeclarationIndexer.swift index e77b3e5f7..16a8b6ff5 100644 --- a/Sources/Declaration/SwiftIndexing/SwiftDeclarationIndexer.swift +++ b/Sources/Declaration/SwiftIndexing/SwiftDeclarationIndexer.swift @@ -183,7 +183,7 @@ public final class SwiftDeclarationIndexer Name? { - switch category { - case .objcClass: - return classSwiftNamesByCName[cName] ?? valueTypeSwiftNamesByCName[cName] - case .objcProtocol: - return protocolSwiftNamesByCName[cName] - case .valueType: - return valueTypeSwiftNamesByCName[cName] - case .other: - return valueTypeSwiftNamesByCName[cName] ?? classSwiftNamesByCName[cName] - } - } - - package func cName(forSwiftName swiftName: String) -> Name? { - cNamesBySwiftName[swiftName] - } - - package func moduleName(forCName cName: String) -> String? { - moduleNamesByCName[cName] - } - - private mutating func registerEntities( - _ entities: [some CommonEntity]?, - declaredIn moduleName: String, - into renameTable: WritableKeyPath - ) { - guard let entities else { return } - for entity in entities { - let cName = entity.name - moduleNamesByCName[cName] = moduleName - guard let swiftName = entity.swiftName, entity.isSwiftPrivate != true else { continue } - self[keyPath: renameTable][cName] = Name(moduleName: moduleName, name: swiftName) - cNamesBySwiftName[swiftName] = Name(moduleName: moduleName, name: cName) - } - } -} - -#endif diff --git a/Sources/Declaration/TypeIndexing/InterfaceDeclarationNode.swift b/Sources/Declaration/TypeIndexing/InterfaceDeclarationNode.swift deleted file mode 100644 index 1fcfb56b6..000000000 --- a/Sources/Declaration/TypeIndexing/InterfaceDeclarationNode.swift +++ /dev/null @@ -1,65 +0,0 @@ -#if os(macOS) - -/// One declaration node of a SourceKit-generated module interface, converted -/// out of the `editor.open.interface` response's `key.substructure` tree into -/// a plain value so extraction is a pure, testable function over it. -/// -/// Only the declaration kinds the type-name extractor distinguishes are -/// modeled; everything else collapses to ``Kind/other`` and is never descended -/// into (nested types occur only inside type bodies and extensions). -@available(macOS 13.0, *) -package struct InterfaceDeclarationNode: Sendable, Equatable { - package enum Kind: Sendable, Equatable { - /// `struct`, `class`, `actor`, `enum`, or `protocol` — a declaration - /// whose (qualified) name enters the index. - case typeDeclaration - /// `typealias` — enters the index by name but declares no members. - case typeAlias - /// An `extension` of some type: contributes its extended type name as - /// a qualification prefix for nested declarations, but is not itself - /// an indexed type. - case `extension` - /// Anything else (functions, properties, enum cases, parameters, …). - case other - } - - package let kind: Kind - - /// The declaration's name as SourceKit reports it. For an extension this - /// is the extended type reference, which may already be dot-qualified - /// (`extension Foo.Bar`). - package let name: String? - - package let children: [InterfaceDeclarationNode] - - package init(kind: Kind, name: String?, children: [InterfaceDeclarationNode] = []) { - self.kind = kind - self.name = name - self.children = children - } - - /// Maps a SourceKit declaration-kind UID string - /// (`source.lang.swift.decl.*`) onto the extractor's kind vocabulary. - package static func kind(forUIDString uidString: String) -> Kind { - switch uidString { - case "source.lang.swift.decl.struct", - "source.lang.swift.decl.class", - "source.lang.swift.decl.actor", - "source.lang.swift.decl.enum", - "source.lang.swift.decl.protocol": - return .typeDeclaration - case "source.lang.swift.decl.typealias": - return .typeAlias - case "source.lang.swift.decl.extension", - "source.lang.swift.decl.extension.struct", - "source.lang.swift.decl.extension.class", - "source.lang.swift.decl.extension.enum", - "source.lang.swift.decl.extension.protocol": - return .extension - default: - return .other - } - } -} - -#endif diff --git a/Sources/Declaration/TypeIndexing/InterfaceTypeNameExtractor.swift b/Sources/Declaration/TypeIndexing/InterfaceTypeNameExtractor.swift deleted file mode 100644 index 3b222cfde..000000000 --- a/Sources/Declaration/TypeIndexing/InterfaceTypeNameExtractor.swift +++ /dev/null @@ -1,53 +0,0 @@ -#if os(macOS) - -/// Extracts the fully-qualified type names a SourceKit-generated module -/// interface declares, from its ``InterfaceDeclarationNode`` tree. -/// -/// Qualification follows the node parent chain: a type nested in a type -/// prefixes the outer name, and a type nested in an extension prefixes the -/// *extended* type's (possibly already dot-qualified) name — so -/// `extension Foo.Bar { public struct Baz }` yields `Foo.Bar.Baz`. The -/// extension node itself is never an indexed name. -/// -/// Only type declarations, type aliases, and extensions are descended into; -/// nothing nested in a function or accessor is reachable in a generated -/// interface, and descending into ``InterfaceDeclarationNode/Kind/other`` -/// nodes would only surface generic parameters and locals. -@available(macOS 13.0, *) -package enum InterfaceTypeNameExtractor { - package static func fullyQualifiedTypeNames(in declarations: [InterfaceDeclarationNode]) -> [String] { - var typeNames: [String] = [] - for declaration in declarations { - appendTypeNames(of: declaration, qualificationPrefix: nil, into: &typeNames) - } - return typeNames - } - - private static func appendTypeNames( - of declaration: InterfaceDeclarationNode, - qualificationPrefix: String?, - into typeNames: inout [String] - ) { - switch declaration.kind { - case .typeDeclaration, .typeAlias: - guard let name = declaration.name, !name.isEmpty else { return } - let qualifiedName = qualificationPrefix.map { "\($0).\(name)" } ?? name - typeNames.append(qualifiedName) - for child in declaration.children { - appendTypeNames(of: child, qualificationPrefix: qualifiedName, into: &typeNames) - } - case .extension: - // Not itself an indexed name; its extended-type name (already - // qualified when SourceKit prints `extension Foo.Bar`) qualifies - // the nested declarations. - guard let extendedTypeName = declaration.name, !extendedTypeName.isEmpty else { return } - for child in declaration.children { - appendTypeNames(of: child, qualificationPrefix: extendedTypeName, into: &typeNames) - } - case .other: - return - } - } -} - -#endif diff --git a/Sources/Declaration/TypeIndexing/ModuleIndexCache.swift b/Sources/Declaration/TypeIndexing/ModuleIndexCache.swift deleted file mode 100644 index 3e238f014..000000000 --- a/Sources/Declaration/TypeIndexing/ModuleIndexCache.swift +++ /dev/null @@ -1,98 +0,0 @@ -#if os(macOS) - -import Foundation -import FoundationToolbox - -/// One module's cached extraction: what the indexer needs at query time, -/// without the interface text it was extracted from. -@available(macOS 13.0, *) -package struct ModuleIndexCacheEntry: Codable, Sendable { - package let moduleName: String - - /// Fully-qualified type names the module (and its indexed submodules) - /// declares, as extracted from the generated interface's substructure. - package let typeNames: [String] - - package let subModuleNames: [String] - - /// Bumped when extraction behavior changes; a mismatching entry is - /// ignored so stale semantics never survive a library update. - package let generatorVersion: Int - - package static let currentGeneratorVersion = 1 - - package init(moduleName: String, typeNames: [String], subModuleNames: [String], generatorVersion: Int = Self.currentGeneratorVersion) { - self.moduleName = moduleName - self.typeNames = typeNames - self.subModuleNames = subModuleNames - self.generatorVersion = generatorVersion - } -} - -/// Per-module JSON cache of extraction results, segmented per platform and -/// per exact SDK build so an Xcode update can never serve stale entries: -/// -/// ``` -/// Application Support/MachOSwiftSection/SDKIndexer//-/.json -/// ``` -/// -/// Every entry stands alone — there is no whole-SDK completion marker, so a -/// partially-warmed cache serves what it has and misses the rest. All cache -/// I/O is best-effort: a failure degrades to regeneration, never to an error. -@available(macOS 13.0, *) -package struct ModuleIndexCache: Sendable { - package let directoryURL: URL - - package init(platform: SDKPlatform, sdkSettings: SDKSettings) { - self.init( - directoryURL: URL.applicationSupportDirectory - .appending(component: "MachOSwiftSection") - .appending(component: "SDKIndexer") - .appending(component: platform.rawValue) - .appending(component: sdkSettings.cacheDirectoryComponent) - ) - } - - /// Direct-directory form, the seam tests use to keep cache I/O out of the - /// real Application Support tree. - package init(directoryURL: URL) { - self.directoryURL = directoryURL - } - - private func entryURL(forModuleNamed moduleName: String) -> URL { - directoryURL.appending(component: "\(moduleName).json") - } - - package func entry(forModuleNamed moduleName: String) -> ModuleIndexCacheEntry? { - let entryURL = entryURL(forModuleNamed: moduleName) - guard let entryData = try? Data(contentsOf: entryURL) else { return nil } - do { - let entry = try JSONDecoder().decode(ModuleIndexCacheEntry.self, from: entryData) - guard entry.generatorVersion == ModuleIndexCacheEntry.currentGeneratorVersion else { return nil } - return entry - } catch { - #log(.error, "Discarding undecodable cache entry at \(entryURL.path(percentEncoded: false), privacy: .public): \(String(describing: error), privacy: .public)") - return nil - } - } - - package func store(_ entry: ModuleIndexCacheEntry) { - do { - try FileManager.default.createDirectory(at: directoryURL, withIntermediateDirectories: true) - let entryData = try JSONEncoder().encode(entry) - try entryData.write(to: entryURL(forModuleNamed: entry.moduleName), options: .atomic) - } catch { - #log(.error, "Failed to store cache entry for module \(entry.moduleName, privacy: .public): \(String(describing: error), privacy: .public)") - } - } -} - -// Protocol-form `@Loggable` — see the note in SDKIndexer.swift: the direct -// type form clashes with the `@available(macOS 13.0, *)` scope. -@Loggable(.fileprivate, subsystem: "com.machoswiftsection.typeindexing", category: "ModuleIndexCache") -fileprivate protocol ModuleIndexCacheLogging {} - -@available(macOS 13.0, *) -extension ModuleIndexCache: ModuleIndexCacheLogging {} - -#endif diff --git a/Sources/Declaration/TypeIndexing/ModuleInterfaceIndexer.swift b/Sources/Declaration/TypeIndexing/ModuleInterfaceIndexer.swift deleted file mode 100644 index 29ecd31af..000000000 --- a/Sources/Declaration/TypeIndexing/ModuleInterfaceIndexer.swift +++ /dev/null @@ -1,88 +0,0 @@ -#if os(macOS) - -import Foundation -import FoundationToolbox - -/// The per-module indexing pipeline: cache lookup → interface generation → -/// type-name extraction → cache store. Runs only for modules the caller's -/// dependency filter selected — this is where the expensive sourcekitd work -/// lives, deliberately downstream of the filter. -@available(macOS 13.0, *) -package struct ModuleInterfaceIndexer: Sendable { - package typealias InterfaceGenerator = @Sendable (_ moduleName: String) async throws -> SourceKitManager.GeneratedModuleInterface - - package let platform: SDKPlatform - package let sdkSettings: SDKSettings - package let cache: ModuleIndexCache - private let generateInterface: InterfaceGenerator - - package init(platform: SDKPlatform, sdkSettings: SDKSettings, cache: ModuleIndexCache, sourceKitManager: SourceKitManager) { - self.init(platform: platform, sdkSettings: sdkSettings, cache: cache) { moduleName in - try await sourceKitManager.interface(for: moduleName, platform: platform, sdkSettings: sdkSettings) - } - } - - /// Test seam: substitutes the sourcekitd-backed generation with an - /// arbitrary closure, so the cache-write discipline (partial entries are - /// never stored) is testable without sourcekitd. - package init(platform: SDKPlatform, sdkSettings: SDKSettings, cache: ModuleIndexCache, interfaceGenerator: @escaping InterfaceGenerator) { - self.platform = platform - self.sdkSettings = sdkSettings - self.cache = cache - self.generateInterface = interfaceGenerator - } - - /// Indexes one module, returning `nil` when its interface cannot be - /// generated — the caller skips that module rather than failing the whole - /// indexing run (one exotic module must not blank the entire database). - /// - /// Submodule interfaces (`Foundation.NSObject`-style imports of the - /// module's own submodules) are generated and folded into the same entry: - /// attribution always names the top-level module, which is what a - /// qualified `Foundation.NSString` spelling needs. - package func indexEntry(forModuleNamed moduleName: String) async -> ModuleIndexCacheEntry? { - if let cachedEntry = cache.entry(forModuleNamed: moduleName) { - return cachedEntry - } - do { - let interface = try await generateInterface(moduleName) - var typeNames = InterfaceTypeNameExtractor.fullyQualifiedTypeNames(in: interface.declarations) - let subModulePrefix = "\(moduleName)." - let subModuleNames = interface.importedModuleNames.filter { $0.hasPrefix(subModulePrefix) } - var allSubModulesSucceeded = true - for subModuleName in subModuleNames { - do { - let subModuleInterface = try await generateInterface(subModuleName) - typeNames.append(contentsOf: InterfaceTypeNameExtractor.fullyQualifiedTypeNames(in: subModuleInterface.declarations)) - } catch { - allSubModulesSucceeded = false - #log(.error, "Skipping submodule \(subModuleName, privacy: .public) of \(moduleName, privacy: .public): \(String(describing: error), privacy: .public)") - } - } - let entry = ModuleIndexCacheEntry(moduleName: moduleName, typeNames: typeNames, subModuleNames: subModuleNames) - // A partial entry (a submodule's generation failed, e.g. one - // sourcekitd timeout) is served for THIS run but never cached: - // the cache has no completeness marker, so storing it would - // freeze the gap until the SDK or generator version changes. - if allSubModulesSucceeded { - cache.store(entry) - } else { - #log(.error, "Not caching partial entry for \(moduleName, privacy: .public); submodule extraction will retry next run") - } - return entry - } catch { - #log(.error, "Skipping module \(moduleName, privacy: .public): interface generation failed: \(String(describing: error), privacy: .public)") - return nil - } - } -} - -// Protocol-form `@Loggable` — see the note in SDKIndexer.swift: the direct -// type form clashes with the `@available(macOS 13.0, *)` scope. -@Loggable(.fileprivate, subsystem: "com.machoswiftsection.typeindexing", category: "ModuleInterfaceIndexer") -fileprivate protocol ModuleInterfaceIndexerLogging {} - -@available(macOS 13.0, *) -extension ModuleInterfaceIndexer: ModuleInterfaceIndexerLogging {} - -#endif diff --git a/Sources/Declaration/TypeIndexing/SDKIndexer.swift b/Sources/Declaration/TypeIndexing/SDKIndexer.swift deleted file mode 100644 index 44291bc23..000000000 --- a/Sources/Declaration/TypeIndexing/SDKIndexer.swift +++ /dev/null @@ -1,121 +0,0 @@ -#if os(macOS) - -import APINotes -import Foundation -import FoundationToolbox - -/// A Swift module discovered in an SDK: just its name and on-disk location. -/// Discovery is deliberately this cheap — interface generation (the expensive -/// sourcekitd work) happens later, only for the modules a binary's dependency -/// filter selects. -@available(macOS 13.0, *) -package struct SwiftModuleDescriptor: Sendable, Hashable { - package let moduleName: String - package let path: String -} - -/// A parsed `.apinotes` file: the compiler's authoritative record of how a -/// module's C declarations surface in Swift (renames, availability). -@available(macOS 13.0, *) -package struct APINotesFile: Sendable { - package let path: String - package let moduleName: String - package let apiNotesModule: APINotes.Module - - package init(path: String) throws { - let apiNotesModule = try APINotes.Module(contentsOf: URL(fileURLWithPath: path)) - self.path = path - self.moduleName = apiNotesModule.name - self.apiNotesModule = apiNotesModule - } -} - -extension APINotes.Module: @unchecked @retroactive Sendable {} - -/// Everything one SDK scan finds: Swift modules (by name and path only) and -/// parsed APINotes files. -@available(macOS 13.0, *) -package struct SDKDiscovery: Sendable { - package let modules: [SwiftModuleDescriptor] - package let apiNotesFiles: [APINotesFile] -} - -/// Walks an SDK's module-bearing directories and reports what is there. -/// -/// This is pure file-system discovery — it never touches sourcekitd, so a full -/// SDK scan is fast. The historical design generated every discovered module's -/// interface *during* the scan, which made first-time indexing hour-scale and -/// made the caller's module filter pointless (evolution proposal 0009). -@available(macOS 13.0, *) -package struct SDKIndexer { - package let platform: SDKPlatform - - /// SDK-relative directories scanned for `.swiftmodule` and `.apinotes` - /// entries, in priority order (an earlier hit wins a module-name tie). - package let searchPaths: [String] - - package init( - platform: SDKPlatform, - searchPaths: [String] = [ - "usr/include", - "usr/lib/swift", - "System/Library/Frameworks", - "System/Library/PrivateFrameworks", - ] - ) { - self.platform = platform - self.searchPaths = searchPaths - } - - package func discover(sdkSettings: SDKSettings) -> SDKDiscovery { - var modulesByName: [String: SwiftModuleDescriptor] = [:] - var orderedModules: [SwiftModuleDescriptor] = [] - var apiNotesFiles: [APINotesFile] = [] - let fileManager = FileManager.default - - for searchPath in searchPaths { - let searchURL = URL(fileURLWithPath: sdkSettings.sdkPath).appending(path: searchPath) - guard fileManager.fileExists(atPath: searchURL.path(percentEncoded: false)) else { continue } - guard let enumerator = fileManager.enumerator(at: searchURL, includingPropertiesForKeys: nil) else { continue } - - while let entryURL = enumerator.nextObject() as? URL { - switch entryURL.pathExtension { - case "swiftmodule": - // A `.swiftmodule` is a directory of per-architecture - // binaries; nothing inside it is a further module. - enumerator.skipDescendants() - let moduleName = entryURL.deletingPathExtension().lastPathComponent - guard modulesByName[moduleName] == nil else { continue } - let descriptor = SwiftModuleDescriptor(moduleName: moduleName, path: entryURL.path(percentEncoded: false)) - modulesByName[moduleName] = descriptor - orderedModules.append(descriptor) - case "apinotes": - do { - let apiNotesFile = try APINotesFile(path: entryURL.path(percentEncoded: false)) - apiNotesFiles.append(apiNotesFile) - } catch { - #log(.error, "Skipping unparsable APINotes file at \(entryURL.path(percentEncoded: false), privacy: .public): \(String(describing: error), privacy: .public)") - } - default: - continue - } - } - } - - #log(.info, "SDK discovery (\(self.platform.rawValue, privacy: .public) \(sdkSettings.cacheDirectoryComponent, privacy: .public)): \(orderedModules.count) Swift modules, \(apiNotesFiles.count) APINotes files") - return SDKDiscovery(modules: orderedModules, apiNotesFiles: apiNotesFiles) - } -} - -// Protocol-form `@Loggable`: the macro's direct type form expands a static -// stored `logger` carrying its own availability annotation, which an -// `@available(macOS 13.0, *)` type rejects ("cannot be more available than -// enclosing scope"). The un-annotated protocol sidesteps that; the annotated -// extension scopes the conformance. -@Loggable(.fileprivate, subsystem: "com.machoswiftsection.typeindexing", category: "SDKIndexer") -fileprivate protocol SDKIndexerLogging {} - -@available(macOS 13.0, *) -extension SDKIndexer: SDKIndexerLogging {} - -#endif diff --git a/Sources/Declaration/TypeIndexing/SDKPlatform.swift b/Sources/Declaration/TypeIndexing/SDKPlatform.swift deleted file mode 100644 index 562393fd1..000000000 --- a/Sources/Declaration/TypeIndexing/SDKPlatform.swift +++ /dev/null @@ -1,115 +0,0 @@ -#if os(macOS) - -import Foundation - -/// An Apple SDK the indexer can point SourceKit at, named by its -/// `xcrun --sdk` identifier. -@available(macOS 13.0, *) -package enum SDKPlatform: String, CaseIterable, Hashable, Codable, Sendable { - case macOS = "macosx" - case iOS = "iphoneos" - case tvOS = "appletvos" - case watchOS = "watchos" - case visionOS = "xros" - case driverKit = "driverkit" - case iOSSimulator = "iphonesimulator" - case tvOSSimulator = "appletvsimulator" - case watchOSSimulator = "watchsimulator" - case visionOSSimulator = "xrsimulator" - - /// The on-disk root of this platform's SDK in the active Xcode. - package func sdkPath() throws -> String { - try Subprocess.xcrun(["--show-sdk-path", "--sdk", rawValue]) - } - - /// The settings of this platform's SDK in the active Xcode. Reads - /// `SDKSettings.plist` once per call; callers cache the result. - package func sdkSettings() throws -> SDKSettings { - try SDKSettings(sdkPath: sdkPath()) - } -} - -/// The subset of an SDK's `SDKSettings.plist` the indexer consumes: enough to -/// form a compiler target triple and to version the on-disk index cache. -@available(macOS 13.0, *) -package struct SDKSettings: Sendable { - package let sdkPath: String - - /// The SDK's marketing version, e.g. `26.5`. - package let version: String - - /// The SDK's build identifier, e.g. `25F76`. Distinguishes beta builds - /// that share a marketing version. Absent from some SDKs. - package let productBuildVersion: String? - - enum Error: Swift.Error { - case malformedSDKSettings(path: String) - } - - /// Test seam: constructs settings without reading an `SDKSettings.plist`. - package init(sdkPath: String, version: String, productBuildVersion: String?) { - self.sdkPath = sdkPath - self.version = version - self.productBuildVersion = productBuildVersion - } - - package init(sdkPath: String) throws { - let settingsPlistURL = URL(fileURLWithPath: sdkPath).appending(component: "SDKSettings.plist") - let settingsPlistData = try Data(contentsOf: settingsPlistURL) - guard - let settingsPlist = try PropertyListSerialization.propertyList(from: settingsPlistData, format: nil) as? [String: Any], - let version = settingsPlist["Version"] as? String - else { - throw Error.malformedSDKSettings(path: settingsPlistURL.path(percentEncoded: false)) - } - self.sdkPath = sdkPath - self.version = version - self.productBuildVersion = settingsPlist["ProductBuildVersion"] as? String - } - - /// One path component identifying this exact SDK build, used to segment - /// the on-disk index cache so an Xcode update never serves stale entries. - package var cacheDirectoryComponent: String { - if let productBuildVersion { - return "\(version)-\(productBuildVersion)" - } - return version - } - - /// The compiler target triple for `platform` at this SDK's version, for - /// the host architecture. - package func targetTriple(for platform: SDKPlatform) -> String { - let architecture: String - #if arch(x86_64) - architecture = "x86_64" - #elseif arch(arm64) - architecture = "arm64" - #else - architecture = "unknown" - #endif - switch platform { - case .macOS: - return "\(architecture)-apple-macos\(version)" - case .iOS: - return "\(architecture)-apple-ios\(version)" - case .tvOS: - return "\(architecture)-apple-tvos\(version)" - case .watchOS: - return "\(architecture)-apple-watchos\(version)" - case .visionOS: - return "\(architecture)-apple-xros\(version)" - case .driverKit: - return "\(architecture)-apple-driverkit\(version)" - case .iOSSimulator: - return "\(architecture)-apple-ios\(version)-simulator" - case .tvOSSimulator: - return "\(architecture)-apple-tvos\(version)-simulator" - case .watchOSSimulator: - return "\(architecture)-apple-watchos\(version)-simulator" - case .visionOSSimulator: - return "\(architecture)-apple-xros\(version)-simulator" - } - } -} - -#endif diff --git a/Sources/Declaration/TypeIndexing/SourceKitManager.swift b/Sources/Declaration/TypeIndexing/SourceKitManager.swift deleted file mode 100644 index c2a6f2b03..000000000 --- a/Sources/Declaration/TypeIndexing/SourceKitManager.swift +++ /dev/null @@ -1,163 +0,0 @@ -#if os(macOS) - -import Csourcekitd -import Foundation -import FoundationToolbox -import SourceKitD - -/// Generates whole-module Swift interfaces through sourcekitd's -/// `editor.open.interface` request — the same request Xcode's generated -/// interface uses, and the only ready-made way to obtain the *Swift view* of a -/// module including its ObjC-imported declarations (the SDK's -/// `.swiftinterface` files carry Swift declarations only). -/// -/// The request is sent with `key.enablesubstructure`, and the response's -/// document-structure tree is converted into plain -/// ``InterfaceDeclarationNode`` values before it leaves this actor, so -/// downstream extraction never touches sourcekitd types. -@available(macOS 13.0, *) -package actor SourceKitManager { - package struct GeneratedModuleInterface: Sendable { - package let moduleName: String - package let sourceText: String - package let declarations: [InterfaceDeclarationNode] - - /// Module names the generated interface imports, in appearance order. - /// Submodule detection (`Foundation.NSObject` inside `Foundation`) - /// filters on these. - package let importedModuleNames: [String] - - package init(moduleName: String, sourceText: String, declarations: [InterfaceDeclarationNode], importedModuleNames: [String]) { - self.moduleName = moduleName - self.sourceText = sourceText - self.declarations = declarations - self.importedModuleNames = importedModuleNames - } - } - - package enum Error: Swift.Error, CustomStringConvertible { - case missingSourceText(moduleName: String) - case missingSubstructure(moduleName: String) - - package var description: String { - switch self { - case .missingSourceText(let moduleName): - return "editor.open.interface returned no source text for module \(moduleName)" - case .missingSubstructure(let moduleName): - return "editor.open.interface returned no substructure for module \(moduleName); the type-name extraction has no input" - } - } - } - - private var cachedSourceKitD: SourceKitD? - - package init() {} - - private func sourcekitd() async throws -> SourceKitD { - if let cachedSourceKitD { - return cachedSourceKitD - } - // Derived from the active developer directory rather than hardcoding - // /Applications/Xcode.app, so Xcode-beta and multi-Xcode setups work. - let developerDirectory = try Subprocess.activeDeveloperDirectory() - let sourcekitdPath = developerDirectory + "/Toolchains/XcodeDefault.xctoolchain/usr/lib/sourcekitd.framework/Versions/A/sourcekitd" - let sourceKitD = try await SourceKitD.getOrCreate(dylibPath: URL(fileURLWithPath: sourcekitdPath), pluginPaths: nil) - cachedSourceKitD = sourceKitD - return sourceKitD - } - - /// Generates `moduleName`'s interface against `sdkSettings`' SDK and - /// converts the structured response. One sourcekitd request per call; a - /// large module takes seconds, which is why callers index only the - /// modules a binary actually depends on and cache the extraction. - package func interface( - for moduleName: String, - platform: SDKPlatform, - sdkSettings: SDKSettings - ) async throws -> GeneratedModuleInterface { - let sourcekitd = try await sourcekitd() - let keys = sourcekitd.keys - let request = sourcekitd.dictionary([ - keys.moduleName: moduleName, - keys.name: UUID().uuidString, - keys.enableStructure: 1, - keys.compilerArgs: [ - "-sdk", sdkSettings.sdkPath, - "-target", sdkSettings.targetTriple(for: platform), - ] as [SKDRequestValue], - ]) - let response = try await sourcekitd.send( - \.editorOpenInterface, - request, - timeout: .seconds(120), - restartTimeout: .seconds(120), - documentUrl: nil, - fileContents: nil - ) - guard let sourceText: String = response[keys.sourceText] else { - throw Error.missingSourceText(moduleName: moduleName) - } - guard let substructure: SKDResponseArray = response[keys.subStructure] else { - throw Error.missingSubstructure(moduleName: moduleName) - } - return GeneratedModuleInterface( - moduleName: moduleName, - sourceText: sourceText, - declarations: Self.declarationNodes(of: substructure, in: sourcekitd), - importedModuleNames: Self.importedModuleNames(inInterfaceSourceText: sourceText) - ) - } - - // MARK: - Response Conversion - - private static func declarationNodes(of substructure: SKDResponseArray, in sourcekitd: SourceKitD) -> [InterfaceDeclarationNode] { - var nodes: [InterfaceDeclarationNode] = [] - substructure.forEach { _, nodeDictionary in - let keys = sourcekitd.keys - let kindUID: sourcekitd_api_uid_t? = nodeDictionary[keys.kind] - let kindUIDString = kindUID.flatMap { uid in - sourcekitd.api.uid_get_string_ptr(uid).map { String(cString: $0) } - } - let kind = kindUIDString.map { InterfaceDeclarationNode.kind(forUIDString: $0) } ?? .other - let name: String? = nodeDictionary[keys.name] - // `other` nodes are never descended into by the extractor, so - // their subtrees are dropped here to keep the value tree small. - let children: [InterfaceDeclarationNode] - if kind != .other, let childSubstructure: SKDResponseArray = nodeDictionary[keys.subStructure] { - children = declarationNodes(of: childSubstructure, in: sourcekitd) - } else { - children = [] - } - nodes.append(InterfaceDeclarationNode(kind: kind, name: name, children: children)) - return true - } - return nodes - } - - // MARK: - Import Scan - - /// Line-level scan for `import Module[.Submodule]` in generated interface - /// text. Machine-generated interfaces spell imports one per line - /// (optionally attributed, e.g. `@_exported import ObjectiveC`), so no - /// syntax parsing is needed here. - package static func importedModuleNames(inInterfaceSourceText sourceText: String) -> [String] { - var importedModuleNames: [String] = [] - var seenModuleNames: Set = [] - sourceText.enumerateLines { line, _ in - let trimmedLine = line.trimmingCharacters(in: .whitespaces) - guard !trimmedLine.hasPrefix("//") else { return } - let tokens = trimmedLine.split(separator: " ") - guard let importTokenIndex = tokens.firstIndex(of: "import"), importTokenIndex + 1 < tokens.count else { return } - // Reject lines where `import` is not a keyword at clause start - // (every leading token of a real import is an attribute/modifier). - let leadingTokens = tokens[.. String { - let process = Process() - process.executableURL = URL(fileURLWithPath: executablePath) - process.arguments = arguments - let standardOutputPipe = Pipe() - process.standardOutput = standardOutputPipe - process.standardError = FileHandle.nullDevice - try process.run() - let outputData = standardOutputPipe.fileHandleForReading.readDataToEndOfFile() - process.waitUntilExit() - guard process.terminationStatus == 0 else { - throw Error.nonZeroTermination(executablePath: executablePath, arguments: arguments, terminationStatus: process.terminationStatus) - } - guard let outputString = String(data: outputData, encoding: .utf8) else { - throw Error.unreadableOutput(executablePath: executablePath, arguments: arguments) - } - return outputString.trimmingCharacters(in: .whitespacesAndNewlines) - } - - static func xcrun(_ arguments: [String]) throws -> String { - try output(of: "/usr/bin/xcrun", arguments: arguments) - } - - /// The active developer directory (`xcode-select -p`), e.g. - /// `/Applications/Xcode.app/Contents/Developer`. - static func activeDeveloperDirectory() throws -> String { - try output(of: "/usr/bin/xcode-select", arguments: ["-p"]) - } -} - -#endif diff --git a/Sources/Declaration/TypeIndexing/SupplementaryAPINotes.swift b/Sources/Declaration/TypeIndexing/SupplementaryAPINotes.swift deleted file mode 100644 index ef38b1865..000000000 --- a/Sources/Declaration/TypeIndexing/SupplementaryAPINotes.swift +++ /dev/null @@ -1,64 +0,0 @@ -#if os(macOS) - -import Foundation -import FoundationToolbox - -/// Loads supplementary `.apinotes` files: user-provided type mappings for -/// frameworks the SDK carries no module for (evolution proposal 0010). -/// AttributeGraph is the canonical case — its `AG_SWIFT_NAME` renames live -/// only in headers the SDK never ships, so `AttributeGraph.Graph` is -/// unrecoverable from any binary and must come from external knowledge. -/// -/// The library ships no mappings of its own: hosts supply files or -/// directories (the CLI via `--supplementary-apinotes`, library consumers via -/// the provider's `supplementaryAPINotesURLs:`), loaded in caller order so a -/// later path overwrites an earlier one inside -/// `APINotesIndex.register(files:)`. -/// -/// A file that fails to parse is skipped and logged, never fatal — the same -/// contract SDK APINotes discovery follows. -@available(macOS 13.0, *) -package enum SupplementaryAPINotesLoader { - /// The `.apinotes` files at the supplied locations. Each URL may be a - /// single file or a directory, whose immediate `.apinotes` entries are - /// loaded in file-name order; the URLs themselves keep caller order, so a - /// later path overwrites an earlier one. - package static func files(atSupplementaryLocations locationURLs: [URL]) -> [APINotesFile] { - var fileURLs: [URL] = [] - for locationURL in locationURLs { - var isDirectory: ObjCBool = false - guard FileManager.default.fileExists(atPath: locationURL.path(percentEncoded: false), isDirectory: &isDirectory) else { - #log(.error, "Skipping missing supplementary APINotes location \(locationURL.path(percentEncoded: false), privacy: .public)") - continue - } - if isDirectory.boolValue { - let entryURLs = (try? FileManager.default.contentsOfDirectory(at: locationURL, includingPropertiesForKeys: nil)) ?? [] - fileURLs.append(contentsOf: entryURLs - .filter { $0.pathExtension == "apinotes" } - .sorted { $0.lastPathComponent < $1.lastPathComponent }) - } else { - fileURLs.append(locationURL) - } - } - var parsedFiles: [APINotesFile] = [] - for fileURL in fileURLs { - do { - parsedFiles.append(try APINotesFile(path: fileURL.path(percentEncoded: false))) - } catch { - #log(.error, "Skipping unparsable supplementary APINotes file at \(fileURL.path(percentEncoded: false), privacy: .public): \(String(describing: error), privacy: .public)") - } - } - return parsedFiles - } -} - -// Protocol-form `@Loggable`: the direct type form's generated static stored -// logger is rejected inside `@available(macOS 13.0, *)` types at -// emit-module time ("cannot be more available than enclosing scope"). -@Loggable(.fileprivate, subsystem: "com.machoswiftsection.typeindexing", category: "SupplementaryAPINotes") -fileprivate protocol SupplementaryAPINotesLogging {} - -@available(macOS 13.0, *) -extension SupplementaryAPINotesLoader: SupplementaryAPINotesLogging {} - -#endif diff --git a/Sources/Declaration/TypeIndexing/SwiftInterfaceBuilderTypeNameProvider.swift b/Sources/Declaration/TypeIndexing/SwiftInterfaceBuilderTypeNameProvider.swift deleted file mode 100644 index 6e2c8e522..000000000 --- a/Sources/Declaration/TypeIndexing/SwiftInterfaceBuilderTypeNameProvider.swift +++ /dev/null @@ -1,101 +0,0 @@ -#if os(macOS) - -import Foundation -import MachOKit -import MachOSwiftSection -import ObjCMetadataSource -import SwiftInterface -import SwiftPrinting - -/// The `SwiftInterfaceBuilder` extra-data provider that restores real module -/// names for `__C` / `__ObjC` types: attach it and the printer's -/// `moduleName(forTypeName:)` delegate resolves `__C.NSString` to -/// `Foundation.NSString` through a ``TypeDatabase`` built for the indexed -/// binary's platform and dependency set. -@available(macOS 13.0, *) -public final class SwiftInterfaceBuilderTypeNameProvider: SwiftInterfaceBuilderExtraDataProvider, ModuleNameResolving, CImportedNameResolving, Sendable { - public let machO: MachO - - private let typeDatabase: TypeDatabase - - private let dependencies: SwiftInterfaceBuilderDependencies - - /// Fails when the binary carries no build-version load command mapping to - /// a known SDK platform — without a platform there is no SDK to index. - /// - /// `supplementaryAPINotesURLs` names `.apinotes` files or directories of - /// user-provided type mappings (evolution proposal 0010), loaded after - /// the SDK's own APINotes so they overwrite them. - public init?(machO: MachO, dependencies: SwiftInterfaceBuilderDependencies, supplementaryAPINotesURLs: [URL] = []) { - guard let platform = machO.loadCommands.buildVersionCommand?.platform.sdkPlatform else { - return nil - } - self.machO = machO - self.dependencies = dependencies - self.typeDatabase = TypeDatabase(platform: platform, supplementaryAPINotesURLs: supplementaryAPINotesURLs) - } - - public func setup() async throws { - // Index only the SDK modules the binary actually links: the module - // filter is keyed on the dependency images' module names, which is - // what makes first-run indexing minutes-of-modules instead of the - // whole SDK. - let dependencyModuleNames = Set(dependencies.dependencies.map { TypeDatabase.moduleName(forImagePath: $0.imagePath) }) - try await typeDatabase.index(dependencies: dependencies.dependencies) { dependencyModuleNames.contains($0) } - } - - public func moduleName(forTypeName typeName: String) async -> String? { - await typeDatabase.moduleName(forTypeName: typeName) - } - - public func swiftName(forCName cName: String, category: CImportedTypeNameCategory) async -> String? { - await typeDatabase.swiftName(forCName: cName, category: category) - } -} - -@available(macOS 13.0, *) -extension MachOKit.Platform { - var sdkPlatform: SDKPlatform? { - switch self { - case .macOS, - .macCatalyst: - return .macOS - case .driverKit: - return .driverKit - case .iOS: - return .iOS - case .tvOS: - return .tvOS - case .watchOS: - return .watchOS - case .visionOS: - return .visionOS - case .iOSSimulator: - return .iOSSimulator - case .tvOSSimulator: - return .tvOSSimulator - case .watchOSSimulator: - return .watchOSSimulator - case .visionOSSimulator: - return .visionOSSimulator - default: - return nil - } - } -} - -extension LoadCommandsProtocol { - var buildVersionCommand: BuildVersionCommand? { - for command in self { - switch command { - case .buildVersion(let buildVersionCommand): - return buildVersionCommand - default: - break - } - } - return nil - } -} - -#endif diff --git a/Sources/Declaration/TypeIndexing/TypeDatabase.swift b/Sources/Declaration/TypeIndexing/TypeDatabase.swift deleted file mode 100644 index 2bcde721c..000000000 --- a/Sources/Declaration/TypeIndexing/TypeDatabase.swift +++ /dev/null @@ -1,265 +0,0 @@ -#if os(macOS) - -import Foundation -import FoundationToolbox -import MachOKit -import ObjCIndexing -import ObjCMetadataSource -import SwiftPrinting - -/// The `__C` module-attribution database: answers "which module declares the -/// type named X" for the ObjC/C-imported types Swift manglings spell as -/// `__C.X` / `__ObjC.X`. -/// -/// Attribution merges three sources, queried in priority order: -/// -/// 1. **Public API** — type names extracted from SourceKit-generated module -/// interfaces (the Swift view of each module, ObjC-imported declarations -/// included), for the modules the indexed binary depends on. -/// 2. **APINotes** — C names registered to their declaring module, covering -/// renamed types whose C spelling never appears in any Swift interface. -/// Written after the interface names, so the compiler's own record wins a -/// conflict. -/// 3. **ObjC metadata (lazy)** — private classes/protocols and harvested C -/// struct/union names read from the binary's dependency images via -/// `ObjCIndexing`. Consulted only on a miss of the first two, one image at -/// a time, stopping at the first hit — declared-in-public-API attribution -/// always outranks "its metadata lives in this image". -@available(macOS 13.0, *) -package actor TypeDatabase { - private let platform: SDKPlatform - - /// User-supplied supplementary APINotes locations (files or directories), - /// loaded after the SDK's own APINotes so they overwrite them (evolution - /// proposal 0010). The library ships no mappings of its own. - private let supplementaryAPINotesURLs: [URL] - - private let sourceKitManager = SourceKitManager() - - /// Type name → declaring module, merged from interfaces then APINotes. - private var moduleNamesByTypeName: [String: String] = [:] - - /// Type name → image-derived module, filled lazily from `ObjCIndexing`. - private var objcModuleNamesByTypeName: [String: String] = [:] - - private var apiNotesIndex = APINotesIndex(files: []) - - /// Dependency images not yet ObjC-indexed, in dependency order. Popped - /// one at a time as misses demand; an image whose indexing fails is - /// dropped (logged), not retried. - private var unindexedDependencies: [MachO] = [] - - package init(platform: SDKPlatform, supplementaryAPINotesURLs: [URL] = []) { - self.platform = platform - self.supplementaryAPINotesURLs = supplementaryAPINotesURLs - } - - // MARK: - Indexing - - /// Builds the database: discovers the SDK (cheap), then generates and - /// extracts interfaces only for modules passing `moduleFilter` (expensive, - /// cached per module per SDK build), registers APINotes attribution, and - /// records `dependencies` for lazy ObjC indexing. - package func index(dependencies: [MachO], moduleFilter: @Sendable (String) -> Bool) async throws { - let sdkSettings = try platform.sdkSettings() - let discovery = SDKIndexer(platform: platform).discover(sdkSettings: sdkSettings) - - let filteredModules = discovery.modules.filter { moduleFilter($0.moduleName) } - let moduleInterfaceIndexer = ModuleInterfaceIndexer( - platform: platform, - sdkSettings: sdkSettings, - cache: ModuleIndexCache(platform: platform, sdkSettings: sdkSettings), - sourceKitManager: sourceKitManager - ) - let collectedEntries = await withTaskGroup(of: ModuleIndexCacheEntry?.self) { group in - for moduleDescriptor in filteredModules { - group.addTask { - await moduleInterfaceIndexer.indexEntry(forModuleNamed: moduleDescriptor.moduleName) - } - } - var entries: [ModuleIndexCacheEntry] = [] - for await entry in group { - if let entry { - entries.append(entry) - } - } - return entries - } - let orderedEntries = Self.entriesInDiscoveryOrder(collectedEntries, discoveryOrder: filteredModules.map(\.moduleName)) - - register(moduleEntries: orderedEntries) - register(apiNotesIndex: APINotesIndex(files: discovery.apiNotesFiles)) - register(supplementaryAPINotesFiles: SupplementaryAPINotesLoader.files(atSupplementaryLocations: supplementaryAPINotesURLs)) - register(dependencies: dependencies) - } - - /// Restores discovery order over task-group results: the group yields - /// entries in COMPLETION order, which varies with per-module cache hits — - /// but registration is last-writer-wins, so it must follow the discovery - /// order (SDKIndexer's search-path priority: "an earlier hit wins a - /// module-name tie"), or two runs could attribute a tied name - /// differently. - package static func entriesInDiscoveryOrder(_ collectedEntries: [ModuleIndexCacheEntry], discoveryOrder moduleNames: [String]) -> [ModuleIndexCacheEntry] { - let entriesByModuleName = Dictionary(collectedEntries.map { ($0.moduleName, $0) }, uniquingKeysWith: { firstEntry, _ in firstEntry }) - return moduleNames.compactMap { entriesByModuleName[$0] } - } - - /// Registers interface-extracted type names. Exposed as a step so merge - /// priority is unit-testable without sourcekitd. - package func register(moduleEntries: [ModuleIndexCacheEntry]) { - for entry in moduleEntries { - for typeName in entry.typeNames { - moduleNamesByTypeName[typeName] = entry.moduleName - } - } - } - - /// Registers APINotes attribution (C name → declaring module), overriding - /// any interface-derived entry for the same name. - package func register(apiNotesIndex: APINotesIndex) { - self.apiNotesIndex = apiNotesIndex - registerAttribution(fromAPINotesIndex: apiNotesIndex) - } - - /// Registers supplementary APINotes bundles (evolution proposal 0010) on - /// top of whatever is already indexed: their entries append into the same - /// `APINotesIndex`, where later files overwrite earlier same-name entries - /// — so calling this after `register(apiNotesIndex:)` gives supplementary - /// mappings the last word over SDK ones. Attribution is then re-synced - /// from the index, whose internal ordering already reflects the override. - package func register(supplementaryAPINotesFiles supplementaryFiles: [APINotesFile]) { - apiNotesIndex.register(files: supplementaryFiles) - registerAttribution(fromAPINotesIndex: apiNotesIndex) - } - - private func registerAttribution(fromAPINotesIndex attributionIndex: APINotesIndex) { - for (cName, moduleName) in attributionIndex.moduleNamesByCName { - moduleNamesByTypeName[cName] = moduleName - } - // Swift spellings too, after the C spellings. A printed `__C` name no - // longer carries one: a foreign descriptor records the imported - // spelling (`Graph` for an `AG_SWIFT_NAME(Graph)` type), but the - // demangler names it by the ABI name in its import info (evolution - // proposal `type-import-info-identity`). What this pass still decides - // is a C name several modules' APINotes list. Foundation's and - // AppKit's list `NSObject` only to annotate category methods, and the - // pass above lets whichever file came last win; ObjectiveC's entry - // renames `NSObject` to itself, so registering that spelling last - // gives the class back to ObjectiveC. Nested renames - // (`ProcessInfo.ActivityOptions`) never appear as one identifier and - // are skipped. - for (swiftName, originalCName) in attributionIndex.cNamesBySwiftName where !swiftName.contains(".") { - moduleNamesByTypeName[swiftName] = originalCName.moduleName - } - } - - /// Records the images consulted lazily for private-type attribution. - package func register(dependencies: [MachO]) { - unindexedDependencies = dependencies - } - - // MARK: - Query - - package func moduleName(forTypeName typeName: String) async -> String? { - if let moduleName = moduleNamesByTypeName[typeName] { - return moduleName - } - if let moduleName = objcModuleNamesByTypeName[typeName] { - return moduleName - } - // Lazy ObjC indexing: fold in one dependency image at a time until - // the name resolves or the images run out. Misses after exhaustion - // cost one dictionary probe, since nothing remains unindexed. - while !unindexedDependencies.isEmpty { - let machO = unindexedDependencies.removeFirst() - await indexObjCMetadata(of: machO) - if let moduleName = objcModuleNamesByTypeName[typeName] { - return moduleName - } - } - return nil - } - - /// The Swift spelling of a C-imported type name, when it differs from the - /// C one. Two sources, in order: - /// - /// 1. **APINotes renames**, per declaration category (`NSDecimal` → - /// `Decimal`; the protocol-only `NSObject` → `NSObjectProtocol` rename - /// never touches class references). - /// 2. **The CF bridge rule**: ClangImporter imports a `CF…Ref` typedef as - /// the `Ref`-stripped native class (`CFStringRef` → `CFString`), while - /// manglings record the C spelling. The stripped name qualifies only - /// when it actually exists in the attribution table — so an ObjC class - /// that merely happens to end in `Ref` is never rewritten — and never - /// applies to protocol references (there is no CF protocol convention). - package func swiftName(forCName cName: String, category: CImportedTypeNameCategory) -> String? { - if let renamedName = apiNotesIndex.swiftName(forCName: cName, category: category) { - return renamedName.name - } - if category != .objcProtocol, cName.hasSuffix("Ref") { - let strippedName = String(cName.dropLast(3)) - if !strippedName.isEmpty, moduleNamesByTypeName[strippedName] != nil { - return strippedName - } - } - return nil - } - - // MARK: - Lazy ObjC Indexing - - private func indexObjCMetadata(of machO: MachO) async { - let imagePath = machO.imagePath - let moduleName = Self.moduleName(forImagePath: imagePath) - let objcInterfaceIndexer = ObjCInterfaceIndexer(machO: machO, imagePath: imagePath) - do { - try await objcInterfaceIndexer.prepare() - } catch { - #log(.error, "Skipping ObjC metadata of \(imagePath, privacy: .public): \(String(describing: error), privacy: .public)") - return - } - let discoveredNames = objcInterfaceIndexer.classNames - + objcInterfaceIndexer.protocolNames - + objcInterfaceIndexer.structNames - + objcInterfaceIndexer.unionNames - for discoveredName in discoveredNames { - // Never overwrite: the declaring image is whichever dependency - // came first in dependency order, and interface/APINotes - // attribution is consulted before this table anyway. - if objcModuleNamesByTypeName[discoveredName] == nil { - objcModuleNamesByTypeName[discoveredName] = moduleName - } - } - } - - /// `…/Foundation.framework/Foundation` → `Foundation`, - /// `libswiftFoundation.dylib` → `Foundation`, `libobjc.A.dylib` → - /// `libobjc`: every path extension is stripped, then the `libswift` - /// overlay prefix is removed. - package static func moduleName(forImagePath imagePath: String) -> String { - var name = URL(fileURLWithPath: imagePath).lastPathComponent - while name.contains(".") { - // A leading-dot name is a fixed point of extension stripping - // (`.hidden` → `.hidden`) — without this guard the loop spins - // forever on such an install name. - let strippedName = URL(fileURLWithPath: name).deletingPathExtension().lastPathComponent - guard strippedName != name, !strippedName.isEmpty else { break } - name = strippedName - } - if name.hasPrefix("libswift") { - name = String(name.dropFirst("libswift".count)) - } - return name - } -} - -// Protocol-form `@Loggable`, required twice over: the type is generic (the -// direct form's static stored logger is illegal there) and carries an -// `@available(macOS 13.0, *)` scope the macro's own annotations would exceed. -// The protocol itself stays un-annotated for the latter reason. -@Loggable(.fileprivate, subsystem: "com.machoswiftsection.typeindexing", category: "TypeDatabase") -fileprivate protocol TypeDatabaseLogging {} - -@available(macOS 13.0, *) -extension TypeDatabase: TypeDatabaseLogging {} - -#endif diff --git a/Sources/Executables/reader-benchmark/ReaderBenchmark.swift b/Sources/Executables/reader-benchmark/ReaderBenchmark.swift index c11aa248a..85bac9712 100644 --- a/Sources/Executables/reader-benchmark/ReaderBenchmark.swift +++ b/Sources/Executables/reader-benchmark/ReaderBenchmark.swift @@ -7,6 +7,7 @@ import SwiftSectionKit import SwiftPrinting import SwiftInterface import SwiftDeclarationRendering +import Semantic /// Measures how long one image's Swift interface takes to index and to print, /// read in-process (`MachOImage`) or offline (`MachOFile`), so the two readers diff --git a/Sources/Executables/swift-section/Commands/DumpCommand.swift b/Sources/Executables/swift-section/Commands/DumpCommand.swift index 716b8ec43..8cd28b91d 100644 --- a/Sources/Executables/swift-section/Commands/DumpCommand.swift +++ b/Sources/Executables/swift-section/Commands/DumpCommand.swift @@ -17,6 +17,9 @@ struct DumpCommand: AsyncParsableCommand, Sendable { @OptionGroup(title: "Comment Templates") var transformerOptions: TransformerOptionGroup + @OptionGroup(title: "Long Types") + var multilineTypeOptions: MultilineTypeOptionGroup + @Option(name: .shortAndLong, help: "The output path for the dump. If not specified, the output will be printed to the console.", completion: .file()) var outputPath: String? @@ -76,6 +79,7 @@ struct DumpCommand: AsyncParsableCommand, Sendable { emitsExportStatus: emitExportStatus, emitsPrivateDeclarationSourceFiles: emitPrivateSourceFiles, emitsHeader: emitHeader, + multilineTypeFormatting: multilineTypeOptions.multilineTypeFormatting, commentTransformers: try transformerOptions.buildTransformerConfiguration(), destination: outputPath.map { .file(path: $0) } ?? .output ) diff --git a/Sources/Executables/swift-section/Commands/InterfaceCommand.swift b/Sources/Executables/swift-section/Commands/InterfaceCommand.swift index b9af7d7b7..05d7d5495 100644 --- a/Sources/Executables/swift-section/Commands/InterfaceCommand.swift +++ b/Sources/Executables/swift-section/Commands/InterfaceCommand.swift @@ -1,6 +1,7 @@ import Foundation import ArgumentParser import SwiftSectionKit +import SwiftPrinting struct InterfaceCommand: AsyncParsableCommand { static let configuration: CommandConfiguration = .init( @@ -17,6 +18,9 @@ struct InterfaceCommand: AsyncParsableCommand { @OptionGroup(title: "Comment Templates") var transformerOptions: TransformerOptionGroup + @OptionGroup(title: "Long Types") + var multilineTypeOptions: MultilineTypeOptionGroup + @Option(name: .shortAndLong, help: "The output path for the dump. If not specified, the output will be printed to the console.", completion: .file()) var outputPath: String? @@ -26,9 +30,15 @@ struct InterfaceCommand: AsyncParsableCommand { @Flag(help: "Parse opaque return value, this option is an experimental feature and may result in parsing errors for complex return types.") var parseOpaqueReturnType: Bool = false - @Flag(help: "Resolve __C/__ObjC type module names to their real modules (__C.NSString -> Foundation.NSString) by indexing the SDK modules the binary links, its APINotes, and its dependencies' ObjC metadata. Requires Xcode; the first run per SDK generates module interfaces through sourcekitd and caches the extraction.") + @Flag(help: "Resolve __C/__ObjC type module names to their real modules (__C.NSString -> Foundation.NSString) by indexing the SDK modules the binary links, its APINotes, its dependencies' ObjC metadata, and, for a CF class the binary's own metadata names, the image among the binary and its dependencies that exports its GetTypeID function (a private CF type: __C.CGSVGDocumentRef -> CoreSVG.CGSVGDocument). Requires Xcode; the first run per SDK generates module interfaces through sourcekitd and caches the extraction.") var resolveCModuleNames: Bool = false + @Flag(help: "Print a Swift type the SDK moved to another module (@_originallyDefinedIn) under the module that declares it now (CoreGraphics.CGFloat -> CoreFoundation.CGFloat, SwiftUI.View -> SwiftUICore.View), when the binary was built against an SDK that had already moved it. Reads the SDK's .swiftinterface files: needs Xcode or the Command Line Tools, not sourcekitd. macOS only.") + var resolveMovedTypeModules: Bool = false + + @Option(name: .customLong("c-imported-type-name-spelling"), help: "How imported C and Objective-C types are spelled. swift-name (the default) prints the name Swift code uses: a type the binary's own descriptors name prints under that name, renamed (__C.AGWeakAttribute -> AnyWeakAttribute) or imported under its C name (__C.AGDescriptionOption -> AGDescriptionOption), under its module when --resolve-c-module-names finds it. Any other keeps __C: a type the binary has no descriptor for, or one whose descriptor may name only the leaf of a member import (__C.NSAttributedStringKey). c-name prints every one as the binary mangles it (__C.AGWeakAttribute), declarations included, and resolves nothing. The expanded field-offset comments follow the same spelling.") + var cImportedTypeNameSpelling: CImportedTypeNameSpelling = .swiftName + @Option(name: .customLong("supplementary-apinotes"), help: "A supplementary .apinotes file (or a directory of them) of user-provided type mappings for frameworks with no SDK module (e.g. AttributeGraph), loaded on top of the SDK's own APINotes. Repeatable; later paths override earlier ones. Only used with --resolve-c-module-names.", completion: .file()) var supplementaryAPINotesPaths: [String] = [] @@ -88,6 +98,7 @@ struct InterfaceCommand: AsyncParsableCommand { showsCImportedTypes: showCImportedTypes, parsesOpaqueReturnTypes: parseOpaqueReturnType, cModuleNameResolution: resolveCModuleNames ? .enabled(supplementaryAPINotesPaths: supplementaryAPINotesPaths) : .disabled, + resolvesMovedTypeModules: resolveMovedTypeModules, fieldOffsetComments: emitExpandedFieldOffsets ? .expanded : (emitOffsetComments ? .flat : .none), emitsMemberAddresses: emitMemberAddresses, emitsVTableOffsets: emitVtableOffsets, @@ -100,9 +111,11 @@ struct InterfaceCommand: AsyncParsableCommand { infersObjCOverridesFromSelectorNames: objcMemberOptions.infersOverridesFromSelectorNames, usesModuleSelectors: moduleSelectors, usesExistentialAny: existentialAny, + cImportedTypeNameSpelling: cImportedTypeNameSpelling, expandsMacros: expandMacros, protocolRequirementPlacement: requirementsOnAssociatedTypes ? .associatedTypes : .protocolWhereClause, emitsHeader: emitHeader, + multilineTypeFormatting: multilineTypeOptions.multilineTypeFormatting, commentTransformers: try transformerOptions.buildTransformerConfiguration(), destination: outputPath.map { .file(path: $0) } ?? .output ) @@ -113,6 +126,9 @@ struct InterfaceCommand: AsyncParsableCommand { // Progress lines have always gone to stdout here, mixed into the // product unless `-o` is given. let output = StandardStreamOutput(colorScheme: colorScheme, standardOutputSeverities: [.progress]) + if resolveCModuleNames, cImportedTypeNameSpelling == .cName { + output.report(SwiftSectionDiagnostic(severity: .warning, message: "warning: --resolve-c-module-names has no effect with --c-imported-type-name-spelling c-name")) + } if !resolveCModuleNames, !supplementaryAPINotesPaths.isEmpty { output.report(SwiftSectionDiagnostic(severity: .warning, message: "warning: --supplementary-apinotes has no effect without --resolve-c-module-names")) } diff --git a/Sources/Executables/swift-section/Commands/ReferencesCommand.swift b/Sources/Executables/swift-section/Commands/ReferencesCommand.swift index 14bf059bb..712342802 100644 --- a/Sources/Executables/swift-section/Commands/ReferencesCommand.swift +++ b/Sources/Executables/swift-section/Commands/ReferencesCommand.swift @@ -5,7 +5,7 @@ import SwiftSectionKit struct ReferencesCommand: AsyncParsableCommand { static let configuration: CommandConfiguration = .init( commandName: "refs", - abstract: "List the code that references a selector, a symbol, a class, a function, an instance variable or a string — or what a function references — across a dyld shared cache or a set of arm64 Mach-O files.", + abstract: "List the code that references a selector, a symbol, a class, a function, an instance variable, a string or a Swift type — or what a function references — across a dyld shared cache or a set of arm64 Mach-O files.", discussion: "Addresses in and out are unslid, as IDA, ipsw and dyld_info show them. Each line is a reference: the referencing instruction's address, its image, its function and the offset into it, the reference's kind and route, and what it references." ) @@ -14,7 +14,7 @@ struct ReferencesCommand: AsyncParsableCommand { @OptionGroup var inputOptions: CrossReferenceInputOptionGroup - @Option(help: "Every send of this selector, super sends included (makeKeyAndOrderFront:).") + @Option(help: "Every send of this selector, super sends included (makeKeyAndOrderFront:), and every other use of it: an argument of respondsToSelector: or performSelector:, a returned selector, an action.") var selector: String? @Option(help: "The callers of the function this symbol names, with its leading underscore: a C function, a Swift mangled name, _OBJC_CLASS_$_ or _OBJC_IVAR_$_.. A function no analyzed image defines is looked for as the imported symbol it is.") @@ -38,6 +38,12 @@ struct ReferencesCommand: AsyncParsableCommand { @Option(help: "Every reference to a C string or constant CFString literal with these characters.") var string: String? + @Option(name: .customLong("type"), help: "Every reference to the Swift struct, enum or class with this mangling (7SwiftUI4TextV), or to the one a $s…Mn, $s…Ma or $s…N symbol names: its metadata accessor called or its address taken, its metadata, a mangled name spelling it.") + var swiftType: String? + + @Option(name: .customLong("type-image"), help: "The image that defines --type's type, by path or file name: needed in a dyld shared cache for a type no image exports.") + var swiftTypeImage: String? + @Option(help: "Report at most this many references, the first in image and address order.") var limit: Int? @@ -45,10 +51,11 @@ struct ReferencesCommand: AsyncParsableCommand { var json: Bool = false func validate() throws { - let queryCount = [selector, symbol, className, function, instanceVariable, string].compactMap { $0 }.count + let queryCount = [selector, symbol, className, function, instanceVariable, string, swiftType].compactMap { $0 }.count guard queryCount == 1 else { - throw ValidationError("Name exactly one of --selector, --symbol, --class, --function, --ivar and --string.") + throw ValidationError("Name exactly one of --selector, --symbol, --class, --function, --ivar, --string and --type.") } + if swiftTypeImage != nil, swiftType == nil { throw ValidationError("--type-image names the image that defines --type's type; it needs --type.") } if callees, function == nil { throw ValidationError("--callees lists a function's references; it needs --function.") } if functionImage != nil, function == nil { throw ValidationError("--function-image names the image of --function's address; it needs --function.") } if let instanceVariable, !Self.isQualifiedInstanceVariableName(instanceVariable) { @@ -79,8 +86,10 @@ struct ReferencesCommand: AsyncParsableCommand { subject = .instanceVariable(className: String(instanceVariable[.. 0 else { + throw ValidationError("--maximum-line-width must be a positive number of columns, got \(maximumLineWidth).") + } + } + + /// The formatting these options ask for; `nil` without `--multiline-types`. + var multilineTypeFormatting: MultilineTypeFormatting? { + guard multilineTypes else { return nil } + guard let maximumLineWidth else { return MultilineTypeFormatting() } + return MultilineTypeFormatting(maximumLineWidth: maximumLineWidth) + } +} diff --git a/Sources/Executables/swift-section/ObjC/Commands/ObjCInterfaceCommand.swift b/Sources/Executables/swift-section/ObjC/Commands/ObjCInterfaceCommand.swift index a2850cb3a..64309545c 100644 --- a/Sources/Executables/swift-section/ObjC/Commands/ObjCInterfaceCommand.swift +++ b/Sources/Executables/swift-section/ObjC/Commands/ObjCInterfaceCommand.swift @@ -42,6 +42,9 @@ struct ObjCInterfaceCommand: AsyncParsableCommand, Sendable { @Flag(name: .customLong("swift"), help: "Print the declaration as Swift imports it — names by the ClangImporter's rules, members Swift implements as their Swift declarations — instead of as an Objective-C header. Classes, categories and protocols only.") var printsSwiftImport: Bool = false + @Flag(name: .customLong("mark-sdk-swift-names"), help: "Mark the NS_SWIFT_NAME and NS_REFINED_FOR_SWIFT the API notes of the binary's SDK give the declaration and its members, read from the active developer directory (Xcode, or the Command Line Tools for macOS and Mac Catalyst). macOS 13 or later; ignored with --swift.") + var marksSDKSwiftNames: Bool = false + /// The library request these flags describe. func makeRequest() throws -> ObjCInterfaceRequest { ObjCInterfaceRequest( @@ -53,7 +56,8 @@ struct ObjCInterfaceCommand: AsyncParsableCommand, Sendable { ivarOffsetComment: transformerOptions.buildIvarOffsetComment(), reportsIndexingProgress: verbose, destination: outputPath.map { .file(path: $0) } ?? .output, - printsSwiftImport: printsSwiftImport + printsSwiftImport: printsSwiftImport, + marksSDKSwiftNames: marksSDKSwiftNames ) } diff --git a/Sources/Executables/swift-section/Output/StandardStreamOutput.swift b/Sources/Executables/swift-section/Output/StandardStreamOutput.swift index 4cfb5213c..9e6a35c06 100644 --- a/Sources/Executables/swift-section/Output/StandardStreamOutput.swift +++ b/Sources/Executables/swift-section/Output/StandardStreamOutput.swift @@ -102,6 +102,11 @@ extension String { return "#56606B" case .keyword: return "#C33381" + case .macro: + // Xcode's Default (Light) preprocessor-macro colour, which + // `objc interface --mark-sdk-swift-names` prints its + // NS_SWIFT_NAME / NS_REFINED_FOR_SWIFT in. + return "#643820" case .type(_, .name): return "#2E0D6E" case .type(_, .declaration): @@ -124,6 +129,9 @@ extension String { return "#6C7987" case .keyword: return "#F2248C" + case .macro: + // Xcode's Default (Dark) preprocessor-macro colour. + return "#FD8F3F" case .type(_, .name): return "#D0A8FF" case .type(_, .declaration): diff --git a/Sources/Executables/swift-section/Version.swift b/Sources/Executables/swift-section/Version.swift index 465dff5ba..a54d7e448 100644 --- a/Sources/Executables/swift-section/Version.swift +++ b/Sources/Executables/swift-section/Version.swift @@ -4,5 +4,5 @@ // release with the same string. // Verified by .github/workflows/version-check.yml (PR) and .github/workflows/release.yml (tag). enum BundledVersion { - static let value = "0.26.0" + static let value = "0.28.0" } diff --git a/Sources/Output/SwiftDeclarationRendering/ConditionalWitnessComment.swift b/Sources/Output/SwiftDeclarationRendering/ConditionalWitnessComment.swift index fc5333e87..ad0a4e540 100644 --- a/Sources/Output/SwiftDeclarationRendering/ConditionalWitnessComment.swift +++ b/Sources/Output/SwiftDeclarationRendering/ConditionalWitnessComment.swift @@ -1,6 +1,7 @@ import Foundation import MachOKit import Demangling +import Semantic extension PlatformAvailabilityCondition { /// The platform's name as `#available` spells it. diff --git a/Sources/Output/SwiftDeclarationRendering/DeclarationRenderConfiguration.swift b/Sources/Output/SwiftDeclarationRendering/DeclarationRenderConfiguration.swift index 78d6a5d1e..c4ab76eed 100644 --- a/Sources/Output/SwiftDeclarationRendering/DeclarationRenderConfiguration.swift +++ b/Sources/Output/SwiftDeclarationRendering/DeclarationRenderConfiguration.swift @@ -103,6 +103,16 @@ public struct DeclarationRenderConfiguration: Sendable { @Init(.ignore) package var marksCommentStructure: Bool = false + /// Set by a printer that spells its declarations' types through + /// `demangleResolver` — `SwiftDeclarationPrinter`, whose resolver is its + /// own type printer: the expanded field offset tree's rows then spell + /// their types the same way, with the C-imported type name spelling, + /// module selectors and `any` (evolution proposal + /// `consistent-c-imported-type-spelling`). The dump never sets it: its + /// rows keep the `.default` spelling the tree was built with. + @Init(.ignore) + package var spellsFieldLayoutTypeNamesThroughResolver: Bool = false + /// Where the dump learns the source file of each private discriminator /// (evolution proposal `private-declaration-source-files`). With one, a /// declaration whose name reads a discriminator the declaration it is @@ -168,6 +178,30 @@ extension DeclarationRenderConfiguration { return configuration } + /// This configuration, spelling the expanded field offset tree's type + /// names through `demangleResolver` or not + /// (``spellsFieldLayoutTypeNamesThroughResolver``). + package func spellingFieldLayoutTypeNamesThroughResolver(_ spellsThroughResolver: Bool) -> Self { + var configuration = self + configuration.spellsFieldLayoutTypeNamesThroughResolver = spellsThroughResolver + return configuration + } + + /// The type name an expanded field offset tree row prints: `typeNode` + /// spelled through `demangleResolver` when + /// ``spellsFieldLayoutTypeNamesThroughResolver`` is set, else + /// `printedName`, the `.default` spelling the row was built with — which + /// is also what the row prints when its type has no node, or the + /// resolver fails or spells nothing, so a row never loses its type. + package func fieldLayoutTypeName(printedName: String, typeNode: Node?) async -> String { + guard spellsFieldLayoutTypeNamesThroughResolver, + let typeNode, + let spelledName = try? await demangleResolver.resolve(for: typeNode).string, + !spelledName.isEmpty + else { return printedName } + return spelledName + } + /// `content`; when marking comment structure, in a region of `kind` — /// one spanning several comments: a field offset and its tree, a tree /// row and the rows under it, a case's layout block. diff --git a/Sources/Output/SwiftDeclarationRendering/Extensions/GenericContext+Dump.swift b/Sources/Output/SwiftDeclarationRendering/Extensions/GenericContext+Dump.swift index bed7dbc68..b8c42878a 100644 --- a/Sources/Output/SwiftDeclarationRendering/Extensions/GenericContext+Dump.swift +++ b/Sources/Output/SwiftDeclarationRendering/Extensions/GenericContext+Dump.swift @@ -4,6 +4,7 @@ import MachOSwiftSection import Utilities @_spi(Internals) import Demangling @_spi(Internals) import SwiftInspection +import SwiftStdlibToolbox package func genericParameterName(depth: Int, index: Int) throws -> String { var charIndex = index diff --git a/Sources/Output/SwiftDeclarationRendering/Extensions/GenericRequirement+Inherited.swift b/Sources/Output/SwiftDeclarationRendering/Extensions/GenericRequirement+Inherited.swift index 12f74633f..51ff3daa8 100644 --- a/Sources/Output/SwiftDeclarationRendering/Extensions/GenericRequirement+Inherited.swift +++ b/Sources/Output/SwiftDeclarationRendering/Extensions/GenericRequirement+Inherited.swift @@ -1,4 +1,5 @@ import MachOSwiftSection +import BinaryParseSupport extension GenericRequirement { /// A protocol-signature requirement that represents an *inherited protocol* diff --git a/Sources/Output/SwiftDeclarationRendering/Extensions/OpaqueType+.swift b/Sources/Output/SwiftDeclarationRendering/Extensions/OpaqueType+.swift index d2e90e927..a88bf07c1 100644 --- a/Sources/Output/SwiftDeclarationRendering/Extensions/OpaqueType+.swift +++ b/Sources/Output/SwiftDeclarationRendering/Extensions/OpaqueType+.swift @@ -2,6 +2,7 @@ import Foundation import Demangling import MachOSwiftSection @_spi(Internals) import SwiftInspection +import SwiftSymbols extension OpaqueType { package func requirements(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> [GenericRequirementDescriptor] { diff --git a/Sources/Output/SwiftDeclarationRendering/MultilineTypeFormatting+BracketTree.swift b/Sources/Output/SwiftDeclarationRendering/MultilineTypeFormatting+BracketTree.swift new file mode 100644 index 000000000..e23b4f829 --- /dev/null +++ b/Sources/Output/SwiftDeclarationRendering/MultilineTypeFormatting+BracketTree.swift @@ -0,0 +1,316 @@ +import Foundation +import Semantic + +extension MultilineTypeFormatting { + /// What a bracketed list is, which decides when it breaks. + enum BracketKind: Equatable { + /// `<…>` after a type: the arguments of a generic type, the only + /// list that breaks for having two or more elements. + case genericArguments + + /// `<…>` right after a declaration's name: the declaration's generic + /// parameters. + case genericParameters + + /// `(…)`: a tuple, a function type's parameters, a declaration's + /// parameters, an enum case's payload, an attribute's arguments. + case parentheses + + /// `[…]`: array and dictionary sugar. + case squareBrackets + + var closingCharacter: Character { + switch self { + case .genericArguments, + .genericParameters: + ">" + case .parentheses: + ")" + case .squareBrackets: + "]" + } + } + } + + /// One bracketed list of a line: its brackets, the commas between its + /// elements, and the elements themselves. + struct BracketList { + let kind: BracketKind + + let opening: SourceFragment + + let closing: SourceFragment + + /// The `,` between the elements, one fewer than `elements`. + let separators: [SourceFragment] + + var elements: [[BracketTreeNode]] + + /// Where the closing bracket stands on its line, counting from 1 at + /// the first character after the line's indentation. + let closingColumn: Int + + /// Whether the list puts each element on a line of its own. Decided + /// by `LineLayout`; the parser leaves it `false`. + var isBroken = false + } + + indirect enum BracketTreeNode { + case text(SourceFragment) + case list(BracketList) + } + + enum BracketTree { + /// `line` taken apart into text and bracketed lists; `nil` when its + /// brackets do not pair up, and the line is then left as printed. + /// + /// Brackets count only in `.standard` components, which is where + /// both printers write punctuation: a type name, a declaration name + /// (an operator's included), a keyword or a comment is text whatever + /// it contains. In a `.standard` component, a string literal, a + /// backtick-quoted name and everything after `//` are text, and the + /// `>` of `->` closes nothing. A line whose brackets still do not + /// pair up — the dump spells an operator `< infix` — is not guessed + /// at. + static func parse(_ line: SourceLine, sourceComponents: [AtomicComponent]) -> [BracketTreeNode]? { + var parser = BracketTreeParser(leadingIndentation: line.leadingIndentation) + for fragment in line.fragments { + let sourceComponent = sourceComponents[fragment.componentIndex] + if sourceComponent.type == .standard { + guard parser.scanPunctuation(in: fragment) else { return nil } + } else { + parser.appendText(fragment, type: sourceComponent.type) + } + } + return parser.finish() + } + } +} + +private struct BracketTreeParser { + typealias SourceFragment = MultilineTypeFormatting.SourceFragment + typealias BracketKind = MultilineTypeFormatting.BracketKind + typealias BracketList = MultilineTypeFormatting.BracketList + typealias BracketTreeNode = MultilineTypeFormatting.BracketTreeNode + + private enum Punctuation { + case opening(Character) + case closing(Character) + case separator + } + + /// A list whose closing bracket has not been read yet. + private struct OpenList { + let kind: BracketKind + let opening: SourceFragment + var separators: [SourceFragment] = [] + var elements: [[BracketTreeNode]] = [] + var currentElement: [BracketTreeNode] = [] + } + + let leadingIndentation: Int + + private var rootNodes: [BracketTreeNode] = [] + + private var openLists: [OpenList] = [] + + /// How many characters of the line have been read, its indentation + /// included. + private var readCharacterCount = 0 + + private var previousCharacter: Character? + + /// The semantic type of the last component that held more than + /// whitespace — what a `<` follows decides whether it opens generic + /// arguments or a declaration's generic parameters. + private var lastSignificantType: SemanticType? + + private var isInStringLiteral = false + + private var escapesNextCharacter = false + + private var isInBacktickName = false + + private var isInLineComment = false + + init(leadingIndentation: Int) { + self.leadingIndentation = leadingIndentation + } + + /// A component that is not punctuation: text whatever it contains. + mutating func appendText(_ fragment: SourceFragment, type: SemanticType) { + appendNode(.text(fragment)) + readCharacterCount += fragment.text.count + if fragment.text.contains(where: { !$0.isWhitespace }) { + lastSignificantType = type + } + previousCharacter = fragment.text.last ?? previousCharacter + } + + /// Reads a `.standard` component, splitting it at every bracket and + /// list separator. `false` when a closing bracket does not match the + /// list it would close. + mutating func scanPunctuation(in fragment: SourceFragment) -> Bool { + let text = fragment.text + var textRunStart = text.startIndex + var characterIndex = text.startIndex + while characterIndex < text.endIndex { + let character = text[characterIndex] + readCharacterCount += 1 + if let punctuation = punctuation(for: character) { + appendStandardText(SourceFragment(componentIndex: fragment.componentIndex, text: text[textRunStart ..< characterIndex])) + let nextIndex = text.index(after: characterIndex) + let punctuationFragment = SourceFragment(componentIndex: fragment.componentIndex, text: text[characterIndex ..< nextIndex]) + switch punctuation { + case .opening(let bracket): + open(bracket, at: punctuationFragment) + case .closing(let bracket): + guard close(bracket, at: punctuationFragment) else { return false } + case .separator: + separate(at: punctuationFragment) + } + textRunStart = nextIndex + } + previousCharacter = character + characterIndex = text.index(after: characterIndex) + } + appendStandardText(SourceFragment(componentIndex: fragment.componentIndex, text: text[textRunStart ..< text.endIndex])) + return true + } + + /// The tree read so far; `nil` while a list is still open. + func finish() -> [BracketTreeNode]? { + openLists.isEmpty ? rootNodes : nil + } + + // MARK: - Reading + + private mutating func punctuation(for character: Character) -> Punctuation? { + if isInLineComment { + return nil + } + if isInStringLiteral { + if escapesNextCharacter { + escapesNextCharacter = false + } else if character == "\\" { + escapesNextCharacter = true + } else if character == "\"" { + isInStringLiteral = false + } + return nil + } + if isInBacktickName { + if character == "`" { + isInBacktickName = false + } + return nil + } + switch character { + case "\"": + isInStringLiteral = true + return nil + case "`": + isInBacktickName = true + return nil + case "/": + if previousCharacter == "/" { + isInLineComment = true + } + return nil + case "<", "(", "[": + return .opening(character) + case ">": + return previousCharacter == "-" ? nil : .closing(character) + case ")", "]": + return .closing(character) + case ",": + return openLists.isEmpty ? nil : .separator + default: + return nil + } + } + + private mutating func appendStandardText(_ fragment: SourceFragment) { + guard !fragment.text.isEmpty else { return } + appendNode(.text(fragment)) + if fragment.text.contains(where: { !$0.isWhitespace }) { + lastSignificantType = .standard + } + } + + private mutating func open(_ bracket: Character, at fragment: SourceFragment) { + let kind: BracketKind + switch bracket { + case "<": + kind = lastSignificantType.map(Self.namesADeclaration) == true ? .genericParameters : .genericArguments + case "(": + kind = .parentheses + default: + kind = .squareBrackets + } + openLists.append(OpenList(kind: kind, opening: fragment)) + lastSignificantType = .standard + } + + private mutating func close(_ bracket: Character, at fragment: SourceFragment) -> Bool { + guard var list = openLists.popLast(), list.kind.closingCharacter == bracket else { return false } + list.elements.append(list.currentElement) + let kind: BracketKind = list.kind == .genericArguments && Self.holdsRequirements(list.elements) ? .genericParameters : list.kind + let closedList = BracketList( + kind: kind, + opening: list.opening, + closing: fragment, + separators: list.separators, + elements: list.elements, + closingColumn: readCharacterCount - leadingIndentation + ) + appendNode(.list(closedList)) + lastSignificantType = .standard + return true + } + + private mutating func separate(at fragment: SourceFragment) { + let innermostIndex = openLists.count - 1 + openLists[innermostIndex].elements.append(openLists[innermostIndex].currentElement) + openLists[innermostIndex].currentElement = [] + openLists[innermostIndex].separators.append(fragment) + lastSignificantType = .standard + } + + private mutating func appendNode(_ node: BracketTreeNode) { + if openLists.isEmpty { + rootNodes.append(node) + } else { + openLists[openLists.count - 1].currentElement.append(node) + } + } + + /// Whether a `<…>` list holds requirements rather than types — a generic + /// signature, which the dump writes after a type name too + /// (`_ConditionalContent< where A: P, B: Q>`, `make`). + /// One element says `where`, `A: P` or `A == B` at its own level, outside + /// any list nested in it. A type argument never does: a module selector's + /// `::` and the dump's `(extension in M):` prefix have no space after the + /// colon, and a tuple's labels sit in a list of their own. + private static func holdsRequirements(_ elements: [[BracketTreeNode]]) -> Bool { + elements.contains { element in + let topLevelText = element.map { node in + if case .text(let fragment) = node { String(fragment.text) } else { " " } + }.joined() + return topLevelText.split(whereSeparator: \.isWhitespace).contains("where") + || topLevelText.contains(": ") + || topLevelText.contains("==") + } + } + + private static func namesADeclaration(_ type: SemanticType) -> Bool { + switch type { + case .type(_, .declaration), + .function(.declaration), + .member(.declaration): + true + default: + false + } + } +} diff --git a/Sources/Output/SwiftDeclarationRendering/MultilineTypeFormatting+Layout.swift b/Sources/Output/SwiftDeclarationRendering/MultilineTypeFormatting+Layout.swift new file mode 100644 index 000000000..2f04dd2f7 --- /dev/null +++ b/Sources/Output/SwiftDeclarationRendering/MultilineTypeFormatting+Layout.swift @@ -0,0 +1,164 @@ +import Semantic + +extension MultilineTypeFormatting { + /// How one line that runs past the width is laid out over several lines. + /// + /// A generic argument list inside no other generic argument list is the + /// outermost list of a type; when its closing `>` lies past the width, + /// that type is long. Inside a long type, every generic argument list + /// with two or more elements breaks. Any list — a long type's or not — + /// breaks when one of its elements spans several lines. Nothing else + /// breaks. + /// + /// `nil` when the line does not parse or has nothing to break, and so + /// stays as printed. + struct LineLayout { + /// How many spaces one level of a broken list indents by. + static let indentationWidth = 4 + + private let nodes: [BracketTreeNode] + + private let leadingIndentation: Int + + private let sourceComponents: [AtomicComponent] + + init?(line: SourceLine, sourceComponents: [AtomicComponent], maximumLineWidth: Int) { + guard let parsedNodes = BracketTree.parse(line, sourceComponents: sourceComponents) else { return nil } + let decision = Self.decidingBreaks( + in: parsedNodes, + maximumLineWidth: maximumLineWidth, + isInsideGenericArguments: false, + isInsideLongType: false + ) + guard decision.containsBrokenList else { return nil } + self.nodes = decision.nodes + self.leadingIndentation = line.leadingIndentation + self.sourceComponents = sourceComponents + } + + func emit(into builder: inout FormattedComponentBuilder) { + emit(nodes, depth: 0, into: &builder) + } + + // MARK: - Deciding + + /// `nodes` with every list's `isBroken` decided, bottom-up. + private static func decidingBreaks( + in nodes: [BracketTreeNode], + maximumLineWidth: Int, + isInsideGenericArguments: Bool, + isInsideLongType: Bool + ) -> (nodes: [BracketTreeNode], containsBrokenList: Bool) { + var decidedNodes: [BracketTreeNode] = [] + decidedNodes.reserveCapacity(nodes.count) + var containsBrokenList = false + for node in nodes { + guard case .list(var list) = node else { + decidedNodes.append(node) + continue + } + let isLongTypeRoot = list.kind == .genericArguments + && !isInsideGenericArguments + && list.closingColumn > maximumLineWidth + let isInLongType = isInsideLongType || isLongTypeRoot + let elementsAreInsideGenericArguments = isInsideGenericArguments || list.kind == .genericArguments + var hasMultilineElement = false + var decidedElements: [[BracketTreeNode]] = [] + decidedElements.reserveCapacity(list.elements.count) + for element in list.elements { + let decision = decidingBreaks( + in: element, + maximumLineWidth: maximumLineWidth, + isInsideGenericArguments: elementsAreInsideGenericArguments, + isInsideLongType: isInLongType + ) + hasMultilineElement = hasMultilineElement || decision.containsBrokenList + decidedElements.append(decision.nodes) + } + list.elements = decidedElements + let hasElements = list.elements.contains { !$0.isEmpty } + let breaksForItsArguments = isInLongType && list.kind == .genericArguments && list.elements.count >= 2 + list.isBroken = hasElements && (hasMultilineElement || breaksForItsArguments) + containsBrokenList = containsBrokenList || list.isBroken + decidedNodes.append(.list(list)) + } + return (decidedNodes, containsBrokenList) + } + + // MARK: - Emitting + + private func emit(_ nodes: [BracketTreeNode], depth: Int, into builder: inout FormattedComponentBuilder) { + for node in nodes { + switch node { + case .text(let fragment): + builder.append(fragment) + case .list(let list): + emit(list, depth: depth, into: &builder) + } + } + } + + /// A list as printed, or — broken — its opening bracket closing its + /// line, each element on a line of its own one level deeper, and its + /// closing bracket on a line of its own back at `depth`. + private func emit(_ list: BracketList, depth: Int, into builder: inout FormattedComponentBuilder) { + builder.append(list.opening) + guard list.isBroken else { + for (elementIndex, element) in list.elements.enumerated() { + emit(element, depth: depth, into: &builder) + if elementIndex < list.separators.count { + builder.append(list.separators[elementIndex]) + } + } + builder.append(list.closing) + return + } + let elementDepth = depth + 1 + for (elementIndex, element) in list.elements.enumerated() { + let precedingPunctuation = elementIndex == 0 ? list.opening : list.separators[elementIndex - 1] + builder.appendLineBreak( + indentation: leadingIndentation + Self.indentationWidth * elementDepth, + identifier: identifier(of: precedingPunctuation) + ) + emit(Self.trimmingWhitespace(of: element), depth: elementDepth, into: &builder) + if elementIndex < list.separators.count { + builder.append(list.separators[elementIndex]) + } + } + builder.appendLineBreak( + indentation: leadingIndentation + Self.indentationWidth * depth, + identifier: identifier(of: list.closing) + ) + builder.append(list.closing) + } + + private func identifier(of fragment: SourceFragment) -> String? { + sourceComponents[fragment.componentIndex].identifier + } + + /// `element` without the whitespace it starts and ends with — the + /// space after a `, ` above all, which a broken list replaces with a + /// line break. + private static func trimmingWhitespace(of element: [BracketTreeNode]) -> [BracketTreeNode] { + var nodes = element + while case .text(let fragment) = nodes.first { + let trimmedText = fragment.text.drop(while: \.isWhitespace) + if trimmedText.isEmpty { + nodes.removeFirst() + continue + } + nodes[0] = .text(SourceFragment(componentIndex: fragment.componentIndex, text: trimmedText)) + break + } + while case .text(let fragment) = nodes.last { + guard let lastVisibleIndex = fragment.text.lastIndex(where: { !$0.isWhitespace }) else { + nodes.removeLast() + continue + } + nodes[nodes.count - 1] = .text(SourceFragment(componentIndex: fragment.componentIndex, text: fragment.text[...lastVisibleIndex])) + break + } + return nodes + } + } +} diff --git a/Sources/Output/SwiftDeclarationRendering/MultilineTypeFormatting+Lines.swift b/Sources/Output/SwiftDeclarationRendering/MultilineTypeFormatting+Lines.swift new file mode 100644 index 000000000..ba11b840c --- /dev/null +++ b/Sources/Output/SwiftDeclarationRendering/MultilineTypeFormatting+Lines.swift @@ -0,0 +1,67 @@ +import Semantic + +extension MultilineTypeFormatting { + /// One line of the source: the fragments between two line breaks, and + /// the line break ending it. + struct SourceLine { + /// The line's text, without its line break. + let fragments: [SourceFragment] + + /// The `"\n"` ending the line; `nil` for the last line. + let terminator: SourceFragment? + + /// How many spaces the line starts with. + let leadingIndentation: Int + + /// The line's length in characters, less its leading indentation. + let contentWidth: Int + + init(fragments: [SourceFragment], terminator: SourceFragment?) { + self.fragments = fragments + self.terminator = terminator + var characterCount = 0 + var leadingSpaceCount = 0 + var isInLeadingIndentation = true + for fragment in fragments { + for character in fragment.text { + characterCount += 1 + if isInLeadingIndentation { + if character == " " { + leadingSpaceCount += 1 + } else { + isInLeadingIndentation = false + } + } + } + } + self.leadingIndentation = leadingSpaceCount + self.contentWidth = characterCount - leadingSpaceCount + } + + /// The lines of `components`, split at every `"\n"` — including one + /// inside a component, whose pieces each keep the component's index. + static func lines(in components: [AtomicComponent]) -> [SourceLine] { + var lines: [SourceLine] = [] + var currentFragments: [SourceFragment] = [] + for (componentIndex, component) in components.enumerated() { + let string = component.string + var segmentStart = string.startIndex + while let lineBreakIndex = string[segmentStart...].firstIndex(of: "\n") { + if segmentStart < lineBreakIndex { + currentFragments.append(SourceFragment(componentIndex: componentIndex, text: string[segmentStart ..< lineBreakIndex])) + } + let afterLineBreak = string.index(after: lineBreakIndex) + let terminator = SourceFragment(componentIndex: componentIndex, text: string[lineBreakIndex ..< afterLineBreak]) + lines.append(SourceLine(fragments: currentFragments, terminator: terminator)) + currentFragments = [] + segmentStart = afterLineBreak + } + if segmentStart < string.endIndex { + currentFragments.append(SourceFragment(componentIndex: componentIndex, text: string[segmentStart...])) + } + } + lines.append(SourceLine(fragments: currentFragments, terminator: nil)) + return lines + } + } +} diff --git a/Sources/Output/SwiftDeclarationRendering/MultilineTypeFormatting.swift b/Sources/Output/SwiftDeclarationRendering/MultilineTypeFormatting.swift new file mode 100644 index 000000000..1f4adb962 --- /dev/null +++ b/Sources/Output/SwiftDeclarationRendering/MultilineTypeFormatting.swift @@ -0,0 +1,142 @@ +import Semantic + +/// Lays the long types of printed Swift source out over several lines. +/// +/// A type that runs past `maximumLineWidth` is broken at its brackets: every +/// generic argument list with two or more arguments puts each argument on a +/// line of its own, and a single-argument generic list, a tuple, a parameter +/// list or collection sugar breaks only when one of its elements spans +/// several lines. A type that fits, and every line that fits, stays as +/// printed. Only a generic argument list running past the width starts a +/// break: a line that is long for any other reason — many short parameters, +/// a trailing comment — is left alone. +/// +/// ```swift +/// let formatting = MultilineTypeFormatting(maximumLineWidth: 100) +/// let interface = formatting.format(try await printer.printTypeDefinition(definition)) +/// ``` +/// +/// Formatting only adds line breaks and indentation, and drops the space of +/// each `, ` between broken elements. Everything else — the text, every +/// component's semantic type and identifier, and so every visibility, +/// definition and annotation region — stays as it was. Format a finished +/// print, not a piece still being composed into a container: when a line +/// changes, the result keeps one element per component rather than the +/// source's element boundaries. When no line changes, the result is `source` +/// itself. +/// +/// The width does not count a line's own indentation, so a declaration +/// breaks the same way at any nesting depth: a nested definition taken out +/// of its formatted parent and stripped of its indentation reads exactly as +/// the definition printed on its own and then formatted. +public struct MultilineTypeFormatting: Hashable, Sendable { + /// The widest a line's content may be, in characters, not counting the + /// line's own indentation. + public var maximumLineWidth: Int + + /// - Precondition: `maximumLineWidth > 0`. + public init(maximumLineWidth: Int = 100) { + precondition(maximumLineWidth > 0, "MultilineTypeFormatting needs a positive maximum line width, got \(maximumLineWidth)") + self.maximumLineWidth = maximumLineWidth + } + + /// `source` with its long types laid out over several lines. + /// + /// - Precondition: `maximumLineWidth > 0`. + public func format(_ source: SemanticString) -> SemanticString { + precondition(maximumLineWidth > 0, "MultilineTypeFormatting needs a positive maximum line width, got \(maximumLineWidth)") + let sourceComponents = source.components + var builder = FormattedComponentBuilder(sourceComponents: sourceComponents) + var hasChangedLine = false + for line in SourceLine.lines(in: sourceComponents) { + if line.contentWidth > maximumLineWidth, let layout = LineLayout(line: line, sourceComponents: sourceComponents, maximumLineWidth: maximumLineWidth) { + layout.emit(into: &builder) + hasChangedLine = true + } else { + builder.append(contentsOf: line.fragments) + } + if let terminator = line.terminator { + builder.append(terminator) + } + } + guard hasChangedLine else { return source } + return SemanticString(components: builder.finish()) + } +} + +// MARK: - Fragments + +extension MultilineTypeFormatting { + /// A run of one source component's text. + /// + /// Fragments are how a line is taken apart without losing where its text + /// came from: every piece of output that is not an inserted line break or + /// indentation is a fragment, and adjacent fragments of one component + /// join back into that component on output. + struct SourceFragment { + let componentIndex: Int + let text: Substring + } + + /// Collects the output components, joining adjacent fragments of one + /// source component back into a single component, so an unchanged run + /// of the source comes out component for component as it went in. + struct FormattedComponentBuilder { + let sourceComponents: [AtomicComponent] + + private var components: [AtomicComponent] = [] + + private var pendingFragment: SourceFragment? + + init(sourceComponents: [AtomicComponent]) { + self.sourceComponents = sourceComponents + } + + mutating func append(_ fragment: SourceFragment) { + guard !fragment.text.isEmpty else { return } + if let pendingFragment, + pendingFragment.componentIndex == fragment.componentIndex, + pendingFragment.text.endIndex == fragment.text.startIndex { + let joinedText = pendingFragment.text.base[pendingFragment.text.startIndex ..< fragment.text.endIndex] + self.pendingFragment = SourceFragment(componentIndex: fragment.componentIndex, text: joinedText) + return + } + flushPendingFragment() + pendingFragment = fragment + } + + mutating func append(contentsOf fragments: [SourceFragment]) { + for fragment in fragments { + append(fragment) + } + } + + /// A line break and the indentation after it, both carrying + /// `identifier` so they sit in the same regions as the component + /// they were inserted next to. + mutating func appendLineBreak(indentation: Int, identifier: String?) { + flushPendingFragment() + components.append(AtomicComponent(string: "\n", type: .standard, identifier: identifier)) + if indentation > 0 { + components.append(AtomicComponent(string: String(repeating: " ", count: indentation), type: .standard, identifier: identifier)) + } + } + + mutating func finish() -> [AtomicComponent] { + flushPendingFragment() + return components + } + + private mutating func flushPendingFragment() { + guard let pendingFragment else { return } + let sourceComponent = sourceComponents[pendingFragment.componentIndex] + if pendingFragment.text.startIndex == pendingFragment.text.base.startIndex, + pendingFragment.text.endIndex == pendingFragment.text.base.endIndex { + components.append(sourceComponent) + } else { + components.append(AtomicComponent(string: String(pendingFragment.text), type: sourceComponent.type, identifier: sourceComponent.identifier)) + } + self.pendingFragment = nil + } + } +} diff --git a/Sources/Output/SwiftDeclarationRendering/NestedFieldOffsetLevel.swift b/Sources/Output/SwiftDeclarationRendering/NestedFieldOffsetLevel.swift index 1a08bc04d..4ec84c721 100644 --- a/Sources/Output/SwiftDeclarationRendering/NestedFieldOffsetLevel.swift +++ b/Sources/Output/SwiftDeclarationRendering/NestedFieldOffsetLevel.swift @@ -1,5 +1,6 @@ import Foundation import FoundationToolbox +import Demangling /// What the in-process nested field-offset walk reads about one metatype: /// everything it prints for that metatype's rows and everything it needs to @@ -26,7 +27,13 @@ enum NestedFieldOffsetLevel: @unchecked Sendable { struct StructField { let fieldName: String + /// The field type printed with `.default`: what the row prints unless + /// the printer spells it (`DeclarationRenderConfiguration.fieldLayoutTypeName(printedName:typeNode:)`). let typeName: String + /// The node `typeName` was printed from, kept so a printer can spell + /// it its own way without demangling the field type again (evolution + /// proposal `consistent-c-imported-type-spelling`). + let typeNode: Node? let relativeOffset: Int /// The field's metatype, or `nil` when the walk does not descend. let childMetatype: Any.Type? @@ -38,7 +45,10 @@ enum NestedFieldOffsetLevel: @unchecked Sendable { struct EnumPayload { let caseName: String + /// As ``StructField/typeName``. let typeName: String + /// As ``StructField/typeNode``. + let typeNode: Node? let payloadMetatype: Any.Type /// Counted over every payload case, including one whose payload did /// not resolve and so has no entry. diff --git a/Sources/Output/SwiftDeclarationRendering/OpaqueReferenceSpelling.swift b/Sources/Output/SwiftDeclarationRendering/OpaqueReferenceSpelling.swift index 20a0e6cb7..d927d65c0 100644 --- a/Sources/Output/SwiftDeclarationRendering/OpaqueReferenceSpelling.swift +++ b/Sources/Output/SwiftDeclarationRendering/OpaqueReferenceSpelling.swift @@ -5,6 +5,7 @@ import SwiftSymbols import MachOSwiftSection @_spi(Internals) import Demangling @_spi(Internals) import SwiftInspection +import OrderedCollections /// How an opaque reference the rewriter could not expand is spelled in the /// tree it leaves behind (evolution proposal diff --git a/Sources/Output/SwiftDeclarationRendering/RuntimeFieldLayoutBackend.swift b/Sources/Output/SwiftDeclarationRendering/RuntimeFieldLayoutBackend.swift index 0773d8513..b3d5bb1f4 100644 --- a/Sources/Output/SwiftDeclarationRendering/RuntimeFieldLayoutBackend.swift +++ b/Sources/Output/SwiftDeclarationRendering/RuntimeFieldLayoutBackend.swift @@ -121,17 +121,17 @@ struct RuntimeFieldLayoutBackend { } else { endOffset = nil } - configuration.optionalContent(.printFieldOffset) { + await configuration.optionalContent(.printFieldOffset) { // The tree belongs to the field offset's region, so a host // folds it under that line. - configuration.commentRegion(.fieldOffset) { + await configuration.commentRegion(.fieldOffset) { configuration.fieldOffsetComment(startOffset: startOffset, endOffset: endOffset) // Expanded offsets hang off the field offset: printed only // when both are on. A field whose specialized resolution // failed may still resolve by its bare name, so the expansion // keeps that second try. - configuration.optionalContent(.printExpandedFieldOffsets) { - expandedFieldOffsets( + await configuration.optionalContent(.printExpandedFieldOffsets) { + await expandedFieldOffsets( of: fieldMetatype ?? (try? RuntimeFunctions.getTypeByMangledNameInContext(mangledTypeName, in: machO)), baseOffset: startOffset, baseIndentation: configuration.indentation, @@ -224,9 +224,9 @@ struct RuntimeFieldLayoutBackend { // rationale on the PAC-fault-avoiding static substitution. @SemanticStringBuilder - func expandedFieldOffsets(of topMetatype: Any.Type?, baseOffset: Int, baseIndentation: Int, ancestors: [Bool]) -> SemanticString { + func expandedFieldOffsets(of topMetatype: Any.Type?, baseOffset: Int, baseIndentation: Int, ancestors: [Bool]) async -> SemanticString { if let topMetatype { - walkNestedExpandedFieldOffsets(of: topMetatype, baseOffset: baseOffset, baseIndentation: baseIndentation, ancestors: ancestors, enclosingMetatypes: []) + await walkNestedExpandedFieldOffsets(of: topMetatype, baseOffset: baseOffset, baseIndentation: baseIndentation, ancestors: ancestors, enclosingMetatypes: []) } } @@ -251,9 +251,11 @@ struct RuntimeFieldLayoutBackend { /// What one level reads about its metatype comes from /// `nestedFieldOffsetLevel(of:)`, built once per metatype; the walk itself /// — the rows, their offsets and tree prefixes, the cycle and depth guards - /// and their log lines — is the same either way. + /// and their log lines — is the same either way. A row's type is spelled + /// as the configuration asks (`fieldLayoutTypeName(printedName:typeNode:)`), + /// from the node the level kept. @SemanticStringBuilder - private func walkNestedExpandedFieldOffsets(of metatype: Any.Type, baseOffset: Int, baseIndentation: Int, ancestors: [Bool], depth: Int = 0, enclosingMetatypes: Set) -> SemanticString { + private func walkNestedExpandedFieldOffsets(of metatype: Any.Type, baseOffset: Int, baseIndentation: Int, ancestors: [Bool], depth: Int = 0, enclosingMetatypes: Set) async -> SemanticString { if enclosingMetatypes.contains(ObjectIdentifier(metatype)) { emitNestedFieldOffsetCycleWarning(for: metatype) } else if depth >= nestedFieldOffsetExpansionDepthLimit { @@ -266,19 +268,21 @@ struct RuntimeFieldLayoutBackend { case .structFields(let fields): for field in fields { let absoluteOffset = baseOffset + field.relativeOffset - configuration.commentRegion(.fieldLayoutNode) { - configuration.expandedFieldOffsetComment(fieldName: field.fieldName, typeName: field.typeName, offset: absoluteOffset, baseIndentation: baseIndentation, ancestors: ancestors, isLast: field.isLast) + let typeName = await configuration.fieldLayoutTypeName(printedName: field.typeName, typeNode: field.typeNode) + await configuration.commentRegion(.fieldLayoutNode) { + configuration.expandedFieldOffsetComment(fieldName: field.fieldName, typeName: typeName, offset: absoluteOffset, baseIndentation: baseIndentation, ancestors: ancestors, isLast: field.isLast) if let childMetatype = field.childMetatype { - walkNestedExpandedFieldOffsets(of: childMetatype, baseOffset: absoluteOffset, baseIndentation: baseIndentation, ancestors: ancestors + [field.isLast], depth: depth + 1, enclosingMetatypes: nestedEnclosingMetatypes) + await walkNestedExpandedFieldOffsets(of: childMetatype, baseOffset: absoluteOffset, baseIndentation: baseIndentation, ancestors: ancestors + [field.isLast], depth: depth + 1, enclosingMetatypes: nestedEnclosingMetatypes) } } } case .enumPayloads(let payloads): for payload in payloads { - configuration.commentRegion(.fieldLayoutNode) { - configuration.expandedFieldOffsetComment(fieldName: payload.caseName, typeName: payload.typeName, offset: baseOffset, baseIndentation: baseIndentation, ancestors: ancestors, isLast: payload.isLast) + let typeName = await configuration.fieldLayoutTypeName(printedName: payload.typeName, typeNode: payload.typeNode) + await configuration.commentRegion(.fieldLayoutNode) { + configuration.expandedFieldOffsetComment(fieldName: payload.caseName, typeName: typeName, offset: baseOffset, baseIndentation: baseIndentation, ancestors: ancestors, isLast: payload.isLast) if payload.descends { - walkNestedExpandedFieldOffsets(of: payload.payloadMetatype, baseOffset: baseOffset, baseIndentation: baseIndentation, ancestors: ancestors + [payload.isLast], depth: depth + 1, enclosingMetatypes: nestedEnclosingMetatypes) + await walkNestedExpandedFieldOffsets(of: payload.payloadMetatype, baseOffset: baseOffset, baseIndentation: baseIndentation, ancestors: ancestors + [payload.isLast], depth: depth + 1, enclosingMetatypes: nestedEnclosingMetatypes) } } } @@ -336,9 +340,11 @@ struct RuntimeFieldLayoutBackend { for (fieldIndex, (nestedFieldRecord, nestedRelativeOffset)) in fieldEntries.enumerated() { guard let fieldName = try? nestedFieldRecord.fieldName(in: .inProcess) else { continue } let nestedMangledTypeName = try? nestedFieldRecord.mangledTypeName(in: .inProcess) + let fieldTypeNode = nestedTypeNode(for: nestedMangledTypeName, parentMetadata: metadata) fields.append(NestedFieldOffsetLevel.StructField( fieldName: fieldName, - typeName: nestedTypeName(for: nestedMangledTypeName, parentMetadata: metadata), + typeName: Self.defaultTypeName(of: fieldTypeNode), + typeNode: fieldTypeNode, relativeOffset: Int(nestedRelativeOffset), childMetatype: nestedMangledTypeName.flatMap { resolveNestedMetatype(for: $0, parentMetadata: metadata) }, isLast: fieldIndex == fieldEntries.count - 1 @@ -359,9 +365,11 @@ struct RuntimeFieldLayoutBackend { !mangledTypeName.isEmpty, let payloadMetatype = resolveNestedMetatype(for: mangledTypeName, parentMetadata: metadata) else { continue } + let payloadTypeNode = nestedTypeNode(for: mangledTypeName, parentMetadata: metadata) payloads.append(NestedFieldOffsetLevel.EnumPayload( caseName: (try? payloadRecord.fieldName(in: .inProcess)) ?? "payload", - typeName: nestedTypeName(for: mangledTypeName, parentMetadata: metadata), + typeName: Self.defaultTypeName(of: payloadTypeNode), + typeNode: payloadTypeNode, payloadMetatype: payloadMetatype, isLast: payloadIndex == payloadRecords.count - 1, // An indirect case stores a `Builtin.NativeObject` box @@ -392,12 +400,21 @@ struct RuntimeFieldLayoutBackend { return try? RuntimeFunctions.getTypeByMangledNameInContext(mangledTypeName) } - private func nestedTypeName(for mangledTypeName: MangledName?, parentMetadata: some ValueMetadataProtocol) -> String { - guard let mangledTypeName else { return "" } + /// A nested field's type with the parent's generic arguments substituted + /// where they can be read, else as the record names it; `nil` when the + /// record names nothing or its name does not demangle. + private func nestedTypeNode(for mangledTypeName: MangledName?, parentMetadata: some ValueMetadataProtocol) -> Node? { + guard let mangledTypeName else { return nil } if let substitutedNode = substitutedNestedTypeNode(for: mangledTypeName, parentMetadata: parentMetadata) { - return substitutedNode.printSemantic(using: .default).string + return substitutedNode } - return (try? SymbolicDemangler.demangleTypeUncached(for: mangledTypeName, in: .inProcess).printSemantic(using: .default).string) ?? "" + return try? SymbolicDemangler.demangleTypeUncached(for: mangledTypeName, in: .inProcess) + } + + /// The `.default` spelling a row keeps beside its node: what the dump + /// prints, and what a printer that spells nothing itself prints. + private static func defaultTypeName(of typeNode: Node?) -> String { + typeNode?.printSemantic(using: .default).string ?? "" } // MARK: - Static generic-argument substitution (PAC-fault-avoiding) @@ -479,9 +496,11 @@ struct RuntimeFieldLayoutBackend { /// `dependentGenericParamType`, whose enclosing `.type` wrapper is preserved /// by the recursion — so `.value` yields the canonical `type(integer)` shape /// and `.type` the canonical `type()`, exactly as the demangler - /// would. The result is print-only (`nestedTypeName` → - /// `printSemantic(using: .default)`); it is never remangled, so a bare - /// `pack` child (printed as `Pack{…}`) needs no further wrapping. + /// would. The result is print-only — a row's `.default` spelling, and the + /// node a printer spells its own way (`nestedTypeNode(for:parentMetadata:)`); + /// it is never remangled, so a bare `pack` child needs no further + /// wrapping: `.default` prints it as `Pack{…}`, the interface printer as + /// its bare elements. private func substitutingGenericParameters(in node: Node, parentMetadata: some ValueMetadataProtocol, layout: TopLevelGenericLayout) -> Node { if #available(macOS 11, iOS 14, tvOS 14, watchOS 7, *), node.kind == .dependentGenericParamType, @@ -687,6 +706,7 @@ struct RuntimeFieldLayoutBackend { let payloadSize = try enumPayloadSize(enumValue.descriptor, in: machOImage) let numberOfPayloadCases = enumValue.numberOfPayloadCases let numberOfEmptyCases = enumValue.numberOfEmptyCases + guard EnumLayoutCalculator.canProjectCases(numPayloadCases: Int(numberOfPayloadCases), numEmptyCases: Int(numberOfEmptyCases)) else { return nil } var layoutResult: EnumLayoutCalculator.LayoutResult if enumValue.isMultiPayload { let node = try SymbolicDemangler.demangleContext(for: .type(.enum(enumValue.descriptor)), in: machOImage.context) diff --git a/Sources/Output/SwiftDeclarationRendering/StaticFieldLayoutBackend.swift b/Sources/Output/SwiftDeclarationRendering/StaticFieldLayoutBackend.swift index 5f70e6ba6..658c12717 100644 --- a/Sources/Output/SwiftDeclarationRendering/StaticFieldLayoutBackend.swift +++ b/Sources/Output/SwiftDeclarationRendering/StaticFieldLayoutBackend.swift @@ -6,6 +6,7 @@ import MachOSwiftSection import SwiftLayout import Utilities @_spi(Internals) import SwiftInspection +import SwiftStdlibToolbox /// `MachOFile` renders field comments **statically** through the `SwiftLayout` /// engine — no process, no metadata accessor. @@ -107,15 +108,15 @@ struct StaticFieldLayoutBackend { } else { endOffset = nil } - configuration.optionalContent(.printFieldOffset) { + await configuration.optionalContent(.printFieldOffset) { // The tree belongs to the field offset's region, so a host // folds it under that line. - configuration.commentRegion(.fieldOffset) { + await configuration.commentRegion(.fieldOffset) { configuration.fieldOffsetComment(startOffset: startOffset, endOffset: endOffset) // Expanded offsets hang off the field offset: printed only // when both are on. - configuration.optionalContent(.printExpandedFieldOffsets) { - expandedFieldOffsets(for: mangledTypeName, baseOffset: startOffset) + await configuration.optionalContent(.printExpandedFieldOffsets) { + await expandedFieldOffsets(for: mangledTypeName, baseOffset: startOffset) } } } @@ -153,6 +154,8 @@ struct StaticFieldLayoutBackend { return "unsupported type kind \(nodeKindName)" case .typeDescriptorNotFound(let qualifiedTypeName): return "type descriptor not found for \(qualifiedTypeName)" + case .ambiguousTypeName(let qualifiedTypeName): + return "\(qualifiedTypeName) names more than one type" case .genericParameterUnsubstituted: return "generic parameter not substituted" case .cyclicLayout: @@ -163,13 +166,15 @@ struct StaticFieldLayoutBackend { return "preceding field unresolved" case .foreignTypeFieldOffsetsUnavailable: return "C-imported type; field offsets not derivable from reflection" + case .sizeOverflow: + return "size exceeds what any value can take" } } // MARK: - Expanded nested field offsets @SemanticStringBuilder - private func expandedFieldOffsets(for mangledTypeName: MangledName, baseOffset: Int) -> SemanticString { + private func expandedFieldOffsets(for mangledTypeName: MangledName, baseOffset: Int) async -> SemanticString { if let provider = configuration.staticFieldLayoutProvider { let tree = if let genericArgumentBinding { provider.nestedFieldOffsetTree( @@ -185,19 +190,20 @@ struct StaticFieldLayoutBackend { depthLimit: nestedFieldOffsetExpansionDepthLimit ) } - renderNestedFieldOffsetTree(tree, ancestors: []) + await renderNestedFieldOffsetTree(tree, ancestors: []) } } @SemanticStringBuilder - private func renderNestedFieldOffsetTree(_ nodes: [NestedFieldOffset], ancestors: [Bool]) -> SemanticString { + private func renderNestedFieldOffsetTree(_ nodes: [NestedFieldOffset], ancestors: [Bool]) async -> SemanticString { for (index, node) in nodes.enumerated() { let isLast = index == nodes.count - 1 + let typeName = await configuration.fieldLayoutTypeName(printedName: node.typeName, typeNode: node.typeNode) // A row's region holds the rows nested under it: the tree is the // regions' nesting. - configuration.commentRegion(.fieldLayoutNode) { - configuration.expandedFieldOffsetComment(fieldName: node.fieldName, typeName: node.typeName, offset: node.offset, baseIndentation: configuration.indentation, ancestors: ancestors, isLast: isLast) - renderNestedFieldOffsetTree(node.children, ancestors: ancestors + [isLast]) + await configuration.commentRegion(.fieldLayoutNode) { + configuration.expandedFieldOffsetComment(fieldName: node.fieldName, typeName: typeName, offset: node.offset, baseIndentation: configuration.indentation, ancestors: ancestors, isLast: isLast) + await renderNestedFieldOffsetTree(node.children, ancestors: ancestors + [isLast]) } } } diff --git a/Sources/Output/SwiftDiffing/ABIDiffer.swift b/Sources/Output/SwiftDiffing/ABIDiffer.swift index af46ccc52..892d95d08 100644 --- a/Sources/Output/SwiftDiffing/ABIDiffer.swift +++ b/Sources/Output/SwiftDiffing/ABIDiffer.swift @@ -1,6 +1,8 @@ import Demangling +import MachOSwiftSection import OrderedCollections import SwiftDeclaration +import SwiftSymbols /// Diffs the Swift ABI of two indexed modules by keying every declaration on /// its remangled `Node` and computing a recursive three-way set difference. diff --git a/Sources/Output/SwiftDiffing/ABIKey.swift b/Sources/Output/SwiftDiffing/ABIKey.swift index 415beea35..6e9cc7304 100644 --- a/Sources/Output/SwiftDiffing/ABIKey.swift +++ b/Sources/Output/SwiftDiffing/ABIKey.swift @@ -1,4 +1,5 @@ import Demangling +import Foundation /// A stable, version-independent identity for a Swift declaration, derived by /// *remangling* its demangled `Node` back into a canonical symbol string. diff --git a/Sources/Output/SwiftDump/Dumper/ObjCImplementationClassDumper.swift b/Sources/Output/SwiftDump/Dumper/ObjCImplementationClassDumper.swift index 9166d3e58..7e6384130 100644 --- a/Sources/Output/SwiftDump/Dumper/ObjCImplementationClassDumper.swift +++ b/Sources/Output/SwiftDump/Dumper/ObjCImplementationClassDumper.swift @@ -17,7 +17,9 @@ import SwiftDeclarationRendering /// the Swift symbols found there, the property list, the protocol list, then /// the Swift member symbols the way `ClassDumper` lists a class's. Nothing /// is guessed: an IMP with no symbol prints as an address, an ivar with no -/// field-offset symbol prints its ObjC facts and no Swift type. +/// field-offset symbol prints its ObjC facts, and the Swift type only when the +/// Objective-C side gives it, saying which part did (evolution proposal +/// `objc-ivar-type-recovery`). package struct ObjCImplementationClassDumper: NamedDumper { package typealias Dumped = ObjCImplementationClass @@ -139,6 +141,7 @@ package struct ObjCImplementationClassDumper: configuration.fieldOffsetComment(startOffset: instanceVariable.offset, endOffset: instanceVariable.offset + instanceVariable.size) } Indent(level: 1) + let recoveredType = instanceVariable.swiftTypeNode == nil ? recoveredSwiftType(of: instanceVariable) : nil if let typeNode = instanceVariable.swiftTypeNode, let propertyName = instanceVariable.swiftPropertyName { // A `lazy var`'s storage prints under the property's name with // its storage type, as `ClassDumper` prints a Swift type's own @@ -157,11 +160,24 @@ package struct ObjCImplementationClassDumper: Standard(":") Space() try await demangleResolver.resolve(for: typeNode.materialize()) + } else if let recoveredType { + if recoveredType.isWeak { + Keyword(.weak) + Space() + Keyword(.var) + } else { + Keyword(recoveredType.isReadOnly ? .let : .var) + } + Space() + MemberDeclaration(instanceVariable.name) + Standard(":") + Space() + try await demangleResolver.resolve(for: recoveredType.typeNode) } else { MemberDeclaration(instanceVariable.name.isEmpty ? "" : instanceVariable.name) } Space() - Comment(instanceVariableComment(for: instanceVariable)) + Comment(instanceVariableComment(for: instanceVariable, recoveredType: recoveredType)) if offset.isEnd { BreakLine() } @@ -169,13 +185,29 @@ package struct ObjCImplementationClassDumper: } } - private func instanceVariableComment(for instanceVariable: ObjCImplementationClassFacts.InstanceVariable) -> String { + /// The Swift type the Objective-C side gives an ivar with no + /// field-offset symbol, as the interface prints it. + private func recoveredSwiftType(of instanceVariable: ObjCImplementationClassFacts.InstanceVariable) -> ObjCInstanceVariableSwiftType? { + guard !instanceVariable.name.isEmpty else { return nil } + let objcProperty = facts.objcProperty(storedIn: instanceVariable, swiftPropertyName: instanceVariable.swiftPropertyName ?? instanceVariable.name) + return ObjCInstanceVariableSwiftType(instanceVariable: instanceVariable, objcProperty: objcProperty, in: machO) + } + + private func instanceVariableComment(for instanceVariable: ObjCImplementationClassFacts.InstanceVariable, recoveredType: ObjCInstanceVariableSwiftType?) -> String { var parts = ["offset 0x\(String(instanceVariable.offset, radix: 16))", "size \(instanceVariable.size)", "alignment \(instanceVariable.alignment)", "encoding \"\(instanceVariable.typeEncoding)\""] if !instanceVariable.name.isEmpty, instanceVariable.swiftPropertyName != nil, instanceVariable.name != instanceVariable.swiftPropertyName { parts.append("ivar \(instanceVariable.name)") } if let symbolName = instanceVariable.swiftFieldOffsetSymbolName { parts.append(symbolName) + } else if let recoveredType { + switch recoveredType.source { + case .instanceVariableEncoding: parts.append("Swift type from the ObjC type encoding") + case .objcProperty: parts.append("Swift type from the ObjC property") + } + if let alternativeNote = recoveredType.alternativeDeclarationNote(named: instanceVariable.name) { + parts.append(alternativeNote) + } } else { parts.append("Swift type not recoverable") } diff --git a/Sources/Output/SwiftDump/Dumper/ObjCMemberRendering.swift b/Sources/Output/SwiftDump/Dumper/ObjCMemberRendering.swift index 599a0f280..8c5bed476 100644 --- a/Sources/Output/SwiftDump/Dumper/ObjCMemberRendering.swift +++ b/Sources/Output/SwiftDump/Dumper/ObjCMemberRendering.swift @@ -2,6 +2,7 @@ import MachOSwiftSection @_spi(Internals) import SwiftSymbols @_spi(Internals) import SwiftInspection import SwiftObjCInterop +import Demangling /// Comment text the dumpers share for the ObjC member facts (evolution /// proposals `objc-ancestor-override-recovery` and diff --git a/Sources/Output/SwiftInterface/AnySwiftEvolutionInterfaceBuilder.swift b/Sources/Output/SwiftInterface/AnySwiftEvolutionInterfaceBuilder.swift index add6a0e91..af564d6e6 100644 --- a/Sources/Output/SwiftInterface/AnySwiftEvolutionInterfaceBuilder.swift +++ b/Sources/Output/SwiftInterface/AnySwiftEvolutionInterfaceBuilder.swift @@ -72,8 +72,8 @@ public final class AnySwiftEvolutionInterfaceBuilder: Sendable { /// `.labelCountMismatch` on invalid input shapes. public init( configuration: SwiftDeclarationIndexConfiguration = .init(), - eventHandlers: [SwiftIndexEvents.Handler] = [], - eventHandlersPerVersion: ((_ versionIndex: Int, _ label: String) -> [SwiftIndexEvents.Handler])? = nil, + eventHandlers: [any SwiftIndexEvents.Handler] = [], + eventHandlersPerVersion: ((_ versionIndex: Int, _ label: String) -> [any SwiftIndexEvents.Handler])? = nil, versions: [MachO], labels: [String], availabilityAnnotationPlatform: String? = nil @@ -108,8 +108,8 @@ public final class AnySwiftEvolutionInterfaceBuilder: Sendable { /// `.labelCountMismatch` on invalid input shapes. public init( configuration: SwiftDeclarationIndexConfiguration = .init(), - eventHandlers: [SwiftIndexEvents.Handler] = [], - eventHandlersPerVersion: ((_ versionIndex: Int, _ label: String) -> [SwiftIndexEvents.Handler])? = nil, + eventHandlers: [any SwiftIndexEvents.Handler] = [], + eventHandlersPerVersion: ((_ versionIndex: Int, _ label: String) -> [any SwiftIndexEvents.Handler])? = nil, imageGroups: [[SwiftEvolutionInterfaceImage]], labels: [String], availabilityAnnotationPlatform: String? = nil @@ -133,7 +133,7 @@ public final class AnySwiftEvolutionInterfaceBuilder: Sendable { /// available everywhere the package deploys. public init( configuration: SwiftDeclarationIndexConfiguration = .init(), - eventHandlers: [SwiftIndexEvents.Handler] = [], + eventHandlers: [any SwiftIndexEvents.Handler] = [], versions: repeat each Reader, labels: [String], availabilityAnnotationPlatform: String? = nil diff --git a/Sources/Output/SwiftInterface/InterfaceVersionRendering.swift b/Sources/Output/SwiftInterface/InterfaceVersionRendering.swift index 52109a493..3a65a4f07 100644 --- a/Sources/Output/SwiftInterface/InterfaceVersionRendering.swift +++ b/Sources/Output/SwiftInterface/InterfaceVersionRendering.swift @@ -108,7 +108,7 @@ final class InterfaceVersionUnit: InterfaceVe /// path, where each version arrives as a bare reader. convenience init( configuration: SwiftDeclarationIndexConfiguration, - eventHandlers: [SwiftIndexEvents.Handler], + eventHandlers: [any SwiftIndexEvents.Handler], machO: MachO, imageName: String? = nil ) { @@ -214,7 +214,7 @@ final class InterfaceVersionGroupUnit: Interf @Mutex private var routing: Routing = Routing() - init(configuration: SwiftDeclarationIndexConfiguration, eventHandlers: [SwiftIndexEvents.Handler], images: [(imageName: String, machO: MachO)]) { + init(configuration: SwiftDeclarationIndexConfiguration, eventHandlers: [any SwiftIndexEvents.Handler], images: [(imageName: String, machO: MachO)]) { self.imageUnits = images.map { image in InterfaceVersionUnit(configuration: configuration, eventHandlers: eventHandlers, machO: image.machO, imageName: image.imageName) } diff --git a/Sources/Output/SwiftInterface/SwiftDeclarationPrinter+DiffRendering.swift b/Sources/Output/SwiftInterface/SwiftDeclarationPrinter+DiffRendering.swift index 864e6ea41..c89441185 100644 --- a/Sources/Output/SwiftInterface/SwiftDeclarationPrinter+DiffRendering.swift +++ b/Sources/Output/SwiftInterface/SwiftDeclarationPrinter+DiffRendering.swift @@ -4,6 +4,7 @@ import MachOSwiftSection import Semantic import Demangling @_spi(Support) import SwiftPrinting +import SwiftDeclarationRendering /// Diff-only rendering entry points on `SwiftDeclarationPrinter`. /// diff --git a/Sources/Output/SwiftInterface/SwiftDiffableInterfaceBuilder.swift b/Sources/Output/SwiftInterface/SwiftDiffableInterfaceBuilder.swift index 74d41afdf..ded37271c 100644 --- a/Sources/Output/SwiftInterface/SwiftDiffableInterfaceBuilder.swift +++ b/Sources/Output/SwiftInterface/SwiftDiffableInterfaceBuilder.swift @@ -5,6 +5,7 @@ import SwiftDiffing import MachOSwiftSection @_spi(Internals) import SwiftSymbols import Dependencies +import OrderedCollections /// The ABI-diff analogue of ``SwiftInterfaceBuilder``. /// @@ -24,7 +25,7 @@ public final class SwiftDiffableInterfaceBuilder: Sen public private(set) var importedModules: OrderedSet = [] @Mutex - public private(set) var extraDataProviders: [SwiftInterfaceBuilderExtraDataProvider] = [] + public private(set) var extraDataProviders: [any SwiftInterfaceBuilderExtraDataProvider] = [] private let eventDispatcher: SwiftIndexEvents.Dispatcher @@ -55,7 +55,7 @@ public final class SwiftInterfaceBuilder: Sen /// - eventDispatcher: An event dispatcher for handling logging and progress events. A new one is created by default. /// - machO: The Mach-O binary to analyze and generate interfaces from. /// - Throws: An error if the binary cannot be read or if required Swift sections are missing. - public init(configuration: SwiftInterfaceBuilderConfiguration = .init(), eventHandlers: [SwiftIndexEvents.Handler] = [], in machO: MachO) throws { + public init(configuration: SwiftInterfaceBuilderConfiguration = .init(), eventHandlers: [any SwiftIndexEvents.Handler] = [], in machO: MachO) throws { self.eventDispatcher = .init() self.machO = machO self.indexer = .init(configuration: configuration.indexConfiguration, eventHandlers: eventHandlers, in: machO) @@ -65,7 +65,7 @@ public final class SwiftInterfaceBuilder: Sen } @_spi(Support) - public init(indexer: SwiftDeclarationIndexer, printer: SwiftDeclarationPrinter, eventHandlers: [SwiftIndexEvents.Handler] = [], in machO: MachO) { + public init(indexer: SwiftDeclarationIndexer, printer: SwiftDeclarationPrinter, eventHandlers: [any SwiftIndexEvents.Handler] = [], in machO: MachO) { self.eventDispatcher = .init() self.machO = machO self.indexer = indexer diff --git a/Sources/Output/SwiftInterface/SwiftInterfaceBuilderDependencies.swift b/Sources/Output/SwiftInterface/SwiftInterfaceBuilderDependencies.swift index 121dbe69d..a2ddd34a4 100644 --- a/Sources/Output/SwiftInterface/SwiftInterfaceBuilderDependencies.swift +++ b/Sources/Output/SwiftInterface/SwiftInterfaceBuilderDependencies.swift @@ -7,7 +7,7 @@ import MachODependencies import MachOSwiftSection import MachOFoundation -/// The images a provider such as TypeIndexing's +/// The images a provider such as `SwiftTypeNameResolution`'s /// `SwiftInterfaceBuilderTypeNameProvider` works against: the root plus its /// **direct** dependencies only. /// @@ -50,7 +50,7 @@ extension SwiftInterfaceBuilderDependencies { /// open. Defaulted, so existing call sites are unaffected — and passing /// none is safe rather than silent: `SwiftIndexEvents.Dispatcher` reports /// an unhandled failure to os_log rather than dropping it. - public init(machO: MachO, searchPaths: [DependencySearchPath], eventHandlers: [SwiftIndexEvents.Handler] = []) { + public init(machO: MachO, searchPaths: [DependencySearchPath], eventHandlers: [any SwiftIndexEvents.Handler] = []) { let closure = DependencyClosure(root: machO, searchPaths: searchPaths, traversal: .direct) if !closure.searchPathLoadFailures.isEmpty { let eventDispatcher = SwiftIndexEvents.Dispatcher() @@ -68,7 +68,7 @@ extension SwiftInterfaceBuilderDependencies { } @available(*, deprecated, renamed: "init(machO:searchPaths:eventHandlers:)") - public init(machO: MachO, paths: [DependencyPath], eventHandlers: [SwiftIndexEvents.Handler] = []) { + public init(machO: MachO, paths: [DependencyPath], eventHandlers: [any SwiftIndexEvents.Handler] = []) { self.init(machO: machO, searchPaths: paths.map(\.searchPath), eventHandlers: eventHandlers) } diff --git a/Sources/Output/SwiftInterface/SwiftInterfaceBuilderExtraDataProvider.swift b/Sources/Output/SwiftInterface/SwiftInterfaceBuilderExtraDataProvider.swift index f1d708d01..bc655852e 100644 --- a/Sources/Output/SwiftInterface/SwiftInterfaceBuilderExtraDataProvider.swift +++ b/Sources/Output/SwiftInterface/SwiftInterfaceBuilderExtraDataProvider.swift @@ -7,7 +7,8 @@ import Demangling /// `setup()` runs during `prepare()`. Resolver-ness is an orthogonal /// capability — a provider that answers printer queries additionally conforms /// to the `TypeNameResolving` role protocols (`ModuleNameResolving`, -/// `CImportedNameResolving`, `OpaqueTypeResolving`), and `addExtraDataProvider` +/// `CImportedNameResolving`, `MovedTypeModuleResolving`, +/// `OpaqueTypeResolving`), and `addExtraDataProvider` /// forwards it to the printer only then. A setup-only provider is a legitimate /// conformer. public protocol SwiftInterfaceBuilderExtraDataProvider: Sendable { diff --git a/Sources/Output/SwiftInterface/SwiftInterfaceBuilderOpaqueTypeProvider.swift b/Sources/Output/SwiftInterface/SwiftInterfaceBuilderOpaqueTypeProvider.swift index 3fcd24760..1e0fc1244 100644 --- a/Sources/Output/SwiftInterface/SwiftInterfaceBuilderOpaqueTypeProvider.swift +++ b/Sources/Output/SwiftInterface/SwiftInterfaceBuilderOpaqueTypeProvider.swift @@ -10,6 +10,7 @@ import Dependencies import SwiftStdlibToolbox import SwiftDeclarationRendering @_spi(Internals) import SwiftInspection +import Semantic /// Carries the logging floor onto the provider. /// diff --git a/Sources/Output/SwiftPrinting/AnnotationRegionKind+CImportedTypeName.swift b/Sources/Output/SwiftPrinting/AnnotationRegionKind+CImportedTypeName.swift new file mode 100644 index 000000000..8cb8d4633 --- /dev/null +++ b/Sources/Output/SwiftPrinting/AnnotationRegionKind+CImportedTypeName.swift @@ -0,0 +1,48 @@ +import Semantic + +/// The two names of a C-imported type: what Swift code calls it and what its C +/// declaration is called (evolution proposal `c-imported-type-name-spelling`). +public struct CImportedTypeNames: Sendable, Hashable { + /// `AnyWeakAttribute`; dotted when a resolver spells a type imported as a + /// member (`NSAttributedString.Key`). + public let swiftName: String + + /// `AGWeakAttribute`, the name every mangled reference spells. + public let cName: String + + public init(swiftName: String, cName: String) { + self.swiftName = swiftName + self.cName = cName + } +} + +extension AnnotationRegion.Kind { + private static let cImportedTypeNamePrefix = "cImportedTypeName" + + /// In no Swift or C name, so a dotted Swift name passes through whole. Not + /// a control character: swift-semantic-string rejects those in a kind, + /// since its own markers are control characters. + private static let cImportedTypeNameSeparator: Character = "|" + + /// The declared name of a C-imported type whose Swift and C names differ, + /// marked when `SwiftDeclarationPrintConfiguration.marksCImportedTypeNames` + /// is on. The region's text is the spelling printed; the kind carries both + /// names, so a host can offer the other one without reading the text. Not a + /// comment: a host drawing annotation regions as comments leaves these out. + public static func cImportedTypeName(_ names: CImportedTypeNames) -> Self { + let separator = String(cImportedTypeNameSeparator) + return Self(cImportedTypeNamePrefix + separator + names.swiftName + separator + names.cName) + } + + /// The names a ``cImportedTypeName(_:)`` kind carries; nil for any other + /// kind. + public var cImportedTypeNames: CImportedTypeNames? { + let components = rawValue.split(separator: Self.cImportedTypeNameSeparator, omittingEmptySubsequences: false) + guard components.count == 3, + components[0] == Self.cImportedTypeNamePrefix, + !components[1].isEmpty, + !components[2].isEmpty + else { return nil } + return CImportedTypeNames(swiftName: String(components[1]), cName: String(components[2])) + } +} diff --git a/Sources/Output/SwiftPrinting/CImportedTypeNameSpelling.swift b/Sources/Output/SwiftPrinting/CImportedTypeNameSpelling.swift new file mode 100644 index 000000000..f28a2c049 --- /dev/null +++ b/Sources/Output/SwiftPrinting/CImportedTypeNameSpelling.swift @@ -0,0 +1,33 @@ +/// How a print spells the types a mangling places in the Clang importer's +/// modules (`__C`, `__C_Synthesized`): imported C structs, enums, typedefs, +/// CF types and Objective-C classes (evolution proposal +/// `c-imported-type-name-spelling`). +/// +/// A type imported from C has two names. Its descriptor carries the one Swift +/// code uses (`AnyWeakAttribute`), while every mangled reference to it carries +/// the C declaration's own (`__C.AGWeakAttribute`), because the compiler +/// mangles Clang declarations by their Clang names. A print picks one of the +/// two for declarations, member types, extension headers and the types the +/// field layout comments name alike (evolution proposal +/// `consistent-c-imported-type-spelling`). +public enum CImportedTypeNameSpelling: String, Sendable, Hashable, CaseIterable { + /// The name Swift code uses. A type whose module a registered resolver + /// finds prints under it (`CoreFoundation.CGRect`, + /// `UIKit.__UICellConfigurationState`); a type the image's own + /// descriptors name prints under that name alone, renamed + /// (`AnyWeakAttribute`) or imported under its C name + /// (`AGDescriptionOption`); any other keeps its mangled spelling + /// (`__C.AGFoo`): the image has no descriptor for it, or its + /// descriptor's name may be only the leaf of a member import + /// (`NSAttributedStringKey`'s says `Key`). + case swiftName + + /// The C declaration's own name, exactly as the mangling spells it: + /// `__C.AGWeakAttribute` in a reference, `AGWeakAttribute` on its + /// declaration. No resolver is asked for what it prints, not even for the + /// module: a C name under the Swift module (`UIKit.UICellConfigurationState`) + /// could read as a Swift type of the same name. A print marking declared + /// names (`marksCImportedTypeNames`) still asks for the Swift name the mark + /// carries. + case cName +} diff --git a/Sources/Output/SwiftPrinting/CImportedTypeSwiftNameTable.swift b/Sources/Output/SwiftPrinting/CImportedTypeSwiftNameTable.swift new file mode 100644 index 000000000..24128b114 --- /dev/null +++ b/Sources/Output/SwiftPrinting/CImportedTypeSwiftNameTable.swift @@ -0,0 +1,131 @@ +import Demangling +import MachOSwiftSection +@_spi(Internals) import SwiftInspection +import BinaryParseSupport + +/// The Swift names the image's own C-imported type descriptors give, keyed by +/// the identity a mangling spells for each type (evolution proposals +/// `c-imported-type-name-spelling`, `consistent-c-imported-type-spelling`). +/// +/// IRGen writes a C-imported type's descriptor name as the type's Swift name +/// and, when the C declaration is called something else, appends that C name +/// as the import info's ABI name (`TypeImportInfo`). Every mangled reference +/// spells the C name, so this table is what turns `__C.AGWeakAttribute` back +/// into the `AnyWeakAttribute` its declaration prints — without an SDK, for +/// private frameworks too. A descriptor with no ABI name proves the two names +/// are one, so `__C.AGDescriptionOption` prints as `AGDescriptionOption`, the +/// way its declaration does. +/// +/// Only names known to be the type's whole Swift name are kept; see +/// ``knownSwiftName(ofDescriptorNamed:importInfo:isDirectlyInImportedModule:)``. +struct CImportedTypeSwiftNameTable: Sendable { + static let empty = Self(swiftNamesByIdentity: [:]) + + /// Keyed by the identity node with any `type` wrapper taken off. `Node` + /// hashes and compares by structure, so a reference demangled from a + /// symbol finds the entry built from the descriptor. + private let swiftNamesByIdentity: [Node: String] + + private init(swiftNamesByIdentity: [Node: String]) { + self.swiftNamesByIdentity = swiftNamesByIdentity + } + + /// Reads every C-imported type descriptor of the image. A descriptor that + /// cannot be read is left out: a missing entry only keeps that type's C + /// name. + init(typeContextDescriptors: [TypeContextDescriptorWrapper], in context: some ReadingContext) { + var swiftNamesByIdentity: [Node: String] = [:] + for descriptorWrapper in typeContextDescriptors { + let descriptor = descriptorWrapper.typeContextDescriptor + guard (try? descriptor.isCImportedContextDescriptor(in: context)) == true, + let userFacingName = try? descriptorWrapper.namedContextDescriptor.name(in: context) + else { continue } + let importInfo: TypeImportInfo? + if descriptor.hasImportInfo { + // An import info that cannot be read is not an absent one: it + // may carry the C name. + guard let readImportInfo = try? descriptor.typeImportInfo(in: context) else { continue } + importInfo = readImportInfo + } else { + importInfo = nil + } + // What the import info rules out — a related entity, a rename + // that is not trusted — is ruled out wherever the type sits, so it + // is settled before the demangle the key needs. + guard Self.knownSwiftName(ofDescriptorNamed: userFacingName, importInfo: importInfo, isDirectlyInImportedModule: true) != nil, + let identity = try? SymbolicDemangler.demangleContext(for: descriptorWrapper.asContextDescriptorWrapper, in: context) + else { continue } + let identityKey = Self.key(for: identity) + let isDirectlyInImportedModule = identityKey.children.first?.kind == .module + guard let swiftName = Self.knownSwiftName(ofDescriptorNamed: userFacingName, importInfo: importInfo, isDirectlyInImportedModule: isDirectlyInImportedModule) else { continue } + swiftNamesByIdentity[identityKey] = swiftName + } + self.swiftNamesByIdentity = swiftNamesByIdentity + } + + /// The known Swift name of the C-imported type `identity` names — a + /// nominal node as a mangling spells it, with or without a `type` wrapper + /// — or nil. + func swiftName(forIdentity identity: Node) -> String? { + guard !swiftNamesByIdentity.isEmpty else { return nil } + return swiftNamesByIdentity[Self.key(for: identity)] + } + + var isEmpty: Bool { + swiftNamesByIdentity.isEmpty + } + + /// Whether a descriptor's user-facing name is the type's whole Swift name. + /// + /// - It has to differ from the ABI name, or there is nothing to rename. + /// - An importer-synthesized related entity (the error struct of an + /// `NS_ERROR_ENUM`) is spelled through its original declaration, not + /// renamed. + /// - A type imported as a member (`NS_SWIFT_NAME(NSAttributedString.Key)`) + /// keeps only its leaf in the descriptor (`Key`), and nothing in the + /// binary names the type it is a member of. Such a C name ends with the + /// leaf (`NSAttributedStringKey`), so a name the ABI name ends with is + /// not trusted. A top-level rename shaped the same way (`NSDecimal` to + /// `Decimal`) is refused with them and keeps its C name. + static func trustsUserFacingName(_ userFacingName: String, importInfo: TypeImportInfo) -> Bool { + guard let abiName = importInfo.abiName, abiName != userFacingName, !importInfo.isRelatedEntity else { return false } + return !abiName.hasSuffix(userFacingName) + } + + /// The Swift name a C-imported type's descriptor name is known to be, or + /// nil. + /// + /// - No ABI name (no import info at all, or one carrying only the symbol + /// namespace): IRGen writes the ABI name only when the C declaration's + /// name differs from the Swift one (`computeIdentity` in + /// `lib/IRGen/GenMeta.cpp`), so the descriptor's name is both — for a + /// type directly in `__C` / `__C_Synthesized`. A type nested in a C + /// type (`__Unnamed_struct__details`) is never looked up by its own + /// name: its parent's reference spells it. + /// - An ABI name: the descriptor's name when it is the type's whole Swift + /// name (``trustsUserFacingName(_:importInfo:)``). + /// - An importer-synthesized related entity: never; it is spelled + /// through its original declaration. + /// + /// The one shape this gets wrong is a type imported as a member of + /// another under its own unprefixed C name (`swift_name("Owner.Foo")` on + /// a C `Foo`): the leaf equals the C name, so no ABI name is written, + /// yet Swift spells it `Owner.Foo`. No SDK type is named that way. + static func knownSwiftName(ofDescriptorNamed userFacingName: String, importInfo: TypeImportInfo?, isDirectlyInImportedModule: Bool) -> String? { + if let importInfo, importInfo.isRelatedEntity { + return nil + } + if let importInfo, let abiName = importInfo.abiName, abiName != userFacingName { + return trustsUserFacingName(userFacingName, importInfo: importInfo) ? userFacingName : nil + } + return isDirectlyInImportedModule ? userFacingName : nil + } + + private static func key(for identity: Node) -> Node { + var node = identity + while node.kind == .type, let wrapped = node.children.first { + node = wrapped + } + return node + } +} diff --git a/Sources/Output/SwiftPrinting/NodePrintables/InterfaceNodePrintable.swift b/Sources/Output/SwiftPrinting/NodePrintables/InterfaceNodePrintable.swift index a6ba64998..99fbaed5a 100644 --- a/Sources/Output/SwiftPrinting/NodePrintables/InterfaceNodePrintable.swift +++ b/Sources/Output/SwiftPrinting/NodePrintables/InterfaceNodePrintable.swift @@ -44,6 +44,8 @@ struct InterfaceNodePrinterContext: InterfaceNodePrin var usesExistentialAny = false + var cImportedTypeNameSpelling: CImportedTypeNameSpelling = .swiftName + /// How many `repeat` patterns enclose the node being printed. `each` is /// only ever written inside one. var packExpansionDepth = 0 diff --git a/Sources/Output/SwiftPrinting/NodePrintables/NodePrintable.swift b/Sources/Output/SwiftPrinting/NodePrintables/NodePrintable.swift index 620944e53..3e0edab9c 100644 --- a/Sources/Output/SwiftPrinting/NodePrintables/NodePrintable.swift +++ b/Sources/Output/SwiftPrinting/NodePrintables/NodePrintable.swift @@ -29,6 +29,11 @@ protocol NodePrintableContext { /// Spell existential types with the `any` keyword. Fixed for a printer's /// lifetime, like `usesModuleSelectors`. var usesExistentialAny: Bool { get } + + /// How the types a mangling places in `__C` / `__C_Synthesized` are + /// spelled (evolution proposal `c-imported-type-name-spelling`). Fixed for + /// a printer's lifetime, like `usesModuleSelectors`. + var cImportedTypeNameSpelling: CImportedTypeNameSpelling { get } } /// Per-call hints for one `printName`. @@ -65,7 +70,7 @@ protocol NodePrintable { /// `*NodePrintableContext` refinement declares. var context: Context { get set } - var delegate: NodePrintableDelegate? { get } + var delegate: (any NodePrintableDelegate)? { get } mutating func printName(_ name: Node, options: NodePrintOptions) async } @@ -175,15 +180,33 @@ extension NodePrintable { /// The module a `module` node names, with a C-imported module spelling /// (`__C` / `__ObjC`) resolved to its real module through the delegate - /// when the sibling identifier finds one. + /// when the sibling identifier finds one. A printer spelling C names + /// (`CImportedTypeNameSpelling.cName`) asks nothing about those and keeps + /// the mangling's module. + /// + /// Any other module is the one a Swift type's mangling names, which for a + /// type the SDK moved (`@_originallyDefinedIn`) is the module it was + /// originally defined in: the delegate is asked for the module declaring + /// it now, by `siblingIdentifier` — the name of the top-level type the + /// module node roots (evolution proposal `moved-swift-type-modules`). func resolvedModuleName(of node: Node, siblingIdentifier: String?) async -> (text: String, isResolvedCImportedModule: Bool) { let moduleName = node.text ?? "" - if moduleName == objcModule || moduleName == cModule, + let isCImportedModule = moduleName == objcModule || moduleName == cModule + if context.cImportedTypeNameSpelling == .swiftName, + isCImportedModule, let identifier = siblingIdentifier, let delegate, let updatedModuleName = await or(await delegate.moduleName(forTypeName: identifier), await delegate.moduleName(forTypeName: identifier.strippedRefSuffix)) { return (updatedModuleName, true) } + if !isCImportedModule, + !moduleName.isEmpty, + let identifier = siblingIdentifier, + !identifier.isEmpty, + let delegate, + let declaringModuleName = await delegate.declaringModuleName(ofMovedTypeNamed: identifier, originallyDefinedIn: moduleName) { + return (declaringModuleName, false) + } return (moduleName, false) } @@ -231,7 +254,9 @@ extension NodePrintable { } extension String { - fileprivate var strippedRefSuffix: String { + /// A CF type's name without the `Ref` its C typedef carries + /// (`CFStringRef` → `CFString`), the name a module resolver knows it by. + var strippedRefSuffix: String { if hasSuffix("Ref") { return String(dropLast(3)) } diff --git a/Sources/Output/SwiftPrinting/NodePrintables/NodePrintableDelegate.swift b/Sources/Output/SwiftPrinting/NodePrintables/NodePrintableDelegate.swift index 7140957f7..e3392eeba 100644 --- a/Sources/Output/SwiftPrinting/NodePrintables/NodePrintableDelegate.swift +++ b/Sources/Output/SwiftPrinting/NodePrintables/NodePrintableDelegate.swift @@ -9,6 +9,7 @@ import Demangling protocol NodePrintableDelegate: AnyObject, Sendable { func moduleName(forTypeName typeName: String) async -> String? func swiftName(forCName cName: String, category: CImportedTypeNameCategory) async -> String? + func declaringModuleName(ofMovedTypeNamed typeName: String, originallyDefinedIn originalModuleName: String) async -> String? func opaqueType(forNode node: Node, index: Int?, spellingOptions: DemangleOptions) async -> String? /// Whether what `opaqueType(forNode:index:)` supplies is to be marked as /// visible only with opaque type resolution on (see @@ -22,4 +23,12 @@ protocol NodePrintableDelegate: AnyObject, Sendable { /// `SwiftDeclarationPrintConfiguration.usesExistentialAny`). A printer /// reads it once, when it is created. var usesExistentialAny: Bool { get } + /// How C-imported type names are spelled (see + /// `SwiftDeclarationPrintConfiguration.cImportedTypeNameSpelling`). A + /// printer reads it once, when it is created. + var cImportedTypeNameSpelling: CImportedTypeNameSpelling { get } + /// The Swift name the image's own descriptor gives the C-imported type + /// `identity` names, when that name is the type's whole Swift name + /// (`CImportedTypeSwiftNameTable`); nil otherwise. + func cImportedTypeSwiftName(forIdentity identity: Node) -> String? } diff --git a/Sources/Output/SwiftPrinting/NodePrintables/TypeNameResolving.swift b/Sources/Output/SwiftPrinting/NodePrintables/TypeNameResolving.swift index 66837bb38..14ffa632a 100644 --- a/Sources/Output/SwiftPrinting/NodePrintables/TypeNameResolving.swift +++ b/Sources/Output/SwiftPrinting/NodePrintables/TypeNameResolving.swift @@ -44,6 +44,19 @@ public protocol CImportedNameResolving: TypeNameResolving { func swiftName(forCName cName: String, category: CImportedTypeNameCategory) async -> String? } +/// Resolves the module that declares a Swift type now when its mangling +/// names the module the type was originally defined in +/// (`@_originallyDefinedIn`): `CoreGraphics.CGFloat` → `CoreFoundation`, +/// `SwiftUI.View` → `SwiftUICore` (evolution proposal +/// `moved-swift-type-modules`). +/// +/// The printer asks for every module other than `__C` / `__ObjC`, by the +/// top-level type's name: a nested type follows its outermost type, as the +/// compiler's mangling does. `nil` keeps the mangling's module. +public protocol MovedTypeModuleResolving: TypeNameResolving { + func declaringModuleName(ofMovedTypeNamed typeName: String, originallyDefinedIn originalModuleName: String) async -> String? +} + /// Expands an opaque return type (`some P`) from its descriptor's generic /// requirements. public protocol OpaqueTypeResolving: TypeNameResolving { diff --git a/Sources/Output/SwiftPrinting/NodePrintables/TypeNodePrintable.swift b/Sources/Output/SwiftPrinting/NodePrintables/TypeNodePrintable.swift index 58b4d8d70..3518c59c6 100644 --- a/Sources/Output/SwiftPrinting/NodePrintables/TypeNodePrintable.swift +++ b/Sources/Output/SwiftPrinting/NodePrintables/TypeNodePrintable.swift @@ -3,6 +3,7 @@ import SwiftDeclarationRendering import SwiftInspection import Demangling import Semantic +import SwiftStdlibToolbox /// The slice of printer state the type layer reads. protocol TypeNodePrintableContext: NodePrintableContext { @@ -183,6 +184,14 @@ extension TypeNodePrintable { var resolvedCImportedModule = false var resolvedCImportedModuleName: String? + // The Swift name the image's own descriptor gives a C-imported type + // (`AnyWeakAttribute` for `__C.AGWeakAttribute`, `AGDescriptionOption` + // for `__C.AGDescriptionOption`; evolution proposals + // `c-imported-type-name-spelling`, `consistent-c-imported-type-spelling`): + // what the identifier prints when no resolver spells it, with no + // module at all when none finds the module either — the name the + // type's declaration prints. + let descriptorSwiftName = swiftNameFromDescriptor(ofCImportedType: name) if shouldPrintContext(), !isLocalType { let writtenUnitCountBeforeContext = target.writtenUnitCount if contextNode.kind == .module { @@ -192,7 +201,9 @@ extension TypeNodePrintable { if resolvedCImportedModule { resolvedCImportedModuleName = moduleName.text } - target.write(moduleName.text, context: .context(for: contextNode, state: .printModule)) + if resolvedCImportedModule || descriptorSwiftName == nil { + target.write(moduleName.text, context: .context(for: contextNode, state: .printModule)) + } // The module→type separator stays inside this leaf's scope so // a fully-qualified top-level name (`AppKit.MenuItem`) // selects as one span. @@ -253,6 +264,8 @@ extension TypeNodePrintable { } else { target.write(swiftSpelling, context: .context(for: declarationName, parentKind: name.kind, state: .printIdentifier)) } + } else if let descriptorSwiftName { + target.write(descriptorSwiftName, context: .context(for: declarationName, parentKind: name.kind, state: .printIdentifier)) } else { await printIdentifier(declarationName, parentKind: name.kind) } @@ -266,6 +279,21 @@ extension TypeNodePrintable { } } + /// The Swift name the image's own descriptor gives the C-imported type + /// `name` refers to, when this printer spells Swift names and the type + /// sits directly in `__C` / `__C_Synthesized`; nil otherwise. A type + /// nested in a C type keeps its own name, and its parent prints through + /// this same rule when its reference is printed. + func swiftNameFromDescriptor(ofCImportedType name: Node) -> String? { + guard context.cImportedTypeNameSpelling == .swiftName, + let delegate, + let contextNode = name.children.first, + contextNode.kind == .module, + contextNode.text == objcModule || contextNode.text == cModule + else { return nil } + return delegate.cImportedTypeSwiftName(forIdentity: name) + } + /// Writes the module selector a nested type's own name carries — the /// `Foundation::` of `Swift::Duration.Foundation::TimeFormatStyle` — when /// this printer uses module selectors. The compiler writes one on every @@ -280,8 +308,16 @@ extension TypeNodePrintable { /// scopes, so the compiler writes none either), nor for a C-imported /// module spelling that does not resolve to a real module. mutating func printModuleSelector(ofNestedType name: Node) async { - guard context.usesModuleSelectors, let module = name.declaringModuleForModuleSelector else { return } - let moduleName = await resolvedModuleName(of: module, siblingIdentifier: name.children.at(1)?.text) + guard context.usesModuleSelectors, let (module, outermostTypeName) = name.declaringModuleForModuleSelector else { return } + // A C-imported module resolves by the nested type's own name; a Swift + // module by the outermost type's, the only name a move + // (`@_originallyDefinedIn`) is recorded under — a nested type moves + // with it (evolution proposal `moved-swift-type-modules`). An + // extension's module has no such name and is not asked about. + let moduleText = module.text ?? "" + let isCImportedModule = moduleText == objcModule || moduleText == cModule + let siblingIdentifier = isCImportedModule ? name.children.at(1)?.text : outermostTypeName + let moduleName = await resolvedModuleName(of: module, siblingIdentifier: siblingIdentifier) guard !moduleName.text.isEmpty, moduleName.text != objcModule, moduleName.text != cModule else { return } target.write(moduleName.text, context: .context(for: module, state: .printModule)) target.write("::") @@ -604,9 +640,13 @@ extension Node { /// of its own. The same rule as the `useModuleSelectors` option of /// swift-demangling's `NodePrinter`. /// + /// With the module at the root comes the name of the outermost type, the + /// one the module node is the context of; with an extension's module, + /// `nil`. + /// /// Iterative: the chain is as long as the nesting, and this walk sits /// outside the depth-checked `printName` recursion. - fileprivate var declaringModuleForModuleSelector: Node? { + fileprivate var declaringModuleForModuleSelector: (module: Node, outermostTypeName: String?)? { switch kind { case .class, .structure, .enum, .protocol, .otherNominalType, .typeAlias: break @@ -614,18 +654,20 @@ extension Node { return nil } var context = children.first + var contextOwner: Node = self while let current = context { switch current.kind { case .module: - return current + return (current, contextOwner.children.at(1)?.text) case .extension: guard let extensionModule = current.children.first, extensionModule.kind == .module else { return nil } - return extensionModule + return (extensionModule, nil) case .type, .class, .structure, .enum, .protocol, .otherNominalType, .typeAlias, .boundGenericClass, .boundGenericStructure, .boundGenericEnum, .boundGenericProtocol, .boundGenericOtherNominalType, .boundGenericTypeAlias: // A type's first child is the type it wraps; a nominal's is its // own context; a bound generic's is its unbound type. + contextOwner = current context = current.children.first default: return nil diff --git a/Sources/Output/SwiftPrinting/NodePrinter/FunctionNodePrinter.swift b/Sources/Output/SwiftPrinting/NodePrinter/FunctionNodePrinter.swift index 49ca39240..abc79a764 100644 --- a/Sources/Output/SwiftPrinting/NodePrinter/FunctionNodePrinter.swift +++ b/Sources/Output/SwiftPrinting/NodePrinter/FunctionNodePrinter.swift @@ -35,6 +35,7 @@ struct FunctionNodePrinter: MemberDeclarationNodePrin self.delegate = delegate context.usesModuleSelectors = delegate?.usesModuleSelectors ?? false context.usesExistentialAny = delegate?.usesExistentialAny ?? false + context.cImportedTypeNameSpelling = delegate?.cImportedTypeNameSpelling ?? .swiftName } mutating func printDeclaration(_ node: Node) async throws { diff --git a/Sources/Output/SwiftPrinting/NodePrinter/SubscriptNodePrinter.swift b/Sources/Output/SwiftPrinting/NodePrinter/SubscriptNodePrinter.swift index b9a356bdd..53d53a7bd 100644 --- a/Sources/Output/SwiftPrinting/NodePrinter/SubscriptNodePrinter.swift +++ b/Sources/Output/SwiftPrinting/NodePrinter/SubscriptNodePrinter.swift @@ -41,6 +41,7 @@ struct SubscriptNodePrinter: MemberDeclarationNodePri self.delegate = delegate context.usesModuleSelectors = delegate?.usesModuleSelectors ?? false context.usesExistentialAny = delegate?.usesExistentialAny ?? false + context.cImportedTypeNameSpelling = delegate?.cImportedTypeNameSpelling ?? .swiftName } init(isOverride: Bool, isClassMember: Bool = false, isFinal: Bool = false, hasSetter: Bool, indentation: Int, delegate: (any NodePrintableDelegate)? = nil) { diff --git a/Sources/Output/SwiftPrinting/NodePrinter/TypeNodePrinter.swift b/Sources/Output/SwiftPrinting/NodePrinter/TypeNodePrinter.swift index 4d86506ec..447d45faf 100644 --- a/Sources/Output/SwiftPrinting/NodePrinter/TypeNodePrinter.swift +++ b/Sources/Output/SwiftPrinting/NodePrinter/TypeNodePrinter.swift @@ -18,6 +18,7 @@ struct TypeNodePrinter: InterfaceNodePrintable { self.delegate = delegate context.usesModuleSelectors = delegate?.usesModuleSelectors ?? false context.usesExistentialAny = delegate?.usesExistentialAny ?? false + context.cImportedTypeNameSpelling = delegate?.cImportedTypeNameSpelling ?? .swiftName context.isProtocol = isProtocol } diff --git a/Sources/Output/SwiftPrinting/NodePrinter/VariableNodePrinter.swift b/Sources/Output/SwiftPrinting/NodePrinter/VariableNodePrinter.swift index 95ef08a25..ca12e78f6 100644 --- a/Sources/Output/SwiftPrinting/NodePrinter/VariableNodePrinter.swift +++ b/Sources/Output/SwiftPrinting/NodePrinter/VariableNodePrinter.swift @@ -44,6 +44,7 @@ struct VariableNodePrinter: MemberDeclarationNodePrin self.delegate = delegate context.usesModuleSelectors = delegate?.usesModuleSelectors ?? false context.usesExistentialAny = delegate?.usesExistentialAny ?? false + context.cImportedTypeNameSpelling = delegate?.cImportedTypeNameSpelling ?? .swiftName } init(isStored: Bool, isOverride: Bool, isClassMember: Bool = false, isFinal: Bool = false, hasSetter: Bool, indentation: Int, delegate: (any NodePrintableDelegate)? = nil) { diff --git a/Sources/Output/SwiftPrinting/ProtocolRequirementPartition.swift b/Sources/Output/SwiftPrinting/ProtocolRequirementPartition.swift index 0d17ef2fe..a50ac9a54 100644 --- a/Sources/Output/SwiftPrinting/ProtocolRequirementPartition.swift +++ b/Sources/Output/SwiftPrinting/ProtocolRequirementPartition.swift @@ -2,6 +2,7 @@ import MachOSwiftSection import Demangling import SwiftDeclarationRendering @_spi(Internals) import SwiftInspection +import BinaryParseSupport /// A protocol's requirement signature split by where each requirement prints /// (evolution proposal `protocol-requirement-placement`). diff --git a/Sources/Output/SwiftPrinting/SwiftDeclarationPrintConfiguration+Transformers.swift b/Sources/Output/SwiftPrinting/SwiftDeclarationPrintConfiguration+Transformers.swift index e423bc1f2..16faedda1 100644 --- a/Sources/Output/SwiftPrinting/SwiftDeclarationPrintConfiguration+Transformers.swift +++ b/Sources/Output/SwiftPrinting/SwiftDeclarationPrintConfiguration+Transformers.swift @@ -1,6 +1,7 @@ import Foundation import OutputTransformer import SwiftOutputTransformer +import ObjCOutputTransformer import SwiftDeclarationRendering extension SwiftDeclarationPrintConfiguration { @@ -15,4 +16,13 @@ extension SwiftDeclarationPrintConfiguration { typeLayoutTransformer = transformers.makeTypeLayoutTransformer() (enumLayoutTransformer, enumLayoutCaseTransformer) = transformers.makeEnumLayoutTransformers() } + + /// Installs what the Objective-C transformer modules change in a Swift + /// print: the replacements of an enabled `cType` module, for the types + /// the interface reads off the Objective-C side (evolution proposal + /// `objc-ivar-type-recovery`), so both sides of a class spell a C + /// primitive alike. A disabled module clears them. + public mutating func applyTransformers(_ transformers: Transformer.ObjCConfiguration) { + cTypeReplacements = transformers.cType.isEnabled ? transformers.cType.replacements.filter { !$0.value.isEmpty } : [:] + } } diff --git a/Sources/Output/SwiftPrinting/SwiftDeclarationPrintConfiguration.swift b/Sources/Output/SwiftPrinting/SwiftDeclarationPrintConfiguration.swift index 34c0398cf..4ce33c8d3 100644 --- a/Sources/Output/SwiftPrinting/SwiftDeclarationPrintConfiguration.swift +++ b/Sources/Output/SwiftPrinting/SwiftDeclarationPrintConfiguration.swift @@ -3,6 +3,8 @@ import MemberwiseInit import Semantic import SwiftDeclarationRendering import MachOSwiftSection +import OutputTransformer +import ObjCOutputTransformer public enum SwiftDeclarationMemberSortOrder: Hashable, Codable, Sendable, CaseIterable { /// Group members by category: allocators, variables, functions, subscripts, then static members. @@ -128,6 +130,26 @@ public struct SwiftDeclarationPrintConfiguration: Equatable, Sendable { /// be written `any Collection`. public var usesExistentialAny: Bool = true + /// How the types a mangling places in `__C` / `__C_Synthesized` are + /// spelled — declarations, member types and extension headers alike + /// (evolution proposal `c-imported-type-name-spelling`). + /// + /// `.swiftName` by default: a type the image's own descriptors rename + /// prints under its Swift name (`AnyWeakAttribute`), under the module a + /// registered resolver finds for it when one does. `.cName` prints every + /// one as the mangling spells it (`__C.AGWeakAttribute`) and asks no + /// resolver. + public var cImportedTypeNameSpelling: CImportedTypeNameSpelling = .swiftName + + /// Mark the declared name of every C-imported type whose Swift and C names + /// differ with a ``AnnotationRegion/Kind/cImportedTypeName(_:)`` region + /// carrying both, so a host can say what the type's other name is. + /// + /// `FrozenSemanticString.separatingAnnotationRegions()` of the frozen + /// print gives exactly the string printed with this off. Off by default, + /// and off the output is unchanged byte for byte. + public var marksCImportedTypeNames: Bool = false + /// Print what an attached macro the type was declared with generated, as /// the binary has it, instead of the macro attribute and the /// declarations the source wrote (evolution proposal @@ -276,6 +298,18 @@ public struct SwiftDeclarationPrintConfiguration: Equatable, Sendable { public var typeLayoutTransformer: TypeLayoutTransformer? = nil public var enumLayoutTransformer: EnumLayoutTransformer? = nil public var enumLayoutCaseTransformer: EnumLayoutCaseTransformer? = nil + + /// Spellings for the C primitive types an Objective-C type encoding names + /// (`.double: "CGFloat"`), used where the interface prints a type it read + /// off the Objective-C side: an `@objc @implementation` stored property + /// recovered from its ivar (evolution proposal `objc-ivar-type-recovery`). + /// A replacement stands in for the whole type, as `Transformer.CType` does + /// in an Objective-C header, but only for the property's type itself, not + /// for a pointee or an element; it prints as written, so give the name + /// Swift code writes (`CGFloat`), no module. An empty spelling is no + /// replacement. Empty by default, which prints the type the importer + /// gives (`Swift.Double`). + public var cTypeReplacements: [Transformer.CType.Pattern: String] = [:] } // MARK: - Visibility Options diff --git a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift index 781c747a8..91d1154f9 100644 --- a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift +++ b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift @@ -8,6 +8,7 @@ import Dependencies import SwiftDeclarationRendering @_spi(Internals) import SwiftSymbols @_spi(Internals) import SwiftInspection +import SwiftStdlibToolbox /// Model-driven declaration-header rendering for the interface path. /// @@ -43,7 +44,7 @@ extension SwiftDeclarationPrinter { if let boundTypeNode { try await BoundDumpedTypeNameRenderer.render(boundTypeNode, using: resolver) } else { - try await renderUnboundTypeName(.struct, descriptorWrapper: .type(.struct(dumped.descriptor)), name: dumped.descriptor.name(in: machO.context), displayParentName: displayParentName, leafNameNode: leafNameNode, resolver: resolver) + try await renderUnboundTypeName(.struct, descriptorWrapper: .type(.struct(dumped.descriptor)), declaredName: declaredTypeName(of: .struct(dumped.descriptor)), displayParentName: displayParentName, leafNameNode: leafNameNode, resolver: resolver) } try await renderGenericSignatureWithInvertibles(genericContext: boundTypeNode == nil ? dumped.genericContext : nil, ownedBy: .type(.struct(dumped.descriptor)), invertibleProtocolSet: dumped.invertibleProtocolSet, resolver: resolver) case .enum(let dumped): @@ -52,7 +53,7 @@ extension SwiftDeclarationPrinter { if let boundTypeNode { try await BoundDumpedTypeNameRenderer.render(boundTypeNode, using: resolver) } else { - try await renderUnboundTypeName(.enum, descriptorWrapper: .type(.enum(dumped.descriptor)), name: dumped.descriptor.name(in: machO.context), displayParentName: displayParentName, leafNameNode: leafNameNode, resolver: resolver) + try await renderUnboundTypeName(.enum, descriptorWrapper: .type(.enum(dumped.descriptor)), declaredName: declaredTypeName(of: .enum(dumped.descriptor)), displayParentName: displayParentName, leafNameNode: leafNameNode, resolver: resolver) } try await renderGenericSignatureWithInvertibles(genericContext: boundTypeNode == nil ? dumped.genericContext : nil, ownedBy: .type(.enum(dumped.descriptor)), invertibleProtocolSet: dumped.invertibleProtocolSet, resolver: resolver) case .class(let dumped): @@ -69,7 +70,7 @@ extension SwiftDeclarationPrinter { if let boundTypeNode { try await BoundDumpedTypeNameRenderer.render(boundTypeNode, using: resolver) } else { - try await renderUnboundTypeName(.class, descriptorWrapper: .type(.class(dumped.descriptor)), name: dumped.descriptor.name(in: machO.context), displayParentName: displayParentName, leafNameNode: leafNameNode, resolver: resolver) + try await renderUnboundTypeName(.class, descriptorWrapper: .type(.class(dumped.descriptor)), declaredName: declaredTypeName(of: .class(dumped.descriptor)), displayParentName: displayParentName, leafNameNode: leafNameNode, resolver: resolver) } let superclass = try await renderClassInheritanceClause(dumped, objcProtocolNames: objcProtocolNames, resolver: resolver) if boundTypeNode == nil, let genericContext = dumped.genericContext { @@ -114,12 +115,88 @@ extension SwiftDeclarationPrinter { } @SemanticStringBuilder - private func renderUnboundTypeName(_ kind: SemanticType.TypeKind, descriptorWrapper: ContextDescriptorWrapper, name: String, displayParentName: Bool, leafNameNode: Node?, resolver: DemangleResolver) async throws -> SemanticString { + private func renderUnboundTypeName(_ kind: SemanticType.TypeKind, descriptorWrapper: ContextDescriptorWrapper, declaredName: DeclaredTypeName, displayParentName: Bool, leafNameNode: Node?, resolver: DemangleResolver) async throws -> SemanticString { if displayParentName { try await resolver.resolve(for: SymbolicDemangler.demangleContext(for: descriptorWrapper, in: machO.context)).replacingTypeNameOrOtherToTypeDeclaration() + } else if configuration.marksCImportedTypeNames, let cImportedTypeNames = declaredName.cImportedTypeNames { + // The declared name of a C-imported type known by two names + // (evolution proposal `c-imported-type-name-spelling`): the region + // tells a host the other one, the text stays what it prints. + AnnotationRegion(.cImportedTypeName(cImportedTypeNames)) { + renderLeafName(kind: kind, bareName: declaredName.name, leafNameNode: leafNameNode) + } } else { - renderLeafName(kind: kind, bareName: name, leafNameNode: leafNameNode) + renderLeafName(kind: kind, bareName: declaredName.name, leafNameNode: leafNameNode) + } + } + + /// The name a type's declaration prints, and the two names of a C-imported + /// type that has two (evolution proposal `c-imported-type-name-spelling`). + struct DeclaredTypeName { + let name: String + /// Both names of a C-imported type whose Swift and C names differ and + /// are both known; nil for any other type. + let cImportedTypeNames: CImportedTypeNames? + } + + /// The name `descriptorWrapper`'s declaration prints. + /// + /// Any type but a C-imported one whose descriptor carries a C name other + /// than its own prints its descriptor name. Such a C-imported type follows + /// the rule its references follow (`TypeNodePrintable.printType`): + /// spelling C names, its C name; spelling Swift names, the Swift spelling + /// a registered resolver gives once it finds the module, else the + /// descriptor name when that is the whole Swift name + /// (`CImportedTypeSwiftNameTable.trustsUserFacingName(_:importInfo:)`), + /// else its C name — a type imported as a member keeps only its leaf + /// (`Key`) in the descriptor, which would read as a type of its own. + func declaredTypeName(of descriptorWrapper: TypeContextDescriptorWrapper) async throws -> DeclaredTypeName { + let userFacingName = try descriptorWrapper.namedContextDescriptor.name(in: machO.context) + let descriptor = descriptorWrapper.typeContextDescriptor + guard descriptor.hasImportInfo, + (try? descriptor.isCImportedContextDescriptor(in: machO.context)) == true, + let importInfo = try? descriptor.typeImportInfo(in: machO.context), + let cName = importInfo.abiName, + cName != userFacingName, + !importInfo.isRelatedEntity + else { + return DeclaredTypeName(name: userFacingName, cImportedTypeNames: nil) + } + // Spelling C names prints the C name whatever the resolvers say; they are asked only for + // the Swift name a marked declaration carries. + let asksResolvers = configuration.cImportedTypeNameSpelling == .swiftName || configuration.marksCImportedTypeNames + let swiftName: String? + if asksResolvers, let resolvedSwiftName = await resolvedSwiftName(ofCImportedDescriptor: descriptorWrapper, cName: cName) { + swiftName = resolvedSwiftName + } else if CImportedTypeSwiftNameTable.trustsUserFacingName(userFacingName, importInfo: importInfo) { + swiftName = userFacingName + } else { + swiftName = nil + } + let cImportedTypeNames = swiftName.map { CImportedTypeNames(swiftName: $0, cName: cName) } + switch configuration.cImportedTypeNameSpelling { + case .swiftName: + return DeclaredTypeName(name: swiftName ?? cName, cImportedTypeNames: cImportedTypeNames) + case .cName: + return DeclaredTypeName(name: cName, cImportedTypeNames: cImportedTypeNames) + } + } + + /// The Swift spelling the registered resolvers give a C-imported type, + /// asked the way a reference to it asks: only once a resolver finds its + /// module, by its C name and the category its mangling spells. + private func resolvedSwiftName(ofCImportedDescriptor descriptorWrapper: TypeContextDescriptorWrapper, cName: String) async -> String? { + var resolvedModuleName = await moduleName(forTypeName: cName) + if resolvedModuleName == nil { + resolvedModuleName = await moduleName(forTypeName: cName.strippedRefSuffix) + } + guard resolvedModuleName != nil, + var identity = try? SymbolicDemangler.demangleContext(for: descriptorWrapper.asContextDescriptorWrapper, in: machO.context) + else { return nil } + while identity.kind == .type, let wrapped = identity.children.first { + identity = wrapped } + return await swiftName(forCName: cName, category: CImportedTypeNameCategory(nodeKind: identity.kind)) } /// Renders a declaration's own leaf name. For an ordinary type this is just @@ -458,7 +535,11 @@ extension SwiftDeclarationPrinter { staticFieldLayoutProvider: staticFieldLayoutProvider(), staticLayoutDependencyResolution: configuration.staticLayoutDependencyResolution, marksOptionalContent: configuration.marksOptionalContent - ).markingCommentStructure(configuration.marksCommentStructure) + ) + .markingCommentStructure(configuration.marksCommentStructure) + // The expanded tree names its types the way the fields below do + // (evolution proposal `consistent-c-imported-type-spelling`). + .spellingFieldLayoutTypeNamesThroughResolver(true) // An offline specialization carries its arguments instead of // metadata (evolution proposal `offline-generic-specialization`): the // static layout path computes the comments for them, and the fields @@ -738,16 +819,69 @@ extension SwiftDeclarationPrinter { /// would read `Holder.Visitor`, a member type the source never declared, /// and alike for every unnamed `Visitor` of `Holder`. Both spellings carry /// module selectors when the configuration asks for them. + /// + /// The extended type of an extension of a C-imported type prints through + /// the type printer, spelled the way its references and its declaration + /// are (evolution proposal `c-imported-type-name-spelling`): spelling Swift + /// names, `extension AnyWeakAttribute`, or `extension CoreFoundation.CGRect` + /// once a resolver finds the module. Spelling C names it prints as the + /// mangling spells it, which the plain spelling below already does. + /// + /// So does the extended type of an extension of a Swift type the SDK + /// moved between modules (evolution proposal `moved-swift-type-modules`): + /// `extension CoreFoundation.CGFloat` where the mangling says + /// `CoreGraphics`, once a `MovedTypeModuleResolving` resolver names the + /// module. Any other type keeps the plain spelling. @SemanticStringBuilder - package func renderExtendedTypeName(_ extensionName: ExtensionName) -> SemanticString { + package func renderExtendedTypeName(_ extensionName: ExtensionName) async -> SemanticString { if spellsPositionNamedLocalType(extensionName.node) { let positionBasedNameOptions = DemangleOptions.interfaceTypeBuilderOnly.union(.showPrivateDiscriminators) TypeDeclaration(kind: extensionName.kind.semanticTypeKind, extensionName.name(using: configuration.usesModuleSelectors ? positionBasedNameOptions.union(.useModuleSelectors) : positionBasedNameOptions)) + } else if configuration.cImportedTypeNameSpelling == .swiftName, + isCImportedTypeReference(extensionName.node), + let spelledName = try? await typeDemangleResolver.resolve(for: extensionName.node) { + spelledName.replacingTypeNameOrOtherToTypeDeclaration() + } else if await isMovedTypeReference(extensionName.node), + let spelledName = try? await typeDemangleResolver.resolve(for: extensionName.node) { + spelledName.replacingTypeNameOrOtherToTypeDeclaration() } else { extensionName.print(usesModuleSelectors: configuration.usesModuleSelectors) } } + /// Whether `name`, with any `type` wrapper taken off, is a Swift type + /// — or nested in one — whose outermost type a registered + /// `MovedTypeModuleResolving` resolver says the SDK moved to another + /// module. Never asks about a `__C` / `__ObjC` type, nor about a type + /// declared in an extension or a function. + private func isMovedTypeReference(_ name: NodeReference) async -> Bool { + var current = name + while current.kind == .type, let wrapped = current.children.first { + current = wrapped + } + while current.kind.isAnyGeneric, let context = current.children.first { + if context.kind == .module { + guard let moduleName = context.text, moduleName != objcModule, moduleName != cModule, + current.children.count > 1, let typeName = current.children[1].text + else { return false } + return await declaringModuleName(ofMovedTypeNamed: typeName, originallyDefinedIn: moduleName) != nil + } + current = context + } + return false + } + + /// Whether `name`, with any `type` wrapper taken off, is a nominal type + /// directly in `__C` / `__C_Synthesized`. + private func isCImportedTypeReference(_ name: NodeReference) -> Bool { + var current = name + while current.kind == .type, let wrapped = current.children.first { + current = wrapped + } + guard let contextNode = current.children.first, contextNode.kind == .module else { return false } + return contextNode.text == objcModule || contextNode.text == cModule + } + /// Whether `name` or a type it is nested in is a position-based local /// type. private func spellsPositionNamedLocalType(_ name: NodeReference) -> Bool { diff --git a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+ObjCImplementation.swift b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+ObjCImplementation.swift index 9042c7368..fa76a7d1d 100644 --- a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+ObjCImplementation.swift +++ b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+ObjCImplementation.swift @@ -4,6 +4,8 @@ import Demangling import Semantic @_spi(Internals) import SwiftInspection import SwiftObjCInterop +import OutputTransformer +import ObjCOutputTransformer // The interface-side rendering of an `@objc @implementation` class's stored // properties (evolution proposal `objc-implementation-class-recognition`). @@ -49,13 +51,29 @@ extension SwiftDeclarationPrinter { try await printUnderObjCVerdicts(of: variable.resolvedObjCMemberFacts(trustingSelectorNameEvidence:)) { objcFacts in objcAttributes(objcFacts) let isLazy = storage.lazyPropertyName != nil + // A lazy var renders as a Swift type's own lazy field does: the + // getter's caller-facing type, not its storage's `Optional`. + let declaredTypeNode = WrappedPropertyRecovery.declaredTypeNode(of: variable) + let typeNode = isLazy + ? declaredTypeNode ?? storage.swiftTypeNode?.materialize() + : storage.swiftTypeNode?.materialize() ?? declaredTypeNode if isLazy { Keyword(.lazy) Space() Keyword(.var) } else if objcProperty?.isWeak == true { - // A `weak` property is a `var`, settable or not. - Keyword(.weak) + // `W` marks a `weak` and an `unowned(unsafe)` property alike + // — the header's `weak` and `unsafe_unretained` — and the + // type tells them apart: `weak` holds only an `Optional`. + // Either is a `var`, settable or not. + if typeNode.map(Self.isOptionalType) == false { + Keyword(.unowned) + Standard("(") + Keyword(.unsafe) + Standard(")") + } else { + Keyword(.weak) + } Space() Keyword(.var) } else { @@ -68,12 +86,6 @@ extension SwiftDeclarationPrinter { MemberDeclaration(variable.name) Standard(":") Space() - // A `lazy var` renders as a Swift type's own lazy field does: the - // getter's caller-facing type, not its storage's `Optional`. - let declaredTypeNode = WrappedPropertyRecovery.declaredTypeNode(of: variable) - let typeNode = isLazy - ? declaredTypeNode ?? storage.swiftTypeNode?.materialize() - : storage.swiftTypeNode?.materialize() ?? declaredTypeNode if let typeNode { try await printThrowingType(typeNode, isProtocol: false, level: level) } else { @@ -82,12 +94,31 @@ extension SwiftDeclarationPrinter { } } + /// Whether `typeNode` is an `Optional`, sugared or not. + static func isOptionalType(_ typeNode: Node) -> Bool { + let node = typeNode.kind == .type ? (typeNode.firstChild ?? typeNode) : typeNode + switch node.kind { + case .sugaredOptional: + return true + case .boundGenericEnum: + return node.firstChild.flatMap { NodeTypeNaming.nominalQualifiedName(of: $0) } == "Swift.Optional" + default: + return false + } + } + /// The ivars no member definition accounts for — their accessor symbols /// were stripped, or they never had any. One with a field-offset symbol /// still renders as a declaration (the symbol carries name and type); one /// without renders as an honest comment naming what the binary does say /// (ObjC name, offset, size, encoding) rather than a fabricated type. /// + /// Before falling back to the comment, the Objective-C side is asked for + /// the Swift type: a complete ivar encoding is the Swift type itself, and + /// a `?` one the bridged form of the Objective-C property synthesized on + /// the ivar (`ObjCInstanceVariableSwiftType`, evolution proposal + /// `objc-ivar-type-recovery`). + /// /// `standIns` replace that comment with a declaration the Objective-C side /// gives, keyed by the ivar's identity: the Generated Interface prints the /// Objective-C property synthesized on the ivar as Swift imports it, @@ -126,6 +157,9 @@ extension SwiftDeclarationPrinter { Space() } await printType(typeNode.materialize(), isProtocol: false, level: level) + } else if let recoveredType = recoveredSwiftType(of: instanceVariable, in: extensionDefinition) { + // One row: `Rows` puts each component on a line of its own. + await recoveredStoredPropertyDeclaration(named: instanceVariable.name, type: recoveredType, level: level) } else { comment(.note(Self.unrecoverableStoredPropertyComment(for: instanceVariable)), as: .note) } @@ -135,6 +169,68 @@ extension SwiftDeclarationPrinter { } } + /// The Swift type the Objective-C side gives `instanceVariable`, or `nil` + /// when it gives none. An unnamed ivar names no property to declare. + private func recoveredSwiftType(of instanceVariable: ObjCImplementationClassFacts.InstanceVariable, in extensionDefinition: ExtensionDefinition) -> ObjCInstanceVariableSwiftType? { + guard !instanceVariable.name.isEmpty, let facts = extensionDefinition.objcImplementation else { return nil } + let objcProperty = facts.objcProperty(storedIn: instanceVariable, swiftPropertyName: instanceVariable.swiftPropertyName ?? instanceVariable.name) + return ObjCInstanceVariableSwiftType(instanceVariable: instanceVariable, objcProperty: objcProperty, in: machO) + } + + /// `[weak] var|let name: Type` for a stored property whose type the + /// Objective-C side gave. With an Objective-C property, `readonly` makes + /// it a `let`; with none, nothing says it cannot be set. + @SemanticStringBuilder + private func recoveredStoredPropertyDeclaration(named name: String, type recoveredType: ObjCInstanceVariableSwiftType, level: Int) async -> SemanticString { + if recoveredType.isWeak { + Keyword(.weak) + Space() + Keyword(.var) + } else { + Keyword(recoveredType.isReadOnly ? .let : .var) + } + Space() + MemberDeclaration(name) + Standard(":") + Space() + if let replacement = cTypeReplacement(for: recoveredType.encodedType) { + TypeName(kind: .other, replacement) + } else { + await printType(recoveredType.typeNode, isProtocol: false, level: level) + } + // `weak` and `unowned(unsafe)`, or a bridged value and an + // `unowned(unsafe)` class, read the same on the Objective-C side: + // say what else it may be. + if let alternativeNote = recoveredType.alternativeDeclarationNote(named: name) { + Space() + comment(.inlineNote(alternativeNote), as: .note) + } + } + + /// The configuration's spelling for `type` when it is a C primitive one + /// of its C type replacements names (`double` → `CGFloat`), as an + /// Objective-C header spells it with the same replacements. + private func cTypeReplacement(for type: ObjCEncodedType) -> String? { + let pattern: Transformer.CType.Pattern? = switch type { + case .character: .char + case .unsignedCharacter: .uchar + case .short: .short + case .unsignedShort: .ushort + case .int: .int + case .unsignedInt: .uint + case .long: .long + case .unsignedLong: .ulong + case .longLong: .longLong + case .unsignedLongLong: .ulongLong + case .float: .float + case .double: .double + case .longDouble: .longDouble + default: nil + } + guard let pattern, let replacement = configuration.cTypeReplacements[pattern], !replacement.isEmpty else { return nil } + return replacement + } + static func unrecoverableStoredPropertyComment(for instanceVariable: ObjCImplementationClassFacts.InstanceVariable) -> String { let name = instanceVariable.name.isEmpty ? "" : instanceVariable.name return "stored property \(name): Swift type not recoverable (ObjC ivar, offset 0x\(String(instanceVariable.offset, radix: 16)), size \(instanceVariable.size), encoding \"\(instanceVariable.typeEncoding)\")" diff --git a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+ObjCImportedDefinitions.swift b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+ObjCImportedDefinitions.swift index c6cc11b15..2f6ba0159 100644 --- a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+ObjCImportedDefinitions.swift +++ b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+ObjCImportedDefinitions.swift @@ -98,7 +98,7 @@ extension SwiftDeclarationPrinter { await DeclarationBlock(level: level) { Keyword(.extension) Space() - renderExtendedTypeName(definition.className.extensionName) + await renderExtendedTypeName(definition.className.extensionName) } body: { await MemberList(level: level) { comment(.note("Objective-C methods of the class that no member of the Swift class answers to. Swift names follow the ClangImporter's rules for these selectors."), as: .note) @@ -262,7 +262,7 @@ extension SwiftDeclarationPrinter { try await DeclarationBlock(level: level) { Keyword(.extension) Space() - renderExtendedTypeName(definition.extendedClassName.extensionName) + await renderExtendedTypeName(definition.extendedClassName.extensionName) try await inheritanceClause(definition.protocolNames.map(\.node)) } body: { try await objcImportedMemberList(definition.members, swiftMembers: swiftMembers, leadingNote: "The Objective-C category \(definition.uniqueName).", level: level) diff --git a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+ObjCProtocols.swift b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+ObjCProtocols.swift index bd8c1f4bc..efdab7017 100644 --- a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+ObjCProtocols.swift +++ b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+ObjCProtocols.swift @@ -165,7 +165,7 @@ extension SwiftDeclarationPrinter { try await DeclarationBlock(level: level) { Keyword(.extension) Space() - renderExtendedTypeName(conformance.extendedTypeName.extensionName) + await renderExtendedTypeName(conformance.extendedTypeName.extensionName) for (offset, protocolName) in conformance.protocolNames.offsetEnumerated() { Standard(offset.isStart ? ":" : ",") Space() diff --git a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+RawLayoutBuiltinStorage.swift b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+RawLayoutBuiltinStorage.swift index bc51c298b..e6ef426ee 100644 --- a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+RawLayoutBuiltinStorage.swift +++ b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+RawLayoutBuiltinStorage.swift @@ -3,6 +3,7 @@ import MachOSwiftSection import SwiftDeclaration @_spi(Internals) import SwiftSymbols @_spi(Internals) import SwiftInspection +import BinaryParseSupport /// The layout a `@_rawLayout` struct records outside its field descriptor. /// diff --git a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift index 76975004d..6968e4530 100644 --- a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift +++ b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift @@ -38,6 +38,7 @@ public final class SwiftDeclarationPrinter: S private struct TypeNameResolverRegistry: Sendable { var moduleNameResolvers: [any ModuleNameResolving] = [] var cImportedNameResolvers: [any CImportedNameResolving] = [] + var movedTypeModuleResolvers: [any MovedTypeModuleResolving] = [] var opaqueTypeResolvers: [any OpaqueTypeResolving] = [] } @@ -119,6 +120,27 @@ public final class SwiftDeclarationPrinter: S case computed([SwiftDeclaration.TypeName: RawLayoutBuiltinStorage]) } + /// The Swift names this image's own C-imported type descriptors give + /// (`CImportedTypeSwiftNameTable`), built once on first use. It depends + /// on the image alone, so no configuration change rebuilds it. + @Mutex + private var memoizedCImportedTypeSwiftNames: CImportedTypeSwiftNameTable? = nil + + func cImportedTypeSwiftNames() -> CImportedTypeSwiftNameTable { + if let table = memoizedCImportedTypeSwiftNames { + return table + } + return _memoizedCImportedTypeSwiftNames.withLock { memoizedTable in + if let table = memoizedTable { + return table + } + let typeContextDescriptors = (try? machO.swift.typeContextDescriptors) ?? [] + let table = CImportedTypeSwiftNameTable(typeContextDescriptors: typeContextDescriptors, in: machO.context) + memoizedTable = table + return table + } + } + func rawLayoutBuiltinStorageByTypeName() -> [SwiftDeclaration.TypeName: RawLayoutBuiltinStorage] { if case .computed(let storage) = memoizedRawLayoutBuiltinStorage { return storage @@ -166,7 +188,7 @@ public final class SwiftDeclarationPrinter: S } } - public init(configuration: SwiftDeclarationPrintConfiguration = .init(), eventHandlers: [SwiftIndexEvents.Handler] = [], in machO: MachO) { + public init(configuration: SwiftDeclarationPrintConfiguration = .init(), eventHandlers: [any SwiftIndexEvents.Handler] = [], in machO: MachO) { self.machO = machO // Before `configuration`: that property is `@Mutex`-wrapped with a // default, so assigning it counts as using `self`, which is only legal @@ -227,6 +249,10 @@ public final class SwiftDeclarationPrinter: S registry.cImportedNameResolvers.append(cImportedNameResolver) matchedAnyRole = true } + if let movedTypeModuleResolver = resolver as? any MovedTypeModuleResolving { + registry.movedTypeModuleResolvers.append(movedTypeModuleResolver) + matchedAnyRole = true + } if let opaqueTypeResolver = resolver as? any OpaqueTypeResolving { registry.opaqueTypeResolvers.append(opaqueTypeResolver) matchedAnyRole = true @@ -685,7 +711,7 @@ public final class SwiftDeclarationPrinter: S } Keyword(.extension) Space() - renderExtendedTypeName(extensionDefinition.extensionName) + await renderExtendedTypeName(extensionDefinition.extensionName) // This print operation's single conformance materialization // (proposal 0002). Propagates on failure: a public entry must not @@ -778,7 +804,7 @@ public final class SwiftDeclarationPrinter: S @SemanticStringBuilder private func printDefinitionContents(_ definition: some Definition, level: Int, refinedForSwiftCommentsByVariableKey: [String: [StructuredComment]] = [:]) async throws -> SemanticString { - if let mutableDefinition = definition as? MutableDefinition { + if let mutableDefinition = definition as? (any MutableDefinition) { try mutableDefinition.index(in: machO) } @@ -1281,6 +1307,10 @@ extension SwiftDeclarationPrinter: NodePrintableDelegate { await typeNameResolverRegistry.cImportedNameResolvers.asyncFirstNonNil { await $0.swiftName(forCName: cName, category: category) } } + public func declaringModuleName(ofMovedTypeNamed typeName: String, originallyDefinedIn originalModuleName: String) async -> String? { + await typeNameResolverRegistry.movedTypeModuleResolvers.asyncFirstNonNil { await $0.declaringModuleName(ofMovedTypeNamed: typeName, originallyDefinedIn: originalModuleName) } + } + public func opaqueType(forNode node: Node, index: Int?) async -> String? { await opaqueType(forNode: node, index: index, spellingOptions: configuration.spellingOptions) } @@ -1305,4 +1335,12 @@ extension SwiftDeclarationPrinter: NodePrintableDelegate { var usesExistentialAny: Bool { configuration.usesExistentialAny } + + var cImportedTypeNameSpelling: CImportedTypeNameSpelling { + configuration.cImportedTypeNameSpelling + } + + func cImportedTypeSwiftName(forIdentity identity: Node) -> String? { + cImportedTypeSwiftNames().swiftName(forIdentity: identity) + } } diff --git a/Sources/Output/SwiftTypeNameResolution/CFDeclaredTypeNames.swift b/Sources/Output/SwiftTypeNameResolution/CFDeclaredTypeNames.swift new file mode 100644 index 000000000..f5ced7845 --- /dev/null +++ b/Sources/Output/SwiftTypeNameResolution/CFDeclaredTypeNames.swift @@ -0,0 +1,107 @@ +#if os(macOS) + +import MachOKit +import TypeIndexing + +/// The Core Foundation types an image defines, as swift-type-indexing's +/// `TypeDatabase` reads them: one for every `…GetTypeID` function the image +/// exports. +/// +/// A CF type's Swift metadata names the type but never its module — its +/// descriptor sits in `__C` — while the framework defining it exports the +/// type's `GetTypeID` function. This attributes a private CF type such as +/// `CGSVGDocumentRef` to the image exporting `CGSVGDocumentGetTypeID` +/// (`CoreSVG`). `TypeDatabase` consults it only for names neither the SDK's +/// module interfaces nor its API notes attribute, and reads the image's +/// exports only on such a miss (evolution proposal `private-cf-type-modules`). +/// +/// `TypeDatabase` keeps one source per image path, so an image whose +/// Objective-C names are registered too goes in as one +/// ``ImageDeclaredTypeNames``, which reads both; this alone is for an image +/// read for its CF types only. +/// +/// ```swift +/// try await typeDatabase.index( +/// dependencies: [CFDeclaredTypeNames(machO: coreSVG, imagePath: coreSVG.imagePath)], +/// moduleFilter: { _ in false } +/// ) +/// ``` +public struct CFDeclaredTypeNames: DeclaredTypeNameSource { + public let imagePath: String + + private let machO: MachO + + /// The only typedef names this source may give, or `nil` for every one the + /// exports imply. + private let admittedTypedefNames: Set? + + /// - Parameters: + /// - machO: The image, in this process or in a file. + /// - imagePath: Its install path, which names the module its types are + /// attributed to (`…/CoreSVG.framework/Versions/A/CoreSVG` → `CoreSVG`). + public init(machO: MachO, imagePath: String) { + self.init(machO: machO, imagePath: imagePath, restrictedTo: nil) + } + + /// A source giving only the names in `admittedTypedefNames` — the CF types + /// a binary's foreign class descriptors confirm, so that an export whose + /// name only looks like the convention (`CFGetTypeID`) or meets a typedef + /// that is no CF class claims nothing. + init(machO: MachO, imagePath: String, restrictedTo admittedTypedefNames: Set?) { + self.machO = machO + self.imagePath = imagePath + self.admittedTypedefNames = admittedTypedefNames + } + + /// The typedef name of every CF type the image exports a `GetTypeID` + /// function for. + public func declaredTypeNames() async -> [String] { + let typedefNames = machO.exportedSymbols.flatMap { exportedSymbol in + Self.typedefNames(forExportedSymbolName: exportedSymbol.name) + } + guard let admittedTypedefNames else { + return typedefNames + } + return typedefNames.filter { admittedTypedefNames.contains($0) } + } + + /// The typedef names an exported symbol implies, by the CF convention that + /// `GetTypeID` returns the type ID of `Ref`: + /// `_CGSVGDocumentGetTypeID` → `["CGSVGDocumentRef"]`. A private function + /// spelled with a leading underscore also names the unprefixed typedef, + /// which is how such a type is usually declared: `__LSASNGetTypeID` → + /// `["_LSASNRef", "LSASNRef"]`. Any other symbol — a Swift or Objective-C + /// one, a function not ending in `GetTypeID` — implies none. + /// + /// A few names it gives are no type at all (`_CFGetTypeID` → `CFRef`); a + /// lookup asks for one only by coincidence, after the SDK's attribution. + static func typedefNames(forExportedSymbolName symbolName: String) -> [String] { + let typeIDFunctionSuffix = "GetTypeID" + // A C function's Mach-O symbol carries one leading underscore. + guard symbolName.hasPrefix("_"), symbolName.hasSuffix(typeIDFunctionSuffix) else { + return [] + } + let functionName = symbolName.dropFirst() + let typeNameStem = functionName.dropLast(typeIDFunctionSuffix.count) + let unprefixedTypeNameStem = typeNameStem.drop { $0 == "_" } + guard !unprefixedTypeNameStem.isEmpty, isCIdentifier(typeNameStem) else { + return [] + } + var typedefNames = [String(typeNameStem) + "Ref"] + if unprefixedTypeNameStem.count != typeNameStem.count { + typedefNames.append(String(unprefixedTypeNameStem) + "Ref") + } + return typedefNames + } + + private static func isCIdentifier(_ candidate: Substring) -> Bool { + guard let firstCharacter = candidate.first, !firstCharacter.isNumber else { + return false + } + return candidate.allSatisfy { character in + character == "_" || (character.isASCII && (character.isLetter || character.isNumber)) + } + } +} + +#endif diff --git a/Sources/Output/SwiftTypeNameResolution/ImageDeclaredTypeNames.swift b/Sources/Output/SwiftTypeNameResolution/ImageDeclaredTypeNames.swift new file mode 100644 index 000000000..916e78129 --- /dev/null +++ b/Sources/Output/SwiftTypeNameResolution/ImageDeclaredTypeNames.swift @@ -0,0 +1,59 @@ +#if os(macOS) + +import ObjCMetadataSource +import ObjCTypeIndexing +import TypeIndexing + +/// Every type an image declares, as one swift-type-indexing source: the +/// classes, protocols, structs and unions its Objective-C metadata names +/// (`ObjCDeclaredTypeNames`), then the CF types it exports a `GetTypeID` +/// function for (`CFDeclaredTypeNames`). +/// +/// `TypeDatabase` keeps one source per image path and skips any later one +/// with the same path, so an image's CF types registered beside its +/// Objective-C names, as a second source, would never be read. Register this +/// instead of the two (evolution proposal `private-cf-type-modules`). +/// +/// ```swift +/// let typeDatabase = TypeDatabase(platform: .macOS) +/// try await typeDatabase.index( +/// dependencies: dependencyImages.map { ImageDeclaredTypeNames(machO: $0, imagePath: $0.imagePath) }, +/// moduleFilter: { dependencyModuleNames.contains($0) } +/// ) +/// ``` +public struct ImageDeclaredTypeNames: DeclaredTypeNameSource { + public let imagePath: String + + private let objectiveCTypeNames: ObjCDeclaredTypeNames + + private let coreFoundationTypeNames: CFDeclaredTypeNames + + /// - Parameters: + /// - machO: The image, in this process or in a file. + /// - imagePath: Its install path, which names the module its types are + /// attributed to (`…/IOSurface.framework/Versions/A/IOSurface` → + /// `IOSurface`). + public init(machO: MachO, imagePath: String) { + self.init(machO: machO, imagePath: imagePath, restrictingCFTypesTo: nil) + } + + /// A source whose CF part gives only the names in `admittedTypedefNames` + /// (`CFDeclaredTypeNames.init(machO:imagePath:restrictedTo:)`); the + /// Objective-C names are all given. + init(machO: MachO, imagePath: String, restrictingCFTypesTo admittedTypedefNames: Set?) { + self.imagePath = imagePath + self.objectiveCTypeNames = ObjCDeclaredTypeNames(machO: machO, imagePath: imagePath) + self.coreFoundationTypeNames = CFDeclaredTypeNames(machO: machO, imagePath: imagePath, restrictedTo: admittedTypedefNames) + } + + /// The Objective-C names, then the CF typedef names. Throws when the + /// Objective-C metadata cannot be read, as `ObjCDeclaredTypeNames` does on + /// its own: `TypeDatabase` then logs the image and skips it whole. + public func declaredTypeNames() async throws -> [String] { + let objectiveCNames = try await objectiveCTypeNames.declaredTypeNames() + let typedefNames = await coreFoundationTypeNames.declaredTypeNames() + return objectiveCNames + typedefNames + } +} + +#endif diff --git a/Sources/Output/SwiftTypeNameResolution/SwiftInterfaceBuilderTypeNameProvider.swift b/Sources/Output/SwiftTypeNameResolution/SwiftInterfaceBuilderTypeNameProvider.swift new file mode 100644 index 000000000..59f54255f --- /dev/null +++ b/Sources/Output/SwiftTypeNameResolution/SwiftInterfaceBuilderTypeNameProvider.swift @@ -0,0 +1,162 @@ +#if os(macOS) + +import Foundation +import MachOKit +import MachOKitExtensions +import MachOSwiftSection +import ObjCMetadataSource +import ObjCTypeIndexing +import SwiftInterface +import SwiftPrinting +import TypeIndexing + +/// What a `SwiftInterfaceBuilderTypeNameProvider` resolves through the SDK. +@available(macOS 13.0, *) +public struct SDKTypeNameResolutions: OptionSet, Hashable, Sendable { + public let rawValue: Int + + public init(rawValue: Int) { + self.rawValue = rawValue + } + + /// `__C` / `__ObjC` types: the module that declares them and the name + /// Swift gives them (`__C.NSString` → `Foundation.NSString`). Indexes the + /// SDK modules the binary links through sourcekitd — the first run per + /// SDK generates their interfaces. + public static let cImportedModules = SDKTypeNameResolutions(rawValue: 1 << 0) + + /// Swift types the SDK moved between modules (`@_originallyDefinedIn`): + /// the module that declares them now (`CoreGraphics.CGFloat` → + /// `CoreFoundation.CGFloat`), for the SDK version the binary was built + /// with. Reads the SDK's textual interfaces; no sourcekitd. + public static let movedTypeModules = SDKTypeNameResolutions(rawValue: 1 << 1) +} + +/// The `SwiftInterfaceBuilder` extra-data provider that resolves type names +/// through the SDK the indexed binary was built for: attach it and +/// `__C.NSString` prints as `Foundation.NSString`, +/// `__C.UICellConfigurationState` as `UIKit.__UICellConfigurationState`, and — +/// with ``SDKTypeNameResolutions/movedTypeModules`` — `CoreGraphics.CGFloat` as +/// `CoreFoundation.CGFloat`, through one swift-type-indexing `TypeDatabase` +/// built for the binary's platform and dependency set. +@available(macOS 13.0, *) +public final class SwiftInterfaceBuilderTypeNameProvider: SwiftInterfaceBuilderExtraDataProvider, ModuleNameResolving, CImportedNameResolving, MovedTypeModuleResolving, Sendable { + public let machO: MachO + + /// What this provider resolves; a role it was not asked for answers + /// `nil`. + public let resolutions: SDKTypeNameResolutions + + private let resolver: TypeDatabaseTypeNameResolver + + /// `nil` unless ``resolutions`` contains + /// ``SDKTypeNameResolutions/movedTypeModules``. + private let movedTypeModuleResolver: TypeDatabaseMovedTypeModuleResolver? + + private let dependencies: SwiftInterfaceBuilderDependencies + + /// Fails when the binary carries no build-version load command mapping to + /// a known SDK platform — without a platform there is no SDK to index. + /// + /// `supplementaryAPINotesURLs` names `.apinotes` files or directories of + /// user-provided type mappings (evolution proposal 0010), loaded after + /// the SDK's own APINotes so they overwrite them. + public init?(machO: MachO, dependencies: SwiftInterfaceBuilderDependencies, resolutions: SDKTypeNameResolutions = .cImportedModules, supplementaryAPINotesURLs: [URL] = []) { + guard + let buildVersionCommand = machO.loadCommands.buildVersionCommand, + let platform = SDKPlatform(buildVersionCommand.platform) + else { + return nil + } + self.machO = machO + self.resolutions = resolutions + self.dependencies = dependencies + let typeDatabase = TypeDatabase(platform: platform, supplementaryAPINotesURLs: supplementaryAPINotesURLs) + self.resolver = TypeDatabaseTypeNameResolver(typeDatabase: typeDatabase) + self.movedTypeModuleResolver = resolutions.contains(.movedTypeModules) + ? TypeDatabaseMovedTypeModuleResolver(typeDatabase: typeDatabase, sdkVersion: OperatingSystemVersion(machOVersion: buildVersionCommand.sdk)) + : nil + } + + public func setup() async throws { + guard resolutions.contains(.cImportedModules) else { + // Moved types come from the SDK discovery alone: a filter + // selecting no module generates no interface. + try await resolver.typeDatabase.index(dependencies: [], moduleFilter: { _ in false }) + return + } + // Index only the SDK modules the binary actually links: the module + // filter is keyed on the dependency images' module names, which is + // what makes first-run indexing minutes-of-modules instead of the + // whole SDK. + let dependencyImages = dependencies.dependencies + let dependencyModuleNames = Set(dependencyImages.map { TypeDatabase.moduleName(forImagePath: $0.imagePath) }) + try await resolver.typeDatabase.index( + dependencies: Self.declaredTypeNameSources(root: machO, dependencies: dependencyImages), + moduleFilter: { dependencyModuleNames.contains($0) } + ) + } + + /// The images' own lists of the types they declare, in the order + /// `TypeDatabase` reads them on a name the SDK does not attribute: the + /// root's CF types first — a type the root defines is its own — then each + /// direct dependency's Objective-C names and CF types, in dependency + /// order. One source per image: `TypeDatabase` skips a second source with + /// the same image path. The root generates no SDK interface: it is not in + /// the module filter. + /// + /// A `GetTypeID` export claims a name only when the root's foreign class + /// descriptors say it is a CF type (``cfTypedefNames(referencedBy:)``): + /// the export locates the type, the descriptor decides what it is. + static func declaredTypeNameSources(root: MachO, dependencies: [MachO]) -> [any DeclaredTypeNameSource] { + let referencedCFTypedefNames = cfTypedefNames(referencedBy: root) + let rootSource: any DeclaredTypeNameSource = CFDeclaredTypeNames(machO: root, imagePath: root.imagePath, restrictedTo: referencedCFTypedefNames) + return [rootSource] + dependencies.map { dependency in + ImageDeclaredTypeNames(machO: dependency, imagePath: dependency.imagePath, restrictingCFTypesTo: referencedCFTypedefNames) + } + } + + /// The typedef names of the CF types `image`'s Swift metadata refers to: + /// its C-imported class descriptors promoted from a C typedef — the + /// foreign class ClangImporter makes of a CF type (a struct or enum from + /// a `swift_wrapper` typedef shares the import info, not the kind). Named + /// by the ABI name a mangling spells, or by the descriptor's own name when + /// ClangImporter kept the C spelling (`IOSurfaceRef`, whose stripped name + /// the Objective-C class `IOSurface` took). + static func cfTypedefNames(referencedBy image: MachO) -> Set { + let context = image.context + var typedefNames: Set = [] + for descriptorWrapper in (try? image.swift.typeContextDescriptors) ?? [] { + guard case .class = descriptorWrapper else { continue } + let descriptor = descriptorWrapper.typeContextDescriptor + guard descriptor.hasImportInfo, + (try? descriptor.isCImportedContextDescriptor(in: context)) == true, + let importInfo = try? descriptor.typeImportInfo(in: context), + importInfo.isCTypedef, + !importInfo.isRelatedEntity + else { continue } + if let abiName = importInfo.abiName { + typedefNames.insert(abiName) + } else if let descriptorName = try? descriptorWrapper.namedContextDescriptor.name(in: context) { + typedefNames.insert(descriptorName) + } + } + return typedefNames + } + + public func moduleName(forTypeName typeName: String) async -> String? { + guard resolutions.contains(.cImportedModules) else { return nil } + return await resolver.moduleName(forTypeName: typeName) + } + + public func swiftName(forCName cName: String, category: CImportedTypeNameCategory) async -> String? { + guard resolutions.contains(.cImportedModules) else { return nil } + return await resolver.swiftName(forCName: cName, category: category) + } + + public func declaringModuleName(ofMovedTypeNamed typeName: String, originallyDefinedIn originalModuleName: String) async -> String? { + await movedTypeModuleResolver?.declaringModuleName(ofMovedTypeNamed: typeName, originallyDefinedIn: originalModuleName) + } +} + +#endif diff --git a/Sources/Output/SwiftTypeNameResolution/TypeDatabaseMovedTypeModuleResolver.swift b/Sources/Output/SwiftTypeNameResolution/TypeDatabaseMovedTypeModuleResolver.swift new file mode 100644 index 000000000..b3dc5c144 --- /dev/null +++ b/Sources/Output/SwiftTypeNameResolution/TypeDatabaseMovedTypeModuleResolver.swift @@ -0,0 +1,47 @@ +#if os(macOS) + +import Foundation +import MachOKit +import SwiftPrinting +import TypeIndexing + +/// Answers the printer's question about a Swift type the SDK moved between +/// modules (`@_originallyDefinedIn`) from a swift-type-indexing +/// `TypeDatabase`: `CoreGraphics.CGFloat` prints as `CoreFoundation.CGFloat`, +/// and for an image built with the macOS 15 SDK or later `SwiftUI.View` as +/// `SwiftUICore.View` (evolution proposal `moved-swift-type-modules`). +/// +/// `sdkVersion` is the version of the SDK the printed image was built with — +/// its `LC_BUILD_VERSION`'s `sdk` — so an image built before a move keeps the +/// module its SDK declared the type in: the macOS 14 SwiftUI declares `View` +/// itself. The database must be built for the image's platform and indexed +/// (`index(dependencies:moduleFilter:)`, which a filter selecting no module +/// satisfies). +/// +/// Register it on a `SwiftDeclarationPrinter` with `addTypeNameResolver(_:)`. +@available(macOS 13.0, *) +public struct TypeDatabaseMovedTypeModuleResolver: MovedTypeModuleResolving { + public let typeDatabase: TypeDatabase + + /// The SDK version the printed image was built with. + public let sdkVersion: OperatingSystemVersion + + public init(typeDatabase: TypeDatabase, sdkVersion: OperatingSystemVersion) { + self.typeDatabase = typeDatabase + self.sdkVersion = sdkVersion + } + + public func declaringModuleName(ofMovedTypeNamed typeName: String, originallyDefinedIn originalModuleName: String) async -> String? { + await typeDatabase.declaringModuleName(ofMovedTypeNamed: typeName, originallyDefinedIn: originalModuleName, builtAgainst: sdkVersion) + } +} + +extension OperatingSystemVersion { + /// A version a Mach-O load command records (`LC_BUILD_VERSION`'s `sdk` + /// or `minos`). + init(machOVersion: MachOKit.Version) { + self.init(majorVersion: machOVersion.major, minorVersion: machOVersion.minor, patchVersion: machOVersion.patch) + } +} + +#endif diff --git a/Sources/Output/SwiftTypeNameResolution/TypeDatabaseTypeNameResolver.swift b/Sources/Output/SwiftTypeNameResolution/TypeDatabaseTypeNameResolver.swift new file mode 100644 index 000000000..505ac7b38 --- /dev/null +++ b/Sources/Output/SwiftTypeNameResolution/TypeDatabaseTypeNameResolver.swift @@ -0,0 +1,90 @@ +#if os(macOS) + +import MachOKit +import SwiftPrinting +import TypeIndexing + +/// Answers the printer's questions about `__C` types from a swift-type-indexing +/// `TypeDatabase`: which module declares a type (`__C.UITraitCollection` → +/// `UIKit.UITraitCollection`) and what Swift calls it +/// (`__C.UICellConfigurationState` → `UIKit.__UICellConfigurationState`). +/// +/// Register it on a `SwiftDeclarationPrinter` with `addTypeNameResolver(_:)`. +/// Several printers may share one database: the database is an actor, and a +/// resolver holds nothing else. +/// +/// ```swift +/// let typeDatabase = TypeDatabase(platform: .macCatalyst) +/// try await typeDatabase.index(dependencies: [], moduleFilter: { $0 == "UIKit" }) +/// printer.addTypeNameResolver(TypeDatabaseTypeNameResolver(typeDatabase: typeDatabase)) +/// ``` +@available(macOS 13.0, *) +public struct TypeDatabaseTypeNameResolver: ModuleNameResolving, CImportedNameResolving { + public let typeDatabase: TypeDatabase + + public init(typeDatabase: TypeDatabase) { + self.typeDatabase = typeDatabase + } + + public func moduleName(forTypeName typeName: String) async -> String? { + await typeDatabase.moduleName(forTypeName: typeName) + } + + public func swiftName(forCName cName: String, category: CImportedTypeNameCategory) async -> String? { + await typeDatabase.swiftName(forCName: cName, category: ImportedTypeNameCategory(category)) + } +} + +extension ImportedTypeNameCategory { + /// The category swift-type-indexing looks a name up in for the printer's + /// category of a reference. The two enumerate the same namespaces. + public init(_ printerCategory: CImportedTypeNameCategory) { + switch printerCategory { + case .objcClass: + self = .objcClass + case .objcProtocol: + self = .objcProtocol + case .valueType: + self = .valueType + case .other: + self = .other + } + } +} + +@available(macOS 13.0, *) +extension SDKPlatform { + /// The SDK an image built for `platform` is read against, or `nil` for a + /// platform no SDK covers. Mac Catalyst has its own case: its frameworks + /// and API notes are the macOS SDK's `System/iOSSupport` ones. + public init?(_ platform: MachOKit.Platform) { + switch platform { + case .macOS: + self = .macOS + case .macCatalyst: + self = .macCatalyst + case .driverKit: + self = .driverKit + case .iOS: + self = .iOS + case .tvOS: + self = .tvOS + case .watchOS: + self = .watchOS + case .visionOS: + self = .visionOS + case .iOSSimulator: + self = .iOSSimulator + case .tvOSSimulator: + self = .tvOSSimulator + case .watchOSSimulator: + self = .watchOSSimulator + case .visionOSSimulator: + self = .visionOSSimulator + default: + return nil + } + } +} + +#endif diff --git a/Sources/Support/SwiftSectionMacros/MachOMacroPlugin.swift b/Sources/Support/SwiftSectionMacros/MachOMacroPlugin.swift index 69dfef489..e23ffbdac 100644 --- a/Sources/Support/SwiftSectionMacros/MachOMacroPlugin.swift +++ b/Sources/Support/SwiftSectionMacros/MachOMacroPlugin.swift @@ -3,7 +3,7 @@ import SwiftSyntaxMacros @main struct MachOMacroPlugin: CompilerPlugin { - let providingMacros: [Macro.Type] = [ + let providingMacros: [any Macro.Type] = [ LayoutMacro.self, ResolvableLocatableLayoutWrapperMacro.self, ] diff --git a/Sources/Support/Utilities/StringBuilder.swift b/Sources/Support/Utilities/StringBuilder.swift index 0b744c63b..07d9cfd61 100644 --- a/Sources/Support/Utilities/StringBuilder.swift +++ b/Sources/Support/Utilities/StringBuilder.swift @@ -8,7 +8,7 @@ package enum StringBuilder { components } - package static func buildBlock(_ components: CustomStringConvertible...) -> [String] { + package static func buildBlock(_ components: any CustomStringConvertible...) -> [String] { components.map { $0.description } } @@ -16,7 +16,7 @@ package enum StringBuilder { components.flatMap { $0 } } - package static func buildBlock(_ components: [CustomStringConvertible]...) -> [String] { + package static func buildBlock(_ components: [any CustomStringConvertible]...) -> [String] { components.flatMap { $0.map { $0.description } } } @@ -26,11 +26,11 @@ package enum StringBuilder { } extension StringBuilder { - package static func buildPartialBlock(first: CustomStringConvertible) -> [String] { + package static func buildPartialBlock(first: any CustomStringConvertible) -> [String] { [first.description] } - package static func buildPartialBlock(accumulated: [String], next: CustomStringConvertible) -> [String] { + package static func buildPartialBlock(accumulated: [String], next: any CustomStringConvertible) -> [String] { accumulated + [next.description] } diff --git a/Sources/Symbols/SwiftSymbols/MachO+Symbol.swift b/Sources/Symbols/SwiftSymbols/MachO+Symbol.swift index 426f150de..26e58f222 100644 --- a/Sources/Symbols/SwiftSymbols/MachO+Symbol.swift +++ b/Sources/Symbols/SwiftSymbols/MachO+Symbol.swift @@ -2,6 +2,7 @@ import MachOKit import MachOKitExtensions import MachOResolving @_spi(Internals) import MachOSymbols +import Demangling extension MachORepresentableWithCache { /// Every symbol the image's index knows at `offset`, building the index diff --git a/Sources/Symbols/SwiftSymbols/SymbolLanguage+Swift.swift b/Sources/Symbols/SwiftSymbols/SymbolLanguage+Swift.swift index 9fedc8d4e..544fa0e08 100644 --- a/Sources/Symbols/SwiftSymbols/SymbolLanguage+Swift.swift +++ b/Sources/Symbols/SwiftSymbols/SymbolLanguage+Swift.swift @@ -1,4 +1,5 @@ import MachOSymbols +import SwiftSymbolsRegistration extension SymbolLanguage { /// A Swift-mangled name (`$s`, `_$s`, `$S`, `_$S`, `$e`, `_$e`, `_T0`, @@ -49,7 +50,20 @@ enum SwiftSymbolNameRecognition { /// Registers ``SymbolLanguage/swift``. `SwiftSymbolsRegistration`'s /// constructor calls it once, when the image loads. +/// +/// Public, behind an SPI nobody imports, only so that its C symbol keeps +/// external linkage. Internal, the symbol is hidden, and Xcode links each +/// package target into a single relocatable object (`ld -r`) first, which +/// turns a hidden symbol local: the constructor, in another target, then +/// fails to link in a Release build ("Undefined symbols: +/// _swift_symbols_register_symbol_language"). +@_spi(SymbolLanguageRegistration) @c(swift_symbols_register_symbol_language) -func registerSwiftSymbolLanguage() { +public func registerSwiftSymbolLanguage() { SymbolLanguageRegistry.shared.register(.swift, where: SwiftSymbolNameRecognition.recognizes) + // Does nothing at run time. The reference is what counts: a static link + // that loads this file (any use of the Swift symbol index, any link with + // -ObjC) loads SwiftSymbolsRegistration.c and its constructor with it, + // which nothing else refers to. See that file. + swift_symbols_registration_anchor() } diff --git a/Sources/Symbols/SwiftSymbolsRegistration/SwiftSymbolsRegistration.c b/Sources/Symbols/SwiftSymbolsRegistration/SwiftSymbolsRegistration.c index 8730be95c..c16266d5b 100644 --- a/Sources/Symbols/SwiftSymbolsRegistration/SwiftSymbolsRegistration.c +++ b/Sources/Symbols/SwiftSymbolsRegistration/SwiftSymbolsRegistration.c @@ -2,11 +2,11 @@ // SwiftSymbolsRegistration.c // SwiftSymbolsRegistration // -// Registers `SymbolLanguage.swift` with MachOKitExtensions' symbol language -// registry when the image holding SwiftSymbols loads, so that every -// classification and the C/C++ symbol index see the language before any -// code asks. Swift has no load-time initializers; a constructor here, in a -// C target SwiftSymbols depends on, runs with no caller involved. +// Registers `SymbolLanguage.swift` with MachOKitExtensions' symbol +// language registry when the image holding SwiftSymbols loads, so that +// every classification and the C/C++ symbol index see the language before +// any code asks. Swift has no load-time initializers; a constructor here, +// in a C target SwiftSymbols depends on, runs with no caller involved. // #include "SwiftSymbolsRegistration.h" @@ -18,3 +18,13 @@ __attribute__((constructor)) static void registerSymbolLanguageAtLoad(void) { swift_symbols_register_symbol_language(); } + +// A linker that reads SwiftSymbols from a static archive (a Tuist static +// framework, a static library) loads an object only for a symbol something +// refers to, and -ObjC does not load an object that defines no Objective-C +// class or category and no Swift type. The constructor above is static, so +// without this function the object would define nothing and never be loaded: +// the image would run without the Swift symbol language registered. SwiftSymbols +// calls this function from the file that registers the language, which every +// use of the Swift symbol index and every link with -ObjC loads. +void swift_symbols_registration_anchor(void) {} diff --git a/Sources/Symbols/SwiftSymbolsRegistration/include/SwiftSymbolsRegistration.h b/Sources/Symbols/SwiftSymbolsRegistration/include/SwiftSymbolsRegistration.h index b3a8af959..db609643c 100644 --- a/Sources/Symbols/SwiftSymbolsRegistration/include/SwiftSymbolsRegistration.h +++ b/Sources/Symbols/SwiftSymbolsRegistration/include/SwiftSymbolsRegistration.h @@ -2,6 +2,14 @@ // SwiftSymbolsRegistration.h // SwiftSymbolsRegistration // -// Nothing to import: the target exists for the constructor in -// SwiftSymbolsRegistration.c. +// The target exists for the constructor in SwiftSymbolsRegistration.c. // + +#ifndef SWIFT_SYMBOLS_REGISTRATION_H +#define SWIFT_SYMBOLS_REGISTRATION_H + +/// Does nothing. Calling it makes a static link that loads the caller load +/// SwiftSymbolsRegistration.c — and its constructor — too. +void swift_symbols_registration_anchor(void); + +#endif diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/BaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/BaselineGenerator.swift index 0888770b7..703b585e8 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/BaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/BaselineGenerator.swift @@ -4,6 +4,7 @@ import MachOKit import SwiftSyntax import SwiftSyntaxBuilder @testable import MachOSwiftSection +import SwiftBasicFormat /// Top-level dispatcher for the per-suite baseline sub-generators. /// @@ -677,18 +678,7 @@ package enum BaselineGenerator { } private static func loadFixtureMachOFile() throws -> MachOFile { - let file = try loadFromFile(named: .SymbolTestsCore) - switch file { - case .fat(let fat): - return try required( - fat.machOFiles().first(where: { $0.header.cpuType == .arm64 }) - ?? fat.machOFiles().first - ) - case .machO(let machO): - return machO - @unknown default: - fatalError() - } + try HostSlice.machOFile(in: loadFromFile(named: .SymbolTestsCore)) } /// Hand-maintained index of every Suite type registered in `dispatchSuite`. diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AccessibleFunction/AccessibleFunctionRecordBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AccessibleFunction/AccessibleFunctionRecordBaselineGenerator.swift index b401fc8ed..35e0f2140 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AccessibleFunction/AccessibleFunctionRecordBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AccessibleFunction/AccessibleFunctionRecordBaselineGenerator.swift @@ -3,6 +3,8 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat +import BinaryParseSupport /// Emits `__Baseline__/AccessibleFunctionRecordBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AnonymousContextBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AnonymousContextBaselineGenerator.swift index 305765e88..a277c1fa4 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AnonymousContextBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AnonymousContextBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/AnonymousContextBaseline.swift` from the /// `SymbolTestsCore` fixture via the MachOFile reader. diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AnonymousContextDescriptorBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AnonymousContextDescriptorBaselineGenerator.swift index 8bf06358e..c5e4c82aa 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AnonymousContextDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AnonymousContextDescriptorBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/AnonymousContextDescriptorBaseline.swift` from the /// `SymbolTestsCore` fixture via the MachOFile reader. diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AnonymousContextDescriptorFlagsBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AnonymousContextDescriptorFlagsBaselineGenerator.swift index 41d04307a..62055eac5 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AnonymousContextDescriptorFlagsBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AnonymousContextDescriptorFlagsBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/AnonymousContextDescriptorFlagsBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AnonymousContextDescriptorProtocolBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AnonymousContextDescriptorProtocolBaselineGenerator.swift index a0f16b18d..d1e9c9a7c 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AnonymousContextDescriptorProtocolBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AnonymousContextDescriptorProtocolBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/AnonymousContextDescriptorProtocolBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AssociatedType/AssociatedTypeBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AssociatedType/AssociatedTypeBaselineGenerator.swift index 279661e13..2087eed2c 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AssociatedType/AssociatedTypeBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AssociatedType/AssociatedTypeBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/AssociatedTypeBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AssociatedType/AssociatedTypeDescriptorBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AssociatedType/AssociatedTypeDescriptorBaselineGenerator.swift index 9ffa49018..df14d7ad1 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AssociatedType/AssociatedTypeDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AssociatedType/AssociatedTypeDescriptorBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/AssociatedTypeDescriptorBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AssociatedType/AssociatedTypeRecordBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AssociatedType/AssociatedTypeRecordBaselineGenerator.swift index fa67ea943..f26985aca 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AssociatedType/AssociatedTypeRecordBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/AssociatedType/AssociatedTypeRecordBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/AssociatedTypeRecordBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/BuiltinType/BuiltinTypeBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/BuiltinType/BuiltinTypeBaselineGenerator.swift index 1b704c3a9..8718c3fc8 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/BuiltinType/BuiltinTypeBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/BuiltinType/BuiltinTypeBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/BuiltinTypeBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/BuiltinType/BuiltinTypeDescriptorBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/BuiltinType/BuiltinTypeDescriptorBaselineGenerator.swift index c9aa15ee5..2f0fe7a66 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/BuiltinType/BuiltinTypeDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/BuiltinType/BuiltinTypeDescriptorBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/BuiltinTypeDescriptorBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Capture/CaptureDescriptorBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Capture/CaptureDescriptorBaselineGenerator.swift index 2f425f37f..0a6c13b3e 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Capture/CaptureDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Capture/CaptureDescriptorBaselineGenerator.swift @@ -3,6 +3,8 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat +import BinaryParseSupport /// Emits `__Baseline__/CaptureDescriptorBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Capture/CaptureTypeRecordBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Capture/CaptureTypeRecordBaselineGenerator.swift index 75fae01cf..1c498cfb9 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Capture/CaptureTypeRecordBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Capture/CaptureTypeRecordBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/CaptureTypeRecordBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Capture/MetadataSourceRecordBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Capture/MetadataSourceRecordBaselineGenerator.swift index fe6b8de95..29905ebab 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Capture/MetadataSourceRecordBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Capture/MetadataSourceRecordBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/MetadataSourceRecordBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/AnyClassMetadataBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/AnyClassMetadataBaselineGenerator.swift index 144886b31..6013c2de5 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/AnyClassMetadataBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/AnyClassMetadataBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/AnyClassMetadataBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/AnyClassMetadataObjCInteropBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/AnyClassMetadataObjCInteropBaselineGenerator.swift index 4e7aa33c3..9083b35cf 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/AnyClassMetadataObjCInteropBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/AnyClassMetadataObjCInteropBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/AnyClassMetadataObjCInteropBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/AnyClassMetadataObjCInteropProtocolBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/AnyClassMetadataObjCInteropProtocolBaselineGenerator.swift index c23cbf33b..16ba2d97f 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/AnyClassMetadataObjCInteropProtocolBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/AnyClassMetadataObjCInteropProtocolBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/AnyClassMetadataObjCInteropProtocolBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/AnyClassMetadataProtocolBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/AnyClassMetadataProtocolBaselineGenerator.swift index 2790b3915..0fdd8fd17 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/AnyClassMetadataProtocolBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/AnyClassMetadataProtocolBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/AnyClassMetadataProtocolBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ClassBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ClassBaselineGenerator.swift index 4aed247da..8d77b0ca1 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ClassBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ClassBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ClassBaseline.swift` from the `SymbolTestsCore` /// fixture via the MachOFile reader. diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ClassDescriptorBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ClassDescriptorBaselineGenerator.swift index 920da1f2d..29f55ec70 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ClassDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ClassDescriptorBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ClassDescriptorBaseline.swift` from the /// `SymbolTestsCore` fixture via the MachOFile reader. diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ClassFlagsBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ClassFlagsBaselineGenerator.swift index b39c4d599..c352ace82 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ClassFlagsBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ClassFlagsBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/ClassFlagsBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ClassMetadataBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ClassMetadataBaselineGenerator.swift index 2a90ba2ed..f89752766 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ClassMetadataBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ClassMetadataBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/ClassMetadataBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ClassMetadataBoundsBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ClassMetadataBoundsBaselineGenerator.swift index b419fedaa..4c0d2efb6 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ClassMetadataBoundsBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ClassMetadataBoundsBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/ClassMetadataBoundsBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ClassMetadataBoundsProtocolBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ClassMetadataBoundsProtocolBaselineGenerator.swift index a86c36638..9441938f4 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ClassMetadataBoundsProtocolBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ClassMetadataBoundsProtocolBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/ClassMetadataBoundsProtocolBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ClassMetadataObjCInteropBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ClassMetadataObjCInteropBaselineGenerator.swift index d9f3a3420..852ee2d7f 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ClassMetadataObjCInteropBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ClassMetadataObjCInteropBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/ClassMetadataObjCInteropBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ExtraClassDescriptorFlagsBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ExtraClassDescriptorFlagsBaselineGenerator.swift index 8577f6114..a36c93d7f 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ExtraClassDescriptorFlagsBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ExtraClassDescriptorFlagsBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ExtraClassDescriptorFlagsBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/FinalClassMetadataProtocolBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/FinalClassMetadataProtocolBaselineGenerator.swift index e61d1d0f4..be03cb55d 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/FinalClassMetadataProtocolBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/FinalClassMetadataProtocolBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/FinalClassMetadataProtocolBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/MethodDefaultOverrideDescriptorBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/MethodDefaultOverrideDescriptorBaselineGenerator.swift index c8626d87e..28cf29f43 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/MethodDefaultOverrideDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/MethodDefaultOverrideDescriptorBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/MethodDefaultOverrideDescriptorBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/MethodDefaultOverrideTableHeaderBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/MethodDefaultOverrideTableHeaderBaselineGenerator.swift index b2db676f8..8419e8fc6 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/MethodDefaultOverrideTableHeaderBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/MethodDefaultOverrideTableHeaderBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/MethodDefaultOverrideTableHeaderBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/MethodDescriptorBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/MethodDescriptorBaselineGenerator.swift index ddb55de3f..65472ee59 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/MethodDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/MethodDescriptorBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/MethodDescriptorBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/MethodDescriptorFlagsBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/MethodDescriptorFlagsBaselineGenerator.swift index edf215378..1e03f77c8 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/MethodDescriptorFlagsBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/MethodDescriptorFlagsBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/MethodDescriptorFlagsBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/MethodDescriptorKindBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/MethodDescriptorKindBaselineGenerator.swift index 98c3fa1b1..df2192d8f 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/MethodDescriptorKindBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/MethodDescriptorKindBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/MethodDescriptorKindBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/MethodOverrideDescriptorBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/MethodOverrideDescriptorBaselineGenerator.swift index 3a78ee4ed..a92864ed7 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/MethodOverrideDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/MethodOverrideDescriptorBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/MethodOverrideDescriptorBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ObjCClassWrapperMetadataBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ObjCClassWrapperMetadataBaselineGenerator.swift index c66f4b07a..6865dd20a 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ObjCClassWrapperMetadataBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ObjCClassWrapperMetadataBaselineGenerator.swift @@ -2,6 +2,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ObjCClassWrapperMetadataBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ObjCResilientClassStubInfoBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ObjCResilientClassStubInfoBaselineGenerator.swift index 4215421a6..39f075722 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ObjCResilientClassStubInfoBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ObjCResilientClassStubInfoBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ObjCResilientClassStubInfoBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/OverrideTableHeaderBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/OverrideTableHeaderBaselineGenerator.swift index d0a0cdd33..098ef9dc8 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/OverrideTableHeaderBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/OverrideTableHeaderBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/OverrideTableHeaderBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ResilientSuperclassBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ResilientSuperclassBaselineGenerator.swift index 5073a291a..dd3d6d52f 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ResilientSuperclassBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/ResilientSuperclassBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ResilientSuperclassBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/StoredClassMetadataBoundsBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/StoredClassMetadataBoundsBaselineGenerator.swift index 26e8e029a..886bfefb0 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/StoredClassMetadataBoundsBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/StoredClassMetadataBoundsBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/StoredClassMetadataBoundsBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/VTableDescriptorHeaderBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/VTableDescriptorHeaderBaselineGenerator.swift index 34812f88d..1a7b2958d 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/VTableDescriptorHeaderBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Class/VTableDescriptorHeaderBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/VTableDescriptorHeaderBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextDescriptorBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextDescriptorBaselineGenerator.swift index de7afd0e0..e8c00e7c8 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextDescriptorBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ContextDescriptorBaseline.swift` from the /// `SymbolTestsCore` fixture via the MachOFile reader. diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextDescriptorFlagsBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextDescriptorFlagsBaselineGenerator.swift index 3a9a0baf9..86d926c29 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextDescriptorFlagsBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextDescriptorFlagsBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ContextDescriptorFlagsBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextDescriptorKindBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextDescriptorKindBaselineGenerator.swift index b51707375..28a37cd90 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextDescriptorKindBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextDescriptorKindBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ContextDescriptorKindBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextDescriptorKindSpecificFlagsBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextDescriptorKindSpecificFlagsBaselineGenerator.swift index 6be978cd9..f575354fb 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextDescriptorKindSpecificFlagsBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextDescriptorKindSpecificFlagsBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ContextDescriptorKindSpecificFlagsBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextDescriptorProtocolBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextDescriptorProtocolBaselineGenerator.swift index 98bb1b2c7..4c6bd1cce 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextDescriptorProtocolBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextDescriptorProtocolBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ContextDescriptorProtocolBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextDescriptorWrapperBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextDescriptorWrapperBaselineGenerator.swift index 5c5c87b3a..82c00ebd0 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextDescriptorWrapperBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextDescriptorWrapperBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ContextDescriptorWrapperBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextProtocolBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextProtocolBaselineGenerator.swift index 6e86650a6..57475aa6c 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextProtocolBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextProtocolBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ContextProtocolBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextWrapperBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextWrapperBaselineGenerator.swift index 359a26bcd..1718a5396 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextWrapperBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ContextWrapperBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ContextWrapperBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/DispatchClass/DispatchClassMetadataBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/DispatchClass/DispatchClassMetadataBaselineGenerator.swift index 734d101a5..84f381fef 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/DispatchClass/DispatchClassMetadataBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/DispatchClass/DispatchClassMetadataBaselineGenerator.swift @@ -2,6 +2,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/DispatchClassMetadataBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Enum/EnumBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Enum/EnumBaselineGenerator.swift index 7d80cffb3..dbda5fe42 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Enum/EnumBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Enum/EnumBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/EnumBaseline.swift` from the `SymbolTestsCore` /// fixture via the MachOFile reader. diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Enum/EnumDescriptorBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Enum/EnumDescriptorBaselineGenerator.swift index 962d00e26..2b1fcbf2d 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Enum/EnumDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Enum/EnumDescriptorBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/EnumDescriptorBaseline.swift` from the /// `SymbolTestsCore` fixture via the MachOFile reader. diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Enum/EnumFunctionsBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Enum/EnumFunctionsBaselineGenerator.swift index 5cf3690c0..13aa9f721 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Enum/EnumFunctionsBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Enum/EnumFunctionsBaselineGenerator.swift @@ -2,6 +2,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/EnumFunctionsBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Enum/EnumMetadataBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Enum/EnumMetadataBaselineGenerator.swift index a2fb86741..0c313dead 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Enum/EnumMetadataBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Enum/EnumMetadataBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/EnumMetadataBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Enum/EnumMetadataProtocolBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Enum/EnumMetadataProtocolBaselineGenerator.swift index 76f256bd7..7fdb22895 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Enum/EnumMetadataProtocolBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Enum/EnumMetadataProtocolBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/EnumMetadataProtocolBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Enum/MultiPayloadEnumDescriptorBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Enum/MultiPayloadEnumDescriptorBaselineGenerator.swift index 2bfe7be29..f88c552d4 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Enum/MultiPayloadEnumDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Enum/MultiPayloadEnumDescriptorBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/MultiPayloadEnumDescriptorBaseline.swift` from the /// `SymbolTestsCore` fixture via the MachOFile reader. diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExistentialType/ExistentialMetatypeMetadataBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExistentialType/ExistentialMetatypeMetadataBaselineGenerator.swift index b21e91ec1..e4f90504d 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExistentialType/ExistentialMetatypeMetadataBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExistentialType/ExistentialMetatypeMetadataBaselineGenerator.swift @@ -2,6 +2,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ExistentialMetatypeMetadataBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExistentialType/ExistentialTypeFlagsBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExistentialType/ExistentialTypeFlagsBaselineGenerator.swift index 70b3de317..2cd69be11 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExistentialType/ExistentialTypeFlagsBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExistentialType/ExistentialTypeFlagsBaselineGenerator.swift @@ -2,6 +2,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ExistentialTypeFlagsBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExistentialType/ExistentialTypeMetadataBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExistentialType/ExistentialTypeMetadataBaselineGenerator.swift index b65e85f2f..08748b344 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExistentialType/ExistentialTypeMetadataBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExistentialType/ExistentialTypeMetadataBaselineGenerator.swift @@ -2,6 +2,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ExistentialTypeMetadataBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExistentialType/ExtendedExistentialTypeMetadataBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExistentialType/ExtendedExistentialTypeMetadataBaselineGenerator.swift index 3dd7105a6..3de15de88 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExistentialType/ExtendedExistentialTypeMetadataBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExistentialType/ExtendedExistentialTypeMetadataBaselineGenerator.swift @@ -2,6 +2,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ExtendedExistentialTypeMetadataBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExistentialType/ExtendedExistentialTypeShapeBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExistentialType/ExtendedExistentialTypeShapeBaselineGenerator.swift index 4a9a3e315..00c4a5a61 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExistentialType/ExtendedExistentialTypeShapeBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExistentialType/ExtendedExistentialTypeShapeBaselineGenerator.swift @@ -2,6 +2,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ExtendedExistentialTypeShapeBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExistentialType/ExtendedExistentialTypeShapeFlagsBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExistentialType/ExtendedExistentialTypeShapeFlagsBaselineGenerator.swift index b40a4bb34..42bf659a2 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExistentialType/ExtendedExistentialTypeShapeFlagsBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExistentialType/ExtendedExistentialTypeShapeFlagsBaselineGenerator.swift @@ -2,6 +2,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ExtendedExistentialTypeShapeFlagsBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExistentialType/NonUniqueExtendedExistentialTypeShapeBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExistentialType/NonUniqueExtendedExistentialTypeShapeBaselineGenerator.swift index 1fe147583..03064ac7e 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExistentialType/NonUniqueExtendedExistentialTypeShapeBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExistentialType/NonUniqueExtendedExistentialTypeShapeBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/NonUniqueExtendedExistentialTypeShapeBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExtensionContextBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExtensionContextBaselineGenerator.swift index 069bdf7fe..61e1c6fb9 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExtensionContextBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExtensionContextBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ExtensionContextBaseline.swift` from the /// `SymbolTestsCore` fixture via the MachOFile reader. diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExtensionContextDescriptorBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExtensionContextDescriptorBaselineGenerator.swift index 0e1c0389e..63b4458ce 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExtensionContextDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExtensionContextDescriptorBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ExtensionContextDescriptorBaseline.swift` from the /// `SymbolTestsCore` fixture via the MachOFile reader. diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExtensionContextDescriptorProtocolBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExtensionContextDescriptorProtocolBaselineGenerator.swift index 132cb3808..e55a9b2d4 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExtensionContextDescriptorProtocolBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ExtensionContextDescriptorProtocolBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ExtensionContextDescriptorProtocolBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/FieldDescriptor/FieldDescriptorBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/FieldDescriptor/FieldDescriptorBaselineGenerator.swift index 9e2f6519f..d4af59f38 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/FieldDescriptor/FieldDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/FieldDescriptor/FieldDescriptorBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/FieldDescriptorBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/FieldRecord/FieldRecordBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/FieldRecord/FieldRecordBaselineGenerator.swift index 9615b8baf..4b88a1da7 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/FieldRecord/FieldRecordBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/FieldRecord/FieldRecordBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/FieldRecordBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/FieldRecord/FieldRecordFlagsBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/FieldRecord/FieldRecordFlagsBaselineGenerator.swift index cdc6cb3f8..080f7a2f7 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/FieldRecord/FieldRecordFlagsBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/FieldRecord/FieldRecordFlagsBaselineGenerator.swift @@ -2,6 +2,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/FieldRecordFlagsBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ForeignType/ForeignClassMetadataBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ForeignType/ForeignClassMetadataBaselineGenerator.swift index a042489f8..da9c641b2 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ForeignType/ForeignClassMetadataBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ForeignType/ForeignClassMetadataBaselineGenerator.swift @@ -2,6 +2,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ForeignClassMetadataBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ForeignType/ForeignReferenceTypeMetadataBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ForeignType/ForeignReferenceTypeMetadataBaselineGenerator.swift index 2468a5647..e71f9e6e4 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ForeignType/ForeignReferenceTypeMetadataBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ForeignType/ForeignReferenceTypeMetadataBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/ForeignReferenceTypeMetadataBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Function/FunctionTypeFlagsBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Function/FunctionTypeFlagsBaselineGenerator.swift index d81f51837..18130760f 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Function/FunctionTypeFlagsBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Function/FunctionTypeFlagsBaselineGenerator.swift @@ -2,6 +2,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/FunctionTypeFlagsBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Function/FunctionTypeMetadataBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Function/FunctionTypeMetadataBaselineGenerator.swift index 788c1660a..84ca17d46 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Function/FunctionTypeMetadataBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Function/FunctionTypeMetadataBaselineGenerator.swift @@ -2,6 +2,8 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder @testable import MachOSwiftSection +import BinaryParseSupport +import SwiftBasicFormat /// Emits `__Baseline__/FunctionTypeMetadataBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/FunctionPointer/AsyncFunctionPointerBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/FunctionPointer/AsyncFunctionPointerBaselineGenerator.swift index b1804be18..0a42a9c80 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/FunctionPointer/AsyncFunctionPointerBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/FunctionPointer/AsyncFunctionPointerBaselineGenerator.swift @@ -3,6 +3,8 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import BinaryParseSupport +import SwiftBasicFormat /// Emits `__Baseline__/AsyncFunctionPointerBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericContextBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericContextBaselineGenerator.swift index 1bd2bb7af..02dbabdf2 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericContextBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericContextBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/GenericContextBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericContextDescriptorFlagsBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericContextDescriptorFlagsBaselineGenerator.swift index 2b0abee06..59b73f16b 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericContextDescriptorFlagsBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericContextDescriptorFlagsBaselineGenerator.swift @@ -2,6 +2,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/GenericContextDescriptorFlagsBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericContextDescriptorHeaderBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericContextDescriptorHeaderBaselineGenerator.swift index 7587e6e28..fa024b54e 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericContextDescriptorHeaderBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericContextDescriptorHeaderBaselineGenerator.swift @@ -3,6 +3,8 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat +import BinaryParseSupport /// Emits `__Baseline__/GenericContextDescriptorHeaderBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericEnvironmentBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericEnvironmentBaselineGenerator.swift index c1b505417..ec0f1948a 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericEnvironmentBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericEnvironmentBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/GenericEnvironmentBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericEnvironmentFlagsBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericEnvironmentFlagsBaselineGenerator.swift index a6f73014f..bae297f85 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericEnvironmentFlagsBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericEnvironmentFlagsBaselineGenerator.swift @@ -2,6 +2,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/GenericEnvironmentFlagsBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericPackShapeDescriptorBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericPackShapeDescriptorBaselineGenerator.swift index b36cca706..70a32fd43 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericPackShapeDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericPackShapeDescriptorBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/GenericPackShapeDescriptorBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericPackShapeHeaderBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericPackShapeHeaderBaselineGenerator.swift index 24555a724..f48ee8593 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericPackShapeHeaderBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericPackShapeHeaderBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/GenericPackShapeHeaderBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericParamDescriptorBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericParamDescriptorBaselineGenerator.swift index 762c1c0d6..0a244b40d 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericParamDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericParamDescriptorBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/GenericParamDescriptorBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericRequirementBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericRequirementBaselineGenerator.swift index 9540eebfb..6428f4b83 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericRequirementBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericRequirementBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/GenericRequirementBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericRequirementContentBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericRequirementContentBaselineGenerator.swift index 586bb3c95..6c59615ed 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericRequirementContentBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericRequirementContentBaselineGenerator.swift @@ -2,6 +2,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/GenericRequirementContentBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericRequirementDescriptorBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericRequirementDescriptorBaselineGenerator.swift index 249d09464..df5c1ad17 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericRequirementDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericRequirementDescriptorBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/GenericRequirementDescriptorBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericRequirementFlagsBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericRequirementFlagsBaselineGenerator.swift index c1ee1d8cc..9f66da2a5 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericRequirementFlagsBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericRequirementFlagsBaselineGenerator.swift @@ -2,6 +2,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/GenericRequirementFlagsBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericValueDescriptorBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericValueDescriptorBaselineGenerator.swift index 1a6a31d21..19a740b79 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericValueDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericValueDescriptorBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/GenericValueDescriptorBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericValueHeaderBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericValueHeaderBaselineGenerator.swift index 2d191ce0e..896f5e17b 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericValueHeaderBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericValueHeaderBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/GenericValueHeaderBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericWitnessTableBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericWitnessTableBaselineGenerator.swift index 7362113da..b7e5b1dcd 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericWitnessTableBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/GenericWitnessTableBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/GenericWitnessTableBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/Pattern/GenericClassMetadataPatternBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/Pattern/GenericClassMetadataPatternBaselineGenerator.swift index 82ae6b0ed..9cd6e8a22 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/Pattern/GenericClassMetadataPatternBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/Pattern/GenericClassMetadataPatternBaselineGenerator.swift @@ -3,6 +3,8 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat +import BinaryParseSupport /// Emits `__Baseline__/GenericClassMetadataPatternBaseline.swift`. package enum GenericClassMetadataPatternBaselineGenerator { diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/Pattern/GenericMetadataPartialPatternBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/Pattern/GenericMetadataPartialPatternBaselineGenerator.swift index 10f63df8e..5283b52f4 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/Pattern/GenericMetadataPartialPatternBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/Pattern/GenericMetadataPartialPatternBaselineGenerator.swift @@ -3,6 +3,8 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat +import BinaryParseSupport /// Emits `__Baseline__/GenericMetadataPartialPatternBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/Pattern/GenericMetadataPatternProtocolBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/Pattern/GenericMetadataPatternProtocolBaselineGenerator.swift index 19e7d8a58..f1696b990 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/Pattern/GenericMetadataPatternProtocolBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/Pattern/GenericMetadataPatternProtocolBaselineGenerator.swift @@ -3,6 +3,8 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat +import BinaryParseSupport /// Emits `__Baseline__/GenericMetadataPatternProtocolBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/Pattern/GenericValueMetadataPatternBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/Pattern/GenericValueMetadataPatternBaselineGenerator.swift index 6787a1a32..94c62fa8c 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/Pattern/GenericValueMetadataPatternBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/Pattern/GenericValueMetadataPatternBaselineGenerator.swift @@ -3,6 +3,8 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat +import BinaryParseSupport /// Emits `__Baseline__/GenericValueMetadataPatternBaseline.swift`. package enum GenericValueMetadataPatternBaselineGenerator { diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/Pattern/ResilientClassMetadataPatternBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/Pattern/ResilientClassMetadataPatternBaselineGenerator.swift index b96a60b0d..55d5a8c4c 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/Pattern/ResilientClassMetadataPatternBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/Pattern/ResilientClassMetadataPatternBaselineGenerator.swift @@ -3,6 +3,8 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat +import BinaryParseSupport /// Emits `__Baseline__/ResilientClassMetadataPatternBaseline.swift`. package enum ResilientClassMetadataPatternBaselineGenerator { diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/TypeGenericContextDescriptorHeaderBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/TypeGenericContextDescriptorHeaderBaselineGenerator.swift index cf278df70..734adcdc0 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/TypeGenericContextDescriptorHeaderBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Generic/TypeGenericContextDescriptorHeaderBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/TypeGenericContextDescriptorHeaderBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Heap/GenericBoxHeapMetadataBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Heap/GenericBoxHeapMetadataBaselineGenerator.swift index 3c1524054..7538e31c5 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Heap/GenericBoxHeapMetadataBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Heap/GenericBoxHeapMetadataBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/GenericBoxHeapMetadataBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Heap/HeapLocalVariableMetadataBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Heap/HeapLocalVariableMetadataBaselineGenerator.swift index 3493fcf1e..f8edcb00f 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Heap/HeapLocalVariableMetadataBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Heap/HeapLocalVariableMetadataBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/HeapLocalVariableMetadataBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/KeyPath/KeyPathComponentHeaderBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/KeyPath/KeyPathComponentHeaderBaselineGenerator.swift index 80acffb54..95348b82c 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/KeyPath/KeyPathComponentHeaderBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/KeyPath/KeyPathComponentHeaderBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/KeyPathComponentHeaderBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/KeyPath/KeyPathComputedPropertyBodyBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/KeyPath/KeyPathComputedPropertyBodyBaselineGenerator.swift index aa576c0e4..122497eec 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/KeyPath/KeyPathComputedPropertyBodyBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/KeyPath/KeyPathComputedPropertyBodyBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/KeyPathComputedPropertyBodyBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/KeyPath/KeyPathStoredFieldOffsetBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/KeyPath/KeyPathStoredFieldOffsetBaselineGenerator.swift index d9065b464..bc1ef7be7 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/KeyPath/KeyPathStoredFieldOffsetBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/KeyPath/KeyPathStoredFieldOffsetBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/KeyPathStoredFieldOffsetBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/KeyPath/PropertyDescriptorBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/KeyPath/PropertyDescriptorBaselineGenerator.swift index f652a1a8d..ef759b919 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/KeyPath/PropertyDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/KeyPath/PropertyDescriptorBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/PropertyDescriptorBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Mangling/MangledNameBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Mangling/MangledNameBaselineGenerator.swift index 9d7ee643c..7cc1a3191 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Mangling/MangledNameBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Mangling/MangledNameBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/MangledNameBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/BorrowTypeMetadataBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/BorrowTypeMetadataBaselineGenerator.swift index e056a8019..5f1d5f4da 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/BorrowTypeMetadataBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/BorrowTypeMetadataBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/BorrowTypeMetadataBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadataAccessorsListEntryBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadataAccessorsListEntryBaselineGenerator.swift index 9aa1ad971..10e0db5cd 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadataAccessorsListEntryBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadataAccessorsListEntryBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/CanonicalSpecializedMetadataAccessorsListEntryBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadatasCachingOnceTokenBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadatasCachingOnceTokenBaselineGenerator.swift index cb03e4e6e..a139dc354 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadatasCachingOnceTokenBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadatasCachingOnceTokenBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/CanonicalSpecializedMetadatasCachingOnceTokenBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadatasListCountBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadatasListCountBaselineGenerator.swift index 37ae2fd05..954673aaa 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadatasListCountBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadatasListCountBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/CanonicalSpecializedMetadatasListCountBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadatasListEntryBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadatasListEntryBaselineGenerator.swift index 3af0def06..6b645e54b 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadatasListEntryBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadatasListEntryBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/CanonicalSpecializedMetadatasListEntryBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/FixedArrayTypeMetadataBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/FixedArrayTypeMetadataBaselineGenerator.swift index 7420bb0f9..f3b8d68ab 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/FixedArrayTypeMetadataBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/FixedArrayTypeMetadataBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/FixedArrayTypeMetadataBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/FullMetadataBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/FullMetadataBaselineGenerator.swift index 0236db4ec..f5fcf89b2 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/FullMetadataBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/FullMetadataBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/FullMetadataBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/Headers/HeapMetadataHeaderBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/Headers/HeapMetadataHeaderBaselineGenerator.swift index ca86f4042..131f167c9 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/Headers/HeapMetadataHeaderBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/Headers/HeapMetadataHeaderBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/HeapMetadataHeaderBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/Headers/HeapMetadataHeaderPrefixBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/Headers/HeapMetadataHeaderPrefixBaselineGenerator.swift index 38a8b4da6..0a9f4a78c 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/Headers/HeapMetadataHeaderPrefixBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/Headers/HeapMetadataHeaderPrefixBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/HeapMetadataHeaderPrefixBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/Headers/TypeMetadataHeaderBaseBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/Headers/TypeMetadataHeaderBaseBaselineGenerator.swift index 6fa85f9ed..82fa9ead4 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/Headers/TypeMetadataHeaderBaseBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/Headers/TypeMetadataHeaderBaseBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/TypeMetadataHeaderBaseBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/Headers/TypeMetadataHeaderBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/Headers/TypeMetadataHeaderBaselineGenerator.swift index c53239932..7a47491d1 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/Headers/TypeMetadataHeaderBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/Headers/TypeMetadataHeaderBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/TypeMetadataHeaderBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/Headers/TypeMetadataLayoutPrefixBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/Headers/TypeMetadataLayoutPrefixBaselineGenerator.swift index acc708fc1..45d25d5ff 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/Headers/TypeMetadataLayoutPrefixBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/Headers/TypeMetadataLayoutPrefixBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/TypeMetadataLayoutPrefixBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataAccessorFunctionBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataAccessorFunctionBaselineGenerator.swift index 36cfefbf3..ba9b777db 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataAccessorFunctionBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataAccessorFunctionBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/MetadataAccessorFunctionBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataBaselineGenerator.swift index 66c1c8b98..cc37f944a 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/MetadataBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataBoundsBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataBoundsBaselineGenerator.swift index 05a3b2f7b..e8f0948bd 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataBoundsBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataBoundsBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/MetadataBoundsBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataBoundsProtocolBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataBoundsProtocolBaselineGenerator.swift index b4293c5d7..8f49f6616 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataBoundsProtocolBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataBoundsProtocolBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/MetadataBoundsProtocolBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataInitialization/ForeignMetadataInitializationBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataInitialization/ForeignMetadataInitializationBaselineGenerator.swift index 38a688455..1872bca57 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataInitialization/ForeignMetadataInitializationBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataInitialization/ForeignMetadataInitializationBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/ForeignMetadataInitializationBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataInitialization/SingletonMetadataInitializationBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataInitialization/SingletonMetadataInitializationBaselineGenerator.swift index 544e4a45d..14ef7cbfe 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataInitialization/SingletonMetadataInitializationBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataInitialization/SingletonMetadataInitializationBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/SingletonMetadataInitializationBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataProtocolBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataProtocolBaselineGenerator.swift index 69f302b42..1d9fd0d52 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataProtocolBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataProtocolBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/MetadataProtocolBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataRequestBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataRequestBaselineGenerator.swift index 0f851c13c..3bb5d5eb8 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataRequestBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataRequestBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/MetadataRequestBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataResponseBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataResponseBaselineGenerator.swift index 18e919182..da0288ea4 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataResponseBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataResponseBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/MetadataResponseBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataWrapperBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataWrapperBaselineGenerator.swift index 5e4eae3d7..46e024cbf 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataWrapperBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetadataWrapperBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/MetadataWrapperBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetatypeMetadataBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetatypeMetadataBaselineGenerator.swift index 47c9bcb6f..add600d11 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetatypeMetadataBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/MetatypeMetadataBaselineGenerator.swift @@ -2,6 +2,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/MetatypeMetadataBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/SingletonMetadataPointerBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/SingletonMetadataPointerBaselineGenerator.swift index 24fb0e920..3b370e517 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/SingletonMetadataPointerBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Metadata/SingletonMetadataPointerBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/SingletonMetadataPointerBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ModuleContextBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ModuleContextBaselineGenerator.swift index 6dbd54ff0..a61d3aaeb 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ModuleContextBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ModuleContextBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ModuleContextBaseline.swift` from the /// `SymbolTestsCore` fixture via the MachOFile reader. diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ModuleContextDescriptorBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ModuleContextDescriptorBaselineGenerator.swift index bc367c643..b54e5994a 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ModuleContextDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ModuleContextDescriptorBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ModuleContextDescriptorBaseline.swift` from the /// `SymbolTestsCore` fixture via the MachOFile reader. diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/NamedContextDescriptorProtocolBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/NamedContextDescriptorProtocolBaselineGenerator.swift index 425696bce..e4a39a93b 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/NamedContextDescriptorProtocolBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/NamedContextDescriptorProtocolBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/NamedContextDescriptorProtocolBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/OpaqueType/OpaqueMetadataBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/OpaqueType/OpaqueMetadataBaselineGenerator.swift index 51a15e950..59718e9c4 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/OpaqueType/OpaqueMetadataBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/OpaqueType/OpaqueMetadataBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/OpaqueMetadataBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/OpaqueType/OpaqueTypeBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/OpaqueType/OpaqueTypeBaselineGenerator.swift index 35d4574d4..3df881fb9 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/OpaqueType/OpaqueTypeBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/OpaqueType/OpaqueTypeBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/OpaqueTypeBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/OpaqueType/OpaqueTypeDescriptorBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/OpaqueType/OpaqueTypeDescriptorBaselineGenerator.swift index 5b67b7028..e02e27c6f 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/OpaqueType/OpaqueTypeDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/OpaqueType/OpaqueTypeDescriptorBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/OpaqueTypeDescriptorBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/OpaqueType/OpaqueTypeDescriptorProtocolBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/OpaqueType/OpaqueTypeDescriptorProtocolBaselineGenerator.swift index ef066a9e4..3cc8fed05 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/OpaqueType/OpaqueTypeDescriptorProtocolBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/OpaqueType/OpaqueTypeDescriptorProtocolBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/OpaqueTypeDescriptorProtocolBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/Invertible/InvertibleProtocolSetBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/Invertible/InvertibleProtocolSetBaselineGenerator.swift index 850202eb4..0f09285f2 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/Invertible/InvertibleProtocolSetBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/Invertible/InvertibleProtocolSetBaselineGenerator.swift @@ -2,6 +2,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/InvertibleProtocolSetBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/Invertible/InvertibleProtocolsRequirementCountBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/Invertible/InvertibleProtocolsRequirementCountBaselineGenerator.swift index 63528e82d..32b4aafae 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/Invertible/InvertibleProtocolsRequirementCountBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/Invertible/InvertibleProtocolsRequirementCountBaselineGenerator.swift @@ -2,6 +2,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/InvertibleProtocolsRequirementCountBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ObjC/ObjCProtocolPrefixBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ObjC/ObjCProtocolPrefixBaselineGenerator.swift index c3f81dd7e..6f7493361 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ObjC/ObjCProtocolPrefixBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ObjC/ObjCProtocolPrefixBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ObjCProtocolPrefixBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ObjC/RelativeObjCProtocolPrefixBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ObjC/RelativeObjCProtocolPrefixBaselineGenerator.swift index 4eca5d227..b111d04aa 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ObjC/RelativeObjCProtocolPrefixBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ObjC/RelativeObjCProtocolPrefixBaselineGenerator.swift @@ -2,6 +2,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/RelativeObjCProtocolPrefixBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolBaseRequirementBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolBaseRequirementBaselineGenerator.swift index b6b7f4649..91f91229b 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolBaseRequirementBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolBaseRequirementBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ProtocolBaseRequirementBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolBaselineGenerator.swift index 834c67985..d4c4a708b 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ProtocolBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolContextDescriptorFlagsBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolContextDescriptorFlagsBaselineGenerator.swift index 56f06c684..de3f105f0 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolContextDescriptorFlagsBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolContextDescriptorFlagsBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ProtocolContextDescriptorFlagsBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolDescriptorBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolDescriptorBaselineGenerator.swift index 36495331f..99e202e83 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolDescriptorBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ProtocolDescriptorBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolDescriptorFlagsBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolDescriptorFlagsBaselineGenerator.swift index ed1b2133c..7742907f6 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolDescriptorFlagsBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolDescriptorFlagsBaselineGenerator.swift @@ -2,6 +2,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ProtocolDescriptorFlagsBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolDescriptorRefBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolDescriptorRefBaselineGenerator.swift index 1c197e8fd..6318d88e5 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolDescriptorRefBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolDescriptorRefBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ProtocolDescriptorRefBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolRecordBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolRecordBaselineGenerator.swift index 512c3d4f5..25ec8338c 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolRecordBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolRecordBaselineGenerator.swift @@ -4,6 +4,7 @@ import SwiftSyntaxBuilder import MachOFoundation import MachOKit @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ProtocolRecordBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolRequirementBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolRequirementBaselineGenerator.swift index dfc416b86..5e9f08a7c 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolRequirementBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolRequirementBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ProtocolRequirementBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolRequirementFlagsBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolRequirementFlagsBaselineGenerator.swift index 6f1a38f1f..058b87ddc 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolRequirementFlagsBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolRequirementFlagsBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ProtocolRequirementFlagsBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolRequirementKindBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolRequirementKindBaselineGenerator.swift index 80bbf6f0c..82881fa63 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolRequirementKindBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolRequirementKindBaselineGenerator.swift @@ -2,6 +2,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ProtocolRequirementKindBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolWitnessTableBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolWitnessTableBaselineGenerator.swift index d62511389..b8c410ebd 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolWitnessTableBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ProtocolWitnessTableBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ProtocolWitnessTableBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ResilientWitnessBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ResilientWitnessBaselineGenerator.swift index 7c5eb575a..38bf4987d 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ResilientWitnessBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ResilientWitnessBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ResilientWitnessBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ResilientWitnessesHeaderBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ResilientWitnessesHeaderBaselineGenerator.swift index 2c6497241..68f556f79 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ResilientWitnessesHeaderBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Protocol/ResilientWitnessesHeaderBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ResilientWitnessesHeaderBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ProtocolConformance/GlobalActorReferenceBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ProtocolConformance/GlobalActorReferenceBaselineGenerator.swift index a285da59a..d4d1dfa12 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ProtocolConformance/GlobalActorReferenceBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ProtocolConformance/GlobalActorReferenceBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/GlobalActorReferenceBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ProtocolConformance/ProtocolConformanceBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ProtocolConformance/ProtocolConformanceBaselineGenerator.swift index 8748700d2..9a43e7fa1 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ProtocolConformance/ProtocolConformanceBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ProtocolConformance/ProtocolConformanceBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ProtocolConformanceBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ProtocolConformance/ProtocolConformanceDescriptorBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ProtocolConformance/ProtocolConformanceDescriptorBaselineGenerator.swift index c45724376..87aaf4f33 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ProtocolConformance/ProtocolConformanceDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ProtocolConformance/ProtocolConformanceDescriptorBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ProtocolConformanceDescriptorBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ProtocolConformance/ProtocolConformanceFlagsBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ProtocolConformance/ProtocolConformanceFlagsBaselineGenerator.swift index 957bb48d8..a7a75e58d 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ProtocolConformance/ProtocolConformanceFlagsBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ProtocolConformance/ProtocolConformanceFlagsBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ProtocolConformanceFlagsBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/StructBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/StructBaselineGenerator.swift index 0a56c36e1..441c83b82 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/StructBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/StructBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat // Pattern note: this generator and its corresponding Suite use **presence flags** // (`hasGenericContext: Bool`, etc.) for heavy optional ivars rather than full diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/StructDescriptorBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/StructDescriptorBaselineGenerator.swift index 74c5b255c..f77a65f37 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/StructDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/StructDescriptorBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/StructDescriptorBaseline.swift` from the /// `SymbolTestsCore` fixture via the MachOFile reader. diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/StructMetadataBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/StructMetadataBaselineGenerator.swift index d97656795..37998ac2c 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/StructMetadataBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/StructMetadataBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/StructMetadataBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/StructMetadataProtocolBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/StructMetadataProtocolBaselineGenerator.swift index 6615e1d50..15ac669e6 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/StructMetadataProtocolBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/StructMetadataProtocolBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/StructMetadataProtocolBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/TupleType/TupleTypeMetadataBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/TupleType/TupleTypeMetadataBaselineGenerator.swift index 0ea47cbb6..452a507e3 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/TupleType/TupleTypeMetadataBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/TupleType/TupleTypeMetadataBaselineGenerator.swift @@ -2,6 +2,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/TupleTypeMetadataBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/TupleType/TupleTypeMetadataElementBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/TupleType/TupleTypeMetadataElementBaselineGenerator.swift index 932762d8e..908ce9890 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/TupleType/TupleTypeMetadataElementBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/TupleType/TupleTypeMetadataElementBaselineGenerator.swift @@ -2,6 +2,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/TupleTypeMetadataElementBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorBaselineGenerator.swift index b36b9b345..4e3aec4cc 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/TypeContextDescriptorBaseline.swift` from the /// `SymbolTestsCore` fixture via the MachOFile reader. diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorFlagsBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorFlagsBaselineGenerator.swift index 7bae57581..a879395fa 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorFlagsBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorFlagsBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/TypeContextDescriptorFlagsBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorProtocolBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorProtocolBaselineGenerator.swift index 03f786fd0..0e216bc36 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorProtocolBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorProtocolBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/TypeContextDescriptorProtocolBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorWrapperBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorWrapperBaselineGenerator.swift index cf84721ec..01fc0d878 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorWrapperBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorWrapperBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/TypeContextDescriptorWrapperBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeContextWrapperBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeContextWrapperBaselineGenerator.swift index a55c2a3c3..17fec8eae 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeContextWrapperBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeContextWrapperBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/TypeContextWrapperBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeMetadataRecordBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeMetadataRecordBaselineGenerator.swift index 59f12f124..f31cc6537 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeMetadataRecordBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeMetadataRecordBaselineGenerator.swift @@ -4,6 +4,7 @@ import SwiftSyntaxBuilder import MachOFoundation import MachOKit @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/TypeMetadataRecordBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeReferenceBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeReferenceBaselineGenerator.swift index 9b3b14abd..01f8cd17f 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeReferenceBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/TypeReferenceBaselineGenerator.swift @@ -4,6 +4,7 @@ import SwiftSyntaxBuilder import MachOFoundation import MachOKit @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/TypeReferenceBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/ValueMetadataBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/ValueMetadataBaselineGenerator.swift index eea88ff92..34dd4dfec 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/ValueMetadataBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/ValueMetadataBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/ValueMetadataBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/ValueMetadataProtocolBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/ValueMetadataProtocolBaselineGenerator.swift index fa0221045..e48d54cf6 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/ValueMetadataProtocolBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/ValueMetadataProtocolBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/ValueMetadataProtocolBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/ValueTypeDescriptorWrapperBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/ValueTypeDescriptorWrapperBaselineGenerator.swift index 16b185d66..4e02c0d14 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/ValueTypeDescriptorWrapperBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/Type/ValueTypeDescriptorWrapperBaselineGenerator.swift @@ -3,6 +3,7 @@ import SwiftSyntax import SwiftSyntaxBuilder import MachOFoundation @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ValueTypeDescriptorWrapperBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ValueWitnessTable/TypeLayoutBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ValueWitnessTable/TypeLayoutBaselineGenerator.swift index 4cba0dae3..0a4790322 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ValueWitnessTable/TypeLayoutBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ValueWitnessTable/TypeLayoutBaselineGenerator.swift @@ -2,6 +2,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/TypeLayoutBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ValueWitnessTable/ValueWitnessFlagsBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ValueWitnessTable/ValueWitnessFlagsBaselineGenerator.swift index 6e251b517..cb0d2b1ed 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ValueWitnessTable/ValueWitnessFlagsBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ValueWitnessTable/ValueWitnessFlagsBaselineGenerator.swift @@ -2,6 +2,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder @testable import MachOSwiftSection +import SwiftBasicFormat /// Emits `__Baseline__/ValueWitnessFlagsBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ValueWitnessTable/ValueWitnessTableBaselineGenerator.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ValueWitnessTable/ValueWitnessTableBaselineGenerator.swift index 1647f8f6f..48811bf46 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ValueWitnessTable/ValueWitnessTableBaselineGenerator.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Baseline/Generators/ValueWitnessTable/ValueWitnessTableBaselineGenerator.swift @@ -1,6 +1,7 @@ import Foundation import SwiftSyntax import SwiftSyntaxBuilder +import SwiftBasicFormat /// Emits `__Baseline__/ValueWitnessTableBaseline.swift`. /// diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/CompiledFixtureCopies.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/CompiledFixtureCopies.swift new file mode 100644 index 000000000..c6b9f0489 --- /dev/null +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/CompiledFixtureCopies.swift @@ -0,0 +1,112 @@ +import Foundation +import MachOKit + +/// Copies of a library `FixtureCompiler` compiled, rewritten after linking, +/// each in a directory of its own so that the shared compiled library stays +/// as it was: what `FixtureCompiler` cannot express yet (the +/// shared-macho-testing-support proposal lists stripping after linking). A +/// rewritten copy is for reading as a file; one whose code changed would +/// need signing again before it loads. +/// +/// Each copy gets an `LC_UUID` of its own. The library's per-image caches +/// key a file on its UUID (`SharedCacheKey`), and a copy keeping the +/// original's read whichever indexes the other had built first: a stripped +/// copy's type index served the unstripped library in a parallel run. +package enum CompiledFixtureCopies { + package struct Failure: Error, CustomStringConvertible { + package let description: String + + package init(description: String) { + self.description = description + } + } + + /// A copy of `library` without its local symbols (`strip -x`) — among + /// them the names of the mangled-name helpers and the `…MXX` symbols + /// naming anonymous contexts, which an optimized OS binary does not keep. + package static func strippedCopy(of library: URL) throws -> URL { + let copy = try copy(of: library) + try run("/usr/bin/xcrun", arguments: ["strip", "-x", copy.path]) + var bytes = try Data(contentsOf: copy) + try replaceUUID(in: &bytes) + try bytes.write(to: copy) + return copy + } + + /// A copy of `library` whose bytes `patch` rewrites, handed the copy as + /// a file read before the rewrite: a malformed binary a compiler does + /// not produce. + package static func patchedCopy(of library: URL, patch: (inout Data, MachOFile) throws -> Void) throws -> URL { + let copy = try copy(of: library) + var bytes = try Data(contentsOf: copy) + try patch(&bytes, try MachOFile(url: copy)) + try replaceUUID(in: &bytes) + try bytes.write(to: copy) + return copy + } + + /// Writes a fresh UUID into the `LC_UUID` command of the thin 64-bit + /// Mach-O `bytes`. + private static func replaceUUID(in bytes: inout Data) throws { + func loadUInt32(at offset: Int) -> UInt32 { + bytes[offset ..< offset + 4].withUnsafeBytes { UInt32(littleEndian: $0.loadUnaligned(as: UInt32.self)) } + } + let headerSize = 32 + let uuidCommand: UInt32 = 0x1B + guard bytes.count >= headerSize, loadUInt32(at: 0) == 0xFEED_FACF else { + throw Failure(description: "not a thin 64-bit Mach-O file") + } + let commandCount = Int(loadUInt32(at: 16)) + var commandOffset = headerSize + for _ in 0 ..< commandCount { + guard commandOffset + 8 <= bytes.count else { break } + let commandSize = Int(loadUInt32(at: commandOffset + 4)) + if loadUInt32(at: commandOffset) == uuidCommand, commandSize >= 24 { + withUnsafeBytes(of: UUID().uuid) { uuidBytes in + bytes.replaceSubrange(commandOffset + 8 ..< commandOffset + 24, with: uuidBytes) + } + return + } + guard commandSize > 0 else { break } + commandOffset += commandSize + } + throw Failure(description: "no LC_UUID load command") + } + + /// Writes `value` little-endian over the four bytes at `fileOffset`. + package static func write(_ value: Int32, at fileOffset: Int, in bytes: inout Data) { + withUnsafeBytes(of: value.littleEndian) { valueBytes in + bytes.replaceSubrange(fileOffset ..< fileOffset + 4, with: valueBytes) + } + } + + /// Writes `value` little-endian over the four bytes at `fileOffset`. + package static func write(_ value: UInt32, at fileOffset: Int, in bytes: inout Data) { + withUnsafeBytes(of: value.littleEndian) { valueBytes in + bytes.replaceSubrange(fileOffset ..< fileOffset + 4, with: valueBytes) + } + } + + private static func copy(of library: URL) throws -> URL { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent("CompiledFixtureCopies-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + let copy = directory.appendingPathComponent(library.lastPathComponent) + try FileManager.default.copyItem(at: library, to: copy) + return copy + } + + private static func run(_ executablePath: String, arguments: [String]) throws { + let process = Process() + process.executableURL = URL(fileURLWithPath: executablePath) + process.arguments = arguments + let output = Pipe() + process.standardOutput = output + process.standardError = output + try process.run() + let printed = output.fileHandleForReading.readDataToEndOfFile() + process.waitUntilExit() + guard process.terminationStatus == 0 else { + throw Failure(description: "\(([executablePath] + arguments).joined(separator: " ")) exited with \(process.terminationStatus): \(String(decoding: printed, as: UTF8.self))") + } + } +} diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Coverage/SuiteBehaviorScanner.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Coverage/SuiteBehaviorScanner.swift index fd5c03e28..f43a77aa1 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Coverage/SuiteBehaviorScanner.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Coverage/SuiteBehaviorScanner.swift @@ -79,7 +79,7 @@ private final class SuiteBehaviorVisitor: SyntaxVisitor { private var currentEnclosingClassBodyText: String? override func visit(_ node: ClassDeclSyntax) -> SyntaxVisitorContinueKind { - currentTestedTypeName = extractTestedTypeName(from: node.memberBlock) + currentTestedTypeName = Self.testedTypeName(fromFixtureSuiteAttributeOf: node) ?? extractTestedTypeName(from: node.memberBlock) currentEnclosingClassBodyText = node.memberBlock.description return .visitChildren } @@ -116,6 +116,28 @@ private final class SuiteBehaviorVisitor: SyntaxVisitor { return .skipChildren } + /// The tested type's name a `@FixtureSuite` attribute gives the class: + /// its `testedTypeName:` literal, else the class name without its + /// `Tests` suffix — the macro's own rule. `nil` without the attribute. + private static func testedTypeName(fromFixtureSuiteAttributeOf node: ClassDeclSyntax) -> String? { + for element in node.attributes { + guard let attribute = element.as(AttributeSyntax.self), + attribute.attributeName.trimmedDescription.split(separator: ".").last == "FixtureSuite" else { + continue + } + for argument in attribute.arguments?.as(LabeledExprListSyntax.self) ?? [] where argument.label?.text == "testedTypeName" { + if let literal = argument.expression.as(StringLiteralExprSyntax.self) { + let value = literal.segments.compactMap { $0.as(StringSegmentSyntax.self)?.content.text }.joined() + if !value.isEmpty { return value } + } + } + let className = node.name.text + guard className.hasSuffix("Tests"), className.count > "Tests".count else { return nil } + return String(className.dropLast("Tests".count)) + } + return nil + } + private func extractTestedTypeName(from memberBlock: MemberBlockSyntax) -> String? { for member in memberBlock.members { guard let varDecl = member.decl.as(VariableDeclSyntax.self) else { continue } diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/DemangleOptions.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/DemangleOptions.swift index 4e4249306..026b64695 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/DemangleOptions.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/DemangleOptions.swift @@ -1,6 +1,7 @@ import Foundation import MachOSwiftSection import SwiftDump +import Demangling extension DemangleOptions { /// Snapshot/baseline fixtures are recorded with interface-style printing: diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/DumpableTests.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/DumpableTests.swift index 97f223e57..581d1ca93 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/DumpableTests.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/DumpableTests.swift @@ -7,6 +7,8 @@ import SwiftDeclarationRendering import Dependencies @_spi(Internals) import SwiftSymbols @_spi(Internals) import SwiftInspection +import Semantic +import Demangling @MainActor package protocol DumpableTests { diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/DyldSharedCachePath+NamedCaches.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/DyldSharedCachePath+NamedCaches.swift new file mode 100644 index 000000000..7898cac2a --- /dev/null +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/DyldSharedCachePath+NamedCaches.swift @@ -0,0 +1,17 @@ +import MachOFixtureSupport + +/// The caches this package's tests name, beside the running system's +/// (`current`) and the archived ones any version names (`macOS(_:)`, +/// `iOS(_:)`) that MachOKitExtensions provides. +extension DyldSharedCachePath { + package static let iOS_18_5 = DyldSharedCachePath(path: "/Volumes/Generic/iOS Systems/22F76__iPhone17,5/dyld_shared_cache_arm64e", versionLabel: "18.5") + package static let iOS_26_1 = DyldSharedCachePath(path: "/Volumes/Generic/iOS Systems/23B85__iPhone17,5/dyld_shared_cache_arm64e", versionLabel: "26.1") + package static let macOS_15_5 = macOS("15.5") + package static let macOS_26_5_1 = macOS("26.5.1") + package static let macOS_26_5_2 = macOS("26.5.2") + package static let macOS_27_0 = macOS("27.0") + /// From iOS 27 beta 3 on a simulator runtime ships its frameworks in a + /// cache of its own instead of as files under `RuntimeRoot`. The runtime's + /// volume is named after its build, so no version alone spells this path. + package static let iOS_27_0_Simulator = DyldSharedCachePath(path: "/Library/Developer/CoreSimulator/Volumes/iOS_24A434/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS 27.0.simruntime/Contents/Resources/RuntimeRoot/System/Library/Caches/com.apple.dyld/dyld_sim_shared_cache_arm64", versionLabel: "27.0") +} diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/DyldSharedCachePath.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/DyldSharedCachePath.swift deleted file mode 100644 index a9b811fb8..000000000 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/DyldSharedCachePath.swift +++ /dev/null @@ -1,56 +0,0 @@ -/// A dyld shared cache file the tests open, and what a version axis calls it. -/// -/// A struct with static members rather than an enum, so that besides the -/// caches named below any archived cache can be named by its version: -/// `.macOS("26.6")`. Not `RawRepresentable`: every value carries a label, -/// which a path alone does not give. -package struct DyldSharedCachePath: Hashable, Sendable { - package let rawValue: String - - /// What a version axis calls this cache, such as the evolution dumps' - /// labels: the version an archived cache was named by, or the label a - /// named cache states. Not necessarily a system version — `current` is - /// labeled `current`. - package let versionLabel: String - - package init(rawValue: String, versionLabel: String) { - self.rawValue = rawValue - self.versionLabel = versionLabel - } - - /// The archived macOS cache of `version`, labeled `version`: - /// `/Volumes/DyldSharedCaches/macOS//dyld_shared_cache_arm64e`. - /// - /// `version` is the directory name on the volume (`26.5.2`, - /// `14.0(Internal)`). Whether that directory holds a cache is the - /// caller's to check; some hold only exported headers. - package static func macOS(_ version: String) -> DyldSharedCachePath { - archived(platformDirectoryName: "macOS", version: version) - } - - /// The archived iOS device cache of `version`, labeled `version`: - /// `/Volumes/DyldSharedCaches/iOS//dyld_shared_cache_arm64e`. - package static func iOS(_ version: String) -> DyldSharedCachePath { - archived(platformDirectoryName: "iOS", version: version) - } - - private static func archived(platformDirectoryName: String, version: String) -> DyldSharedCachePath { - DyldSharedCachePath( - rawValue: "/Volumes/DyldSharedCaches/\(platformDirectoryName)/\(version)/dyld_shared_cache_arm64e", - versionLabel: version - ) - } - - /// The running system's cache. - package static let current = DyldSharedCachePath(rawValue: "/System/Volumes/Preboot/Cryptexes/OS/System/Library/dyld/dyld_shared_cache_arm64e", versionLabel: "current") - package static let iOS_18_5 = DyldSharedCachePath(rawValue: "/Volumes/Generic/iOS Systems/22F76__iPhone17,5/dyld_shared_cache_arm64e", versionLabel: "18.5") - package static let iOS_26_1 = DyldSharedCachePath(rawValue: "/Volumes/Generic/iOS Systems/23B85__iPhone17,5/dyld_shared_cache_arm64e", versionLabel: "26.1") - package static let macOS_15_5 = macOS("15.5") - package static let macOS_26_5_1 = macOS("26.5.1") - package static let macOS_26_5_2 = macOS("26.5.2") - package static let macOS_27_0 = macOS("27.0") - /// From iOS 27 beta 3 on a simulator runtime ships its frameworks in a - /// cache of its own instead of as files under `RuntimeRoot`. The runtime's - /// volume is named after its build, so no version alone spells this path. - package static let iOS_27_0_Simulator = DyldSharedCachePath(rawValue: "/Library/Developer/CoreSimulator/Volumes/iOS_24A434/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS 27.0.simruntime/Contents/Resources/RuntimeRoot/System/Library/Caches/com.apple.dyld/dyld_sim_shared_cache_arm64", versionLabel: "27.0") -} diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Exports.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Exports.swift new file mode 100644 index 000000000..d1b113a07 --- /dev/null +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/Exports.swift @@ -0,0 +1,7 @@ +// The Swift-free test support shared with MachOKitExtensions: fixture names, +// opening caches and images, slice picking, the fixture compiler and +// `.print()`. Re-exported so that a test importing this module reaches it +// without an import of its own; this module adds the package's own fixture +// names and named caches to it (`MachOFileName+SymbolTests.swift`, +// `MachOImageName+SymbolTests.swift`, `DyldSharedCachePath+NamedCaches.swift`). +@_exported import MachOFixtureSupport diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/Extensions.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/Extensions.swift deleted file mode 100644 index 7f71a78a1..000000000 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/Extensions.swift +++ /dev/null @@ -1,56 +0,0 @@ -import Foundation -import MachOKit -import UniformTypeIdentifiers - -package func loadFromFile(named: MachOFileName) throws -> File { - let url: URL - let filePath = named.rawValue - if filePath.starts(with: "../") || filePath.starts(with: "./") { - url = URL(fileURLWithPath: filePath, relativeTo: URL(fileURLWithPath: #filePath)) - } else { - url = URL(fileURLWithPath: filePath) - } - return try File.loadFromFile(url: url) -} - -extension MachOImage { - package init?(named: MachOImageName) { - self.init(name: named.rawValue) - } -} - -extension FullDyldCache { - package convenience init(path: DyldSharedCachePath) throws { - try self.init(url: URL(fileURLWithPath: path.rawValue)) - } - - package func machOFile(named: MachOImageName) -> MachOFile? { - machOFile(by: .name(named.rawValue)) - } -} - -extension DyldCache { - package convenience init(path: DyldSharedCachePath) throws { - try self.init(url: URL(fileURLWithPath: path.rawValue)) - } - - package func machOFile(named: MachOImageName) -> MachOFile? { - machOFile(by: .name(named.rawValue)) - } -} - -extension CustomStringConvertible { - package func print() { - #if !SILENT_TEST - Swift.print(self) - #endif - } -} - -extension Error { - package func print() { - #if !SILENT_TEST - Swift.print(self) - #endif - } -} diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/InProcess/InProcessMetadataPicker.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/InProcess/InProcessMetadataPicker.swift index 3cf8bb1cc..1f63e106c 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/InProcess/InProcessMetadataPicker.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/InProcess/InProcessMetadataPicker.swift @@ -222,33 +222,14 @@ extension InProcessMetadataPicker { /// Idempotently dlopens `SymbolTestsCore.framework` so that subsequent /// `dlsym(RTLD_NOW, ...)` calls can locate fixture-binary symbols. - /// Resolves the framework path relative to this source file, mirroring - /// `MachOSwiftSectionFixtureTests.dlopenOnce` so the test process and - /// the standalone `baseline-generator` process behave identically. + /// Loads the file `MachOFileName.SymbolTestsCore` names, the one + /// `MachOSwiftSectionFixtureTests` loads, so the test process and the + /// standalone `baseline-generator` process behave identically. private static func ensureFixtureLoaded() throws { _ = dlopenOnce } private static let dlopenOnce: Void = { - let absolute = resolveFixturePath(MachOImageName.SymbolTestsCore.rawValue) - _ = absolute.withCString { dlopen($0, RTLD_LAZY) } + _ = MachOFileName.SymbolTestsCore.path.withCString { dlopen($0, RTLD_LAZY) } }() - - /// Resolve a relative `MachOImageName` path (rooted at the package-relative - /// `../../../Tests/...` convention used by `loadFromFile`) to an absolute path. - /// - /// Caveat: `MachOImageName.SymbolTestsCore.rawValue` is rooted as if the - /// caller lives in `Sources///Foo.swift`, i.e. exactly three - /// `../` hops to reach the package root. This file lives one level deeper - /// in `Sources/TestSupport/SwiftSectionFixtureSupport/InProcess/`, so we anchor - /// against `Sources/TestSupport/SwiftSectionFixtureSupport/` (one path component up - /// from `#filePath`'s parent) to make the existing `../../../...` rawValue - /// resolve correctly. - private static func resolveFixturePath(_ relativePath: String) -> String { - if relativePath.hasPrefix("/") { return relativePath } - let parentOfThisFile = URL(fileURLWithPath: #filePath).deletingLastPathComponent() - let oneLevelUp = parentOfThisFile.deletingLastPathComponent() - let url = URL(fileURLWithPath: relativePath, relativeTo: oneLevelUp) - return url.standardizedFileURL.path - } } diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/MachOFileName+SymbolTests.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/MachOFileName+SymbolTests.swift new file mode 100644 index 000000000..7489a8d49 --- /dev/null +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/MachOFileName+SymbolTests.swift @@ -0,0 +1,26 @@ +import Foundation +import MachOFixtureSupport + +extension MachOFileName { + /// The package root, which the SymbolTests fixtures are built under. + /// + /// Anchored at this file, `Sources/TestSupport/SwiftSectionFixtureSupport/`, + /// so a path relative to it climbs three levels to reach the root (see + /// `AGENTS.md` on `Sources/` grouping and `#filePath`). + private static let packageRootAnchor = URL(fileURLWithPath: #filePath) + + private static func symbolTestsProduct(_ productName: String) -> MachOFileName { + MachOFileName( + path: "../../../Tests/Projects/SymbolTests/DerivedData/SymbolTests/Build/Products/Release/\(productName).framework/Versions/A/\(productName)", + relativeTo: packageRootAnchor + ) + } + + package static let SymbolTests = symbolTestsProduct("SymbolTests") + package static let SymbolTestsCore = symbolTestsProduct("SymbolTestsCore") + /// SymbolTestsCore's resilient-parent dependency. Kept OUT of the shared + /// suites deliberately: `PerImageCacheEvictionTests` needs an image no + /// concurrently-running suite touches, so its cache-membership + /// assertions cannot race another suite's indexer lifecycle. + package static let SymbolTestsHelper = symbolTestsProduct("SymbolTestsHelper") +} diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/MachOFileName.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/MachOFileName.swift deleted file mode 100644 index 089a173a4..000000000 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/MachOFileName.swift +++ /dev/null @@ -1,27 +0,0 @@ -import Foundation - -package enum MachOFileName: String { - case iOS_18_5_Simulator_SwiftUI = "/Library/Developer/CoreSimulator/Volumes/iOS_22F77/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS 18.5.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/SwiftUI.framework/SwiftUI" - case iOS_18_5_Simulator_SwiftUICore = "/Library/Developer/CoreSimulator/Volumes/iOS_22F77/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS 18.5.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/SwiftUICore.framework/SwiftUICore" - case iOS_26_5_Simulator_SwiftUI = "/Library/Developer/CoreSimulator/Volumes/iOS_23F77/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS 26.5.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/SwiftUI.framework/SwiftUI" - case iOS_26_5_Simulator_SwiftUICore = "/Library/Developer/CoreSimulator/Volumes/iOS_23F77/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS 26.5.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/SwiftUICore.framework/SwiftUICore" - - case SourceEdit = "/Applications/SourceEdit.app" - case SourceEditorFromSourceEdit = "/Applications/SourceEdit.app/Contents/Frameworks/SourceEditor.framework" - case SourceEditorFromXcode = "/Applications/Xcode.app/Contents/SharedFrameworks/SourceEditor.framework" - - case Finder = "/System/Library/CoreServices/Finder.app" - case Dock = "/System/Library/CoreServices/Dock.app" - case iPhoneMirroring = "/System/Applications/iPhone Mirroring.app" - case ScreenContinuityUI = "/System/Applications/iPhone Mirroring.app/Contents/Frameworks/ScreenContinuityUI.framework" - case ControlCenter = "/System/Library/CoreServices/ControlCenter.app" - case Freeform = "/System/Applications/Freeform.app" - - case SymbolTests = "../../../Tests/Projects/SymbolTests/DerivedData/SymbolTests/Build/Products/Release/SymbolTests.framework/Versions/A/SymbolTests" - case SymbolTestsCore = "../../../Tests/Projects/SymbolTests/DerivedData/SymbolTests/Build/Products/Release/SymbolTestsCore.framework/Versions/A/SymbolTestsCore" - /// SymbolTestsCore's resilient-parent dependency. Kept OUT of the shared - /// suites deliberately: `PerImageCacheEvictionTests` needs an image no - /// concurrently-running suite touches, so its cache-membership - /// assertions cannot race another suite's indexer lifecycle. - case SymbolTestsHelper = "../../../Tests/Projects/SymbolTests/DerivedData/SymbolTests/Build/Products/Release/SymbolTestsHelper.framework/Versions/A/SymbolTestsHelper" -} diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/MachOImageName+SymbolTests.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/MachOImageName+SymbolTests.swift new file mode 100644 index 000000000..a15931a92 --- /dev/null +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/MachOImageName+SymbolTests.swift @@ -0,0 +1,9 @@ +import MachOFixtureSupport + +extension MachOImageName { + /// The SymbolTests fixtures as this process knows them once loaded: the + /// bare image name `MachOImage(name:)` matches. Their files are the + /// `MachOFileName` members of the same names. + package static let SymbolTests: MachOImageName = "SymbolTests" + package static let SymbolTestsCore: MachOImageName = "SymbolTestsCore" +} diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/MachOImageName.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/MachOImageName.swift deleted file mode 100644 index b7a94897f..000000000 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/MachOImageName.swift +++ /dev/null @@ -1,32 +0,0 @@ -package enum MachOImageName: String { - case AppKit - case UIFoundation - case CollectionViewCore - case CoreAutoLayout - case SwiftUI - case SwiftUICore - case AttributeGraph - case Foundation - case Combine - case DeveloperToolsSupport - case CodableSwiftUI - case AAAFoundationSwift - case UIKitCore - case HomeKit - case Network - case ScreenContinuityServices - case Sharing - case FeatureFlags - case ScreenSharingKit - case DesignLibrary - case SFSymbols - case SnippetUI - case SiriOntology - - case SymbolTests = "../../../Tests/Projects/SymbolTests/DerivedData/SymbolTests/Build/Products/Release/SymbolTests.framework/Versions/A/SymbolTests" - case SymbolTestsCore = "../../../Tests/Projects/SymbolTests/DerivedData/SymbolTests/Build/Products/Release/SymbolTestsCore.framework/Versions/A/SymbolTestsCore" - - var path: String { - "/\(rawValue)" - } -} diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/SnapshotDumpableTests.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/SnapshotDumpableTests.swift index f952c3c70..3df134a70 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/SnapshotDumpableTests.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/SnapshotDumpableTests.swift @@ -7,6 +7,7 @@ import SwiftDeclarationRendering import Demangling // Needs SPI access to SymbolicDemangler.demangleType for associated-type owning-protocol lookup. @_spi(Internals) import SwiftInspection +import Semantic @MainActor package protocol SnapshotDumpableTests {} diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/SnapshotInterfaceTests.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/SnapshotInterfaceTests.swift index 24c90054d..52581ad52 100644 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/SnapshotInterfaceTests.swift +++ b/Sources/TestSupport/SwiftSectionFixtureSupport/SnapshotInterfaceTests.swift @@ -3,6 +3,9 @@ import MachOKit import MachOFoundation import MachOSwiftSection import SwiftInterface +import SwiftIndexing +import Semantic +import SwiftPrinting @MainActor package protocol SnapshotInterfaceTests {} diff --git a/Sources/TestSupport/SwiftSectionFixtureSupport/XcodeMachOFileName.swift b/Sources/TestSupport/SwiftSectionFixtureSupport/XcodeMachOFileName.swift deleted file mode 100644 index 9fabfd897..000000000 --- a/Sources/TestSupport/SwiftSectionFixtureSupport/XcodeMachOFileName.swift +++ /dev/null @@ -1,459 +0,0 @@ -package enum XcodeMachOFileName: CaseIterable { - package enum Frameworks: String, CaseIterable { - case AssetCatalogAppleTVFoundation - case AssetCatalogAppleTVKit - case AssetCatalogCocoaTouchFoundation - case AssetCatalogCocoaTouchKit - case AssetCatalogFoundation - case AssetCatalogKit - case AssetCatalogVisionExtensions - case AssetCatalogVisionFoundation - case AssetCatalogVisionKit - case DVTNFASupport - case DebuggerFoundation - case DevToolsCore - case DevToolsSupport - case GameCenterResourcesAppStoreConnectClient - case GameCenterResourcesCore - case GameCenterResourcesCoreModels - case IBAutolayoutFoundation - case IBCocoaTouchToolFoundation - case IDEEditorGalleryPreviewSupport - case IDEEvaluationKit - case IDEFoundation - case IDEGameKitCommonEditor - case IDEGameKitEditor - case IDEGameKitInspectorCore - case IDEGameKitInspectorEditor - case IDEKit - case IDELanguageModelKit - case IDENoticesFoundation - case IDENoticesKit - case IDESettingsPanel - case IDESimulatorFoundation - case IDESourceEditorGalleryExhibit - case IDETrayKit - case SiriSSUKit - case SiriSSUKitModel - case Xcode3Core - case Xcode3UI - case libIDEApplicationLoader - case libLTO - case libclang - case libswiftDemangle - case libxcodebuildLoader - } - - package enum SharedFrameworks: String, CaseIterable { - case AccessibilityAudit - case AccessibilitySupport - case AppResourceGeneration - case AppThinning - case AssetRuntimeSupport - case AuthenticationAPI - case BuildServerProtocol - case ChooseIdentity - case CodeCompletionFoundation - case CodeCompletionKit - case CodeGenerationIntelligence - case CombineXPC - case CommonXcodeCloudAPI - case ContentDelivery - case ContentDeliveryServices - case CoreDocumentation - case CoreSymbolicationDT - case CreateMLSwiftProtobuf - case DNTDocumentationModel - case DNTDocumentationSupport - case DNTSourceKitSupport - case DNTTransformer - case DTDeviceKit - case DTDeviceKitBase - case DTDeviceServices - case DTGTGraph - case DTGTTimeline - case DTGanache - case DTGanacheBufferViewer - case DTGanacheImageProcessor - case DTGanacheImageViewer - case DTGanacheTensorViewer - case DTGraphKit - case DTMLOpGraph - case DTXConnectionServices - case DVTAnalytics - case DVTAnalyticsClient - case DVTAnalyticsKit - case DVTAnalyticsMetrics - case DVTAnalyticsMetricsClient - case DVTAppStoreConnect - case DVTCocoaAdditionsKit - case DVTCoreDeviceCore - case DVTCoreGlyphs - case DVTCrashLogFoundation - case DVTDeviceFoundation - case DVTDeviceKit - case DVTDeviceProvisioning - case DVTDocumentation - case DVTExplorableKit - case DVTFeedbackReporting - case DVTFoundation - case DVTITunesSoftware - case DVTITunesSoftwareServiceFoundation - case DVTIconKit - case DVTInstrumentsAnalysisCore - case DVTInstrumentsFoundation - case DVTInstrumentsUtilities - case DVTKeychain - case DVTKeychainService - case DVTKeychainUtilities - case DVTKit - case DVTLibraryKit - case DVTMacroFoundation - case DVTMarkup - case DVTPlaygroundCommunication - case DVTPlaygroundStubMacServices - case DVTPortal - case DVTProducts - case DVTProductsUI - case DVTServices - case DVTSmartSearch - case DVTSourceControl - case DVTSourceEditor - case DVTStructuredLayoutKit - case DVTSystemPrerequisites - case DVTSystemPrerequisitesUI - case DVTUserInterfaceKit - case DVTViewControllerKit - case DebugHierarchyFoundation - case DebugHierarchyKit - case DebugSymbolsDT - case DeltaFoundation - case DeltaKit - case EventsAPI - case GLTools - case GLToolsAnalysisEngine - case GLToolsCore - case GLToolsExpert - case GLToolsInterface - case GLToolsServices - case GLToolsShaderProfiler - case GPUTools - case GPUToolsCore - case GPUToolsDesktopFoundation - case GPUToolsMobileFoundation - case GPUToolsPlatform - case GPUToolsRenderer - case GPUToolsServices - case GPUToolsShaderProfiler - case GameToolsFoundation - case HexFiend - case IDEAnalyticsMetrics - case IDECodeGenerationIntelligence - case IDEDistribution - case IDEDistributionKit - case IDEMLCompilerCore - case IDEMLModelCore - case IDEMLModelEditorKit - case IDENotifications - case IDENotificationsKit - case IDEPlaygroundEditor - case IDEPlaygroundExecution - case IDEPlaygroundResultsFoundation - case IDEPlaygroundResultsKit - case IDEPlaygroundsFoundation - case IDEPlaygroundsKit - case IDEProducts - case IDEResultKit - case IndexStoreDB_CIndexStoreDB - case IndexStoreDB_Core - case IndexStoreDB_Database - case IndexStoreDB_Index - case IndexStoreDB_LLVMSupport - case IndexStoreDB_Support - case IndexStoreDatabase - case LLDB - case LLDBRPC - case LanguageServerProtocol - case LiveExecutionResultsFoundation - case LiveExecutionResultsHost - case Localization - case LoggingSupportHost - case MLCloudDeployment - case MLCloudDeploymentXPCServiceProtocol - case MLCore - case MLCoreKit - case MLDataSource - case MLDataSourceKit - case MLDocumentFormat - case MLEvaluation - case MLEvaluationKit - case MLExperiment - case MLExplorationKit - case MLFeature - case MLKnownObjectTracking - case MLModelCore - case MLModelFormatEditor - case MLModelKit - case MLPersistenceEngine - case MLPersistenceEntity - case MLRecipeCore - case MLRecipeExecutionController - case MLRecipeExecutionServiceProtocol - case MLShared - case MLSharedKit - case MLToolsCoreML - case MLTraceReport - case MTLTools - case MTLToolsAnalysisEngine - case MTLToolsServices - case MTLToolsShaderProfiler - case MallocStackLoggingDT - case ManagedBackgroundAssetsXcodeSupport - case MarkupSupport - case Notarization - case ODTDevTool - case OpenAPIRuntime - case OpenAPIURLSession - case PackedPaths - case PreviewsDeveloperTools - case PreviewsFoundationHost - case PreviewsMessagingHost - case PreviewsModel - case PreviewsPipeline - case PreviewsPlatforms - case PreviewsScenes - case PreviewsSyntax - case PreviewsUI - case PreviewsXROSMessaging - case PreviewsXROSServices - case PreviewsXcodeUI - case RealityKitAdditions - case RealityKitInspection - case RealityToolKit - case RealityToolsDeviceSupport - case RecountDT - case SourceEditor - case SourceEditorRegExSupport - case SourceEditorSwiftSupport - case SourceKit - case SourceKitLSPSupport - case SourceKitSupport - case SourceModel - case SourceModelSupport - case SpatialInspectorFoundation - case SpatialInspectorHost - case StatusAPI - case SwiftBasicFormat - case SwiftBuild - case SwiftDiagnostics - case SwiftIDEUtils - case SwiftOperators - case SwiftPM - case SwiftParser - case SwiftParserDiagnostics - case SwiftRefactor - case SwiftSyntax - case SwiftSyntaxBuilder - case SwiftSyntaxCShims - case SwiftSyntaxSupport - case SwiftUITracingSupportDT - case SymbolCache - case SymbolCacheIndexing - case SymbolCacheSupport - case SymbolicationDT - case TestResultsUI - case Testing - case USDLib_FormatLoaderProxy_Xcode - case UVTestSupport - case XCBuild - case XCResultKit - case XCServices - case XCSourceControl - case XCStringsParser - case XCTAutomationSupport - case XCTDaemonControl - case XCTDaemonControlMobileDevice - case XCTHarness - case XCTest - case XCTestCore - case XCTestSupport - case XCUIAutomation - case XCUnit - case XcodeCloudAPI - case XcodeCloudCombineAPI - case XcodeCloudDataSource - case XcodeCloudFoundation - case XcodeCloudKit - case XcodeCloudModels - case XcodeCloudUI - case _CodeCompletionFoundation - case _Testing_Foundation - case kperfdataDT - case ktraceDT - case libXCTestSwiftSupport - case llbuild - case swiftargumentparser_ArgumentParser - package var pathComponent: String { - "/SharedFrameworks/\(rawValue).framework" - } - } - - package enum Plugins: String, CaseIterable { - case AppShortcutsEditor - case AppShortcutsEditorUI - case DVTCorePlistStructDefs - case DVTFeedbackReportingDiagnosticExtension - case DVTiOSPlistStructDefs - case DebugHelperSupportUI - case DebuggerKit - case DebuggerLLDB - case DebuggerLLDBService - case DebuggerUI - case GPUDebugger - case GPUDebuggerGLSupport - case HexEditor - case IBBuildSupport - case IBCocoaBuildSupport - case IBExternalGeniusResults - case IDEAnalytics - case IDEAnalyticsKit - case IDEAnalyticsMetricsKit - case IDEAnalyticsMetricsNotifications - case IDEConsoleKit - case IDEDelta - case IDEDocViewer - case IDEDocumentation - case IDEDocumentationLivePreview - case IDEIODebugGaugesCore - case IDEIODebugGaugesUI - case IDEInstrumentsService - case IDEIntelligenceChat - case IDEIntelligenceFoundation - case IDEIntelligenceMessaging - case IDEIntelligenceModelService - case IDEIntentBuilderCore - case IDEIntentBuilderEditor - case IDEInterfaceBuilderCocoaIntegration - case IDEInterfaceBuilderCocoaTouchIntegration - case IDEInterfaceBuilderDFRSupport - case IDEInterfaceBuilderEditorDFRSupport - case IDEInterfaceBuilderKit - case IDEInterfaceBuilderiOSIntegration - case IDEInterfaceBuilderiOSMacIntegration - case IDELocalizationCatalogCore - case IDELocalizationCatalogEditor - case IDEMLCodeGeneratorPlugin - case IDEMLModelEditorPlugin - case IDEMemoryGraphDebugger - case IDEModelEditor - case IDEModelFoundation - case IDEPDFViewer - case IDEPegasusSourceEditor - case IDEPerformanceDebugger - case IDEPlaygroundSimulator - case IDEProductsUI - case IDEQuickHelp - case IDEQuickLookEditor - case IDERTFEditor - case IDESceneKitEditor - case IDESourceControlUI - case IDESourceEditor - case IDESpriteKitParticleEditor - case IDEStandardExecutionActionsCore - case IDEStandardExecutionActionsUI - case IDEStoreKitCore - case IDEStoreKitEditor - case IDESwiftPackageCore - case IDESwiftPackageUI - case IDETestPlanEditor - case IDETestResultsUI - case IDETestingPlatformSupport - case IDETimeline - case IDEXCBuildSupportCore - case IDEXCBuildSupportUI - case IDEXCStringsCommentGenerationSupport - case IDEXCStringsSupport - case IDEXCStringsSupportCore - case IDEiOSDebugger - case IDEiOSSupportCore - case IDEiPhoneSupport - case PlaygroundLiveExecution - case PlistEditor - case PreviewsIDEAPI - case PreviewsXcode - case PreviewsXcodeXROSSupport - case PreviewsXcodeXROSUI - case ProvisoningProfileQuicklookExtension - case RCPIDEFoundation - case RCPIDESupportCore - case RCPIDESupportUI - case ScriptingDefinitionEditor - case SpatialInspectorXcodePlugin - case XCCFeedbackReportingDiagnosticExtension - case XcodeCloud - } - - case frameworks(Frameworks) - case sharedFrameworks(SharedFrameworks) - case plugins(Plugins) - - package var contentsDirectory: String { - "/Applications/Xcode.app/Contents/" - } - - package var rawValue: String { - switch self { - case .frameworks(let framework): - return "Frameworks/" + framework.rawValue - case .sharedFrameworks(let framework): - return "SharedFrameworks/" + framework.rawValue - case .plugins(let plugin): - return "Plugins/" + plugin.rawValue - } - } - - package var url: URL { - return URL(fileURLWithPathWithoutExtension: "\(contentsDirectory)\(rawValue)") - } - - package static var allCases: [XcodeMachOFileName] { - Frameworks.allCases.map { .frameworks($0) } + - SharedFrameworks.allCases.map { .sharedFrameworks($0) } + - Plugins.allCases.map { .plugins($0) } - } -} - -import Foundation -import Darwin - -extension URL { - init(fileURLWithPathWithoutExtension pathWithoutExtension: String) { - // 1. Create a glob pattern by appending ".*" - // e.g., "/Folder/A" becomes "/Folder/A.*" - let pattern = pathWithoutExtension + ".*" - - // 2. Prepare a glob_t structure to hold the results. - var globResult = glob_t() - - // 3. Call the glob function. - // It takes the pattern, flags, an error function (nil), and a pointer to the result struct. - let returnCode = glob(pattern, 0, nil, &globResult) - - // IMPORTANT: Always free the memory allocated by glob when you're done. - // `defer` ensures this is called before the function exits. - defer { - globfree(&globResult) - } - - // 4. Check if glob succeeded (returnCode == 0) and found at least one match. - if returnCode == 0, let firstMatchPath = globResult.gl_pathv[0] { - // 5. Convert the C string result back to a Swift String. - let swiftPath = String(cString: firstMatchPath) - // 6. Create and return a URL from the path. - self = URL(fileURLWithPath: swiftPath) - } else { - // If no matches were found or an error occurred, return nil. - fatalError() - } - } -} diff --git a/Sources/TestSupport/SwiftSectionTestingMacros/FixtureSuiteMacro.swift b/Sources/TestSupport/SwiftSectionTestingMacros/FixtureSuiteMacro.swift new file mode 100644 index 000000000..d280dbd14 --- /dev/null +++ b/Sources/TestSupport/SwiftSectionTestingMacros/FixtureSuiteMacro.swift @@ -0,0 +1,176 @@ +import SwiftDiagnostics +import SwiftSyntax +import SwiftSyntaxBuilder +import SwiftSyntaxMacros + +/// `@FixtureSuite`: the two `FixtureSuite` requirements of a fixture suite +/// class, and its conformance. +/// +/// The tested type's name defaults to the class name without its `Tests` +/// suffix, and the baseline to the same stem followed by `Baseline`: +/// +/// @FixtureSuite +/// final class StructDescriptorTests: MachOSwiftSectionFixtureTests, @unchecked Sendable {} +/// +/// gets `static let testedTypeName = "StructDescriptor"` and +/// `static var registeredTestMethodNames` returning +/// `StructDescriptorBaseline.registeredTestMethodNames`. Either is named +/// explicitly with a literal: `@FixtureSuite(testedTypeName: "EnumTagCounts")`, +/// `@FixtureSuite(testedTypeName: "OpaqueType", baseline: OpaqueTypeBaseline.self)`. +public struct FixtureSuiteMacro: MemberMacro, ExtensionMacro { + public static func expansion( + of node: AttributeSyntax, + providingMembersOf declaration: some DeclGroupSyntax, + conformingTo protocols: [TypeSyntax], + in context: some MacroExpansionContext + ) throws -> [DeclSyntax] { + guard let suite = FixtureSuiteDescription(attribute: node, declaration: declaration, context: context) else { + return [] + } + return [ + "static let testedTypeName: Swift.String = \(literal: suite.testedTypeName)", + """ + static var registeredTestMethodNames: Swift.Set { + \(raw: suite.baselineTypeName).registeredTestMethodNames + } + """, + ] + } + + public static func expansion( + of node: AttributeSyntax, + attachedTo declaration: some DeclGroupSyntax, + providingExtensionsOf type: some TypeSyntaxProtocol, + conformingTo protocols: [TypeSyntax], + in context: some MacroExpansionContext + ) throws -> [ExtensionDeclSyntax] { + // The member role reports a misuse; this role only stays silent. + guard declaration.is(ClassDeclSyntax.self), !protocols.isEmpty else { return [] } + let conformances = protocols.map(\.trimmedDescription).joined(separator: ", ") + return [try ExtensionDeclSyntax("extension \(type.trimmed): \(raw: conformances) {}")] + } +} + +/// What a `@FixtureSuite` attribute and the class it is attached to say. +struct FixtureSuiteDescription { + static let classNameSuffix = "Tests" + + let testedTypeName: String + let baselineTypeName: String + + /// `nil` after diagnosing a misuse. + init?(attribute: AttributeSyntax, declaration: some DeclGroupSyntax, context: some MacroExpansionContext) { + guard let classDeclaration = declaration.as(ClassDeclSyntax.self) else { + context.diagnose(Diagnostic(node: attribute, message: FixtureSuiteDiagnostic.notAClass)) + return nil + } + let className = classDeclaration.name.text + let stem = className.hasSuffix(Self.classNameSuffix) && className.count > Self.classNameSuffix.count + ? String(className.dropLast(Self.classNameSuffix.count)) + : nil + + var explicitTestedTypeName: String? + var explicitBaselineTypeName: String? + for argument in attribute.arguments?.as(LabeledExprListSyntax.self) ?? [] { + switch argument.label?.text { + case "testedTypeName": + if argument.expression.is(NilLiteralExprSyntax.self) { continue } + guard let literal = Self.plainStringLiteral(argument.expression) else { + context.diagnose(Diagnostic(node: argument.expression, message: FixtureSuiteDiagnostic.testedTypeNameIsNotALiteral)) + return nil + } + explicitTestedTypeName = literal + case "baseline": + if argument.expression.is(NilLiteralExprSyntax.self) { continue } + guard let memberAccess = argument.expression.as(MemberAccessExprSyntax.self), + memberAccess.declName.baseName.tokenKind == .keyword(.self), + let base = memberAccess.base else { + context.diagnose(Diagnostic(node: argument.expression, message: FixtureSuiteDiagnostic.baselineIsNotATypeLiteral)) + return nil + } + explicitBaselineTypeName = base.trimmedDescription + default: + continue + } + } + + guard let testedTypeName = explicitTestedTypeName ?? stem, + let baselineTypeName = explicitBaselineTypeName ?? stem.map({ $0 + "Baseline" }) else { + var fixed = attribute + let arguments: LabeledExprListSyntax = [ + LabeledExprSyntax(label: "testedTypeName", expression: StringLiteralExprSyntax(content: explicitTestedTypeName ?? className)) + .with(\.trailingComma, .commaToken(trailingTrivia: .space)), + LabeledExprSyntax(label: "baseline", expression: ExprSyntax("\(raw: explicitBaselineTypeName ?? className + "Baseline").self")), + ] + fixed.leftParen = .leftParenToken() + fixed.arguments = .argumentList(arguments) + fixed.rightParen = .rightParenToken() + context.diagnose(Diagnostic( + node: attribute, + message: FixtureSuiteDiagnostic.classNameHasNoTestsSuffix(className: className), + fixIt: FixIt(message: FixtureSuiteFixIt.nameTheTestedTypeAndBaseline, changes: [.replace(oldNode: Syntax(attribute), newNode: Syntax(fixed))]) + )) + return nil + } + self.testedTypeName = testedTypeName + self.baselineTypeName = baselineTypeName + } + + /// The text of a string literal without interpolation; `nil` for any + /// other expression. + private static func plainStringLiteral(_ expression: ExprSyntax) -> String? { + guard let literal = expression.as(StringLiteralExprSyntax.self) else { return nil } + var text = "" + for segment in literal.segments { + guard let plainSegment = segment.as(StringSegmentSyntax.self) else { return nil } + text += plainSegment.content.text + } + return text + } +} + +enum FixtureSuiteDiagnostic: DiagnosticMessage { + case notAClass + case testedTypeNameIsNotALiteral + case baselineIsNotATypeLiteral + case classNameHasNoTestsSuffix(className: String) + + var message: String { + switch self { + case .notAClass: + "@FixtureSuite applies to a fixture suite class" + case .testedTypeNameIsNotALiteral: + "testedTypeName: must be a string literal without interpolation" + case .baselineIsNotATypeLiteral: + "baseline: must be a type literal such as SomeBaseline.self" + case .classNameHasNoTestsSuffix(let className): + "'\(className)' does not end with 'Tests'; name the tested type and the baseline" + } + } + + var diagnosticID: MessageID { + let identifier = switch self { + case .notAClass: "notAClass" + case .testedTypeNameIsNotALiteral: "testedTypeNameIsNotALiteral" + case .baselineIsNotATypeLiteral: "baselineIsNotATypeLiteral" + case .classNameHasNoTestsSuffix: "classNameHasNoTestsSuffix" + } + return MessageID(domain: "SwiftSectionTestingMacros", id: identifier) + } + + var severity: DiagnosticSeverity { + .error + } +} + +enum FixtureSuiteFixIt: FixItMessage { + case nameTheTestedTypeAndBaseline + + var message: String { + "Name the tested type and the baseline" + } + + var fixItID: MessageID { + MessageID(domain: "SwiftSectionTestingMacros", id: "nameTheTestedTypeAndBaseline") + } +} diff --git a/Sources/TestSupport/SwiftSectionTestingMacros/TestingMacroPlugin.swift b/Sources/TestSupport/SwiftSectionTestingMacros/TestingMacroPlugin.swift new file mode 100644 index 000000000..0ac8ad91f --- /dev/null +++ b/Sources/TestSupport/SwiftSectionTestingMacros/TestingMacroPlugin.swift @@ -0,0 +1,9 @@ +import SwiftCompilerPlugin +import SwiftSyntaxMacros + +@main +struct TestingMacroPlugin: CompilerPlugin { + let providingMacros: [any Macro.Type] = [ + FixtureSuiteMacro.self, + ] +} diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/ClassesWithoutClassObjectsFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/ClassesWithoutClassObjectsFixture.swift index cffffc7ea..35eba53af 100644 --- a/Sources/TestSupport/SwiftSectionTestingSupport/ClassesWithoutClassObjectsFixture.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/ClassesWithoutClassObjectsFixture.swift @@ -144,7 +144,7 @@ package enum ClassesWithoutClassObjectsFixture { } /// Compiled once per process; every variant shares one working directory. - private static let compilationResult: Result = { + private static let compilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("\(moduleName)-\(UUID().uuidString)") @@ -224,13 +224,7 @@ package enum ClassesWithoutClassObjectsFixture { package static func machOFile(_ variant: Variant) throws -> MachOFile { let libraryURL = try libraryURL(variant) - switch try MachOKit.loadFromFile(url: libraryURL) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } + return try HostSlice.machOFile(at: libraryURL) } /// The `.full` client loaded into the test process — only that variant: diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/DyldCacheTests.swift b/Sources/TestSupport/SwiftSectionTestingSupport/DyldCacheTests.swift deleted file mode 100644 index 70810e2a0..000000000 --- a/Sources/TestSupport/SwiftSectionTestingSupport/DyldCacheTests.swift +++ /dev/null @@ -1,37 +0,0 @@ -import Foundation -import Testing -import MachOKit -import MachOFoundation -import SwiftSectionFixtureSupport - -@MainActor -package class DyldCacheTests: Sendable { - package let mainCache: DyldCache - - package let subCache: DyldCache - - package let fullCache: FullDyldCache - - package let machOFileInMainCache: MachOFile - - package let machOFileInSubCache: MachOFile - - package let machOFileInCache: MachOFile - - package class var platform: MachOKit.Platform { .macOS } - - package class var mainCacheImageName: MachOImageName { .SwiftUI } - - package class var cacheImageName: MachOImageName { .SwiftUI } - - package class var cachePath: DyldSharedCachePath { .current } - - package init() async throws { - self.mainCache = try DyldCache(path: Self.cachePath) - self.subCache = try required(mainCache.subCaches?.first?.subcache(for: mainCache)) - self.fullCache = try FullDyldCache(path: Self.cachePath) - self.machOFileInCache = try #require(fullCache.machOFile(named: Self.cacheImageName)) - self.machOFileInMainCache = try #require(mainCache.machOFile(named: Self.mainCacheImageName)) - self.machOFileInSubCache = try #require(subCache.machOFiles().first(where: { _ in true })) - } -} diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/ExclusiveImageAccess+FixtureNames.swift b/Sources/TestSupport/SwiftSectionTestingSupport/ExclusiveImageAccess+FixtureNames.swift new file mode 100644 index 000000000..c2db7a92e --- /dev/null +++ b/Sources/TestSupport/SwiftSectionTestingSupport/ExclusiveImageAccess+FixtureNames.swift @@ -0,0 +1,36 @@ +import Foundation +import MachOTestingSupport +import SwiftSectionFixtureSupport + +extension ExclusiveImageAccess { + /// Spelled from the fixture's name so a typo is a compile error rather + /// than a silently ineffective exclusion. `package`, matching the fixture + /// names this package adds — a suite reaching the image by a hand-built + /// path (which is how the sharing went unnoticed) uses the `String` + /// initializer with the same key, the image's name. + package init(_ fileName: MachOFileName) { + self.init(fileName.exclusiveAccessKey) + } + + package init(_ imageName: MachOImageName) { + self.init(imageName.exclusiveAccessKey) + } +} + +extension MachOFileName { + /// What ``ExclusiveImageAccess`` keys this file by: the name of the image + /// it holds, the last path component without its extension, so that a + /// suite naming a fixture by its file and one naming it by its image + /// (`MachOImageName`) exclude each other. + package var exclusiveAccessKey: String { + url.deletingPathExtension().lastPathComponent + } +} + +extension MachOImageName { + /// What ``ExclusiveImageAccess`` keys this image by: its name, the same + /// key as the file it was loaded from (``MachOFileName/exclusiveAccessKey``). + package var exclusiveAccessKey: String { + name + } +} diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/ExclusiveImageAccess.swift b/Sources/TestSupport/SwiftSectionTestingSupport/ExclusiveImageAccess.swift deleted file mode 100644 index 194ea0340..000000000 --- a/Sources/TestSupport/SwiftSectionTestingSupport/ExclusiveImageAccess.swift +++ /dev/null @@ -1,129 +0,0 @@ -import Foundation -import SwiftSectionFixtureSupport -import Testing - -/// Serializes every test that declares the same fixture image — **across -/// suites and across test targets**. -/// -/// `.serialized` cannot do this. Its documentation is explicit: it "does not -/// affect the execution of a test relative to its peers or to unrelated tests", -/// so it orders tests *within* one container and nothing more. A whole-process -/// resource like a per-image cache needs ordering between containers. -/// -/// A global actor cannot do it either. These tests are `async`, and `await` -/// suspends and yields the actor: an actor guarantees no *concurrent* execution, -/// not the absence of *interleaving*, so a sibling test resumes in the middle of -/// one that is mid-way through clearing and re-checking a cache. `TestScoping` -/// wraps the entire test body, suspension points included, which is the one -/// primitive that gives a real critical section. -/// -/// Apply it to every suite that touches the image, not just the one making the -/// assertions — an exclusion held by one side is not an exclusion: -/// -/// @Suite(.serialized, ExclusiveImageAccess(.SymbolTestsHelper)) -/// final class PerImageCacheEvictionTests: MachOFileTests { … } -/// -/// @Suite(ExclusiveImageAccess(.SymbolTestsHelper)) -/// final class DependencyClosureLayoutTests: MachOSwiftSectionFixtureTests { … } -/// -/// It also makes the sharing *greppable*, which is the failure this exists to -/// prevent. `PerImageCacheEvictionTests` documented in prose that it ran against -/// "an image no other suite indexes"; that was true of every suite naming the -/// image through `MachOFileName`, and false in fact, because -/// `DependencyClosureLayoutTests` reached the same binary by building its path -/// by hand. Searching for the fixture case name could not find it. Searching for -/// `ExclusiveImageAccess` finds every declared user. -public struct ExclusiveImageAccess: TestTrait, SuiteTrait, TestScoping { - private let imageName: String - - public init(_ imageName: String) { - self.imageName = imageName - } - - /// Applied to a suite, this must reach the suite's tests — the scope is - /// provided per test function, never at the suite level (verified against - /// the 6.3.3 runtime: `provideScope` is called only for functions, so the - /// non-reentrant lock below cannot nest with itself). - public var isRecursive: Bool { true } - - public func provideScope( - for test: Test, - testCase: Test.Case?, - performing function: () async throws -> Void - ) async throws { - try await FixtureImageExclusion.withExclusiveAccess(to: imageName, performing: function) - } -} - -/// Runs `body` while holding the image, then releases it. -/// -/// Free-standing rather than a method on the actor: the test body is a -/// non-`Sendable` closure, and handing it to an actor method would cross an -/// isolation boundary, which Swift 6 rejects (`sending value of non-Sendable -/// type … risks causing data races`). Only the *lock state* belongs on the -/// actor; the body stays in its caller's isolation, where the testing library -/// put it. -public enum FixtureImageExclusion { - public static func withExclusiveAccess( - to imageName: String, - performing body: () async throws -> Void - ) async rethrows { - await FixtureImageLock.shared.acquire(imageName) - do { - try await body() - } catch { - // Release before rethrowing: leaving the image held would turn one - // failing test into a hang for every later test that declares it. - await FixtureImageLock.shared.release(imageName) - throw error - } - await FixtureImageLock.shared.release(imageName) - } -} - -extension ExclusiveImageAccess { - /// Spelled from the fixture case so a typo is a compile error rather than a - /// silently ineffective exclusion. `package`, matching the fixture enums — - /// a suite reaching the image by a hand-built path (which is how the sharing - /// went unnoticed) uses the `String` initializer with the same key. - package init(_ fileName: MachOFileName) { - self.init(fileName.rawValue) - } - - package init(_ imageName: MachOImageName) { - self.init(imageName.rawValue) - } -} - -/// Process-wide mutual exclusion keyed on a fixture image. -/// -/// Non-reentrant on purpose: a scope is only ever provided per test function -/// (never additionally at the suite level), so nesting cannot arise, and the -/// simpler invariant is easier to keep true than a reentrancy counter. -actor FixtureImageLock { - static let shared = FixtureImageLock() - - private var busyImageNames: Set = [] - private var waitersByImageName: [String: [CheckedContinuation]] = [:] - - func acquire(_ imageName: String) async { - // A loop, not a single check: being resumed only means the previous - // holder released. Re-acquiring the actor is itself a suspension, so a - // newly arriving test can slip in first and take the image — at which - // point this one waits again. - while busyImageNames.contains(imageName) { - await withCheckedContinuation { continuation in - waitersByImageName[imageName, default: []].append(continuation) - } - } - busyImageNames.insert(imageName) - } - - func release(_ imageName: String) { - busyImageNames.remove(imageName) - guard var waiters = waitersByImageName[imageName], !waiters.isEmpty else { return } - let next = waiters.removeFirst() - waitersByImageName[imageName] = waiters.isEmpty ? nil : waiters - next.resume() - } -} diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/ExistentialAnyFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/ExistentialAnyFixture.swift index 6df9396e4..b757f26f0 100644 --- a/Sources/TestSupport/SwiftSectionTestingSupport/ExistentialAnyFixture.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/ExistentialAnyFixture.swift @@ -89,64 +89,17 @@ package enum ExistentialAnyFixture { } """ - package struct CompilationError: Swift.Error, CustomStringConvertible { - package let diagnostics: String - package var description: String { "\(moduleName) fixture compilation failed:\n\(diagnostics)" } - } - - private enum WorkingDirectoryCleanup { - nonisolated(unsafe) static var directories: [URL] = [] - static let registration: Void = { - atexit { - for directory in WorkingDirectoryCleanup.directories { - try? FileManager.default.removeItem(at: directory) - } - } - }() - } - - /// Compiled once per process. - private static let compilationResult: Result = { - Result { - let workingDirectory = FileManager.default.temporaryDirectory - .appendingPathComponent("\(moduleName)-\(UUID().uuidString)") - try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) - _ = WorkingDirectoryCleanup.registration - WorkingDirectoryCleanup.directories.append(workingDirectory) - - let sourceURL = workingDirectory.appendingPathComponent("Fixture.swift") - let libraryURL = workingDirectory.appendingPathComponent("lib\(moduleName).dylib") - try source.write(to: sourceURL, atomically: true, encoding: .utf8) - - let process = Process() - process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") - process.arguments = [ - // The language mode pinned: CI's toolchain and a newer local - // one must compile the same source the same way. - "swiftc", "-swift-version", "5", "-emit-library", "-enable-library-evolution", - "-module-name", moduleName, - sourceURL.path, "-o", libraryURL.path, - ] - let standardErrorPipe = Pipe() - process.standardError = standardErrorPipe - try process.run() - // Drain BEFORE waitUntilExit, or a long diagnostic deadlocks both sides. - let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() - process.waitUntilExit() - guard process.terminationStatus == 0 else { - throw CompilationError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) - } - return libraryURL - } - }() - + /// Compiled once per process by the shared compiler. The source keeps + /// the file name it always had, which private discriminators hash. package static func machOFile() throws -> MachOFile { - switch try MachOKit.loadFromFile(url: try compilationResult.get()) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } + let libraryURL = try FixtureCompiler.shared.dynamicLibrary( + named: moduleName, + language: .swift, + sourceFiles: [FixtureSourceFile(name: "Fixture.swift", contents: source)], + // The language mode pinned: CI's toolchain and a newer local + // one must compile the same source the same way. + arguments: ["-swift-version", "5", "-enable-library-evolution"] + ) + return try HostSlice.machOFile(at: libraryURL) } } diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/ExportedOnlyFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/ExportedOnlyFixture.swift index 2f8131b44..1613ccc61 100644 --- a/Sources/TestSupport/SwiftSectionTestingSupport/ExportedOnlyFixture.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/ExportedOnlyFixture.swift @@ -143,62 +143,14 @@ package enum ExportedOnlyFixture { } """ - package struct CompilationError: Swift.Error, CustomStringConvertible { - package let diagnostics: String - package var description: String { "\(moduleName) fixture compilation failed:\n\(diagnostics)" } - } - - private enum WorkingDirectoryCleanup { - nonisolated(unsafe) static var directories: [URL] = [] - static let registration: Void = { - atexit { - for directory in WorkingDirectoryCleanup.directories { - try? FileManager.default.removeItem(at: directory) - } - } - }() - } - - /// Compiled once per process. - private static let compilationResult: Result = { - Result { - let workingDirectory = FileManager.default.temporaryDirectory - .appendingPathComponent("\(moduleName)-\(UUID().uuidString)") - try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) - _ = WorkingDirectoryCleanup.registration - WorkingDirectoryCleanup.directories.append(workingDirectory) - - let sourceURL = workingDirectory.appendingPathComponent("\(moduleName).swift") - let libraryURL = workingDirectory.appendingPathComponent("lib\(moduleName).dylib") - try source.write(to: sourceURL, atomically: true, encoding: .utf8) - - let process = Process() - process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") - process.arguments = [ - "swiftc", "-emit-library", "-enable-library-evolution", - "-module-name", moduleName, - sourceURL.path, "-o", libraryURL.path, - ] + unexportedSymbolNames.flatMap { ["-Xlinker", "-unexported_symbol", "-Xlinker", $0] } - let standardErrorPipe = Pipe() - process.standardError = standardErrorPipe - try process.run() - // Drain BEFORE waitUntilExit, or a long diagnostic deadlocks both sides. - let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() - process.waitUntilExit() - guard process.terminationStatus == 0 else { - throw CompilationError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) - } - return libraryURL - } - }() - + /// Compiled once per process by the shared compiler. package static func machOFile() throws -> MachOFile { - switch try MachOKit.loadFromFile(url: try compilationResult.get()) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } + let libraryURL = try FixtureCompiler.shared.dynamicLibrary( + named: moduleName, + language: .swift, + source: source, + arguments: ["-enable-library-evolution"] + unexportedSymbolNames.flatMap { ["-Xlinker", "-unexported_symbol", "-Xlinker", $0] } + ) + return try HostSlice.machOFile(at: libraryURL) } } diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/Exports.swift b/Sources/TestSupport/SwiftSectionTestingSupport/Exports.swift new file mode 100644 index 000000000..df486100e --- /dev/null +++ b/Sources/TestSupport/SwiftSectionTestingSupport/Exports.swift @@ -0,0 +1,10 @@ +// The Testing half of the test support shared with MachOKitExtensions: +// `ExclusiveImageAccess`, the `MachOFileTests`, `MachOImageTests`, +// `DyldCacheTests`, `XcodeMachOFileTests` and `MachOFixtureTests` base +// classes. Re-exported so that a test importing this module reaches them +// without an import of its own. +@_exported import MachOTestingSupport +// The Swift-free half too: `ForwardingMachOReader` takes its +// `DeclaredWrapper` / `UndeclaredWrapper` markers from it, so a test naming +// one through this module alone still finds it. +@_exported import MachOFixtureSupport diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/ExtensionContextExportFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/ExtensionContextExportFixture.swift index 640b2b079..524c9700c 100644 --- a/Sources/TestSupport/SwiftSectionTestingSupport/ExtensionContextExportFixture.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/ExtensionContextExportFixture.swift @@ -137,7 +137,7 @@ package enum ExtensionContextExportFixture { } /// Compiled once per process; every variant shares one working directory. - private static let compilationResult: Result<[Variant: URL], Swift.Error> = { + private static let compilationResult: Result<[Variant: URL], any Swift.Error> = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("ExtensionContextExportFixture-\(UUID().uuidString)") @@ -220,12 +220,6 @@ package enum ExtensionContextExportFixture { package static func machOFile(_ variant: Variant) throws -> MachOFile { let libraries = try compilationResult.get() let libraryURL = try #require(libraries[variant], "no library for variant \(variant.rawValue)") - switch try MachOKit.loadFromFile(url: libraryURL) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } + return try HostSlice.machOFile(at: libraryURL) } } diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/FixtureSuiteMacro.swift b/Sources/TestSupport/SwiftSectionTestingSupport/FixtureSuiteMacro.swift new file mode 100644 index 000000000..3ad39007a --- /dev/null +++ b/Sources/TestSupport/SwiftSectionTestingSupport/FixtureSuiteMacro.swift @@ -0,0 +1,27 @@ +import SwiftSectionFixtureSupport + +/// Makes a fixture suite class a ``FixtureSuite``: adds `testedTypeName`, +/// `registeredTestMethodNames` and the conformance. +/// +/// ```swift +/// @Suite +/// @FixtureSuite +/// final class StructDescriptorTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { … } +/// ``` +/// +/// The tested type's name defaults to the class name without its `Tests` +/// suffix (`StructDescriptor`), and the baseline whose +/// `registeredTestMethodNames` the suite reports to the same stem followed by +/// `Baseline` (`StructDescriptorBaseline`). Name either when it differs, with +/// a literal: +/// +/// ```swift +/// @FixtureSuite(testedTypeName: "EnumTagCounts") +/// @FixtureSuite(testedTypeName: "OpaqueType", baseline: OpaqueTypeBaseline.self) +/// ``` +/// +/// `SuiteBehaviorScanner` reads the tested type's name from this attribute +/// the same way. +@attached(member, names: named(testedTypeName), named(registeredTestMethodNames)) +@attached(extension, conformances: FixtureSuite) +package macro FixtureSuite(testedTypeName: String? = nil, baseline: Any.Type? = nil) = #externalMacro(module: "SwiftSectionTestingMacros", type: "FixtureSuiteMacro") diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/ForwardingMachOReader+MachOReaderWrapper.swift b/Sources/TestSupport/SwiftSectionTestingSupport/ForwardingMachOReader+MachOReaderWrapper.swift index 96cf97f3b..aed04a828 100644 --- a/Sources/TestSupport/SwiftSectionTestingSupport/ForwardingMachOReader+MachOReaderWrapper.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/ForwardingMachOReader+MachOReaderWrapper.swift @@ -1,4 +1,5 @@ import MachOKitExtensions +import SwiftSectionFixtureSupport import SwiftDeclarationRendering /// A wrapper that declares what it wraps can say so to the library: the diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/ForwardingMachOReader.swift b/Sources/TestSupport/SwiftSectionTestingSupport/ForwardingMachOReader.swift index 1d51746d6..cdf95cc48 100644 --- a/Sources/TestSupport/SwiftSectionTestingSupport/ForwardingMachOReader.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/ForwardingMachOReader.swift @@ -3,17 +3,14 @@ import MachOKit import MachOKitExtensions import MachOReading import MachOSwiftSection +import SwiftSectionFixtureSupport -/// Whether a ``ForwardingMachOReader`` tells the library what it wraps. -package protocol ForwardingMachOReaderDeclaration: Sendable {} - -/// The reader declares the reader it forwards to — a host's wrapper that -/// adopted `MachOReaderWrapper`. -package enum DeclaredWrapper: ForwardingMachOReaderDeclaration {} - -/// The reader forwards every read and says nothing about it — a host's -/// wrapper written before `MachOReaderWrapper` existed. -package enum UndeclaredWrapper: ForwardingMachOReaderDeclaration {} +// Whether a ``ForwardingMachOReader`` tells the library what it wraps is said +// with MachOKitExtensions' markers for its own `ForwardingReader`: +// `DeclaredWrapper` — a host's wrapper that adopted `MachOReaderWrapper` — +// and `UndeclaredWrapper` — one written before `MachOReaderWrapper` existed. +// The reader itself stays here: it forwards this package's reading protocol, +// `MachOSwiftSectionRepresentableWithCache`, which `ForwardingReader` does not. /// A reader that forwards every requirement to `base` and adds nothing. /// @@ -24,7 +21,7 @@ package enum UndeclaredWrapper: ForwardingMachOReaderDeclaration {} /// requirement is forwarded, the defaulted ones too, so nothing a default /// implementation computes differently from `base`'s own can tell the two /// apart. -package struct ForwardingMachOReader: MachOSwiftSectionRepresentableWithCache { +package struct ForwardingMachOReader: MachOSwiftSectionRepresentableWithCache { package let base: Base package init(_ base: Base) { diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/GenericSpecializationFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/GenericSpecializationFixture.swift index 265a6b964..219d3b8aa 100644 --- a/Sources/TestSupport/SwiftSectionTestingSupport/GenericSpecializationFixture.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/GenericSpecializationFixture.swift @@ -222,68 +222,23 @@ package enum GenericSpecializationFixture { package var description: String { "\(moduleName) fixture compilation failed:\n\(diagnostics)" } } - private enum WorkingDirectoryCleanup { - nonisolated(unsafe) static var directories: [URL] = [] - static let registration: Void = { - atexit { - for directory in WorkingDirectoryCleanup.directories { - try? FileManager.default.removeItem(at: directory) - } - } - }() - } - - private static let compilationResult: Result = { - Result { - let workingDirectory = FileManager.default.temporaryDirectory - .appendingPathComponent("\(moduleName)-\(UUID().uuidString)") - try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) - _ = WorkingDirectoryCleanup.registration - WorkingDirectoryCleanup.directories.append(workingDirectory) - - let sourceURL = workingDirectory.appendingPathComponent("Fixture.swift") - let libraryURL = workingDirectory.appendingPathComponent("lib\(moduleName).dylib") - try source.write(to: sourceURL, atomically: true, encoding: .utf8) - - let process = Process() - process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") - process.arguments = [ - // The language mode pinned: CI's toolchain and a newer local one - // must compile the same source the same way. `-Onone` keeps the - // private type, which nothing references. - "swiftc", "-swift-version", "5", "-Onone", "-emit-library", - "-module-name", moduleName, - // The absolute output path as the install name, so the - // in-process leg loads with no rpath. - "-Xlinker", "-install_name", "-Xlinker", libraryURL.path, - sourceURL.path, "-o", libraryURL.path, - ] - let standardErrorPipe = Pipe() - process.standardError = standardErrorPipe - try process.run() - // Drain BEFORE waitUntilExit, or a long diagnostic deadlocks both sides. - let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() - process.waitUntilExit() - guard process.terminationStatus == 0 else { - throw CompilationError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) - } - return libraryURL - } - }() - + /// Compiled once per process by the shared compiler. The source keeps + /// the file name it always had, which private discriminators hash. package static func libraryURL() throws -> URL { - try compilationResult.get() + try FixtureCompiler.shared.dynamicLibrary( + named: moduleName, + language: .swift, + sourceFiles: [FixtureSourceFile(name: "Fixture.swift", contents: source)], + // The language mode pinned: CI's toolchain and a newer local one + // must compile the same source the same way. `-Onone` keeps the + // private type, which nothing references. + arguments: ["-swift-version", "5", "-Onone"] + ) } /// The fixture read from disk — what the offline path sees. package static func machOFile() throws -> MachOFile { - switch try MachOKit.loadFromFile(url: libraryURL()) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } + try HostSlice.machOFile(at: libraryURL()) } /// The fixture loaded into the test process — what the runtime path sees. @@ -307,7 +262,7 @@ package enum GenericSpecializationFixture { /// the offline indexer's sub-indexer for the standard library's /// protocols and conformances. package static func systemStandardLibraryFile() throws -> MachOFile { - let cache = try DyldCache(url: URL(fileURLWithPath: DyldSharedCachePath.current.rawValue)) + let cache = try #require(FullDyldCache.cachedHost, "no host dyld shared cache").mainCache return try #require(cache.machOFile(by: .name("libswiftCore")), "libswiftCore not found in the running system's dyld shared cache") } } diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/GenericSpecializationFixtureIndexers.swift b/Sources/TestSupport/SwiftSectionTestingSupport/GenericSpecializationFixtureIndexers.swift index 708769ec2..6b55ea018 100644 --- a/Sources/TestSupport/SwiftSectionTestingSupport/GenericSpecializationFixtureIndexers.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/GenericSpecializationFixtureIndexers.swift @@ -4,6 +4,7 @@ import Foundation import Testing import MachOKit import MachOSwiftSection +import OrderedCollections /// The `GenericSpecializationFixture`'s prepared indexers, one per reading /// path, each built once per process and shared by every suite: the runtime diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/ImageGroupFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/ImageGroupFixture.swift index e9f3b37a9..55973d6b3 100644 --- a/Sources/TestSupport/SwiftSectionTestingSupport/ImageGroupFixture.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/ImageGroupFixture.swift @@ -222,7 +222,7 @@ package enum ImageGroupFixture { /// Compiled once per process, each version in a directory of its own, /// since every version reuses the two module names. Per version the /// libraries' URLs, the core image's first when there is one. - private static let compilationResult: Result<[[(name: String, libraryURL: URL)]], Swift.Error> = { + private static let compilationResult: Result<[[(name: String, libraryURL: URL)]], any Swift.Error> = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("\(moduleName)-\(UUID().uuidString)") @@ -288,7 +288,7 @@ package enum ImageGroupFixture { package static func imageGroups() throws -> [[Image]] { try compilationResult.get().map { libraries in try libraries.map { library in - try Image(name: library.name, machOFile: machOFile(at: library.libraryURL)) + try Image(name: library.name, machOFile: HostSlice.machOFile(at: library.libraryURL)) } } } @@ -298,14 +298,4 @@ package enum ImageGroupFixture { let image = try imageGroups()[versionIndex].first { $0.name == imageName } return try #require(image, "\(imageName) is not part of version \(labels[versionIndex])").machOFile } - - private static func machOFile(at libraryURL: URL) throws -> MachOFile { - switch try MachOKit.loadFromFile(url: libraryURL) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } - } } diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/InitAccessorFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/InitAccessorFixture.swift index 2686b5b1e..2c46c19e7 100644 --- a/Sources/TestSupport/SwiftSectionTestingSupport/InitAccessorFixture.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/InitAccessorFixture.swift @@ -272,8 +272,8 @@ package enum InitAccessorFixture { private final class OneTimeCompilation: @unchecked Sendable { private let lock = NSLock() - private var result: Result<[Variant: URL], Swift.Error>? - private var waiters: [CheckedContinuation<[Variant: URL], Swift.Error>] = [] + private var result: Result<[Variant: URL], any Swift.Error>? + private var waiters: [CheckedContinuation<[Variant: URL], any Swift.Error>] = [] private var hasStarted = false func libraries() async throws -> [Variant: URL] { @@ -363,13 +363,7 @@ package enum InitAccessorFixture { package static func machOFile(_ variant: Variant) async throws -> MachOFile { let libraryURL = try await libraryURL(variant) - switch try MachOKit.loadFromFile(url: libraryURL) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } + return try HostSlice.machOFile(at: libraryURL) } /// The `.release` variant loaded into the test process — only that one: diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/LocalTypeFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/LocalTypeFixture.swift index bc11675a2..018033110 100644 --- a/Sources/TestSupport/SwiftSectionTestingSupport/LocalTypeFixture.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/LocalTypeFixture.swift @@ -351,7 +351,7 @@ package enum LocalTypeFixture { } /// Compiled once per process; every variant shares one working directory. - private static let compilationResult: Result<[Variant: URL], Swift.Error> = { + private static let compilationResult: Result<[Variant: URL], any Swift.Error> = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("LocalTypeFixture-\(UUID().uuidString)") @@ -472,13 +472,7 @@ package enum LocalTypeFixture { package static func machOFile(_ variant: Variant) throws -> MachOFile { let libraryURL = try libraryURL(variant) - switch try MachOKit.loadFromFile(url: libraryURL) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } + return try HostSlice.machOFile(at: libraryURL) } /// The variant loaded into the test process. diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/MachOFileTests.swift b/Sources/TestSupport/SwiftSectionTestingSupport/MachOFileTests.swift deleted file mode 100644 index 063cd74e6..000000000 --- a/Sources/TestSupport/SwiftSectionTestingSupport/MachOFileTests.swift +++ /dev/null @@ -1,26 +0,0 @@ -import Foundation -import Testing -import MachOKit -import MachOFoundation -import SwiftSectionFixtureSupport - -@MainActor -package class MachOFileTests: Sendable { - package let machOFile: MachOFile - - package class var fileName: MachOFileName { .Finder } - - package class var preferredArchitecture: CPUType { .arm64 } - - package init() async throws { - let file = try loadFromFile(named: Self.fileName) - switch file { - case .fat(let fatFile): - self.machOFile = try required(fatFile.machOFiles().first(where: { $0.header.cpuType == Self.preferredArchitecture }) ?? fatFile.machOFiles().first) - case .machO(let machO): - self.machOFile = machO - @unknown default: - fatalError() - } - } -} diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/MachOImageTests.swift b/Sources/TestSupport/SwiftSectionTestingSupport/MachOImageTests.swift deleted file mode 100644 index 28e4f9550..000000000 --- a/Sources/TestSupport/SwiftSectionTestingSupport/MachOImageTests.swift +++ /dev/null @@ -1,16 +0,0 @@ -import Foundation -import Testing -import MachOKit -import MachOFoundation -import SwiftSectionFixtureSupport - -@MainActor -package class MachOImageTests: Sendable { - package let machOImage: MachOImage - - package class var imageName: MachOImageName { .Foundation } - - package init() async throws { - self.machOImage = try #require(MachOImage(named: Self.imageName)) - } -} diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/MachOSwiftSectionFixtureTests.swift b/Sources/TestSupport/SwiftSectionTestingSupport/MachOSwiftSectionFixtureTests.swift index 007637af5..80685c177 100644 --- a/Sources/TestSupport/SwiftSectionTestingSupport/MachOSwiftSectionFixtureTests.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/MachOSwiftSectionFixtureTests.swift @@ -1,153 +1,32 @@ import Foundation -import Testing -import MachOKit -import MachOFoundation -import MachOReading -import MachOResolving +import MachOTestingSupport import SwiftSectionFixtureSupport -@MainActor -package class MachOSwiftSectionFixtureTests: Sendable { - package let machOFile: MachOFile - package let machOImage: MachOImage - - package let fileContext: MachOContext - package let imageContext: MachOContext - package let inProcessContext: InProcessContext - +/// A suite that reads the SymbolTestsCore fixture both from its file and as +/// this process loaded it. +/// +/// The readers, the reading contexts and `acrossAllReaders` / +/// `acrossAllContexts` / `usingInProcessOnly` come from MachOKitExtensions' +/// `MachOFixtureTests`; this class says which fixture to read and turns a +/// fixture that cannot be read into a `FixtureLoadError` that tells how to +/// rebuild it. +package class MachOSwiftSectionFixtureTests: MachOFixtureTests { package class var fixtureFileName: MachOFileName { .SymbolTestsCore } package class var fixtureImageName: MachOImageName { .SymbolTestsCore } - package class var preferredArchitecture: CPUType { .arm64 } - - package init() async throws { - // 1) Load MachO from disk. - let file: File - do { - file = try loadFromFile(named: Self.fixtureFileName) - } catch { - // If the file doesn't exist on disk, surface a fixture-specific - // error with rebuild instructions. Otherwise propagate the original - // error so unrelated load failures aren't masked. - let resolvedPath = Self.resolveFixturePath(Self.fixtureFileName.rawValue) - if !FileManager.default.fileExists(atPath: resolvedPath) { - throw FixtureLoadError.fixtureFileMissing(path: resolvedPath) - } - throw error - } - switch file { - case .fat(let fatFile): - self.machOFile = try required( - fatFile.machOFiles().first(where: { $0.header.cpuType == Self.preferredArchitecture }) - ?? fatFile.machOFiles().first - ) - case .machO(let machO): - self.machOFile = machO - @unknown default: - fatalError() - } - - // 2) Ensure fixture is dlopen'd into the test process so MachOImage(name:) succeeds. - // `MachOImage(name:)` matches by the bare module name (last path component - // with extension stripped), not by the full path. Derive that from the - // fixtureImageName rawValue, which is a relative filesystem path. - try Self.ensureFixtureLoaded() - let imageLookupName = Self.imageLookupName(from: Self.fixtureImageName.rawValue) - guard let image = MachOImage(name: imageLookupName) else { - throw FixtureLoadError.imageNotFoundAfterDlopen( - path: Self.fixtureImageName.rawValue, - dlerror: Self.lastDlerror() - ) - } - self.machOImage = image - - // 3) Three ReadingContext instances over the same fixture. - self.fileContext = MachOContext(machOFile) - self.imageContext = MachOContext(machOImage) - self.inProcessContext = InProcessContext() - } - - private static let dlopenOnce: Void = { - let absolute = resolveFixturePath(MachOImageName.SymbolTestsCore.rawValue) - _ = absolute.withCString { dlopen($0, RTLD_LAZY) } - }() - - private static func ensureFixtureLoaded() throws { - _ = dlopenOnce - } - /// Resolve a relative MachOImageName path (rooted at the package-relative `../../../Tests/...` - /// convention) to an absolute filesystem path. Uses the same anchor strategy as - /// `loadFromFile` for parity: relative paths resolve against the directory containing - /// this source file (i.e. `Sources/TestSupport/SwiftSectionTestingSupport/`). - private static func resolveFixturePath(_ relativePath: String) -> String { - if relativePath.hasPrefix("/") { return relativePath } - let url = URL(fileURLWithPath: relativePath, relativeTo: URL(fileURLWithPath: #filePath)) - return url.standardizedFileURL.path + /// The file of ``fixtureFileName``, found in this process by + /// ``fixtureImageName`` after loading it. + override package class var fixture: MachOFixture { + MachOFixture(fileURL: fixtureFileName.url, imageName: fixtureImageName.name, loadsIntoProcess: true) } - private static func lastDlerror() -> String? { - guard let cString = dlerror() else { return nil } - return String(cString: cString) - } - - /// Derive the bare module name `MachOImage(name:)` expects (last path component - /// with extension stripped) from a path-form `MachOImageName.rawValue`. - private static func imageLookupName(from rawValue: String) -> String { - let lastComponent = rawValue.components(separatedBy: "/").last ?? rawValue - return lastComponent.components(separatedBy: ".").first ?? lastComponent - } -} - -extension MachOSwiftSectionFixtureTests { - /// Run `body` against each (label, reader) pair, asserting all results equal the first. - /// Returns the unique value. Fails fast with the label of the first mismatching reader. - package func acrossAllReaders( - file fileWork: () throws -> T, - image imageWork: () throws -> T, - inProcess inProcessWork: (() throws -> T)? = nil, - sourceLocation: SourceLocation = #_sourceLocation - ) throws -> T { - let fromFile = try fileWork() - let fromImage = try imageWork() - #expect(fromFile == fromImage, "MachOFile vs MachOImage diverged", sourceLocation: sourceLocation) - if let inProcessWork { - let fromInProcess = try inProcessWork() - #expect(fromFile == fromInProcess, "MachOFile vs InProcess diverged", sourceLocation: sourceLocation) - } - return fromFile - } - - /// Run `body` against each ReadingContext (file/image/inProcess), asserting all equal. - package func acrossAllContexts( - file fileWork: () throws -> T, - image imageWork: () throws -> T, - inProcess inProcessWork: (() throws -> T)? = nil, - sourceLocation: SourceLocation = #_sourceLocation - ) throws -> T { - let fromFileCtx = try fileWork() - let fromImageCtx = try imageWork() - #expect(fromFileCtx == fromImageCtx, "fileContext vs imageContext diverged", sourceLocation: sourceLocation) - if let inProcessWork { - let fromInProcessCtx = try inProcessWork() - #expect(fromFileCtx == fromInProcessCtx, "fileContext vs inProcessContext diverged", sourceLocation: sourceLocation) + package override init() async throws { + do { + try await super.init() + } catch MachOFixtureError.fileMissing(let path) { + throw FixtureLoadError.fixtureFileMissing(path: path) + } catch MachOFixtureError.imageNotLoaded(_, let dynamicLoaderError) { + throw FixtureLoadError.imageNotFoundAfterDlopen(path: Self.fixtureFileName.path, dlerror: dynamicLoaderError) } - return fromFileCtx - } -} - -extension MachOSwiftSectionFixtureTests { - /// Run `body` against the in-process reader only. Used by Suites covering - /// runtime-only metadata types (MetatypeMetadata, TupleTypeMetadata, - /// FunctionTypeMetadata, etc.) — types that the Swift runtime allocates - /// at type-load time and that have no Mach-O section to read from. - /// - /// Cross-reader equality is not asserted because `MachOFile` and - /// `MachOImage` cannot reach this metadata. Single-reader assertion + - /// baseline literal pinning is the deepest coverage achievable. - package func usingInProcessOnly( - _ work: (InProcessContext) throws -> T, - sourceLocation: SourceLocation = #_sourceLocation - ) throws -> T { - try work(inProcessContext) } } diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/ModuleSelectorFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/ModuleSelectorFixture.swift index 5102fd3a9..8c1405f91 100644 --- a/Sources/TestSupport/SwiftSectionTestingSupport/ModuleSelectorFixture.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/ModuleSelectorFixture.swift @@ -92,57 +92,6 @@ package enum ModuleSelectorFixture { } """ - package struct CompilationError: Swift.Error, CustomStringConvertible { - package let diagnostics: String - package var description: String { "\(moduleName) fixture compilation failed:\n\(diagnostics)" } - } - - private enum WorkingDirectoryCleanup { - nonisolated(unsafe) static var directories: [URL] = [] - static let registration: Void = { - atexit { - for directory in WorkingDirectoryCleanup.directories { - try? FileManager.default.removeItem(at: directory) - } - } - }() - } - - /// Compiled once per process. - private static let compilationResult: Result = { - Result { - let workingDirectory = FileManager.default.temporaryDirectory - .appendingPathComponent("\(moduleName)-\(UUID().uuidString)") - try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) - _ = WorkingDirectoryCleanup.registration - WorkingDirectoryCleanup.directories.append(workingDirectory) - - let sourceURL = workingDirectory.appendingPathComponent("Fixture.swift") - let libraryURL = workingDirectory.appendingPathComponent("lib\(moduleName).dylib") - try source.write(to: sourceURL, atomically: true, encoding: .utf8) - - let process = Process() - process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") - process.arguments = [ - // The language mode pinned: CI's toolchain and a newer local - // one must compile the same source the same way. - "swiftc", "-swift-version", "5", "-emit-library", "-enable-library-evolution", - "-module-name", moduleName, - sourceURL.path, "-o", libraryURL.path, - ] - let standardErrorPipe = Pipe() - process.standardError = standardErrorPipe - try process.run() - // Drain BEFORE waitUntilExit, or a long diagnostic deadlocks both sides. - let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() - process.waitUntilExit() - guard process.terminationStatus == 0 else { - throw CompilationError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) - } - return libraryURL - } - }() - /// Every name in `output` still qualified the dotted way by a module that /// `output` spells with a selector somewhere — what a print path writing a /// qualified name by hand, instead of through the type printer, leaves @@ -164,13 +113,17 @@ package enum ModuleSelectorFixture { return dottedQualifications } + /// Compiled once per process by the shared compiler. The source keeps + /// the file name it always had, which private discriminators hash. package static func machOFile() throws -> MachOFile { - switch try MachOKit.loadFromFile(url: try compilationResult.get()) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } + let libraryURL = try FixtureCompiler.shared.dynamicLibrary( + named: moduleName, + language: .swift, + sourceFiles: [FixtureSourceFile(name: "Fixture.swift", contents: source)], + // The language mode pinned: CI's toolchain and a newer local + // one must compile the same source the same way. + arguments: ["-swift-version", "5", "-enable-library-evolution"] + ) + return try HostSlice.machOFile(at: libraryURL) } } diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/ObjCImplementationFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/ObjCImplementationFixture.swift index 453a7a151..953cbfab1 100644 --- a/Sources/TestSupport/SwiftSectionTestingSupport/ObjCImplementationFixture.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/ObjCImplementationFixture.swift @@ -43,6 +43,10 @@ import Testing /// recognition's first version accepted only the `identifier` shape and left /// both untyped even with every symbol present. /// +/// `AdaptiveTransitionWidget` (evolution proposal `objc-ivar-type-recovery`) +/// has one stored property per ivar encoding shape, all internal, so the +/// stripped variants keep only the Objective-C side of each. +/// /// Five link/strip variants exercise the evidence tiers and the bind formats: /// - `.full`: every symbol present — accessor, field-offset globals, `To` /// thunks at the class's own IMPs. @@ -137,6 +141,31 @@ package enum ObjCImplementationFixture { - (void)activate; @end + // Shaped after UIKitCore's `_UISplitViewControllerAdaptiveLayoutTransition` + // on macOS 27.2 (evolution proposal `objc-ivar-type-recovery`): with its + // field-offset symbols stripped, only the ivar encodings and the + // Objective-C properties say what its stored properties' types are. + @protocol AdaptiveLayout + @end + + @interface AdaptiveTransitionWidget : NSObject + @property (nonatomic, strong) NSObject *containerView; + @property (nonatomic, strong) NSMutableString *buffer; + @property (nonatomic, strong) id previousLayout; + @property (nonatomic, readonly) NSString *identifier; + @property (nonatomic, weak, nullable) NSObject *observer; + @property (nonatomic) BOOL isAnimated; + @property (nonatomic) CGFloat interactiveProgress; + @property (nonatomic) NSInteger stepCount; + @property (nonatomic, readonly) NSInteger revision; + @property (nonatomic) NSRange selectedRange; + @property (nonatomic, copy) NSArray *names; + @property (nonatomic, strong) id payload; + @property (nonatomic, unsafe_unretained) NSObject *unretainedObserver; + @property (nonatomic, readonly, unsafe_unretained) NSString *unretainedOwner; + - (void)begin; + @end + NS_ASSUME_NONNULL_END """ @@ -343,6 +372,49 @@ package enum ObjCImplementationFixture { priority += 1 } } + + // Shaped after UIKitCore's `_UISplitViewControllerAdaptiveLayoutTransition` + // (evolution proposal `objc-ivar-type-recovery`). Internal members, so + // `strip -x` takes every field-offset symbol and accessor: one ivar per + // encoding shape — a class, a class Swift does not bridge, a protocol + // existential, `B`, `d`, `q`, a structure — the bridged ones the ivar + // marks `?` (`String`, `[String]`, `Any`), a `weak` one, a `let` behind a + // `readonly` property, and a Swift-only one with no encoding at all. + final class StandInAdaptiveLayout: NSObject, AdaptiveLayout {} + + // What the `unowned(unsafe)` properties point at, kept alive. + let adaptiveTransitionSharedObserver = NSObject() + let adaptiveTransitionSharedOwner = NSString(string: "owner") + + @objc @implementation extension AdaptiveTransitionWidget { + var containerView: NSObject = NSObject() + var buffer: NSMutableString = NSMutableString() + var previousLayout: any AdaptiveLayout = StandInAdaptiveLayout() + let identifier: String = "transition" + weak var observer: NSObject? + var isAnimated: Bool = false + // The header's `CGFloat` imports as `Double` into this fixture. + var interactiveProgress: Double = 0 + var stepCount: Int = 0 + let revision: Int = 1 + var selectedRange: NSRange = NSRange(location: 0, length: 0) + var names: [String] = [] + var payload: Any = NSNull() + final var transitionAnimations: [() -> Void] = [] + // The header's `unsafe_unretained` imports as `unowned(unsafe)`, + // the only `unowned` an `@implementation` body may declare. The + // compiler marks its storage `?` and its property `W` — as for + // `weak` — or, read-only, nothing but `R`, as for a bridged `let` + // (2026-11-29 codebase audit, finding 2). + unowned(unsafe) var unretainedObserver: NSObject = adaptiveTransitionSharedObserver + unowned(unsafe) let unretainedOwner: NSString = adaptiveTransitionSharedOwner + + func begin() { + isAnimated = true + stepCount += names.count + transitionAnimations.append {} + } + } """ package struct CompilationError: Swift.Error, CustomStringConvertible { @@ -369,7 +441,7 @@ package enum ObjCImplementationFixture { } /// Compiled once per process; every variant shares one working directory. - private static let compilationResult: Result = { + private static let compilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("\(moduleName)-\(UUID().uuidString)") @@ -440,7 +512,7 @@ package enum ObjCImplementationFixture { let standardErrorPipe = Pipe() process.standardError = standardErrorPipe try process.run() - // Drain BEFORE waitUntilExit — see LegacyDyldInfoBindTests. + // Drain BEFORE waitUntilExit, or a long diagnostic deadlocks both sides. let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() process.waitUntilExit() guard process.terminationStatus == 0 else { @@ -470,12 +542,6 @@ package enum ObjCImplementationFixture { package static func machOFile(_ variant: Variant) throws -> MachOFile { let libraryURL = try libraryURL(variant) - switch try MachOKit.loadFromFile(url: libraryURL) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } + return try HostSlice.machOFile(at: libraryURL) } } diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/ObjCWrittenCategoriesFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/ObjCWrittenCategoriesFixture.swift new file mode 100644 index 000000000..7b1dcee19 --- /dev/null +++ b/Sources/TestSupport/SwiftSectionTestingSupport/ObjCWrittenCategoriesFixture.swift @@ -0,0 +1,167 @@ +import Foundation +import MachOFoundation +import MachOKit +import Testing + +/// An on-the-fly fixture for the categories Objective-C code declares in an +/// image: a category that adopts a protocol is an extension of Swift's only +/// when the Swift compiler emitted it, and only an image Swift code went into +/// — its `objc_image_info` records a Swift version — can hold one. +/// +/// Two variants of one library: +/// - `.objectiveCOnly`: Objective-C code alone, as every OS framework from +/// before Swift ships — OS X 10.9's AppKit, whose `NSString`, `NSURL`, +/// `NSAttributedString` and `NSFileVersion` categories adopt protocols and +/// were printed as Swift conformance extensions. +/// - `.mixed`: the same Objective-C code linked into a Swift module whose two +/// extensions of `DateFormatter` adopt `@objc` protocols, as a framework +/// carrying both languages does (AppKit since its overlay merged into it). +/// The linker merges the categories of one class: the image holds one +/// `NSDateFormatter` category, named after the first, listing the +/// Objective-C protocol and both Swift ones, and one `NSString` category. +package enum ObjCWrittenCategoriesFixture { + package enum Variant: String, CaseIterable, Sendable { + case objectiveCOnly + case mixed + } + + package static let moduleName = "ObjCWrittenCategoriesFixture" + + package static let objectiveCSource = """ + #import + + @protocol OWCObjectiveCWrittenAdoption + - (void)owc_objectiveCWrittenPoke; + @end + + // Categories Objective-C code declares, adopting a protocol: no Swift + // extension stands behind them. + @interface NSString (OWCObjectiveCWritten) + @end + + @implementation NSString (OWCObjectiveCWritten) + - (void)owc_objectiveCWrittenPoke {} + @end + + @interface NSDateFormatter (OWCObjectiveCWritten) + @end + + @implementation NSDateFormatter (OWCObjectiveCWritten) + - (void)owc_objectiveCWrittenPoke {} + @end + """ + + package static let swiftSource = """ + import Foundation + + @objc public protocol SwiftDeclaredAdoption { + func swiftDeclaredPoke() + } + + @objc public protocol SecondSwiftDeclaredAdoption { + func secondSwiftDeclaredPoke() + } + + // Two extensions of one class of another module: two categories, named + // `\(moduleName)` and `\(moduleName)1`, before the linker merges them. + extension DateFormatter: SwiftDeclaredAdoption { + public func swiftDeclaredPoke() {} + } + + extension DateFormatter: SecondSwiftDeclaredAdoption { + public func secondSwiftDeclaredPoke() {} + } + """ + + package struct CompilationError: Swift.Error, CustomStringConvertible { + package let step: String + package let diagnostics: String + package var description: String { "\(moduleName) fixture \(step) failed:\n\(diagnostics)" } + } + + private enum WorkingDirectoryCleanup { + nonisolated(unsafe) static var directories: [URL] = [] + static let registration: Void = { + atexit { + for directory in WorkingDirectoryCleanup.directories { + try? FileManager.default.removeItem(at: directory) + } + } + }() + } + + /// Compiled once per process; both variants share one working directory. + private static let compilationResult: Result<[Variant: URL], any Swift.Error> = { + Result { + let workingDirectory = FileManager.default.temporaryDirectory + .appendingPathComponent("\(moduleName)-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) + _ = WorkingDirectoryCleanup.registration + WorkingDirectoryCleanup.directories.append(workingDirectory) + + let objectiveCSourceURL = workingDirectory.appendingPathComponent("Categories.m") + let objectiveCObjectURL = workingDirectory.appendingPathComponent("Categories.o") + let swiftSourceURL = workingDirectory.appendingPathComponent("Fixture.swift") + try objectiveCSource.write(to: objectiveCSourceURL, atomically: true, encoding: .utf8) + try swiftSource.write(to: swiftSourceURL, atomically: true, encoding: .utf8) + + let objectiveCOnlyLibraryURL = workingDirectory.appendingPathComponent("lib\(moduleName)-\(Variant.objectiveCOnly.rawValue).dylib") + try run(step: "clang (\(Variant.objectiveCOnly.rawValue))", [ + "clang", "-dynamiclib", "-fobjc-arc", "-framework", "Foundation", + "-install_name", objectiveCOnlyLibraryURL.path, + objectiveCSourceURL.path, "-o", objectiveCOnlyLibraryURL.path, + ]) + + let mixedLibraryURL = workingDirectory.appendingPathComponent("lib\(moduleName)-\(Variant.mixed.rawValue).dylib") + try run(step: "clang (\(Variant.mixed.rawValue) object)", [ + "clang", "-c", "-fobjc-arc", objectiveCSourceURL.path, "-o", objectiveCObjectURL.path, + ]) + try run(step: "swiftc (\(Variant.mixed.rawValue))", [ + // The language mode pinned: CI's toolchain and a newer local + // one must compile the same source the same way. + "swiftc", "-swift-version", "5", "-emit-library", "-Onone", "-module-name", moduleName, + "-Xlinker", "-install_name", "-Xlinker", mixedLibraryURL.path, + swiftSourceURL.path, objectiveCObjectURL.path, "-framework", "Foundation", + "-o", mixedLibraryURL.path, + ]) + return [.objectiveCOnly: objectiveCOnlyLibraryURL, .mixed: mixedLibraryURL] + } + }() + + private static func run(step: String, _ arguments: [String]) throws { + let process = Process() + process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") + process.arguments = arguments + let standardErrorPipe = Pipe() + process.standardError = standardErrorPipe + try process.run() + // Drain BEFORE waitUntilExit, or a long diagnostic deadlocks both sides. + let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() + process.waitUntilExit() + guard process.terminationStatus == 0 else { + throw CompilationError(step: step, diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) + } + } + + package static func libraryURL(_ variant: Variant) throws -> URL { + let libraries = try compilationResult.get() + guard let libraryURL = libraries[variant] else { + throw CompilationError(step: "lookup", diagnostics: "no library for variant \(variant.rawValue)") + } + return libraryURL + } + + package static func machOFile(_ variant: Variant) throws -> MachOFile { + try HostSlice.machOFile(at: libraryURL(variant)) + } + + /// A variant loaded into the test process. Both may be: they declare the + /// same Objective-C protocol and categories, but no class, so the runtime + /// keeps both images' records without a conflict. + package static func loadedImage(_ variant: Variant) throws -> MachOImage { + let libraryURL = try libraryURL(variant) + _ = libraryURL.path.withCString { dlopen($0, RTLD_NOW) } + let imageName = libraryURL.deletingPathExtension().lastPathComponent + return try #require(MachOImage(name: imageName), "the fixture dylib did not load in-process") + } +} diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/ObservableMacroFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/ObservableMacroFixture.swift index 05e278b38..419bd4e49 100644 --- a/Sources/TestSupport/SwiftSectionTestingSupport/ObservableMacroFixture.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/ObservableMacroFixture.swift @@ -187,8 +187,8 @@ package enum ObservableMacroFixture { private final class OneTimeCompilation: @unchecked Sendable { private let lock = NSLock() - private var result: Result<[Variant: URL], Swift.Error>? - private var waiters: [CheckedContinuation<[Variant: URL], Swift.Error>] = [] + private var result: Result<[Variant: URL], any Swift.Error>? + private var waiters: [CheckedContinuation<[Variant: URL], any Swift.Error>] = [] private var hasStarted = false func libraries() async throws -> [Variant: URL] { @@ -278,13 +278,7 @@ package enum ObservableMacroFixture { package static func machOFile(_ variant: Variant) async throws -> MachOFile { let libraryURL = try await libraryURL(variant) - switch try MachOKit.loadFromFile(url: libraryURL) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } + return try HostSlice.machOFile(at: libraryURL) } /// The `.release` variant loaded into the test process — only that one: diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/ProcessMemory.swift b/Sources/TestSupport/SwiftSectionTestingSupport/ProcessMemory.swift deleted file mode 100644 index 250b0200a..000000000 --- a/Sources/TestSupport/SwiftSectionTestingSupport/ProcessMemory.swift +++ /dev/null @@ -1,79 +0,0 @@ -import Foundation - -public enum ProcessMemory { - public enum Metric { - case physicalFootprint - - case residentSize - - case compressed - - case virtualSize - - var displayName: String { - switch self { - case .physicalFootprint: return "Physical Footprint" - case .residentSize: return "Resident Size (RSS)" - case .compressed: return "Compressed Memory" - case .virtualSize: return "Virtual Size" - } - } - } - - private nonisolated(unsafe) static let byteFormatter: ByteCountFormatter = { - let formatter = ByteCountFormatter() - formatter.countStyle = .memory - formatter.allowsNonnumericFormatting = false - formatter.includesUnit = true - return formatter - }() - - public static func value(of metric: Metric) -> UInt64 { - guard let info = getTaskVMInfo() else { return 0 } - - switch metric { - case .physicalFootprint: return UInt64(info.phys_footprint) - case .residentSize: return UInt64(info.resident_size) - case .compressed: return UInt64(info.compressed) - case .virtualSize: return UInt64(info.virtual_size) - } - } - - public static func formatted(of metric: Metric) -> String { - let bytes = value(of: metric) - return byteFormatter.string(fromByteCount: Int64(bytes)) - } - - public static func report() { - guard let info = getTaskVMInfo() else { - print("❌ [ProcessMemory] Failed to retrieve task info.") - return - } - - print("====== 🧠 Process Memory Report ======") - printItem(name: Metric.physicalFootprint.displayName, bytes: UInt64(info.phys_footprint)) - printItem(name: Metric.residentSize.displayName, bytes: UInt64(info.resident_size)) - printItem(name: Metric.compressed.displayName, bytes: UInt64(info.compressed)) - print("--------------------------------------") - } - - // MARK: - Private Helpers - - private static func printItem(name: String, bytes: UInt64) { - let str = byteFormatter.string(fromByteCount: Int64(bytes)) - print(String(format: "%-20@ : %@", name, str)) - } - - private static func getTaskVMInfo() -> task_vm_info_data_t? { - var info = task_vm_info_data_t() - var count = mach_msg_type_number_t(MemoryLayout.size) / 4 - - let result: kern_return_t = withUnsafeMutablePointer(to: &info) { - $0.withMemoryRebound(to: integer_t.self, capacity: Int(count)) { - task_info(mach_task_self_, task_flavor_t(TASK_VM_INFO), $0, &count) - } - } - - return result == KERN_SUCCESS ? info : nil - } -} diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/ProtocolRequirementPlacementFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/ProtocolRequirementPlacementFixture.swift index b296b48c6..76240f085 100644 --- a/Sources/TestSupport/SwiftSectionTestingSupport/ProtocolRequirementPlacementFixture.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/ProtocolRequirementPlacementFixture.swift @@ -124,11 +124,6 @@ package enum ProtocolRequirementPlacementFixture { } """ - package struct CompilationError: Swift.Error, CustomStringConvertible { - package let diagnostics: String - package var description: String { "\(moduleName) fixture compilation failed:\n\(diagnostics)" } - } - /// The fixture: `supportSource` and `protocolSource` in one library. package static func machOFile() throws -> MachOFile { try machOFile(compiling: protocolSource) @@ -137,80 +132,18 @@ package enum ProtocolRequirementPlacementFixture { /// `supportSource` and `protocolDeclarations` compiled into one library /// named `moduleName`, as the fixture itself is, so every name a printed /// protocol mentions resolves to the same declaration again. Each - /// distinct source compiles once per process. + /// distinct source compiles once per process, by the shared compiler; + /// the source keeps the file name it always had, which private + /// discriminators hash. package static func machOFile(compiling protocolDeclarations: String) throws -> MachOFile { - let libraryURL = try CompiledLibraries.shared.libraryURL(for: supportSource + "\n\n" + protocolDeclarations) - switch try MachOKit.loadFromFile(url: libraryURL) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } - } - - private enum WorkingDirectoryCleanup { - nonisolated(unsafe) static var directories: [URL] = [] - static let registration: Void = { - atexit { - for directory in WorkingDirectoryCleanup.directories { - try? FileManager.default.removeItem(at: directory) - } - } - }() - } - - private final class CompiledLibraries: @unchecked Sendable { - static let shared = CompiledLibraries() - - private let lock = NSLock() - - private var libraryURLsBySource: [String: URL] = [:] - - /// Compiles under the lock: two tests asking for the same source wait - /// for one compiler run. The wait is on `swiftc`, never on a pool - /// thread. - func libraryURL(for source: String) throws -> URL { - lock.lock() - defer { lock.unlock() } - if let libraryURL = libraryURLsBySource[source] { - return libraryURL - } - let libraryURL = try Self.compile(source) - libraryURLsBySource[source] = libraryURL - return libraryURL - } - - private static func compile(_ source: String) throws -> URL { - let workingDirectory = FileManager.default.temporaryDirectory - .appendingPathComponent("\(moduleName)-\(UUID().uuidString)") - try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) - _ = WorkingDirectoryCleanup.registration - WorkingDirectoryCleanup.directories.append(workingDirectory) - - let sourceURL = workingDirectory.appendingPathComponent("Fixture.swift") - let libraryURL = workingDirectory.appendingPathComponent("lib\(moduleName).dylib") - try source.write(to: sourceURL, atomically: true, encoding: .utf8) - - let process = Process() - process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") - process.arguments = [ - // The language mode pinned: CI's toolchain and a newer local - // one must compile the same source the same way. - "swiftc", "-swift-version", "5", "-emit-library", - "-module-name", moduleName, - sourceURL.path, "-o", libraryURL.path, - ] - let standardErrorPipe = Pipe() - process.standardError = standardErrorPipe - try process.run() - // Drain BEFORE waitUntilExit, or a long diagnostic deadlocks both sides. - let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() - process.waitUntilExit() - guard process.terminationStatus == 0 else { - throw CompilationError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) - } - return libraryURL - } + let libraryURL = try FixtureCompiler.shared.dynamicLibrary( + named: moduleName, + language: .swift, + sourceFiles: [FixtureSourceFile(name: "Fixture.swift", contents: supportSource + "\n\n" + protocolDeclarations)], + // The language mode pinned: CI's toolchain and a newer local + // one must compile the same source the same way. + arguments: ["-swift-version", "5"] + ) + return try HostSlice.machOFile(at: libraryURL) } } diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/RenamedObjCClassFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/RenamedObjCClassFixture.swift index a62167e25..afba1a87e 100644 --- a/Sources/TestSupport/SwiftSectionTestingSupport/RenamedObjCClassFixture.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/RenamedObjCClassFixture.swift @@ -160,7 +160,7 @@ package enum RenamedObjCClassFixture { } /// Compiled once per process; every variant shares one working directory. - private static let compilationResult: Result = { + private static let compilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("\(moduleName)-\(UUID().uuidString)") @@ -251,13 +251,7 @@ package enum RenamedObjCClassFixture { package static func machOFile(_ variant: Variant) throws -> MachOFile { let libraryURL = try libraryURL(variant) - switch try MachOKit.loadFromFile(url: libraryURL) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } + return try HostSlice.machOFile(at: libraryURL) } /// The `.full` client loaded into the test process — only that variant: diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/Swift64DeclarationShapesFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/Swift64DeclarationShapesFixture.swift index 2feab426c..8e065ee7e 100644 --- a/Sources/TestSupport/SwiftSectionTestingSupport/Swift64DeclarationShapesFixture.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/Swift64DeclarationShapesFixture.swift @@ -199,7 +199,7 @@ package enum Swift64DeclarationShapesFixture { } /// Compiled once per process. - private static let compilationResult: Result = { + private static let compilationResult: Result = { Result { guard let toolchain else { throw CompilationError(diagnostics: "no Swift 6.4 or newer toolchain is installed") @@ -226,12 +226,6 @@ package enum Swift64DeclarationShapesFixture { }() package static func machOFile() throws -> MachOFile { - switch try MachOKit.loadFromFile(url: try compilationResult.get()) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } + return try HostSlice.machOFile(at: compilationResult.get()) } } diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/SwiftDeclaredObjCProtocolsFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/SwiftDeclaredObjCProtocolsFixture.swift index 7dec3ae05..e669b1878 100644 --- a/Sources/TestSupport/SwiftSectionTestingSupport/SwiftDeclaredObjCProtocolsFixture.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/SwiftDeclaredObjCProtocolsFixture.swift @@ -204,7 +204,7 @@ package enum SwiftDeclaredObjCProtocolsFixture { } /// Compiled once per process; every variant shares one working directory. - private static let compilationResult: Result = { + private static let compilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("\(moduleName)-\(UUID().uuidString)") @@ -285,13 +285,7 @@ package enum SwiftDeclaredObjCProtocolsFixture { package static func machOFile(_ variant: Variant) throws -> MachOFile { let libraryURL = try libraryURL(variant) - switch try MachOKit.loadFromFile(url: libraryURL) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } + return try HostSlice.machOFile(at: libraryURL) } /// The `.full` client loaded into the test process — only that variant: diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/TestActor.swift b/Sources/TestSupport/SwiftSectionTestingSupport/TestActor.swift deleted file mode 100644 index 86f461b3b..000000000 --- a/Sources/TestSupport/SwiftSectionTestingSupport/TestActor.swift +++ /dev/null @@ -1,6 +0,0 @@ -import Foundation - -@globalActor -public actor TestActor { - public static let shared = TestActor() -} diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/ThunkOnlyMemberFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/ThunkOnlyMemberFixture.swift index 9bddb5894..2d5d8f758 100644 --- a/Sources/TestSupport/SwiftSectionTestingSupport/ThunkOnlyMemberFixture.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/ThunkOnlyMemberFixture.swift @@ -129,7 +129,7 @@ package enum ThunkOnlyMemberFixture { } /// Compiled once per process; both variants share one working directory. - private static let compilationResult: Result<[Variant: URL], Swift.Error> = { + private static let compilationResult: Result<[Variant: URL], any Swift.Error> = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("\(moduleName)-\(UUID().uuidString)") @@ -183,13 +183,7 @@ package enum ThunkOnlyMemberFixture { } package static func machOFile(_ variant: Variant) throws -> MachOFile { - switch try MachOKit.loadFromFile(url: try libraryURL(variant)) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } + return try HostSlice.machOFile(at: libraryURL(variant)) } /// The `.wholeModuleOptimized` build loaded into the test process — only diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/UnobservablePresenceFixture.swift b/Sources/TestSupport/SwiftSectionTestingSupport/UnobservablePresenceFixture.swift index cb3188450..3ed5ba37c 100644 --- a/Sources/TestSupport/SwiftSectionTestingSupport/UnobservablePresenceFixture.swift +++ b/Sources/TestSupport/SwiftSectionTestingSupport/UnobservablePresenceFixture.swift @@ -167,7 +167,7 @@ package enum UnobservablePresenceFixture { } /// Compiled once per process; the versions share one working directory. - private static let compilationResult: Result<[URL], Swift.Error> = { + private static let compilationResult: Result<[URL], any Swift.Error> = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("\(moduleName)-\(UUID().uuidString)") @@ -220,13 +220,7 @@ package enum UnobservablePresenceFixture { /// The compiled versions as readers, oldest first. package static func machOFiles() throws -> [MachOFile] { try libraryURLs().map { libraryURL in - switch try MachOKit.loadFromFile(url: libraryURL) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } + return try HostSlice.machOFile(at: libraryURL) } } } diff --git a/Sources/TestSupport/SwiftSectionTestingSupport/XcodeMachOFileTests.swift b/Sources/TestSupport/SwiftSectionTestingSupport/XcodeMachOFileTests.swift deleted file mode 100644 index 520cef0ae..000000000 --- a/Sources/TestSupport/SwiftSectionTestingSupport/XcodeMachOFileTests.swift +++ /dev/null @@ -1,25 +0,0 @@ -import Foundation -import Testing -import MachOKit -import MachOFoundation -import SwiftSectionFixtureSupport - -package class XcodeMachOFileTests { - package let machOFile: MachOFile - - package class var fileName: XcodeMachOFileName { .sharedFrameworks(.DNTDocumentationModel) } - - package class var preferredArchitecture: CPUType { .arm64 } - - package init() async throws { - let file = try File.loadFromFile(url: Self.fileName.url) - switch file { - case .fat(let fatFile): - self.machOFile = try required(fatFile.machOFiles().first(where: { $0.header.cpuType == Self.preferredArchitecture }) ?? fatFile.machOFiles().first) - case .machO(let machO): - self.machOFile = machO - @unknown default: - fatalError() - } - } -} diff --git a/Tests/CrossReferenceAnalysisTests/ClassOfReceiverSendTests.swift b/Tests/CrossReferenceAnalysisTests/ClassOfReceiverSendTests.swift index 3f60219c6..f964789fb 100644 --- a/Tests/CrossReferenceAnalysisTests/ClassOfReceiverSendTests.swift +++ b/Tests/CrossReferenceAnalysisTests/ClassOfReceiverSendTests.swift @@ -21,7 +21,7 @@ struct ClassOfReceiverSendTests { private static let fixture = Result { // Without ARC, so no call the compiler adds stands among them. try CompiledFixture.load( - libraryName: "libCrossReferenceClassOfReceiver.dylib", + named: "CrossReferenceClassOfReceiver", sources: [ "ClassOfReceiver.m": """ #import diff --git a/Tests/CrossReferenceAnalysisTests/CompiledFixture.swift b/Tests/CrossReferenceAnalysisTests/CompiledFixture.swift index 310217b5f..e18e7e29c 100644 --- a/Tests/CrossReferenceAnalysisTests/CompiledFixture.swift +++ b/Tests/CrossReferenceAnalysisTests/CompiledFixture.swift @@ -1,38 +1,42 @@ import Foundation import MachOKit +import SwiftSectionFixtureSupport @_spi(Internals) import MachOCodeReferences @_spi(Internals) import ObjCCodeReferences /// A dynamic library compiled from source for one suite, rewritten after -/// linking when the suite asks, and loaded into the test process. +/// linking when the suite asks, and loaded into the test process. Suites that +/// only read a compiled binary as a file call `FixtureCompiler` directly. enum CompiledFixture { struct Failure: Error, CustomStringConvertible { let description: String } /// Compiles `sources` — file names and their contents — into the arm64 - /// library `libraryName`, hands the linked bytes to `rewrite` and signs - /// the result again when there is one, and loads it. The library stays - /// loaded after its directory is removed; the analyzers made from then on - /// see it under the path this returns. + /// library `lib.dylib` through the shared compiler, copies it to a + /// directory of its own, hands the copied bytes to `rewrite` and signs the + /// result again when there is one, and loads the copy. The compiled + /// library is shared by every test, so it is never rewritten itself. The + /// copy stays loaded after its directory is removed; the analyzers made + /// from then on see it under the path this returns. @discardableResult static func load( - libraryName: String, + named name: String, sources: KeyValuePairs, compilerArguments: [String], rewrite: ((inout Data, MachOFile) throws -> Void)? = nil ) throws -> String { + let compiledLibrary = try FixtureCompiler.shared.dynamicLibrary( + named: name, + language: .c, + sourceFiles: sources.map { FixtureSourceFile(name: $0.key, contents: $0.value) }, + arguments: ["-arch", "arm64"] + compilerArguments + ) let directory = FileManager.default.temporaryDirectory.appendingPathComponent("CrossReferenceAnalysisTests-\(UUID().uuidString)") try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) defer { try? FileManager.default.removeItem(at: directory) } - var sourcePaths: [String] = [] - for (fileName, contents) in sources { - let sourceURL = directory.appendingPathComponent(fileName) - try contents.write(to: sourceURL, atomically: true, encoding: .utf8) - sourcePaths.append(sourceURL.path) - } - let library = directory.appendingPathComponent(libraryName) - try run("/usr/bin/xcrun", arguments: ["clang", "-dynamiclib", "-arch", "arm64"] + compilerArguments + ["-o", library.path] + sourcePaths) + let library = directory.appendingPathComponent(compiledLibrary.lastPathComponent) + try FileManager.default.copyItem(at: compiledLibrary, to: library) if let rewrite { var bytes = try Data(contentsOf: library) try rewrite(&bytes, try MachOFile(url: library)) @@ -41,46 +45,11 @@ enum CompiledFixture { try run("/usr/bin/codesign", arguments: ["--force", "--sign", "-", library.path]) } guard dlopen(library.path, RTLD_NOW | RTLD_LOCAL) != nil else { - throw Failure(description: "could not load \(libraryName): \(dlerror().map { String(cString: $0) } ?? "")") + throw Failure(description: "could not load \(library.lastPathComponent): \(dlerror().map { String(cString: $0) } ?? "")") } return library.path } - /// Compiles `sources` into the arm64 library `libraryName` and leaves it - /// on disk, unloaded, for a suite that reads it as a file. The caller - /// removes `directory`. - static func build( - libraryName: String, - sources: KeyValuePairs, - compilerArguments: [String], - architecture: String = "arm64", - isExecutable: Bool = false - ) throws -> (directory: URL, library: URL) { - let directory = FileManager.default.temporaryDirectory.appendingPathComponent("CrossReferenceAnalysisTests-\(UUID().uuidString)") - try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) - var sourcePaths: [String] = [] - for (fileName, contents) in sources { - let sourceURL = directory.appendingPathComponent(fileName) - try contents.write(to: sourceURL, atomically: true, encoding: .utf8) - sourcePaths.append(sourceURL.path) - } - let library = directory.appendingPathComponent(libraryName) - try run("/usr/bin/xcrun", arguments: ["clang"] + (isExecutable ? [] : ["-dynamiclib"]) + ["-arch", architecture] + compilerArguments + ["-o", library.path] + sourcePaths) - return (directory, library) - } - - /// Compiles one Swift source into the arm64 library `libraryName`, - /// optimized, and leaves it on disk. The caller removes `directory`. - static func buildSwift(libraryName: String, source: String) throws -> (directory: URL, library: URL) { - let directory = FileManager.default.temporaryDirectory.appendingPathComponent("CrossReferenceAnalysisTests-\(UUID().uuidString)") - try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) - let sourceURL = directory.appendingPathComponent("Fixture.swift") - try source.write(to: sourceURL, atomically: true, encoding: .utf8) - let library = directory.appendingPathComponent(libraryName) - try run("/usr/bin/xcrun", arguments: ["swiftc", "-O", "-emit-library", "-target", "arm64-apple-macos14", "-module-name", "Fixture", "-o", library.path, sourceURL.path]) - return (directory, library) - } - private static func run(_ executablePath: String, arguments: [String]) throws { let process = Process() process.executableURL = URL(fileURLWithPath: executablePath) diff --git a/Tests/CrossReferenceAnalysisTests/CrossReferenceAnalyzerTests.swift b/Tests/CrossReferenceAnalysisTests/CrossReferenceAnalyzerTests.swift index a131cb419..6888c0f7e 100644 --- a/Tests/CrossReferenceAnalysisTests/CrossReferenceAnalyzerTests.swift +++ b/Tests/CrossReferenceAnalysisTests/CrossReferenceAnalyzerTests.swift @@ -256,7 +256,7 @@ struct CrossReferenceAnalyzerTests { private func imagesReferencing(_ keys: Set, among imageIndices: [Int]) -> Set { let found = ImageIndexCollector() let analyzer = analyzer - DispatchQueue.concurrentPerform(iterations: imageIndices.count) { position in + ImageScanConcurrency.concurrentPerform(iterations: imageIndices.count) { position in let imageIndex = imageIndices[position] if !analyzer.references(to: keys, inImageAt: imageIndex).isEmpty { found.insert(imageIndex) } } diff --git a/Tests/CrossReferenceAnalysisTests/FileModeTests.swift b/Tests/CrossReferenceAnalysisTests/FileModeTests.swift index 3a54295ad..f3a3efdfa 100644 --- a/Tests/CrossReferenceAnalysisTests/FileModeTests.swift +++ b/Tests/CrossReferenceAnalysisTests/FileModeTests.swift @@ -1,6 +1,7 @@ import Foundation import Testing import MachOKit +import SwiftSectionFixtureSupport import MachOKitExtensions @_spi(Internals) import MachOCodeReferences @_spi(Internals) import ObjCCodeReferences @@ -192,16 +193,16 @@ struct FileModeTests { /// slot binds by name, to itself. The bind leads to the function; a call /// into a library the analyzer does not cover stays an imported name. @Test func standaloneAppResolvesImportedAndSelfBoundSymbols() throws { - let (directory, library) = try CompiledFixture.build( - libraryName: "libSelfBound.dylib", - sources: ["SelfBound.c": """ + let library = try FixtureCompiler.shared.dynamicLibrary( + named: "SelfBound", + language: .c, + sourceFiles: [FixtureSourceFile(name: "SelfBound.c", contents: """ #include __attribute__((noinline)) int selfBoundCallee(int value) { return value * 3; } int selfBoundCaller(int value) { puts("called"); return selfBoundCallee(value) + 1; } - """], - compilerArguments: ["-O1", "-Wl,-interposable"] + """)], + arguments: ["-arch", "arm64", "-O1", "-Wl,-interposable"] ) - defer { try? FileManager.default.removeItem(at: directory) } let analyzer = try CrossReferenceAnalyzer(machOFiles: [MachOFile(url: library)]) #expect(analyzer.imageCount == 1) #expect(analyzer.images.isEmpty) @@ -220,19 +221,18 @@ struct FileModeTests { /// start, so the cleanup's calls are found: `_Unwind_Resume` is called /// nowhere else. @Test func fileModeScansExceptionCleanupCodeAfterReturn() throws { - let (directory, library) = try CompiledFixture.build( - libraryName: "libCleanup.dylib", - sources: ["Cleanup.cpp": """ + let library = try FixtureCompiler.shared.dynamicLibrary( + named: "Cleanup", + language: .c, + sourceFiles: [FixtureSourceFile(name: "Cleanup.cpp", contents: """ #include extern "C" __attribute__((noinline)) void cleanupCallee(void) { asm volatile(""); } struct Guard { ~Guard() { cleanupCallee(); } }; __attribute__((noinline)) void mayThrow(int value) { if (value > 3) throw std::runtime_error("too large"); } extern "C" int withCleanup(int value) { Guard guard; mayThrow(value); return value + 1; } - """], - compilerArguments: ["-O1", "-lc++"], - architecture: "arm64e" + """)], + arguments: ["-arch", "arm64e", "-O1", "-lc++"] ) - defer { try? FileManager.default.removeItem(at: directory) } let analyzer = try CrossReferenceAnalyzer(machOFiles: [MachOFile(url: library)]) let withCleanup = try #require(analyzer.functions(inImageAt: 0).first { $0.name == .symbol("_withCleanup") }) let references = analyzer.references(madeBy: withCleanup) @@ -294,9 +294,10 @@ struct FileModeTests { /// selector references of `__objc_stubs` then lead nowhere, and every /// send through one reads as an unrecognized call. @Test func standaloneExecutableResolvesRebasesAndObjectiveCStubs() throws { - let (directory, executable) = try CompiledFixture.build( - libraryName: "ObjectiveCExecutable", - sources: ["Main.m": """ + let executable = try FixtureCompiler.shared.executable( + named: "ObjectiveCExecutable", + language: .c, + sourceFiles: [FixtureSourceFile(name: "Main.m", contents: """ #import __attribute__((noinline)) static void target(void) { asm volatile(""); } void (*volatile functionPointer)(void) = target; @@ -308,11 +309,9 @@ struct FileModeTests { return (int)[array count]; } } - """], - compilerArguments: ["-O1", "-fobjc-arc", "-framework", "Foundation"], - isExecutable: true + """)], + arguments: ["-arch", "arm64", "-O1", "-fobjc-arc", "-framework", "Foundation"] ) - defer { try? FileManager.default.removeItem(at: directory) } let file = try MachOFile(url: executable) let analyzer = try CrossReferenceAnalyzer(machOFiles: [file]) let main = try #require(analyzer.functions(inImageAt: 0).first { $0.name == .symbol("_main") }) diff --git a/Tests/CrossReferenceAnalysisTests/FunctionAddressReferenceTests.swift b/Tests/CrossReferenceAnalysisTests/FunctionAddressReferenceTests.swift new file mode 100644 index 000000000..aa4b3a02f --- /dev/null +++ b/Tests/CrossReferenceAnalysisTests/FunctionAddressReferenceTests.swift @@ -0,0 +1,67 @@ +import Foundation +import Testing +import MachOKit +import SwiftSectionFixtureSupport +@_spi(Internals) import MachOCodeReferences +@testable import CrossReferenceAnalysis + +/// Code that builds a function's address references the function, and a +/// query for the function's callers lists it beside the calls (evolution +/// proposal `cross-reference-recall-gaps`): the callback handed to +/// `dispatch_async_f`, the invoke function of a block built on the stack. +@Suite +struct FunctionAddressReferenceTests { + private static let source = """ + #include + extern void consume(int value); + __attribute__((noinline)) void work(void *context) { consume((int)(long)context); } + void scheduleWork(void) { dispatch_async_f(dispatch_get_main_queue(), 0, work); } + void callWork(void) { work(0); } + void scheduleBlock(int value) { dispatch_async(dispatch_get_main_queue(), ^{ consume(value); }); } + """ + + private static func analyzer() throws -> CrossReferenceAnalyzer { + let library = try FixtureCompiler.shared.dynamicLibrary( + named: "FunctionAddressReferences", + language: .c, + sourceFiles: [FixtureSourceFile(name: "FunctionAddressReferences.c", contents: source)], + arguments: ["-arch", "arm64", "-O2", "-fblocks", "-Wl,-undefined,dynamic_lookup"] + ) + return try CrossReferenceAnalyzer(machOFiles: [MachOFile(url: library)]) + } + + private static func function(where matches: (String) -> Bool, in analyzer: CrossReferenceAnalyzer) throws -> CodeFunction { + try #require(analyzer.functions(inImageAt: 0).first { if case .symbol(let symbol)? = $0.name { matches(symbol) } else { false } }) + } + + @Test func functionQueriesReturnCallsAndAddressTakingSites() throws { + let analyzer = try Self.analyzer() + let work = try Self.function(where: { $0 == "_work" }, in: analyzer) + let scheduleWork = try Self.function(where: { $0 == "_scheduleWork" }, in: analyzer) + let callWork = try Self.function(where: { $0 == "_callWork" }, in: analyzer) + let references = analyzer.references(to: [.function(work.location)], inImageAt: 0) + // `callWork` calls it, or branches to it. + #expect(references.contains { $0.function == callWork.location && $0.kind != .reference }) + // `scheduleWork` builds its address for `dispatch_async_f`. + let taken = references.filter { $0.function == scheduleWork.location } + #expect(taken.count == 1) + #expect(taken.first?.kind == .reference) + #expect(taken.first?.route == .addressMaterialization) + } + + @Test func aStackBlockIsReferencedByTheFunctionThatBuildsIt() throws { + let analyzer = try Self.analyzer() + let scheduleBlock = try Self.function(where: { $0 == "_scheduleBlock" }, in: analyzer) + let invoke = try Self.function(where: { $0.hasPrefix("___scheduleBlock_block_invoke") }, in: analyzer) + let references = analyzer.references(to: [.function(invoke.location)], inImageAt: 0) + #expect(references.contains { $0.function == scheduleBlock.location && $0.kind == .reference }) + } + + /// The whole image's table carries them too. + @Test func theWholeTableHoldsFunctionAddressReferences() throws { + let analyzer = try Self.analyzer() + let work = try Self.function(where: { $0 == "_work" }, in: analyzer) + let table = analyzer.referenceTable(ofImageAt: 0) + #expect(table.references(to: .function(work.location)).contains { $0.kind == .reference }) + } +} diff --git a/Tests/CrossReferenceAnalysisTests/FunctionStartOutsideTextTests.swift b/Tests/CrossReferenceAnalysisTests/FunctionStartOutsideTextTests.swift index cb5e7a734..4aa11ba15 100644 --- a/Tests/CrossReferenceAnalysisTests/FunctionStartOutsideTextTests.swift +++ b/Tests/CrossReferenceAnalysisTests/FunctionStartOutsideTextTests.swift @@ -1,5 +1,7 @@ import Foundation import Testing +import MachOKit +import SwiftSectionFixtureSupport @testable import CrossReferenceAnalysis @_spi(Internals) import MachOCodeReferences @_spi(Internals) import ObjCCodeReferences @@ -9,7 +11,6 @@ import Testing /// always did; reading it at an offset from `__text` underflowed and trapped /// the first scan of every image of the macOS 27.2 cache (the throughput /// benchmark of the layer split, 2026-11-19). -@Suite(.enabled(if: SharedAnalyzer.analyzer != nil, "needs an arm64 process with a dyld shared cache")) struct FunctionStartOutsideTextTests { private var analyzer: CrossReferenceAnalyzer { SharedAnalyzer.analyzer! } @@ -21,14 +22,15 @@ struct FunctionStartOutsideTextTests { defer { flags.deallocate() } nonisolated(unsafe) let flagsBase = flags.baseAddress! let analyzer = self.analyzer - DispatchQueue.concurrentPerform(iterations: imageCount) { imageIndex in + ImageScanConcurrency.concurrentPerform(iterations: imageCount) { imageIndex in let table = analyzer.imageSet.transientFunctionTable(ofImageAt: imageIndex) (flagsBase + imageIndex).pointee = table.starts.contains { $0 < table.textStart || $0 >= table.textEnd } } return (0 ..< imageCount).filter { flags[$0] } } - @Test func aFunctionStartingOutsideTextScansWhereItLies() throws { + @Test(.enabled(if: SharedAnalyzer.analyzer != nil, "needs an arm64 process with a dyld shared cache")) + func aFunctionStartingOutsideTextScansWhereItLies() throws { let images = imagesWithAStartOutsideText() try #require(!images.isEmpty, "no image of this system's cache has a function start outside __text") for imageIndex in images.prefix(3) { @@ -36,4 +38,61 @@ struct FunctionStartOutsideTextTests { #expect(table.imageIndex == imageIndex, "\(analyzer.imagePaths[imageIndex])") } } + + /// A main executable's symbol table files `__mh_execute_header` — the + /// Mach header itself, at the start of `__TEXT` — under `__text`, so the + /// header and the load commands scan as a function below the section. + /// An index counted its offsets from `__text` and could not hold a + /// reference made there: a Debug build trapped on its assertion, and a + /// Release build stored the offset truncated and named a function 4 GiB + /// away (RuntimeViewer indexing iOS 27's `Preferences`, 2026-11-20). A + /// call planted in the padding before `__text` stands for whatever the + /// load commands happen to decode to. + @Test func anIndexKeepsTheReferencesOfAFunctionBelowText() throws { + let executable = try FixtureCompiler.shared.executable( + named: "Executable", + language: .c, + sourceFiles: [FixtureSourceFile(name: "Main.c", contents: """ + __attribute__((noinline)) void target(void) { __asm__ volatile(""); } + int main(void) { + target(); + return 0; + } + """)], + arguments: ["-arch", "arm64", "-O1"] + ) + let linked = try MachOFile(url: executable) + let textSection = try #require(linked.sections64.first { $0.segmentName == "__TEXT" && $0.sectionName == "__text" }) + let loadCommandsEnd = MemoryLayout.size + Int(linked.header.sizeofcmds) + let siteOffset = textSection.offset - 4 + try #require(siteOffset >= loadCommandsEnd, "no padding between the load commands and __text") + let siteAddress = UInt64(textSection.address) - 4 + let linkedAnalyzer = try CrossReferenceAnalyzer(machOFiles: [linked]) + let target = try #require(linkedAnalyzer.functions(inImageAt: 0).first { $0.name == .symbol("_target") }) + var bytes = try Data(contentsOf: executable) + let call = InstructionEncoding.branchWithLink(at: siteAddress, to: target.location.address) + withUnsafeBytes(of: call.littleEndian) { bytes.replaceSubrange(siteOffset ..< siteOffset + 4, with: $0) } + // The compiled executable is shared by every test; the patched copy + // goes to a directory of its own. + let directory = FileManager.default.temporaryDirectory.appendingPathComponent("CrossReferenceAnalysisTests-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + let patched = directory.appendingPathComponent("PatchedExecutable") + try bytes.write(to: patched) + + let analyzer = try CrossReferenceAnalyzer(machOFiles: [MachOFile(url: patched)]) + let functionTable = analyzer.imageSet.transientFunctionTable(ofImageAt: 0) + let headerFunction = try #require(functionTable.starts.first) + try #require(headerFunction < functionTable.textStart, "the executable's first function start lies in __text") + let table = analyzer.referenceTable(ofImageAt: 0) + let plantedCall = table.references(to: .function(target.location)).first { $0.instructionAddress == siteAddress } + #expect(plantedCall?.function.address == headerFunction, "\(table.references(to: .function(target.location)))") + + let index = analyzer.referenceIndex(ofImageAt: 0) + var mismatchedKeys: [CodeReferenceTable.Key] = [] + for key in table.keys where index.references(to: [key]) != table.references(to: key) { + mismatchedKeys.append(key) + } + #expect(mismatchedKeys.isEmpty, "\(mismatchedKeys)") + } } diff --git a/Tests/CrossReferenceAnalysisTests/ImageScanConcurrency.swift b/Tests/CrossReferenceAnalysisTests/ImageScanConcurrency.swift new file mode 100644 index 000000000..02a286a44 --- /dev/null +++ b/Tests/CrossReferenceAnalysisTests/ImageScanConcurrency.swift @@ -0,0 +1,63 @@ +import Foundation + +/// How many images this target's parallel scans may read at once: half of the +/// cores, at least two. +/// +/// A Debug scan of the whole shared cache keeps every core it is given busy +/// for minutes, and Swift Testing runs the suites holding these scans in +/// parallel. The budget is therefore one for the whole process, not one per +/// call: four suites with a width each would add up to every core again +/// (evolution proposal `cross-reference-test-scan-load`). +/// `ParallelScanSourceTests` keeps every parallel scan of the target on it. +enum ImageScanConcurrency { + static let maximumConcurrentScans = max(2, ProcessInfo.processInfo.activeProcessorCount / 2) + + private static let permits = DispatchSemaphore(value: maximumConcurrentScans) + + /// Runs `body` once for every index in `0 ..< iterations`, as + /// `DispatchQueue.concurrentPerform(iterations:execute:)` does, with at + /// most `maximumConcurrentScans` bodies running at once across the + /// process. + /// + /// Each call starts no more workers than the budget, so the threads + /// waiting for a permit stay bounded; each worker takes the next index and + /// holds a permit only while its body runs. A permit is never held across + /// a wait for other work, so the callers — the calling thread of + /// `concurrentPerform` may be a cooperative thread — always get one in the + /// end. + /// + /// `body` must not call this function again: a nested call waits for a + /// permit while its caller holds one, and with every permit held that way + /// none is ever released. + static func concurrentPerform(iterations: Int, execute body: (Int) -> Void) { + guard iterations > 0 else { return } + let cursor = IterationCursor(iterationCount: iterations) + DispatchQueue.concurrentPerform(iterations: min(maximumConcurrentScans, iterations)) { _ in + while let index = cursor.next() { + permits.wait() + defer { permits.signal() } + body(index) + } + } + } +} + +/// Hands out each index of `0 ..< iterationCount` once, to whichever worker +/// asks first. +private final class IterationCursor: @unchecked Sendable { + private let lock = NSLock() + private let iterationCount: Int + private var nextIndex = 0 + + init(iterationCount: Int) { + self.iterationCount = iterationCount + } + + func next() -> Int? { + lock.lock() + defer { lock.unlock() } + guard nextIndex < iterationCount else { return nil } + defer { nextIndex += 1 } + return nextIndex + } +} diff --git a/Tests/CrossReferenceAnalysisTests/ImageScanConcurrencyTests.swift b/Tests/CrossReferenceAnalysisTests/ImageScanConcurrencyTests.swift new file mode 100644 index 000000000..b82c73fe7 --- /dev/null +++ b/Tests/CrossReferenceAnalysisTests/ImageScanConcurrencyTests.swift @@ -0,0 +1,107 @@ +import Foundation +import Testing + +/// Pins `ImageScanConcurrency` (evolution proposal +/// `cross-reference-test-scan-load`): every index runs once, and no more +/// bodies run at once than the budget — within one call, and across calls +/// made at the same time, which is what Swift Testing's parallel suites do. +@Suite +struct ImageScanConcurrencyTests { + @Test func everyIterationRunsExactlyOnce() { + let runs = RunCounter(iterationCount: 1000) + ImageScanConcurrency.concurrentPerform(iterations: 1000) { index in + runs.record(index) + } + #expect(runs.indicesNotRunExactlyOnce.isEmpty) + } + + @Test func noMoreThanTheBudgetRunAtOnce() { + let tracker = InFlightTracker() + ImageScanConcurrency.concurrentPerform(iterations: 300) { _ in + tracker.run { Thread.sleep(forTimeInterval: 0.002) } + } + #expect(tracker.completedCount == 300) + #expect(tracker.peak <= ImageScanConcurrency.maximumConcurrentScans) + } + + /// The other call runs on a thread of its own, never on a pool thread + /// this test would block waiting for. + @Test func twoCallsAtOnceShareTheBudget() { + let tracker = InFlightTracker() + let otherCallFinished = DispatchSemaphore(value: 0) + Thread { + ImageScanConcurrency.concurrentPerform(iterations: 300) { _ in + tracker.run { Thread.sleep(forTimeInterval: 0.002) } + } + otherCallFinished.signal() + }.start() + ImageScanConcurrency.concurrentPerform(iterations: 300) { _ in + tracker.run { Thread.sleep(forTimeInterval: 0.002) } + } + otherCallFinished.wait() + #expect(tracker.completedCount == 600) + #expect(tracker.peak <= ImageScanConcurrency.maximumConcurrentScans) + } + + @Test func zeroIterationsReturnWithoutRunning() { + let tracker = InFlightTracker() + ImageScanConcurrency.concurrentPerform(iterations: 0) { _ in + tracker.run {} + } + #expect(tracker.completedCount == 0) + } +} + +/// How many times each index ran. +private final class RunCounter: @unchecked Sendable { + private let lock = NSLock() + private var counts: [Int] + + init(iterationCount: Int) { + counts = Array(repeating: 0, count: iterationCount) + } + + func record(_ index: Int) { + lock.lock() + defer { lock.unlock() } + counts[index] += 1 + } + + var indicesNotRunExactlyOnce: [Int] { + lock.lock() + defer { lock.unlock() } + return counts.indices.filter { counts[$0] != 1 } + } +} + +/// The most bodies seen running at once, and how many finished. +private final class InFlightTracker: @unchecked Sendable { + private let lock = NSLock() + private var running = 0 + private var highestRunning = 0 + private var completed = 0 + + func run(_ body: () -> Void) { + lock.lock() + running += 1 + highestRunning = max(highestRunning, running) + lock.unlock() + body() + lock.lock() + running -= 1 + completed += 1 + lock.unlock() + } + + var peak: Int { + lock.lock() + defer { lock.unlock() } + return highestRunning + } + + var completedCount: Int { + lock.lock() + defer { lock.unlock() } + return completed + } +} diff --git a/Tests/CrossReferenceAnalysisTests/LazyBindingTests.swift b/Tests/CrossReferenceAnalysisTests/LazyBindingTests.swift index db5fb296c..277081773 100644 --- a/Tests/CrossReferenceAnalysisTests/LazyBindingTests.swift +++ b/Tests/CrossReferenceAnalysisTests/LazyBindingTests.swift @@ -1,5 +1,6 @@ import Foundation import Testing +import SwiftSectionFixtureSupport @testable import CrossReferenceAnalysis @_spi(Internals) import MachOCodeReferences @_spi(Internals) import ObjCCodeReferences @@ -15,24 +16,16 @@ import Testing @Suite(.enabled(if: SharedAnalyzer.analyzer != nil, "needs an arm64 process with a dyld shared cache")) struct LazyBindingTests { @Test func aLazilyBoundStubReachesItsTarget() throws { - let directory = FileManager.default.temporaryDirectory.appendingPathComponent("CrossReferenceAnalysisTests-\(UUID().uuidString)") - try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) - defer { try? FileManager.default.removeItem(at: directory) } - let source = directory.appendingPathComponent("LazyBinding.c") - try "#include \nvoid crossReferenceLazyBindingCall(void) { puts(\"called\"); }\n".write(to: source, atomically: true, encoding: .utf8) - let library = directory.appendingPathComponent("libLazyBinding.dylib") - - let compiler = Process() - compiler.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") - compiler.arguments = [ - "clang", "-dynamiclib", "-arch", "arm64", "-O1", - // Classic dyld info rather than chained fixups: lazy pointers and a __stub_helper. - "-mmacosx-version-min=11.0", "-Wl,-no_fixup_chains", - "-o", library.path, source.path, - ] - try compiler.run() - compiler.waitUntilExit() - try #require(compiler.terminationStatus == 0, "could not build the lazily bound fixture") + let library = try FixtureCompiler.shared.dynamicLibrary( + named: "LazyBinding", + language: .c, + sourceFiles: [FixtureSourceFile(name: "LazyBinding.c", contents: "#include \nvoid crossReferenceLazyBindingCall(void) { puts(\"called\"); }\n")], + arguments: [ + "-arch", "arm64", "-O1", + // Classic dyld info rather than chained fixups: lazy pointers and a __stub_helper. + "-mmacosx-version-min=11.0", "-Wl,-no_fixup_chains", + ] + ) _ = try #require(dlopen(library.path, RTLD_LAZY | RTLD_LOCAL)) let analyzer = try #require(CrossReferenceAnalyzer()) diff --git a/Tests/CrossReferenceAnalysisTests/LinkerOptimizationHintTests.swift b/Tests/CrossReferenceAnalysisTests/LinkerOptimizationHintTests.swift index 82d5d6ace..e06ee55cb 100644 --- a/Tests/CrossReferenceAnalysisTests/LinkerOptimizationHintTests.swift +++ b/Tests/CrossReferenceAnalysisTests/LinkerOptimizationHintTests.swift @@ -36,7 +36,7 @@ struct LinkerOptimizationHintTests { /// Both libraries, loaded before the analyzer that reads them is made. private static let fixtures = Result { try CompiledFixture.load( - libraryName: "libCrossReferenceLinkerHints.dylib", + named: "CrossReferenceLinkerHints", sources: [ "Probe.m": """ #import @@ -75,7 +75,7 @@ struct LinkerOptimizationHintTests { // A stub is shared by every call to its function, so the stub fixture // imports nothing a send needs. try CompiledFixture.load( - libraryName: "libCrossReferenceRewrittenStub.dylib", + named: "CrossReferenceRewrittenStub", sources: ["Stub.c": "#include \nvoid crossReferenceCallsThroughARewrittenStub(void) { puts(\"called\"); }\n"], compilerArguments: ["-O1", "-mmacosx-version-min=12.0"] ) { bytes, machO in diff --git a/Tests/CrossReferenceAnalysisTests/ObjectiveCClassReferenceTests.swift b/Tests/CrossReferenceAnalysisTests/ObjectiveCClassReferenceTests.swift index 038d13eea..a4e987fed 100644 --- a/Tests/CrossReferenceAnalysisTests/ObjectiveCClassReferenceTests.swift +++ b/Tests/CrossReferenceAnalysisTests/ObjectiveCClassReferenceTests.swift @@ -193,7 +193,7 @@ struct ObjectiveCClassReferenceTests { private func imagesReferencing(_ className: String, at location: CodeLocation, among imageIndices: [Int]) -> Set { let found = ImageIndexCollector() let analyzer = analyzer - DispatchQueue.concurrentPerform(iterations: imageIndices.count) { position in + ImageScanConcurrency.concurrentPerform(iterations: imageIndices.count) { position in let imageIndex = imageIndices[position] let references = analyzer.references(to: [.objectiveCClass(className)], inImageAt: imageIndex) if references.contains(where: { $0.target == .objectiveCClass(name: className, location: location) }) { found.insert(imageIndex) } diff --git a/Tests/CrossReferenceAnalysisTests/ParallelScanSourceTests.swift b/Tests/CrossReferenceAnalysisTests/ParallelScanSourceTests.swift new file mode 100644 index 000000000..5c82d52f0 --- /dev/null +++ b/Tests/CrossReferenceAnalysisTests/ParallelScanSourceTests.swift @@ -0,0 +1,53 @@ +import Foundation +import Testing + +/// Every parallel scan of this target goes through `ImageScanConcurrency`, +/// whose one budget keeps the suites Swift Testing runs at once from taking +/// every core between them (evolution proposal +/// `cross-reference-test-scan-load`). The throughput benchmark is the +/// exception: it measures the scan on every core, and runs only when asked. +@Suite +struct ParallelScanSourceTests { + /// The budget itself, the benchmark, and this file, whose discrimination + /// test spells the call it looks for. + private static let filesAllowedToCallDispatchDirectly: Set = [ + "ImageScanConcurrency.swift", + "ScanThroughputBenchmarkTests.swift", + "ParallelScanSourceTests.swift", + ] + + @Test func everyParallelScanGoesThroughTheSharedBudget() throws { + let fileURLs = try Self.targetSourceFiles() + try #require(fileURLs.contains { $0.lastPathComponent == "ImageScanConcurrency.swift" }, "not this target's directory") + var offendingLines: [String] = [] + for fileURL in fileURLs where !Self.filesAllowedToCallDispatchDirectly.contains(fileURL.lastPathComponent) { + let contents = try String(contentsOf: fileURL, encoding: .utf8) + for (lineNumber, line) in contents.components(separatedBy: .newlines).enumerated() { + let code = line.trimmingCharacters(in: .whitespaces) + guard !code.hasPrefix("//"), Self.callsDispatchDirectly(code) else { continue } + offendingLines.append("\(fileURL.lastPathComponent):\(lineNumber + 1): \(code)") + } + } + #expect(offendingLines.isEmpty, "scan through `ImageScanConcurrency.concurrentPerform`:\n\(offendingLines.joined(separator: "\n"))") + } + + /// The scan must see a direct call, and nothing else — its silence proves + /// nothing otherwise. + @Test func theScanDiscriminates() { + #expect(Self.callsDispatchDirectly("DispatchQueue.concurrentPerform(iterations: imageIndices.count) { position in")) + #expect(Self.callsDispatchDirectly("DispatchQueue.concurrentPerform(iterations: imageCount, execute: readTrie)")) + #expect(!Self.callsDispatchDirectly("ImageScanConcurrency.concurrentPerform(iterations: imageIndices.count) { position in")) + #expect(!Self.callsDispatchDirectly("DispatchQueue.global().async {")) + } + + private static func callsDispatchDirectly(_ code: String) -> Bool { + code.contains("DispatchQueue.concurrentPerform(") + } + + private static func targetSourceFiles() throws -> [URL] { + let targetDirectory = URL(fileURLWithPath: #filePath).deletingLastPathComponent() // CrossReferenceAnalysisTests + return try FileManager.default + .contentsOfDirectory(at: targetDirectory, includingPropertiesForKeys: nil) + .filter { $0.pathExtension == "swift" } + } +} diff --git a/Tests/CrossReferenceAnalysisTests/ReferenceKindAndRouteTests.swift b/Tests/CrossReferenceAnalysisTests/ReferenceKindAndRouteTests.swift index 6ffa3117c..723d36729 100644 --- a/Tests/CrossReferenceAnalysisTests/ReferenceKindAndRouteTests.swift +++ b/Tests/CrossReferenceAnalysisTests/ReferenceKindAndRouteTests.swift @@ -1,6 +1,7 @@ import Foundation import Testing import MachOKit +import SwiftSectionFixtureSupport @_spi(Internals) import MachOCodeReferences @_spi(Internals) import ObjCCodeReferences @_spi(Internals) import ARM64InstructionDecoding @@ -42,13 +43,14 @@ struct ReferenceKindAndRouteTests { } """ - private func objectiveCLibrary(stripped: Bool = false) throws -> (directory: URL, file: MachOFile) { - let (directory, library) = try CompiledFixture.build( - libraryName: "libKinds.dylib", - sources: ["Kinds.m": Self.objectiveCSource], - compilerArguments: ["-O1", "-fobjc-arc", "-framework", "Foundation"] + (stripped ? ["-Wl,-x"] : []) + private func objectiveCLibrary(stripped: Bool = false) throws -> MachOFile { + let library = try FixtureCompiler.shared.dynamicLibrary( + named: "Kinds", + language: .c, + sourceFiles: [FixtureSourceFile(name: "Kinds.m", contents: Self.objectiveCSource)], + arguments: ["-arch", "arm64", "-O1", "-fobjc-arc", "-framework", "Foundation"] + (stripped ? ["-Wl,-x"] : []) ) - return (directory, try MachOFile(url: library)) + return try MachOFile(url: library) } private func function(named name: String, in analyzer: CrossReferenceAnalyzer) throws -> CodeFunction { @@ -67,8 +69,7 @@ struct ReferenceKindAndRouteTests { /// list, whose entry points at the same variable. @Test(arguments: [false, true]) func instanceVariableOffsetLoadsBecomeInstanceVariableReferences(stripped: Bool) throws { - let (directory, file) = try objectiveCLibrary(stripped: stripped) - defer { try? FileManager.default.removeItem(at: directory) } + let file = try objectiveCLibrary(stripped: stripped) let analyzer = try CrossReferenceAnalyzer(machOFiles: [file]) for method in ["-[Counter increment]", "-[Counter describe]"] { let references = analyzer.references(madeBy: try function(named: method, in: analyzer)) @@ -83,8 +84,7 @@ struct ReferenceKindAndRouteTests { /// Strings are recorded when the analyzer is made to, or for a query for /// a string key — not in a whole-image table otherwise. @Test func stringReferencesAreRecordedOnlyWhenRequested() throws { - let (directory, file) = try objectiveCLibrary() - defer { try? FileManager.default.removeItem(at: directory) } + let file = try objectiveCLibrary() let withoutStrings = try CrossReferenceAnalyzer(machOFiles: [file]) #expect(!withoutStrings.recordsStringReferences) #expect(!withoutStrings.referenceTable(ofImageAt: 0).references.contains { reference in @@ -106,8 +106,7 @@ struct ReferenceKindAndRouteTests { /// A constant `CFString` is referenced by its characters, eight-bit or /// UTF-16 alike. @Test func constantStringReferencesCarryTheirCharacters() throws { - let (directory, file) = try objectiveCLibrary() - defer { try? FileManager.default.removeItem(at: directory) } + let file = try objectiveCLibrary() let analyzer = try CrossReferenceAnalyzer(machOFiles: [file], recordingStringReferences: true) let ascii = analyzer.references(madeBy: try function(named: "_constantStringFunction", in: analyzer)).map(\.target) #expect(ascii.contains(.constantString("a constant string literal")), "\(ascii)") @@ -121,12 +120,12 @@ struct ReferenceKindAndRouteTests { /// `add` to the characters, `sub #0x20`. The `add` names the string; the /// subtraction names no other. @Test func swiftLargeStringLiteralPointsAtItsCharacters() throws { - let (directory, library) = try CompiledFixture.buildSwift(libraryName: "libLargeString.dylib", source: """ + // The module is `Fixture`, which the expected symbol spells. + let library = try FixtureCompiler.shared.dynamicLibrary(named: "Fixture", language: .swift, source: """ @inline(never) public func largeStringLiteral() -> String { "a string literal longer than fifteen bytes" } - """) - defer { try? FileManager.default.removeItem(at: directory) } + """, arguments: ["-O", "-target", "arm64-apple-macos14"]) let analyzer = try CrossReferenceAnalyzer(machOFiles: [MachOFile(url: library)], recordingStringReferences: true) let function = try #require(analyzer.functions(inImageAt: 0).first { $0.name == .symbol("_$s7Fixture18largeStringLiteralSSyF") }) let strings = analyzer.references(madeBy: function).filter { if case .cString = $0.target { true } else { false } } @@ -139,8 +138,7 @@ struct ReferenceKindAndRouteTests { /// address is built, an instance variable's offset is loaded through its /// slot. @Test func everyReferenceCarriesTheRouteItTook() throws { - let (directory, file) = try objectiveCLibrary() - defer { try? FileManager.default.removeItem(at: directory) } + let file = try objectiveCLibrary() let analyzer = try CrossReferenceAnalyzer(machOFiles: [file], recordingStringReferences: true) let references = analyzer.references(madeBy: try function(named: "_callEverything", in: analyzer)) func route(of target: CodeReferenceTarget) -> CodeReferenceRoute? { @@ -180,8 +178,7 @@ struct ReferenceKindAndRouteTests { /// The table and the index a host keeps answer the same — the new kinds /// and every route included. @Test func referenceIndexRoundTripsNewTargetsAndRoutes() throws { - let (directory, file) = try objectiveCLibrary() - defer { try? FileManager.default.removeItem(at: directory) } + let file = try objectiveCLibrary() let analyzer = try CrossReferenceAnalyzer(machOFiles: [file], recordingStringReferences: true) let table = analyzer.referenceTable(ofImageAt: 0) let index = analyzer.referenceIndex(ofImageAt: 0) diff --git a/Tests/CrossReferenceAnalysisTests/RuntimeSendEntryPointTests.swift b/Tests/CrossReferenceAnalysisTests/RuntimeSendEntryPointTests.swift index 3cc6a968d..a0e057105 100644 --- a/Tests/CrossReferenceAnalysisTests/RuntimeSendEntryPointTests.swift +++ b/Tests/CrossReferenceAnalysisTests/RuntimeSendEntryPointTests.swift @@ -21,7 +21,7 @@ struct RuntimeSendEntryPointTests { private static let fixture = Result { // Without ARC, so no call the compiler adds stands among them. try CompiledFixture.load( - libraryName: "libCrossReferenceRuntimeSends.dylib", + named: "CrossReferenceRuntimeSends", sources: [ "Sends.m": """ #import diff --git a/Tests/CrossReferenceAnalysisTests/SelectorReferenceTests.swift b/Tests/CrossReferenceAnalysisTests/SelectorReferenceTests.swift new file mode 100644 index 000000000..1ca3d6f93 --- /dev/null +++ b/Tests/CrossReferenceAnalysisTests/SelectorReferenceTests.swift @@ -0,0 +1,89 @@ +import Foundation +import Testing +import MachOKit +import SwiftSectionFixtureSupport +@_spi(Internals) import MachOCodeReferences +@testable import CrossReferenceAnalysis + +/// A selector code loads but sends nothing with is a selector reference, +/// filed under the selector's key beside its sends (evolution proposal +/// `cross-reference-recall-gaps`): an argument of `respondsToSelector:` or +/// `performSelector:`, a returned selector. +@Suite +struct SelectorReferenceTests { + private static let source = """ + #import + BOOL probeResponds(id object) { + return [object respondsToSelector:@selector(coalescingNodeObserver:openSyncCompleted:)]; + } + SEL probeReturnsSelector(void) { + return @selector(name); + } + id probePerforms(id object) { + return [object performSelector:@selector(copy)]; + } + """ + + /// Classic sends: the selector references are loaded in the functions + /// themselves, the shape a selector stub hides. + private static func analyzer() throws -> CrossReferenceAnalyzer { + let library = try FixtureCompiler.shared.dynamicLibrary( + named: "SelectorReferences", + language: .c, + sourceFiles: [FixtureSourceFile(name: "SelectorReferences.m", contents: source)], + arguments: ["-arch", "arm64", "-O2", "-fno-objc-msgsend-selector-stubs", "-framework", "Foundation"] + ) + return try CrossReferenceAnalyzer(machOFiles: [MachOFile(url: library)]) + } + + private static func function(named name: String, in analyzer: CrossReferenceAnalyzer) throws -> CodeFunction { + try #require(analyzer.functions(inImageAt: 0).first { if case .symbol(name)? = $0.name { true } else { false } }) + } + + @Test func selectorQueriesReturnSendsAndSelectorReferences() throws { + let analyzer = try Self.analyzer() + let performs = try Self.function(named: "_probePerforms", in: analyzer) + let copies = analyzer.references(to: [.selector("copy")], inImageAt: 0) + #expect(copies.map(\.target) == [.selector("copy")]) + #expect(copies.allSatisfy { $0.function == performs.location && $0.kind == .reference }) + let performSelectors = analyzer.references(to: [.selector("performSelector:")], inImageAt: 0) + #expect(performSelectors.contains { if case .messageSend("performSelector:", _) = $0.target { true } else { false } }) + #expect(!performSelectors.contains { $0.target == .selector("performSelector:") }) + #expect(analyzer.references(to: [.selector("name")], inImageAt: 0).map(\.target) == [.selector("name")]) + #expect(analyzer.references(to: [.selector("coalescingNodeObserver:openSyncCompleted:")], inImageAt: 0).map(\.target) == [.selector("coalescingNodeObserver:openSyncCompleted:")]) + } + + @Test func selectorReferencesSurviveTheCompactIndex() throws { + let analyzer = try Self.analyzer() + let index = analyzer.referenceIndex(ofImageAt: 0) + for selector in ["copy", "name", "performSelector:"] { + #expect(Set(index.references(to: [.selector(selector)])) == Set(analyzer.references(to: [.selector(selector)], inImageAt: 0)), "\(selector)") + } + } + + /// Recorded when the scan leaves the function, a selector reference is + /// listed where its instruction lies among the function's references. + @Test func aFunctionsReferencesStayInInstructionOrder() throws { + let analyzer = try Self.analyzer() + let references = try analyzer.references(madeBy: Self.function(named: "_probePerforms", in: analyzer)) + #expect(references.contains { $0.target == .selector("copy") }) + #expect(references.map(\.instructionAddress) == references.map(\.instructionAddress).sorted()) + } + + @Test func symbolicationCallsASelectorReferenceSlotASelector() throws { + let analyzer = try Self.analyzer() + let library = try FixtureCompiler.shared.dynamicLibrary( + named: "SelectorReferences", + language: .c, + sourceFiles: [FixtureSourceFile(name: "SelectorReferences.m", contents: Self.source)], + arguments: ["-arch", "arm64", "-O2", "-fno-objc-msgsend-selector-stubs", "-framework", "Foundation"] + ) + let machO = try MachOFile(url: library) + let selectorReferences = try #require(machO.sections64.first { $0.segmentName == "__DATA" && $0.sectionName == "__objc_selrefs" }) + let meaning = analyzer.symbolication(of: UInt64(selectorReferences.address), inImageAt: 0).meaning + guard case .pointerSlot(.selectorReference, let target) = meaning, case .selector = target else { + Issue.record("\(meaning)") + return + } + } +} diff --git a/Tests/CrossReferenceAnalysisTests/SlotAddressReferenceTests.swift b/Tests/CrossReferenceAnalysisTests/SlotAddressReferenceTests.swift new file mode 100644 index 000000000..38c921f15 --- /dev/null +++ b/Tests/CrossReferenceAnalysisTests/SlotAddressReferenceTests.swift @@ -0,0 +1,44 @@ +import Foundation +import Testing +import MachOKit +import SwiftSectionFixtureSupport +@_spi(Internals) import MachOCodeReferences +@testable import CrossReferenceAnalysis + +/// Optimized Swift code hands an Objective-C class's GOT slot to the merged +/// helper that makes the class's metadata (`$sSo…CMaTm`), building only the +/// slot's address: `adrp x2; add x2, ; bl`. That `add` references the +/// class (evolution proposal `cross-reference-recall-gaps`; ControlCenter +/// 26.7 has 554 such calls). +@Suite +struct SlotAddressReferenceTests { + private static func analyzer() throws -> (analyzer: CrossReferenceAnalyzer, machO: MachOFile) { + let library = try FixtureCompiler.shared.dynamicLibrary( + named: "SlotAddressReferences", + language: .swift, + sourceFiles: [FixtureSourceFile(name: "SlotAddressReferences.swift", contents: """ + import Foundation + public func descriptorClass() -> Any.Type { NSAppleEventDescriptor.self } + public func timerClass() -> Any.Type { Timer.self } + """)], + arguments: ["-O", "-swift-version", "5"] + ) + let machO = try MachOFile(url: library) + return (try CrossReferenceAnalyzer(machOFiles: [machO]), machO) + } + + /// In a file analyzed without Foundation, the slot binds to an imported + /// class: the reference a `refs --class NSTimer` query also takes. + @Test func slotAddressHandedToAHelperIsAClassReference() throws { + let (analyzer, _) = try Self.analyzer() + let timerClass = try #require(analyzer.functions(inImageAt: 0).first { function in + if case .symbol(let symbol)? = function.name { symbol.hasPrefix("_$s21SlotAddressReferences10timerClass") } else { false } + }) + let references = analyzer.references(to: [.objectiveCClass("NSTimer"), .importedSymbol("_OBJC_CLASS_$_NSTimer")], inImageAt: 0) + let inTimerClass = references.filter { $0.function == timerClass.location } + #expect(inTimerClass.count == 1) + #expect(inTimerClass.first?.target == .importedSymbol(name: "_OBJC_CLASS_$_NSTimer")) + #expect(inTimerClass.first?.kind == .reference) + #expect(inTimerClass.first?.route == .pointerSlot) + } +} diff --git a/Tests/CrossReferenceAnalysisTests/SlotSymbolicationTests.swift b/Tests/CrossReferenceAnalysisTests/SlotSymbolicationTests.swift new file mode 100644 index 000000000..45901f78e --- /dev/null +++ b/Tests/CrossReferenceAnalysisTests/SlotSymbolicationTests.swift @@ -0,0 +1,119 @@ +import Foundation +import Testing +import MachOKit +import SwiftSectionFixtureSupport +@_spi(Internals) import MachOCodeReferences +@testable import CrossReferenceAnalysis + +/// What a pointer slot holds, in libraries compiled for the test and loaded +/// into the process (2026-11-29 codebase audit, findings 4 and 11). +@Suite(.enabled(if: SharedAnalyzer.analyzer != nil, "needs an arm64 process with a dyld shared cache")) +struct SlotSymbolicationTests { + /// `FixtureAnchor` is ballast: a fixture dylib with no class has no + /// `__DATA` segment, which older MachOKit releases mis-walked. The + /// metatype reads `Int`'s metadata through a GOT slot. + private static let swiftSource = """ + public final class FixtureAnchor {} + + @inline(never) public func integerType() -> Any.Type { Int.self } + """ + + /// The process's analyzer, made after `library` was loaded, and the + /// library's position in it. + private static func analyzer(afterLoading library: URL) throws -> (analyzer: CrossReferenceAnalyzer, imageIndex: Int) { + guard dlopen(library.path, RTLD_NOW | RTLD_LOCAL) != nil else { + throw CompiledFixture.Failure(description: "could not load \(library.lastPathComponent): \(dlerror().map { String(cString: $0) } ?? "")") + } + let analyzer = try #require(CrossReferenceAnalyzer()) + let imageIndex = try #require(analyzer.imagePaths.firstIndex { $0.hasSuffix("/" + library.lastPathComponent) }) + return (analyzer, imageIndex) + } + + /// The unslid address of the image's GOT slot holding `value`. + private static func globalOffsetTableSlot(holding value: UInt, inImageAt imageIndex: Int, of analyzer: CrossReferenceAnalyzer) -> UInt64? { + for section in analyzer.images[imageIndex].sections64 where section.sectionName == "__got" || section.sectionName == "__auth_got" { + for slot in stride(from: UInt64(section.address), to: UInt64(section.address) + UInt64(section.size), by: 8) { + let runtimeSlot = analyzer.imageSet.runtimeAddress(of: CodeLocation(imageIndex: imageIndex, address: slot)) + if analyzer.memory.pointer(at: runtimeSlot) == value { return slot } + } + } + return nil + } + + private static func runtimeAddress(ofSymbolNamed name: String) throws -> UInt { + UInt(bitPattern: try #require(dlsym(UnsafeMutableRawPointer(bitPattern: -2), name), "no \(name) in the process")) + } + + /// `__TEXT` holds more than code — a protocol or method descriptor, a + /// constant — and a slot holding the address of any of it was said to + /// lead to a function. Here a constant one library exports, which the + /// other reads through its GOT. + @Test func aSlotHoldingDataInTextLeadsToNoFunction() throws { + let provider = try FixtureCompiler.shared.dynamicLibrary( + named: "SlotSymbolicationProvider", + language: .c, + sourceFiles: [FixtureSourceFile(name: "Provider.c", contents: "const long slotProvidedConstant[4] = {1, 2, 3, 4};\n")], + arguments: ["-arch", "arm64", "-O1"] + ) + let reader = try FixtureCompiler.shared.dynamicLibrary( + named: "SlotSymbolicationReader", + language: .c, + sourceFiles: [FixtureSourceFile(name: "Reader.c", contents: """ + extern const long slotProvidedConstant[4]; + long readSlotProvidedConstant(int index) { return slotProvidedConstant[index]; } + """)], + // The provider's install name is `@rpath/…`. + arguments: ["-arch", "arm64", "-O1", provider.path, "-Wl,-rpath," + provider.deletingLastPathComponent().path] + ) + let (analyzer, imageIndex) = try Self.analyzer(afterLoading: reader) + let constant = try Self.runtimeAddress(ofSymbolNamed: "slotProvidedConstant") + let constantLocation = try #require(analyzer.location(ofRuntimeAddress: constant), "the constant lies in no image's __TEXT") + let slot = try #require(Self.globalOffsetTableSlot(holding: constant, inImageAt: imageIndex, of: analyzer), "no GOT slot holds the constant") + #expect(analyzer.symbolication(of: slot, inImageAt: imageIndex).meaning == .pointerSlot(.globalOffsetTable, target: .unrecognized(address: constantLocation.address))) + } + + /// A struct's metadata is the type, as the scan reads it. + @Test func aSlotHoldingValueMetadataLeadsToItsType() throws { + let library = try FixtureCompiler.shared.dynamicLibrary(named: "SlotSymbolicationFixture", language: .swift, source: Self.swiftSource, arguments: ["-swift-version", "5", "-O", "-target", "arm64-apple-macosx15.0"]) + let (analyzer, imageIndex) = try Self.analyzer(afterLoading: library) + let integerMetadata = try Self.runtimeAddress(ofSymbolNamed: "$sSiN") + let integerDescriptor = try #require(analyzer.location(ofRuntimeAddress: try Self.runtimeAddress(ofSymbolNamed: "$sSiMn"))) + let slot = try #require(Self.globalOffsetTableSlot(holding: integerMetadata, inImageAt: imageIndex, of: analyzer), "no GOT slot holds Int's metadata") + #expect(analyzer.symbolication(of: slot, inImageAt: imageIndex).meaning == .pointerSlot(.globalOffsetTable, target: .swiftType(descriptor: integerDescriptor))) + } + + /// A protocol reference whose value is no protocol: `protocol_t`'s name + /// was read eight bytes past it without asking whether anything is + /// mapped there, and the process faulted. libobjc fixes up the protocol + /// references of an image it knows, so the slot sits in a C library + /// with no `__objc_imageinfo`, which libobjc leaves alone. In a child + /// process, where the read used to fault. + @Test func aProtocolReferenceToNothingMappedReadsAsUnrecognized() async { + await #expect(processExitsWith: .success) { + exit(Self.symbolicateAProtocolReferenceToNothingMapped()) + } + } + + private static func symbolicateAProtocolReferenceToNothingMapped() -> Int32 { + do { + let library = try CompiledFixture.load( + named: "MalformedProtocolReference", + sources: ["MalformedProtocolReference.c": """ + __attribute__((used, section("__DATA,__objc_protorefs"))) static void *malformedProtocolReference = (void *)0x10; + int malformedProtocolReferenceAnchor(void) { return 1; } + """], + compilerArguments: ["-O1"] + ) + // dyld names the temporary directory by its real path, under + // `/private`. + let libraryName = "/" + (library as NSString).lastPathComponent + guard let analyzer = CrossReferenceAnalyzer() else { return 3 } + guard let imageIndex = analyzer.imagePaths.firstIndex(where: { $0.hasSuffix(libraryName) }) else { return 4 } + guard let section = analyzer.images[imageIndex].sections64.first(where: { $0.sectionName == "__objc_protorefs" }) else { return 5 } + let meaning = analyzer.symbolication(of: UInt64(section.address), inImageAt: imageIndex).meaning + return meaning == .pointerSlot(.protocolReference, target: .unrecognized(address: 0x10)) ? EXIT_SUCCESS : 2 + } catch { + return EXIT_FAILURE + } + } +} diff --git a/Tests/CrossReferenceAnalysisTests/StandaloneFileReferenceDumpTests.swift b/Tests/CrossReferenceAnalysisTests/StandaloneFileReferenceDumpTests.swift index 68084ab80..834b4689b 100644 --- a/Tests/CrossReferenceAnalysisTests/StandaloneFileReferenceDumpTests.swift +++ b/Tests/CrossReferenceAnalysisTests/StandaloneFileReferenceDumpTests.swift @@ -71,6 +71,8 @@ struct StandaloneFileReferenceDumpTests { "class \(name) 0x\(String(location.address, radix: 16))" case .objectiveCInstanceVariable(let className, let name): "ivar \(className).\(name)" + case .selector(let selector): + "selector \(selector)" case .cString(let characters): "cString \(characters.debugDescription)" case .constantString(let characters): diff --git a/Tests/CrossReferenceAnalysisTests/StrippedStandaloneInstantiationTests.swift b/Tests/CrossReferenceAnalysisTests/StrippedStandaloneInstantiationTests.swift new file mode 100644 index 000000000..f96f028b5 --- /dev/null +++ b/Tests/CrossReferenceAnalysisTests/StrippedStandaloneInstantiationTests.swift @@ -0,0 +1,59 @@ +import Foundation +import Testing +import MachOKit +import SwiftSectionFixtureSupport +@testable import CrossReferenceAnalysis + +/// A type instantiated from its mangled name, read from a standalone file. +/// +/// The set of files holds no libswiftCore, so the image's +/// `__swift_instantiateConcreteTypeFromMangledName` helper reaches the +/// runtime's `swift_getTypeByMangledNameInContext…` through a stub that +/// resolves to an imported symbol, not to a function. The scan recognized +/// such a helper by its name or, stripped of that name, by calling a function +/// it knew to be the runtime's — never by the imported symbol. So in a +/// stripped file, the shape the scan exists for, every instantiation went +/// unreported, and `refs --type` answered nothing (2026-11-29 codebase +/// audit, finding 3). +@Suite +struct StrippedStandaloneInstantiationTests { + private static let moduleName = "StrippedStandaloneInstantiationFixture" + + /// `FixtureAnchor` is ballast: a fixture dylib with no class has no + /// `__DATA` segment, which older MachOKit releases mis-walked. Each + /// function instantiates a standard library generic from its mangled + /// name. + private static let source = """ + public final class FixtureAnchor {} + + @inline(never) public func arrayOfStringsType() -> Any.Type { [String].self } + @inline(never) public func dictionaryType() -> Any.Type { [String: Int].self } + """ + + private func compiledLibrary() throws -> URL { + try FixtureCompiler.shared.dynamicLibrary( + named: Self.moduleName, + language: .swift, + source: Self.source, + arguments: ["-swift-version", "5", "-O", "-target", "arm64-apple-macosx15.0"] + ) + } + + /// The mangled names the file's functions instantiate, in scan order. + private func instantiatedNames(inFileAt url: URL) throws -> [SwiftTypeName] { + let analyzer = try CrossReferenceAnalyzer(machOFiles: [try MachOFile(url: url)]) + return analyzer.referenceTable(ofImageAt: 0).references.compactMap { reference in + guard case .swiftTypeName(let name) = reference.target, case .mangledName = name else { return nil } + return name + } + } + + @Test func aStrippedFileStillInstantiatesItsTypesFromMangledNames() throws { + let library = try compiledLibrary() + let unstripped = try instantiatedNames(inFileAt: library) + try #require(unstripped.count >= 2, "the fixture instantiates \(unstripped.count) types from mangled names") + // Without its local symbols, the helper's name among them. + let stripped = try instantiatedNames(inFileAt: try CompiledFixtureCopies.strippedCopy(of: library)) + #expect(stripped == unstripped) + } +} diff --git a/Tests/CrossReferenceAnalysisTests/SwiftTypeReferenceTests.swift b/Tests/CrossReferenceAnalysisTests/SwiftTypeReferenceTests.swift index 99e2e984c..a2949e033 100644 --- a/Tests/CrossReferenceAnalysisTests/SwiftTypeReferenceTests.swift +++ b/Tests/CrossReferenceAnalysisTests/SwiftTypeReferenceTests.swift @@ -321,7 +321,7 @@ struct SwiftTypeReferenceTests { private func imagesReferencing(_ identity: SwiftTypeIdentity, among imageIndices: [Int]) -> Set { let found = ImageIndexCollector() let analyzer = analyzer - DispatchQueue.concurrentPerform(iterations: imageIndices.count) { position in + ImageScanConcurrency.concurrentPerform(iterations: imageIndices.count) { position in if !analyzer.references(toSwiftType: identity, inImageAt: imageIndices[position]).isEmpty { found.insert(imageIndices[position]) } } return found.indices diff --git a/Tests/CrossReferenceAnalysisTests/SymbolicationTests.swift b/Tests/CrossReferenceAnalysisTests/SymbolicationTests.swift index 268bdf2f4..82ade1c24 100644 --- a/Tests/CrossReferenceAnalysisTests/SymbolicationTests.swift +++ b/Tests/CrossReferenceAnalysisTests/SymbolicationTests.swift @@ -1,10 +1,12 @@ import Foundation import Testing import MachOKit +import SwiftSectionFixtureSupport @_spi(Internals) import MachOCodeReferences @_spi(Internals) import ObjCCodeReferences @_spi(Internals) import ARM64InstructionDecoding @testable import CrossReferenceAnalysis +import MachOKitExtensions /// What an address is (evolution proposal /// `offline-cross-references-and-symbolication`, step 6). @@ -112,16 +114,16 @@ struct SymbolicationTests { /// library the analyzer does not cover, or — linked `-interposable` — to /// its own function. @Test func symbolicatesGlobalOffsetTableSlotToItsBoundSymbol() throws { - let (directory, library) = try CompiledFixture.build( - libraryName: "libSlots.dylib", - sources: ["Slots.c": """ + let library = try FixtureCompiler.shared.dynamicLibrary( + named: "Slots", + language: .c, + sourceFiles: [FixtureSourceFile(name: "Slots.c", contents: """ #include __attribute__((noinline)) int slotCallee(int value) { return value * 5; } int slotCaller(int value) { puts("calling"); return slotCallee(value); } - """], - compilerArguments: ["-O1", "-Wl,-interposable"] + """)], + arguments: ["-arch", "arm64", "-O1", "-Wl,-interposable"] ) - defer { try? FileManager.default.removeItem(at: directory) } let file = try MachOFile(url: library) let analyzer = try CrossReferenceAnalyzer(machOFiles: [file]) let callee = try #require(analyzer.functions(inImageAt: 0).first { $0.name == .symbol("_slotCallee") }) @@ -172,9 +174,10 @@ struct SymbolicationTests { /// Strings, an instance variable's offset variable and a selector /// reference, in a library compiled for the test. @Test func symbolicatesStringsAndObjectiveCSlots() throws { - let (directory, library) = try CompiledFixture.build( - libraryName: "libObjectiveCSlots.dylib", - sources: ["Slots.m": """ + let library = try FixtureCompiler.shared.dynamicLibrary( + named: "ObjectiveCSlots", + language: .c, + sourceFiles: [FixtureSourceFile(name: "Slots.m", contents: """ #import @interface Holder : NSOperation { @public long _held; } @end @@ -183,10 +186,9 @@ struct SymbolicationTests { long readHeld(Holder *holder) { return holder->_held; } const char *cString(void) { return "symbolicated characters"; } NSString *constantString(void) { return @"symbolicated constant"; } - """], - compilerArguments: ["-O1", "-fobjc-arc", "-framework", "Foundation"] + """)], + arguments: ["-arch", "arm64", "-O1", "-fobjc-arc", "-framework", "Foundation"] ) - defer { try? FileManager.default.removeItem(at: directory) } let file = try MachOFile(url: library) let analyzer = try CrossReferenceAnalyzer(machOFiles: [file], recordingStringReferences: true) let references = analyzer.referenceTable(ofImageAt: 0).references diff --git a/Tests/CrossReferenceAnalysisTests/TypeNameRetentionTests.swift b/Tests/CrossReferenceAnalysisTests/TypeNameRetentionTests.swift index ea57e008d..a2373d2b2 100644 --- a/Tests/CrossReferenceAnalysisTests/TypeNameRetentionTests.swift +++ b/Tests/CrossReferenceAnalysisTests/TypeNameRetentionTests.swift @@ -7,6 +7,7 @@ import MachOSwiftSection @_spi(Internals) import ObjCCodeReferences @_spi(Internals) import SwiftInspection @testable import CrossReferenceAnalysis +import MachOKit /// A type of this test bundle that nothing else names: its key comes from /// its `…Mn` symbol. Internal, so that no private discriminator joins it. diff --git a/Tests/IntegrationTests/InspectionDumps/CrossVersionMachOFileTests.swift b/Tests/IntegrationTests/InspectionDumps/CrossVersionMachOFileTests.swift new file mode 100644 index 000000000..4ea327f28 --- /dev/null +++ b/Tests/IntegrationTests/InspectionDumps/CrossVersionMachOFileTests.swift @@ -0,0 +1,58 @@ +import Foundation +import Testing +import MachOKit +import SwiftSectionFixtureSupport +import SwiftSectionTestingSupport +@testable import MachOSwiftSection +import FoundationToolbox +import SwiftStdlibToolbox + +/// The same file in two simulator runtimes, and the runtime versions that +/// label them on the axis. A suite points at one of these; to look at +/// another file, add one. +struct SimulatorFilePairConfiguration: Sendable { + let oldFileName: MachOFileName + let newFileName: MachOFileName + let oldVersionLabel: String + let newVersionLabel: String + + static var swiftUICore: Self { + Self(oldFileName: .iOS_18_5_Simulator_SwiftUICore, newFileName: .iOS_26_5_Simulator_SwiftUICore, oldVersionLabel: "18.5", newVersionLabel: "26.5") + } + + static var swiftUI: Self { + Self(oldFileName: .iOS_18_5_Simulator_SwiftUI, newFileName: .iOS_26_5_Simulator_SwiftUI, oldVersionLabel: "18.5", newVersionLabel: "26.5") + } +} + +/// The same file from two simulator runtimes, by fixture name — the +/// two-version counterpart of `SwiftSectionTestingSupport.MachOFileTests`, +/// which loads one. `configuration` names the pair. +@TestActor +class CrossVersionMachOFileTests: Sendable { + let oldMachOFile: MachOFile + let newMachOFile: MachOFile + private let axes: VersionAxes + + class var configuration: SimulatorFilePairConfiguration { .swiftUICore } + + init() async throws { + let configuration = Self.configuration + let oldMachOFile = try HostSlice.machOFile(in: loadFromFile(named: configuration.oldFileName)) + let newMachOFile = try HostSlice.machOFile(in: loadFromFile(named: configuration.newFileName)) + self.oldMachOFile = oldMachOFile + self.newMachOFile = newMachOFile + self.axes = VersionAxes( + versions: [ + AxisVersion(label: configuration.oldVersionLabel, images: [AxisImage(imageName: oldMachOFile.imagePath.lastPathComponent, machOFile: oldMachOFile)]), + AxisVersion(label: configuration.newVersionLabel, images: [AxisImage(imageName: newMachOFile.imagePath.lastPathComponent, machOFile: newMachOFile)]), + ], + comparesImageGroups: false, + availabilityPlatform: nil + ) + } + + nonisolated func versionAxis(for language: MetadataLanguage) -> VersionAxis { + axes.axis(for: language) + } +} diff --git a/Tests/IntegrationTests/InspectionDumps/CrossVersionXcodeFrameworkTests.swift b/Tests/IntegrationTests/InspectionDumps/CrossVersionXcodeFrameworkTests.swift new file mode 100644 index 000000000..0a7b8c01b --- /dev/null +++ b/Tests/IntegrationTests/InspectionDumps/CrossVersionXcodeFrameworkTests.swift @@ -0,0 +1,61 @@ +import Foundation +import Testing +import MachOKit +import SwiftSectionFixtureSupport +import SwiftSectionTestingSupport +@testable import MachOSwiftSection +import FoundationToolbox +import SwiftStdlibToolbox + +/// A shared framework of two installed Xcode applications, picked by +/// version — `/Applications/Xcode-.app` — which also labels it on +/// the axis. A suite points at one of these; to look at another framework or +/// other Xcodes, add one. +struct XcodeFrameworkPairConfiguration: Sendable { + let frameworkName: String + let oldXcodeVersion: String + let newXcodeVersion: String + + static var dvtProductsUI: Self { + Self(frameworkName: "DVTProductsUI", oldXcodeVersion: "26.3.0", newXcodeVersion: "26.4.0") + } +} + +/// The same shared framework from two installed Xcode applications, picked +/// by version: `/Applications/Xcode-.app`. The shared +/// `XcodeMachOFileName` fixture names a single Xcode, so this loads by path. +/// `configuration` names the framework and the two versions. +@TestActor +class CrossVersionXcodeFrameworkTests: Sendable { + let oldMachOFile: MachOFile + let newMachOFile: MachOFile + private let axes: VersionAxes + + class var configuration: XcodeFrameworkPairConfiguration { .dvtProductsUI } + + init() async throws { + let configuration = Self.configuration + let frameworkName = configuration.frameworkName + let oldMachOFile = try Self.loadSharedFramework(named: frameworkName, fromXcodeVersion: configuration.oldXcodeVersion) + let newMachOFile = try Self.loadSharedFramework(named: frameworkName, fromXcodeVersion: configuration.newXcodeVersion) + self.oldMachOFile = oldMachOFile + self.newMachOFile = newMachOFile + self.axes = VersionAxes( + versions: [ + AxisVersion(label: configuration.oldXcodeVersion, images: [AxisImage(imageName: frameworkName, machOFile: oldMachOFile)]), + AxisVersion(label: configuration.newXcodeVersion, images: [AxisImage(imageName: frameworkName, machOFile: newMachOFile)]), + ], + comparesImageGroups: false, + availabilityPlatform: nil + ) + } + + nonisolated func versionAxis(for language: MetadataLanguage) -> VersionAxis { + axes.axis(for: language) + } + + private static func loadSharedFramework(named name: String, fromXcodeVersion xcodeVersion: String) throws -> MachOFile { + let binaryPath = "/Applications/Xcode-\(xcodeVersion).app/Contents/SharedFrameworks/\(name).framework/Versions/A/\(name)" + return try HostSlice.machOFile(at: URL(fileURLWithPath: binaryPath)) + } +} diff --git a/Tests/IntegrationTests/InspectionDumps/DiffDumpTests.swift b/Tests/IntegrationTests/InspectionDumps/DiffDumpTests.swift new file mode 100644 index 000000000..d11d3a242 --- /dev/null +++ b/Tests/IntegrationTests/InspectionDumps/DiffDumpTests.swift @@ -0,0 +1,163 @@ +import Foundation +import Testing +import MachOKit +import SwiftSectionFixtureSupport +import SwiftSectionTestingSupport +@testable import MachOSwiftSection +import SwiftDeclarationRendering +@_spi(Support) @testable import SwiftInterface +@_spi(Support) @testable import SwiftIndexing +import SwiftDiffing +import ObjCDiffing +import Semantic + +/// The three two-version outputs, each the pipeline of one subcommand. +enum DiffDumpKind: Sendable { + /// `swift-section diff` and `diff --json`: the change list with the + /// verdict line (`-Diff.txt`) and its machine-readable form + /// (`-Diff.json`). + case swiftReport + /// `swift-section diff --interface`: the new interface annotated with + /// inline `+`/`-` markers (`-AnnotatedInterface-Inline.swiftinterface`) + /// and as a unified diff (`-AnnotatedInterface-Unified.swiftinterface`); + /// the console prints the inline one. + case swiftInterface + /// `swift-section objc diff` and `objc diff --json`: the change list + /// with the verdict line (`-ObjCDiff.txt`) and its JSON + /// (`-ObjCDiff.json`). Objective-C has no annotated header for a diff. + case objcReport + + var language: MetadataLanguage { + switch self { + case .swiftReport, .swiftInterface: .swift + case .objcReport: .objc + } + } +} + +/// The diff dumps: the first and last version of a version axis — two +/// simulator runtimes, two dyld shared caches, two Xcodes — run through the +/// pipelines of `swift-section diff` and `swift-section objc diff`. A diff +/// reads each version's primary image: neither differ compares groups of +/// images. +/// +/// A conforming suite supplies the axis (`VersionAxisDumpTests`), usually by +/// inheriting one of the axis base classes and naming two versions. Like its +/// siblings this is a maintainer-inspection dump: it prints / writes results +/// without assertions. +protocol DiffDumpTests: VersionAxisDumpTests {} + +@available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) +extension DiffDumpTests { + /// Runs one pipeline over the first and last version of this suite's + /// axis for the pipeline's language, then prints the result, or writes + /// it named after the new version's image. An axis left with fewer than + /// two versions carrying the metadata has nothing to compare: the dump + /// says so and writes nothing. + /// + /// Left unoptimized: the Swift 6.3 optimizer of Xcode 26.6 crashes in its + /// CopyPropagation pass on this function's specialization for a + /// conforming suite in a release build, and a maintainer's inspection + /// dump gains nothing from being optimized. + @_optimize(none) + func dump(_ kind: DiffDumpKind, to destination: DumpDestination) async throws { + let axis = versionAxis(for: kind.language) + guard axis.versions.count >= 2, let oldVersion = axis.versions.first, let newVersion = axis.versions.last else { + printResult("No diff: \(axis.versions.count) version(s) carry the \(kind.language) metadata") + return + } + let output: DumpOutput + switch kind { + case .swiftReport: + output = try await swiftReport(old: oldVersion, new: newVersion) + case .swiftInterface: + output = try await swiftInterface(old: oldVersion, new: newVersion, rendersUnifiedDiff: destination == .file) + case .objcReport: + output = try await objcReport(old: oldVersion, new: newVersion) + } + try deliver(output, to: destination) { file in + try write(file.text, forImageGroup: [newVersion.primaryImage], suffix: file.suffix, fileExtension: file.fileExtension) + } + } + + // MARK: - Swift + + /// Both primary images indexed in one timed step — the differ needs both + /// sides before it can compare them, so the printed duration covers the + /// whole preparation. + private func preparedBuilders( + old oldVersion: AxisVersion, + new newVersion: AxisVersion + ) async throws -> (old: SwiftDiffableInterfaceBuilder, new: SwiftDiffableInterfaceBuilder) { + let oldBuilder = SwiftDiffableInterfaceBuilder(configuration: indexConfiguration, in: oldVersion.primaryImage.machOFile) + let newBuilder = SwiftDiffableInterfaceBuilder(configuration: indexConfiguration, in: newVersion.primaryImage.machOFile) + try await measuringPreparation { + try await oldBuilder.prepare() + try await newBuilder.prepare() + } + return (oldBuilder, newBuilder) + } + + /// The change list plus the one-line compatibility verdict, as + /// `swift-section diff` prints it, and the diff as `diff --json` writes + /// it. + private func swiftReport(old oldVersion: AxisVersion, new newVersion: AxisVersion) async throws -> DumpOutput { + let builders = try await preparedBuilders(old: oldVersion, new: newVersion) + let diff = ABIDiffer().diff(old: builders.old.abiModule(), new: builders.new.abiModule()) + let verdict = "ABI-breaking: \(diff.hasBreakingChange) · backward-compatible: \(diff.isBackwardCompatible)" + let report = ABIDiffReporter().report(diff) + "\n\n" + verdict + return DumpOutput( + consoleText: report, + files: [ + DumpFile(suffix: "Diff", fileExtension: "txt", text: report), + DumpFile(suffix: "Diff", fileExtension: "json", text: String(decoding: try ABIJSON.encoder().encode(diff), as: UTF8.self)), + ] + ) + } + + /// The new interface annotated against the old, as `diff --interface` + /// prints it: with inline markers always, as a unified diff only when it + /// goes to a file — each form is a full print of its own. + private func swiftInterface( + old oldVersion: AxisVersion, + new newVersion: AxisVersion, + rendersUnifiedDiff: Bool + ) async throws -> DumpOutput { + let builders = try await preparedBuilders(old: oldVersion, new: newVersion) + let inlineInterface = await SwiftDiffableInterfaceRenderer(old: builders.old, new: builders.new) + .printAnnotatedInterface(format: .inline) + .string + var files = [DumpFile(suffix: "AnnotatedInterface-Inline", fileExtension: "swiftinterface", text: inlineInterface)] + if rendersUnifiedDiff { + let unifiedInterface = await SwiftDiffableInterfaceRenderer(old: builders.old, new: builders.new) + .printAnnotatedInterface(format: .unified()) + .string + files.append(DumpFile(suffix: "AnnotatedInterface-Unified", fileExtension: "swiftinterface", text: unifiedInterface)) + } + return DumpOutput(consoleText: inlineInterface, files: files) + } + + // MARK: - Objective-C + + /// The change list plus the verdict line, as `swift-section objc diff` + /// prints it, and the diff as `objc diff --json` writes it. Both sides + /// go through the persisted snapshot form, the way the command line reads + /// a binary. + private func objcReport(old oldVersion: AxisVersion, new newVersion: AxisVersion) async throws -> DumpOutput { + let documents = try await measuringPreparation { + let oldDocument = try await objcSnapshotDocument(of: oldVersion.primaryImage, label: oldVersion.label) + let newDocument = try await objcSnapshotDocument(of: newVersion.primaryImage, label: newVersion.label) + return (old: oldDocument, new: newDocument) + } + let diff = ObjCAPIDiffer().diff(old: documents.old, new: documents.new) + let verdict = "API-breaking: \(diff.hasBreakingChange) · backward-compatible: \(diff.isBackwardCompatible)" + let report = ObjCAPIDiffReporter().report(diff) + "\n\n" + verdict + return DumpOutput( + consoleText: report, + files: [ + DumpFile(suffix: "ObjCDiff", fileExtension: "txt", text: report), + DumpFile(suffix: "ObjCDiff", fileExtension: "json", text: String(decoding: try ObjCAPIJSON.encoder().encode(diff), as: UTF8.self)), + ] + ) + } +} diff --git a/Tests/IntegrationTests/InspectionDumps/DiffTests.swift b/Tests/IntegrationTests/InspectionDumps/DiffTests.swift new file mode 100644 index 000000000..4fc003757 --- /dev/null +++ b/Tests/IntegrationTests/InspectionDumps/DiffTests.swift @@ -0,0 +1,166 @@ +import Foundation +import Testing +import MachOKit +import SwiftSectionFixtureSupport +@testable import SwiftSectionTestingSupport +@testable import MachOSwiftSection + +/// Every diff the maintainer inspects, one suite per place the two versions +/// come from. Each suite runs every diff output on one pair, which its +/// `configuration` names; the pairs come from the version axis base classes +/// the evolution suites read too (`MultiVersionDyldCacheImageTests`, +/// `CrossVersionMachOFileTests`, `CrossVersionXcodeFrameworkTests`). To diff +/// another framework, add a configuration and point the suite at it. +enum Diff { + /// The same file in two simulator runtimes (iOS 18.5 → 26.5). + final class SimulatorFiles: CrossVersionMachOFileTests, nonisolated DiffDumpTests, @unchecked Sendable { + override class var configuration: SimulatorFilePairConfiguration { .swiftUICore } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftReportFile() async throws { + try await dump(.swiftReport, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftReportString() async throws { + try await dump(.swiftReport, to: .console) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftInterfaceFile() async throws { + try await dump(.swiftInterface, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftInterfaceString() async throws { + try await dump(.swiftInterface, to: .console) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcReportFile() async throws { + try await dump(.objcReport, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcReportString() async throws { + try await dump(.objcReport, to: .console) + } + } + + /// The same image from two dyld shared caches (macOS 26.5.1 → 27.0), + /// each opened whole the way `swift-section --dyld-shared-cache` opens + /// it. Cross-image references resolve through each cache. + final class Caches: MultiVersionDyldCacheImageTests, nonisolated DiffDumpTests, @unchecked Sendable { + override class var cachePaths: [DyldSharedCachePath] { [.macOS_26_5_1, .macOS_27_0] } + + override class var configuration: CacheImagesConfiguration { .appKit } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftReportFile() async throws { + try await dump(.swiftReport, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftReportString() async throws { + try await dump(.swiftReport, to: .console) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftInterfaceFile() async throws { + try await dump(.swiftInterface, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftInterfaceString() async throws { + try await dump(.swiftInterface, to: .console) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcReportFile() async throws { + try await dump(.objcReport, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcReportString() async throws { + try await dump(.objcReport, to: .console) + } + } + + /// The same image from two archived macOS caches, picked by version: + /// point the two versions at any directories under + /// `/Volumes/DyldSharedCaches/macOS` that hold a cache. + final class ArchivedCaches: MultiVersionDyldCacheImageTests, nonisolated DiffDumpTests, @unchecked Sendable { + class var oldCacheVersion: String { "26.6" } + + class var newCacheVersion: String { "27.0" } + + override class var cachePaths: [DyldSharedCachePath] { [.macOS(oldCacheVersion), .macOS(newCacheVersion)] } + + override class var configuration: CacheImagesConfiguration { .appKit } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftReportFile() async throws { + try await dump(.swiftReport, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftReportString() async throws { + try await dump(.swiftReport, to: .console) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftInterfaceFile() async throws { + try await dump(.swiftInterface, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftInterfaceString() async throws { + try await dump(.swiftInterface, to: .console) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcReportFile() async throws { + try await dump(.objcReport, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcReportString() async throws { + try await dump(.objcReport, to: .console) + } + } + + /// The same shared framework in two installed Xcodes (26.3.0 → 26.4.0). + final class XcodeFrameworks: CrossVersionXcodeFrameworkTests, nonisolated DiffDumpTests, @unchecked Sendable { + override class var configuration: XcodeFrameworkPairConfiguration { .dvtProductsUI } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftReportFile() async throws { + try await dump(.swiftReport, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftReportString() async throws { + try await dump(.swiftReport, to: .console) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftInterfaceFile() async throws { + try await dump(.swiftInterface, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftInterfaceString() async throws { + try await dump(.swiftInterface, to: .console) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcReportFile() async throws { + try await dump(.objcReport, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcReportString() async throws { + try await dump(.objcReport, to: .console) + } + } +} diff --git a/Tests/IntegrationTests/InspectionDumps/EvolutionDumpTests.swift b/Tests/IntegrationTests/InspectionDumps/EvolutionDumpTests.swift new file mode 100644 index 000000000..f1e20fba6 --- /dev/null +++ b/Tests/IntegrationTests/InspectionDumps/EvolutionDumpTests.swift @@ -0,0 +1,275 @@ +import Foundation +import Testing +import MachOKit +import SwiftSectionFixtureSupport +import SwiftSectionTestingSupport +@testable import MachOSwiftSection +import SwiftDeclarationRendering +@_spi(Support) @testable import SwiftInterface +@_spi(Support) @testable import SwiftIndexing +import SwiftDiffing +import ObjCMetadataSource +import ObjCIndexing +import ObjCInterface +import ObjCDiffing +import Semantic + +/// The four evolution outputs `swift-section` produces, each the pipeline of +/// one subcommand. +enum EvolutionDumpKind: Sendable { + /// `swift-section evolution`: the lineage report (`-Evolution.txt`) and + /// its machine-readable form (`-Evolution.json`). + case swiftReport + /// `swift-section evolution --interface`: the union interface with + /// lifecycle annotations (`-EvolutionInterface.swiftinterface`). + case swiftInterface + /// `swift-section objc evolution`: the lineage report + /// (`-ObjCEvolution.txt`) and its JSON (`-ObjCEvolution.json`). + case objcReport + /// `swift-section objc evolution --interface`: the union header with + /// lifecycle annotations (`-ObjCEvolutionInterface.h`). + case objcInterface + + var language: MetadataLanguage { + switch self { + case .swiftReport, .swiftInterface: .swift + case .objcReport, .objcInterface: .objc + } + } +} + +/// The evolution dumps: an *ordered series* of versions of one image — or +/// of one group of images per version (evolution proposal +/// `image-group-evolution`) — run through the pipelines of `swift-section +/// evolution` and `swift-section objc evolution`, with and without +/// `--interface`. +/// +/// The report pipelines freeze every version into a snapshot document +/// round-tripped through the persisted JSON form, so the codec and the +/// format-version gate run on real-world data. The interface pipelines +/// render the versions merged into one interface, each declaration's +/// lifecycle annotated; read one against the report of the same axis — the +/// annotations are the same lineages. +/// +/// A conforming suite supplies the axis each pipeline runs over +/// (`VersionAxisDumpTests`). Like its siblings this is a maintainer-inspection +/// dump: it prints / writes results without assertions. +protocol EvolutionDumpTests: VersionAxisDumpTests {} + +@available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) +extension EvolutionDumpTests { + /// Runs one pipeline over this suite's axis for the pipeline's language, + /// then prints the text, or writes the text — and a report's JSON — + /// named after the newest version's images. + /// + /// Left unoptimized for the same Swift 6.3 optimizer crash as + /// `DiffDumpTests.dump(_:to:)`: Xcode 26.6's CopyPropagation pass crashes + /// on this function's specialization for a conforming suite in a release + /// build. + @_optimize(none) + func dump(_ kind: EvolutionDumpKind, to destination: DumpDestination) async throws { + let axis = versionAxis(for: kind.language) + let output: DumpOutput + switch kind { + case .swiftReport: + output = try await swiftReport(over: axis) + case .swiftInterface: + output = try await swiftInterface(over: axis) + case .objcReport: + output = try await objcReport(over: axis) + case .objcInterface: + output = try await objcInterface(over: axis) + } + try deliver(output, to: destination) { file in + guard let newestVersion = axis.versions.last else { return } + try write(file.text, forImageGroup: newestVersion.images, suffix: file.suffix, fileExtension: file.fileExtension) + } + } + + // MARK: - Swift + + /// One image indexed the way `swift-section snapshot` indexes it and + /// frozen into a labeled snapshot document, round-tripped through the + /// persisted form: what the evolution consumes is exactly what a saved + /// baseline would decode to. + private func swiftSnapshotDocument(of image: AxisImage, label: String) async throws -> ABISnapshotDocument { + let builder = SwiftDiffableInterfaceBuilder(configuration: indexConfiguration, in: image.machOFile) + try await builder.prepare() + let document = ABISnapshotDocument( + provenance: ABIProvenance( + label: label, + binaryPath: image.machOFile.imagePath, + generatorVersion: "IntegrationTests", + createdAt: Date() + ), + snapshot: builder.snapshot() + ) + return try ABISnapshotDocument.decode(from: document.encoded()) + } + + /// The lineage report and its JSON. The timed step covers indexing every + /// image of every version — the real cost; the lineage math afterwards + /// is milliseconds. + private func swiftReport(over axis: VersionAxis) async throws -> DumpOutput { + var documentsByVersion: [[ABISnapshotDocument]] = [] + try await measuringPreparation { + for version in axis.versions { + var documents: [ABISnapshotDocument] = [] + for image in version.images { + documents.append(try await swiftSnapshotDocument(of: image, label: version.label)) + } + documentsByVersion.append(documents) + } + } + let evolution: ABIEvolution + var report: String + if axis.comparesImageGroups { + let imageGroups = zip(axis.versions, documentsByVersion).map { version, documents in + zip(version.images, documents).map { image, document in + ABIImageSnapshot(imageName: image.imageName, snapshot: document.snapshot) + } + } + evolution = try ABIEvolutionBuilder().evolution( + ofImageGroups: imageGroups, + versions: axis.versions.map { ABIVersionDescriptor(label: $0.label) } + ) + report = ABIEvolutionReporter().report(evolution) + } else { + let documents = documentsByVersion.flatMap { $0 } + evolution = try ABIEvolutionBuilder().evolution(of: documents) + report = ABIEvolutionReporter().report(evolution) + // For a two-version series the lineage events must match the + // two-sided differ verbatim — print both verdicts so the manual + // inspection can eyeball the consistency on real-world data. + if documents.count == 2, let oldDocument = documents.first, let newDocument = documents.last { + let diff = ABIDiffer().diff(old: oldDocument, new: newDocument) + report += "\n\nPairwise cross-check — evolution ABI-breaking: \(evolution.hasBreakingChange) · diff ABI-breaking: \(diff.hasBreakingChange)" + } + } + return DumpOutput( + consoleText: report, + files: [ + DumpFile(suffix: "Evolution", fileExtension: "txt", text: report), + DumpFile(suffix: "Evolution", fileExtension: "json", text: String(decoding: try ABIJSON.encoder().encode(evolution), as: UTF8.self)), + ] + ) + } + + /// The annotated union interface plus the per-axis verdict line, so the + /// manual inspection can eyeball the CI-gate input next to the + /// rendering. The timed step covers indexing every version; the lineage + /// join and rendering afterwards are cheap by comparison. + private func swiftInterface(over axis: VersionAxis) async throws -> DumpOutput { + let labels = axis.versions.map(\.label) + let availabilityAnnotationPlatform = axis.availabilityPlatform?.swiftSpelling + let builder: AnySwiftEvolutionInterfaceBuilder + if axis.comparesImageGroups { + // Each version's images render as one interface, every + // declaration through the image that indexed it. + builder = try AnySwiftEvolutionInterfaceBuilder( + configuration: indexConfiguration, + imageGroups: axis.versions.map { version in + version.images.map { SwiftEvolutionInterfaceImage(imageName: $0.imageName, machO: $0.machOFile) } + }, + labels: labels, + availabilityAnnotationPlatform: availabilityAnnotationPlatform + ) + } else { + builder = try AnySwiftEvolutionInterfaceBuilder( + configuration: indexConfiguration, + versions: axis.versions.map(\.primaryImage.machOFile), + labels: labels, + availabilityAnnotationPlatform: availabilityAnnotationPlatform + ) + } + try await measuringPreparation { + try await builder.prepare() + } + var report = try await builder.printAnnotatedInterface().string + if let evolution = builder.evolution { + report += "\n\n// ABI-breaking on this axis: \(evolution.hasBreakingChange)" + } + return DumpOutput( + consoleText: report, + files: [DumpFile(suffix: "EvolutionInterface", fileExtension: "swiftinterface", text: report)] + ) + } + + // MARK: - Objective-C + + /// The lineage report and its JSON, as `swiftReport(over:)` builds the + /// Swift ones. + private func objcReport(over axis: VersionAxis) async throws -> DumpOutput { + var documentsByVersion: [[ObjCAPISnapshotDocument]] = [] + try await measuringPreparation { + for version in axis.versions { + var documents: [ObjCAPISnapshotDocument] = [] + for image in version.images { + documents.append(try await objcSnapshotDocument(of: image, label: version.label)) + } + documentsByVersion.append(documents) + } + } + let evolution: ObjCAPIEvolution + var report: String + if axis.comparesImageGroups { + let imageGroups = zip(axis.versions, documentsByVersion).map { version, documents in + zip(version.images, documents).map { image, document in + ObjCAPIImageSnapshot(imageName: image.imageName, snapshot: document.snapshot) + } + } + evolution = try ObjCAPIEvolutionBuilder().evolution( + ofImageGroups: imageGroups, + versions: axis.versions.map { ObjCAPIVersionDescriptor(label: $0.label) } + ) + report = ObjCAPIEvolutionReporter().report(evolution) + } else { + let documents = documentsByVersion.flatMap { $0 } + evolution = try ObjCAPIEvolutionBuilder().evolution(of: documents) + report = ObjCAPIEvolutionReporter().report(evolution) + if documents.count == 2, let oldDocument = documents.first, let newDocument = documents.last { + let diff = ObjCAPIDiffer().diff(old: oldDocument, new: newDocument) + report += "\n\nPairwise cross-check — evolution API-breaking: \(evolution.hasBreakingChange) · diff API-breaking: \(diff.hasBreakingChange)" + } + } + return DumpOutput( + consoleText: report, + files: [ + DumpFile(suffix: "ObjCEvolution", fileExtension: "txt", text: report), + DumpFile(suffix: "ObjCEvolution", fileExtension: "json", text: String(decoding: try ObjCAPIJSON.encoder().encode(evolution), as: UTF8.self)), + ] + ) + } + + /// The annotated union header plus the per-axis verdict line. Every + /// version is indexed the way `objc evolution --interface` indexes it and + /// handed to the builder, which keeps what it rendered and snapshotted, + /// never the indexer; a group's images go in together, the primary image + /// first, so a class that moved between them stays one declaration. + private func objcInterface(over axis: VersionAxis) async throws -> DumpOutput { + var builder = ObjCEvolutionInterfaceBuilder() + try await measuringPreparation { + for version in axis.versions { + let versionDescriptor = ObjCAPIVersionDescriptor(label: version.label) + if axis.comparesImageGroups { + var images: [ObjCEvolutionInterfaceImage] = [] + for image in version.images { + let indexer = try await preparedObjCIndexer(of: image.machOFile) + images.append(ObjCEvolutionInterfaceImage(imageName: image.imageName, indexer: indexer, machO: image.machOFile)) + } + builder.addVersion(images: images, version: versionDescriptor) + } else { + let image = version.primaryImage + let indexer = try await preparedObjCIndexer(of: image.machOFile) + builder.addVersion(indexer: indexer, machO: image.machOFile, version: versionDescriptor) + } + } + } + let evolutionInterface = try builder.build(availabilityPlatform: axis.availabilityPlatform?.objcSpelling) + let header = evolutionInterface.interface.string + "\n\n// API-breaking on this axis: \(evolutionInterface.evolution.hasBreakingChange)" + return DumpOutput( + consoleText: header, + files: [DumpFile(suffix: "ObjCEvolutionInterface", fileExtension: "h", text: header)] + ) + } +} diff --git a/Tests/IntegrationTests/InspectionDumps/EvolutionTests.swift b/Tests/IntegrationTests/InspectionDumps/EvolutionTests.swift new file mode 100644 index 000000000..9336b2a59 --- /dev/null +++ b/Tests/IntegrationTests/InspectionDumps/EvolutionTests.swift @@ -0,0 +1,198 @@ +import Foundation +import Testing +import MachOKit +import SwiftSectionFixtureSupport +@testable import SwiftSectionTestingSupport +@testable import MachOSwiftSection +@_spi(Support) @testable import SwiftInterface +@_spi(Support) @testable import SwiftIndexing +import Semantic + +/// Every evolution the maintainer inspects, one suite per place the versions +/// come from. Each suite runs every evolution output — the Swift and +/// Objective-C reports and interfaces alike — on one series of versions, +/// which its `configuration` names; each language's pipelines see only the +/// versions whose images carry their metadata (see +/// `MultiVersionDyldCacheImageTests`). To follow another framework or group +/// of images, add a configuration and point the suite at it. +/// +/// Read an interface against the report of the same axis: the two views +/// must tell one story. An annotated interface is worth reading only from +/// three versions up — introduced mid-axis, removed mid-axis, modified +/// twice, gone-and-back bitmaps; for two, `diff --interface` already covers +/// it. +enum Evolution { + /// The default three macOS caches (15.5 → 26.5.2 → 27.0) — the N == 3 + /// lineage: introduced / modified / removed / re-added stories only + /// visible with more than two versions. + final class Caches: MultiVersionDyldCacheImageTests, nonisolated EvolutionDumpTests, @unchecked Sendable { + override class var configuration: CacheImagesConfiguration { .swiftUIGroup } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftReportFile() async throws { + try await dump(.swiftReport, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftReportString() async throws { + try await dump(.swiftReport, to: .console) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftInterfaceFile() async throws { + try await dump(.swiftInterface, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftInterfaceString() async throws { + try await dump(.swiftInterface, to: .console) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcReportFile() async throws { + try await dump(.objcReport, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcReportString() async throws { + try await dump(.objcReport, to: .console) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcInterfaceFile() async throws { + try await dump(.objcInterface, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcInterfaceString() async throws { + try await dump(.objcInterface, to: .console) + } + + /// The pack-generic façade on the first three versions' primary + /// images: the axis through `SwiftEvolutionInterfaceBuilder` (compile-time arity), dumped for eyeball + /// comparison against `swiftInterfaceString()` — byte-identical when + /// the configuration reads one image per version. + @available(macOS 14.0, iOS 17.0, tvOS 17.0, watchOS 10.0, *) + @Test func swiftInterfaceStringViaPackFacade() async throws { + let versions = versionAxis(for: .swift).versions + guard versions.count >= 3 else { + printResult("No pack façade dump: \(versions.count) version(s) carry Swift metadata") + return + } + let builder = try SwiftEvolutionInterfaceBuilder( + configuration: indexConfiguration, + versions: versions[0].primaryImage.machOFile, versions[1].primaryImage.machOFile, versions[2].primaryImage.machOFile, + labels: versions.prefix(3).map(\.label) + ) + // No `measuringPreparation` here: this @Test runs on the suite's + // @TestActor, and handing it an actor-isolated closure trips + // region-isolation checking (the extension helpers avoid this by + // being nonisolated themselves). + try await builder.prepare() + printResult(try await builder.printAnnotatedInterface().string) + } + } + + /// Every archived macOS cache, 11.0 → 27.0. Every label is a version + /// number, so both interfaces also spell each lifecycle one attribute or + /// macro can express (`@available(macOS, …)`, `API_AVAILABLE(macos(…))`). + /// A group whose other images join late reads them from where they + /// appear: SwiftUICore joins SwiftUI in 15.0, where an evolution of + /// SwiftUI alone reads every declaration moved into SwiftUICore as + /// removed. + final class ArchivedCaches: MultiVersionDyldCacheImageTests, nonisolated EvolutionDumpTests, @unchecked Sendable { + override class var cachePaths: [DyldSharedCachePath] { archivedMacOSCachePaths } + + override class var availabilityPlatform: AvailabilityPlatform? { .macOS } + + override class var configuration: CacheImagesConfiguration { .swiftUIGroup } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftReportFile() async throws { + try await dump(.swiftReport, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftReportString() async throws { + try await dump(.swiftReport, to: .console) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftInterfaceFile() async throws { + try await dump(.swiftInterface, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftInterfaceString() async throws { + try await dump(.swiftInterface, to: .console) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcReportFile() async throws { + try await dump(.objcReport, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcReportString() async throws { + try await dump(.objcReport, to: .console) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcInterfaceFile() async throws { + try await dump(.objcInterface, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcInterfaceString() async throws { + try await dump(.objcInterface, to: .console) + } + } + + /// The same file in two simulator runtimes (iOS 18.5 → 26.5) — the + /// N == 2 case, whose printed pairwise cross-check line must agree with + /// the two-sided differ. + final class SimulatorFiles: CrossVersionMachOFileTests, nonisolated EvolutionDumpTests, @unchecked Sendable { + override class var configuration: SimulatorFilePairConfiguration { .swiftUICore } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftReportFile() async throws { + try await dump(.swiftReport, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftReportString() async throws { + try await dump(.swiftReport, to: .console) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftInterfaceFile() async throws { + try await dump(.swiftInterface, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftInterfaceString() async throws { + try await dump(.swiftInterface, to: .console) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcReportFile() async throws { + try await dump(.objcReport, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcReportString() async throws { + try await dump(.objcReport, to: .console) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcInterfaceFile() async throws { + try await dump(.objcInterface, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcInterfaceString() async throws { + try await dump(.objcInterface, to: .console) + } + } +} diff --git a/Tests/IntegrationTests/InspectionDumps/InspectionDumpTests.swift b/Tests/IntegrationTests/InspectionDumps/InspectionDumpTests.swift new file mode 100644 index 000000000..da06ec86c --- /dev/null +++ b/Tests/IntegrationTests/InspectionDumps/InspectionDumpTests.swift @@ -0,0 +1,222 @@ +import Foundation +import MachOKit +import SwiftSectionFixtureSupport +@testable import MachOSwiftSection +@_spi(Support) @testable import SwiftIndexing +import ObjCMetadataSource +import ObjCIndexing +import FoundationToolbox +import SwiftStdlibToolbox + +/// Shared scaffolding for the maintainer-inspection dumps: the +/// single-version interfaces (`InterfaceDumpTests`), the two-version diffs +/// (`DiffDumpTests`) and the N-version evolutions (`EvolutionDumpTests`). +/// +/// Every dump has the same shape — index the images (timed), run one +/// `swift-section` pipeline over them, then print the result or write it +/// next to the others — so the common machinery lives here once: the output +/// directory, the index configuration every pipeline shares, the +/// `prepare()` timer, the console and file sinks, and the file names that +/// identify the images. Like the dumps themselves, nothing here asserts. +protocol InspectionDumpTests {} + +/// The metadata a pipeline reads: an image without it has nothing to index, +/// and indexing it anyway only logs extraction failures. +enum MetadataLanguage: Sendable { + /// `__swift5_*` sections. AppKit kept its Swift API in + /// `libswiftAppKit.dylib` until macOS 14, so a Swift axis of AppKit + /// reaching further back starts at 14.0. + case swift + /// `__objc_*` sections, which AppKit carries in every cache. + case objc + + func isCarried(by machOFile: MachOFile) -> Bool { + let sectionNamePrefix = switch self { + case .swift: "__swift5_" + case .objc: "__objc_" + } + return machOFile.sections.contains(where: { $0.sectionName.hasPrefix(sectionNamePrefix) }) + } +} + +/// Where a dump goes: printed for a quick look, or written next to the +/// other dumps for inspection. +enum DumpDestination: Sendable { + case console + case file +} + +/// One file a dump writes, named +/// `--.`. +struct DumpFile: Sendable { + let suffix: String + let fileExtension: String + let text: String +} + +/// What one pipeline produced: the text the console destination prints, +/// and the files the file destination writes. +struct DumpOutput: Sendable { + let consoleText: String + let files: [DumpFile] +} + +@available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) +extension InspectionDumpTests { + /// The directory every dump is written under, shared so the interface, + /// diff and evolution artifacts of the same binary co-locate for manual + /// inspection. + var rootDirectory: URL { + .documentsDirectory.appending(path: "SwiftInterfaceTests") + } + + /// How every pipeline indexes Swift metadata. + var indexConfiguration: SwiftDeclarationIndexConfiguration { + .init(showCImportedTypes: false) + } + + /// Runs `prepare`, prints how long it took (unless running silently) and + /// returns what it prepared. Callers pass the whole preparation step — + /// for a diff that means preparing *both* binaries — so the printed + /// duration covers the real work. + func measuringPreparation(_ prepare: () async throws -> Prepared) async rethrows -> Prepared { + let clock = ContinuousClock() + let start = clock.now + let prepared = try await prepare() + #if !SILENT_TEST + print(clock.now - start) + #endif + return prepared + } + + /// Prints a rendered dump to the console, unless running silently. + func printResult(_ string: String) { + #if !SILENT_TEST + print(string) + #endif + } + + /// Prints `output`'s console text, or hands each of its files to + /// `writeFile`, which names it after the images the dump read. + func deliver(_ output: DumpOutput, to destination: DumpDestination, writingFile writeFile: (DumpFile) throws -> Void) rethrows { + switch destination { + case .console: + printResult(output.consoleText) + case .file: + for file in output.files { + try writeFile(file) + } + } + } + + /// Writes a rendered dump into `rootDirectory` under a name that identifies + /// the binary by its build version and file name, so repeated runs overwrite + /// in place and different binaries never collide. + func write( + _ string: String, + for machO: some MachOSwiftSectionRepresentableWithCache, + suffix: String, + fileExtension: String = "swiftinterface" + ) throws { + try rootDirectory.createDirectoryIfNeeded() + let fileName = "\(machO.loadCommands.buildVersionCommand!)-\(machO.imagePath.lastPathComponent)-\(suffix).\(fileExtension)" + try string.write(to: rootDirectory.appending(path: fileName), atomically: true, encoding: .utf8) + } + + /// `write(_:for:suffix:fileExtension:)` for one version of a version + /// axis, which may be a group of images (evolution proposal + /// `image-group-evolution`): named after the primary image's build + /// version and every image of the version, joined by `+` + /// (`…-SwiftUI+SwiftUICore-Evolution.txt`). A version of one image gets + /// the name `write(_:for:…)` gives it. + func write( + _ string: String, + forImageGroup images: [AxisImage], + suffix: String, + fileExtension: String = "swiftinterface" + ) throws { + guard let primaryImage = images.first else { return } + try rootDirectory.createDirectoryIfNeeded() + let imageGroupName = images.map { $0.machOFile.imagePath.lastPathComponent }.joined(separator: "+") + let fileName = "\(primaryImage.machOFile.loadCommands.buildVersionCommand!)-\(imageGroupName)-\(suffix).\(fileExtension)" + try string.write(to: rootDirectory.appending(path: fileName), atomically: true, encoding: .utf8) + } +} + +/// One image indexed the way the `objc` subcommands index it: the Swift +/// classes that keep no class object supplied from Swift metadata. +@available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) +func preparedObjCIndexer(of machO: MachO) async throws -> ObjCInterfaceIndexer { + let indexer = ObjCInterfaceIndexer( + machO: machO, + imagePath: machO.imagePath, + suppliedClasses: ObjCSuppliedClass.swiftClassesWithoutClassObjects(in: machO) + ) + try await indexer.prepare() + return indexer +} + +extension BuildVersionCommand: @retroactive CustomStringConvertible { + public var description: String { + "\(platform.stringValue)-\(sdk)" + } +} + +extension MachOKit.Platform { + var stringValue: String { + switch self { + case .unknown: + "Unknown" + case .any: + "Any" + case .macOS: + "macOS" + case .iOS: + "iOS" + case .tvOS: + "tvOS" + case .watchOS: + "watchOS" + case .bridgeOS: + "bridgeOS" + case .macCatalyst: + "macCatalyst" + case .iOSSimulator: + "iOSSimulator" + case .tvOSSimulator: + "tvOSSimulator" + case .watchOSSimulator: + "watchOSSimulator" + case .driverKit: + "DriverKit" + case .visionOS: + "visionOS" + case .visionOSSimulator: + "visionOSSimulator" + case .firmware: + "Firmware" + case .sepOS: + "sepOS" + case .macOSExclaveCore: + "macOSExclaveCore" + case .macOSExclaveKit: + "macOSExclaveKit" + case .iOSExclaveCore: + "iOSExclaveCore" + case .iOSExclaveKit: + "iOSExclaveKit" + case .tvOSExclaveCore: + "tvOSExclaveCore" + case .tvOSExclaveKit: + "tvOSExclaveKit" + case .watchOSExclaveCore: + "watchOSExclaveCore" + case .watchOSExclaveKit: + "watchOSExclaveKit" + case .visionOSExclaveCore: + "visionOSExclaveCore" + case .visionOSExclaveKit: + "visionOSExclaveKit" + } + } +} diff --git a/Tests/IntegrationTests/InspectionDumps/InterfaceDumpTests.swift b/Tests/IntegrationTests/InspectionDumps/InterfaceDumpTests.swift new file mode 100644 index 000000000..6d7323bd7 --- /dev/null +++ b/Tests/IntegrationTests/InspectionDumps/InterfaceDumpTests.swift @@ -0,0 +1,154 @@ +import Foundation +import Testing +import MachOKit +import SwiftSectionFixtureSupport +@testable import MachOSwiftSection +import SwiftDeclarationRendering +@_spi(Support) @testable import SwiftPrinting +@_spi(Support) @testable import SwiftInterface +@_spi(Support) @testable import SwiftIndexing +import ObjCMetadataSource +import ObjCIndexing +import ObjCInterface +import ObjCDeclarationRendering +import Semantic + +/// The two single-version outputs, each the pipeline of one subcommand. +enum InterfaceDumpKind: Sendable { + /// `swift-section interface`: the image's Swift interface + /// (`-FileDump.swiftinterface`, or `-ImageDump.swiftinterface` for an + /// image read in process). + case swiftInterface + /// `swift-section objc dump`: every Objective-C declaration of the image + /// (`-ObjCFileDump.h` / `-ObjCImageDump.h`). + case objcInterface +} + +/// The single-version dumps: one image — a file, an image of a dyld shared +/// cache, or an image this process loaded — run through the pipelines of +/// `swift-section interface` and `swift-section objc dump`. +/// +/// A conforming suite inherits the `MachOTestingSupport` base class that +/// loads its image and passes that image to `dump(_:of:to:)`. Both outputs +/// print every comment the binary supports, so the dump carries as much as +/// the binary tells. Like its siblings this is a maintainer-inspection dump: +/// it prints / writes results without assertions. +protocol InterfaceDumpTests: InspectionDumpTests { + /// Whether both outputs print only what the image exports — what + /// `interface --exported-only` does, and the Objective-C header's + /// `printExportedDeclarationsOnly` option. A suite isolated to an actor + /// overrides it `nonisolated`. + var printsExportedDeclarationsOnly: Bool { get } +} + +@available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) +extension InterfaceDumpTests { + var printsExportedDeclarationsOnly: Bool { false } + + var builderConfiguration: SwiftInterfaceBuilderConfiguration { + SwiftInterfaceBuilderConfiguration( + indexConfiguration: indexConfiguration, + printConfiguration: .init( + printStrippedSymbolicItem: true, + printFieldOffset: true, + printExpandedFieldOffsets: true, + printMemberAddress: true, + printVTableOffset: true, + printPWTOffset: true, + printExportedDeclarationsOnly: printsExportedDeclarationsOnly, + infersObjCOverridesFromSelectorNames: true, + usesModuleSelectors: true, + protocolRequirementPlacement: .associatedTypes, + memberSortOrder: .byOffset, + printTypeLayout: true, + printEnumLayout: true, + ), + ) + } + + /// Every comment an Objective-C declaration can carry: ivar offsets, + /// property attributes, method and accessor addresses. + var objcGenerationOptions: ObjCGenerationOptions { + var options = ObjCGenerationOptions.default + options.addIvarOffsetComments = true + options.addPropertyAttributesComments = true + options.addMethodIMPAddressComments = true + options.addPropertyAccessorAddressComments = true + options.printExportedDeclarationsOnly = printsExportedDeclarationsOnly + return options + } + + /// Runs one pipeline over `machO`, then prints the result, or writes it + /// named after the image and the reader that read it. + /// + /// Left unoptimized, like `DiffDumpTests.dump(_:to:)` and + /// `EvolutionDumpTests.dump(_:to:)`, whose specializations crash the + /// CopyPropagation pass of Xcode 26.6's Swift 6.3 optimizer in a release + /// build: this one has the same shape. + @_optimize(none) + func dump( + _ kind: InterfaceDumpKind, + of machO: MachO, + to destination: DumpDestination + ) async throws { + let output: DumpOutput + switch kind { + case .swiftInterface: + output = try await swiftInterface(of: machO) + case .objcInterface: + output = try await objcInterface(of: machO) + } + try deliver(output, to: destination) { file in + try write(file.text, for: machO, suffix: file.suffix, fileExtension: file.fileExtension) + } + } + + /// `ImageDump` for an image read in process, `FileDump` for a file, so + /// the file name tells which reader produced it. + private func readerSuffix(of machO: some MachORepresentableWithCache) -> String { + machO.asMachOImage != nil ? "ImageDump" : "FileDump" + } + + /// The interface `swift-section interface` prints. The timed step is the + /// indexing; printing afterwards is not timed. + private func swiftInterface(of machO: MachO) async throws -> DumpOutput { + let builder = try SwiftInterfaceBuilder(configuration: builderConfiguration, eventHandlers: [], in: machO) + builder.addExtraDataProvider(SwiftInterfaceBuilderOpaqueTypeProvider(machO: machO)) + try await measuringPreparation { try await builder.prepare() } + let interface = try await builder.printRoot().string + return DumpOutput( + consoleText: interface, + files: [DumpFile(suffix: readerSuffix(of: machO), fileExtension: "swiftinterface", text: interface)] + ) + } + + /// Every Objective-C declaration of the image, the way `objc dump` + /// writes them to a file: classes, protocols, categories, structs and + /// unions in that order, each kind sorted by name — the index keeps its + /// names in dictionaries, whose order is not stable across runs — and a + /// blank line after each. + private func objcInterface(of machO: MachO) async throws -> DumpOutput { + let indexer = try await measuringPreparation { try await preparedObjCIndexer(of: machO) } + let builder = ObjCInterfaceBuilder(indexer: indexer, machO: machO) + let options = objcGenerationOptions + let declarationKinds: [(names: [String], interface: (String) -> SemanticString?)] = [ + (indexer.classNames.sorted(), { builder.classInterface(named: $0, options: options) }), + (indexer.protocolNames.sorted(), { builder.protocolInterface(named: $0, options: options) }), + (indexer.categoryNames.sorted(), { builder.categoryInterface(uniqueName: $0, options: options) }), + (indexer.structNames.sorted(), { builder.structInterface(named: $0, options: options) }), + (indexer.unionNames.sorted(), { builder.unionInterface(named: $0, options: options) }), + ] + var header = "" + for declarationKind in declarationKinds { + for name in declarationKind.names { + guard let interface = declarationKind.interface(name) else { continue } + header.append(interface.string) + header.append("\n\n") + } + } + return DumpOutput( + consoleText: header, + files: [DumpFile(suffix: "ObjC" + readerSuffix(of: machO), fileExtension: "h", text: header)] + ) + } +} diff --git a/Tests/IntegrationTests/InspectionDumps/InterfaceTests.swift b/Tests/IntegrationTests/InspectionDumps/InterfaceTests.swift new file mode 100644 index 000000000..09e7cf7aa --- /dev/null +++ b/Tests/IntegrationTests/InspectionDumps/InterfaceTests.swift @@ -0,0 +1,147 @@ +import Foundation +import Testing +import MachOKit +import SwiftSectionFixtureSupport +@testable import SwiftSectionTestingSupport +@testable import MachOSwiftSection + +/// Every single-version interface the maintainer inspects, one suite per +/// place an image is read from. Each suite runs both outputs on one image, +/// which is its configuration: point `cacheImageName`, `fileName` or +/// `imageName` at any image to look at it. +enum Interface { + /// An image of this Mac's dyld shared cache. + class SystemCache: SwiftSectionTestingSupport.DyldCacheTests, nonisolated InterfaceDumpTests, @unchecked Sendable { + override class var cacheImageName: MachOImageName { .AppKit } + + override class var cachePath: DyldSharedCachePath { .current } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftInterfaceFile() async throws { + try await dump(.swiftInterface, of: machOFileInCache, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftInterfaceString() async throws { + try await dump(.swiftInterface, of: machOFileInCache, to: .console) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcInterfaceFile() async throws { + try await dump(.objcInterface, of: machOFileInCache, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcInterfaceString() async throws { + try await dump(.objcInterface, of: machOFileInCache, to: .console) + } + } + + /// An image of an archived macOS cache, picked by version: point + /// `cacheVersion` at any directory under `/Volumes/DyldSharedCaches/macOS` + /// that holds a cache. + class ArchivedCache: SwiftSectionTestingSupport.DyldCacheTests, nonisolated InterfaceDumpTests, @unchecked Sendable { + class var cacheVersion: String { "26.6" } + + override class var cachePath: DyldSharedCachePath { .macOS(cacheVersion) } + + override class var cacheImageName: MachOImageName { .AppKit } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftInterfaceFile() async throws { + try await dump(.swiftInterface, of: machOFileInCache, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftInterfaceString() async throws { + try await dump(.swiftInterface, of: machOFileInCache, to: .console) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcInterfaceFile() async throws { + try await dump(.objcInterface, of: machOFileInCache, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcInterfaceString() async throws { + try await dump(.objcInterface, of: machOFileInCache, to: .console) + } + } + + /// A file on disk. + class File: SwiftSectionTestingSupport.MachOFileTests, nonisolated InterfaceDumpTests, @unchecked Sendable { + override class var fileName: MachOFileName { .SymbolTestsCore } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftInterfaceFile() async throws { + try await dump(.swiftInterface, of: machOFile, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftInterfaceString() async throws { + try await dump(.swiftInterface, of: machOFile, to: .console) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcInterfaceFile() async throws { + try await dump(.objcInterface, of: machOFile, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcInterfaceString() async throws { + try await dump(.objcInterface, of: machOFile, to: .console) + } + } + + /// An image this process loaded, read in process. + class InProcessImage: SwiftSectionTestingSupport.MachOImageTests, nonisolated InterfaceDumpTests, @unchecked Sendable { + override class var imageName: MachOImageName { .SwiftUICore } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftInterfaceFile() async throws { + try await dump(.swiftInterface, of: machOImage, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftInterfaceString() async throws { + try await dump(.swiftInterface, of: machOImage, to: .console) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcInterfaceFile() async throws { + try await dump(.objcInterface, of: machOImage, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcInterfaceString() async throws { + try await dump(.objcInterface, of: machOImage, to: .console) + } + } + + /// A file inside Xcode, printed with only what it exports. + class XcodeFile: SwiftSectionTestingSupport.XcodeMachOFileTests, InterfaceDumpTests { + override class var fileName: XcodeMachOFileName { .sharedFrameworks(.SourceEditor) } + + var printsExportedDeclarationsOnly: Bool { true } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftInterfaceFile() async throws { + try await dump(.swiftInterface, of: machOFile, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func swiftInterfaceString() async throws { + try await dump(.swiftInterface, of: machOFile, to: .console) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcInterfaceFile() async throws { + try await dump(.objcInterface, of: machOFile, to: .file) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func objcInterfaceString() async throws { + try await dump(.objcInterface, of: machOFile, to: .console) + } + } +} diff --git a/Tests/IntegrationTests/InspectionDumps/MultiVersionDyldCacheImageTests.swift b/Tests/IntegrationTests/InspectionDumps/MultiVersionDyldCacheImageTests.swift new file mode 100644 index 000000000..2974db017 --- /dev/null +++ b/Tests/IntegrationTests/InspectionDumps/MultiVersionDyldCacheImageTests.swift @@ -0,0 +1,174 @@ +import Foundation +import Testing +import MachOKit +import SwiftSectionFixtureSupport +import SwiftSectionTestingSupport +@testable import MachOSwiftSection +import FoundationToolbox +import SwiftStdlibToolbox + +/// The images a dyld shared cache suite reads out of each cache, the +/// primary image first. More than one makes every version a group of images +/// (evolution proposal `image-group-evolution`): AppKit with the frameworks +/// Apple moved its classes into, SwiftUI with SwiftUICore. Each other image +/// joins its group where the cache has it with the metadata — +/// CollectionViewCore is in the macOS caches from 13.0 on, SwiftUICore from +/// 15.0 on. +/// +/// A suite points at one of these; to look at another framework, add one and +/// point the suite at it. +struct CacheImagesConfiguration: Sendable { + let imageNames: [MachOImageName] + + static var swiftUI: Self { Self(imageNames: [.SwiftUI]) } + static var swiftUICore: Self { Self(imageNames: [.SwiftUICore]) } + /// AppKit kept its Swift API in `libswiftAppKit.dylib` until macOS 14, + /// so its Swift axis starts at 14.0; its Objective-C metadata is in every + /// cache. + static var appKit: Self { Self(imageNames: [.AppKit]) } + static var swiftUIGroup: Self { Self(imageNames: [.SwiftUI, .SwiftUICore]) } + static var appKitGroup: Self { Self(imageNames: [.AppKit, .UIFoundation, .CollectionViewCore, .CoreAutoLayout]) } +} + +/// Extracts the same images from an *ordered series* of dyld shared caches: +/// N versions for an evolution, two for a diff. The caches are retained +/// because the extracted `MachOFile`s resolve cross-image references through +/// them while indexing. +/// +/// One instance serves every pipeline: it keeps, per cache, every image of +/// `configuration` the cache holds, and each language's axis then keeps +/// the images carrying that language's metadata. A version whose primary +/// image is missing, or lacks the metadata, is off that axis — there is +/// nothing to index. A cache that cannot be opened still throws. +/// +/// Each cache is opened whole, the way `swift-section --dyld-shared-cache` +/// opens it, so the dumps match what the command line prints. Opened from +/// its main file alone, every read into another sub-cache file mapped that +/// file once more until MachOObjCSection 0.8.109, and an evolution over +/// every archived macOS minor ran past 5 GB. A diff reads the primary image +/// of each version only. +@TestActor +class MultiVersionDyldCacheImageTests: Sendable { + let caches: [FullDyldCache] + private let axes: VersionAxes + + /// Oldest first; each cache's `versionLabel` labels it on the axis. + class var cachePaths: [DyldSharedCachePath] { defaultMacOSCachePaths } + + /// The images whose declarations make up one version. + class var configuration: CacheImagesConfiguration { .swiftUI } + + /// Set on an axis whose every label is a version number. + class var availabilityPlatform: AvailabilityPlatform? { nil } + + /// The three macOS caches most evolution suites read: 15.5 → 26.5.2 → 27.0. + static var defaultMacOSCachePaths: [DyldSharedCachePath] { + [.macOS_15_5, .macOS_26_5_2, .macOS_27_0] + } + + /// One archived cache per macOS minor, oldest first: the directories + /// under `/Volumes/DyldSharedCaches/macOS` that hold a cache. A cache is + /// labeled with its version, or with the major release + /// `archivedMacOSVersionLabelsByCacheVersion` names for it, so every label + /// is a version number. + static var archivedMacOSCachePaths: [DyldSharedCachePath] { + archivedMacOSCacheVersions.map { cacheVersion in + let cachePath = DyldSharedCachePath.macOS(cacheVersion) + guard let versionLabel = archivedMacOSVersionLabelsByCacheVersion[cacheVersion] else { return cachePath } + return DyldSharedCachePath(path: cachePath.path, versionLabel: versionLabel) + } + } + + static var archivedMacOSCacheVersions: [String] { [ + "11.0.1", + "11.1", + "11.2", + "11.3", + "11.4", + "11.5", + "11.6", + "11.7", + "12.0.1", + "12.1", + "12.2", + "12.3", + "12.4", + "12.5", + "12.6", + "12.7", + "13.0", + "13.1", + "13.2", + "13.3", + "13.4", + "13.5", + "13.6", + "13.7", + "14.0", + "14.1", + "14.2", + "14.3", + "14.4", + "14.5", + "14.6", + "14.7", + "14.8", + "15.0", + "15.1", + "15.2", + "15.3", + "15.4", + "15.5", + "15.6", + "15.7", + "15.8", + "26.0", + "26.1", + "26.2", + "26.3", + "26.4", + "26.5", + "26.6", + "26.7", + "27.0", + ] } + + /// AppleDB offers no macOS 11.0 or 12.0 image, only 11.0.1 and 12.0.1, + /// so those are the directories the volume has; the axis still labels + /// them 11.0 and 12.0, the versions an SDK's availability attributes name. + static var archivedMacOSVersionLabelsByCacheVersion: [String: String] { + ["11.0.1": "11.0", "12.0.1": "12.0"] + } + + init() async throws { + let imageNames = Self.configuration.imageNames + let primaryImageName = imageNames.first?.name + var caches: [FullDyldCache] = [] + var versions: [AxisVersion] = [] + for cachePath in Self.cachePaths { + let cache = try FullDyldCache(path: cachePath) + let images = imageNames.compactMap { imageName -> AxisImage? in + guard let machOFile = cache.machOFile(named: imageName) else { return nil } + return AxisImage(imageName: imageName.name, machOFile: machOFile) + } + guard let primaryImage = images.first, primaryImage.imageName == primaryImageName else { + continue + } + caches.append(cache) + versions.append(AxisVersion(label: cachePath.versionLabel, images: images)) + } + self.caches = caches + self.axes = VersionAxes( + versions: versions, + comparesImageGroups: imageNames.count > 1, + availabilityPlatform: Self.availabilityPlatform + ) + } + + /// The axis a pipeline reading `language` runs over. Computed at + /// initialization: the class properties it derives from are isolated to + /// the test actor, the pipelines are not. + nonisolated func versionAxis(for language: MetadataLanguage) -> VersionAxis { + axes.axis(for: language) + } +} diff --git a/Tests/IntegrationTests/InspectionDumps/VersionAxis.swift b/Tests/IntegrationTests/InspectionDumps/VersionAxis.swift new file mode 100644 index 000000000..e9fb0aee2 --- /dev/null +++ b/Tests/IntegrationTests/InspectionDumps/VersionAxis.swift @@ -0,0 +1,90 @@ +import Foundation +import MachOKit +@testable import MachOSwiftSection + +/// The platform a version axis spells availability for — what +/// `evolution --interface --emit-available --platform` passes — each +/// pipeline in its own spelling. +enum AvailabilityPlatform: Sendable { + case macOS + + /// The platform of `@available(macOS, …)`. + var swiftSpelling: String { + switch self { + case .macOS: "macOS" + } + } + + /// The platform of `API_AVAILABLE(macos(…))`. + var objcSpelling: String { + switch self { + case .macOS: "macos" + } + } +} + +/// One image of one version on a version axis. +struct AxisImage: Sendable { + let imageName: String + let machOFile: MachOFile +} + +/// One version on a version axis: its label and the images whose +/// declarations make it up, the primary image first. +struct AxisVersion: Sendable { + let label: String + let images: [AxisImage] + + var primaryImage: AxisImage { images[0] } + + /// This version as a pipeline reading `language` sees it: only the + /// images carrying that metadata, or `nil` — off the axis — when the + /// primary image does not. + func keepingImages(carrying language: MetadataLanguage) -> AxisVersion? { + guard language.isCarried(by: primaryImage.machOFile) else { return nil } + return AxisVersion(label: label, images: images.filter { language.isCarried(by: $0.machOFile) }) + } +} + +/// One ordered series of versions (oldest first), as one pipeline reads it: +/// a diff reads its first and last version, an evolution every version. +struct VersionAxis: Sendable { + let versions: [AxisVersion] + /// Whether every version is a group of images (evolution proposal + /// `image-group-evolution`). It picks the evolution builders' + /// image-group entry points, which name each version's images and + /// record moves between them, so a version of one image still reads + /// differently from a group of one. + let comparesImageGroups: Bool + /// Set when every label is a version number, so the evolution + /// interfaces also spell each lifecycle one attribute or macro can + /// express. + let availabilityPlatform: AvailabilityPlatform? +} + +/// The axis of each metadata language over one series of versions: each +/// keeps the versions whose primary image carries that language's metadata. +struct VersionAxes: Sendable { + private let swiftAxis: VersionAxis + private let objcAxis: VersionAxis + + init(versions: [AxisVersion], comparesImageGroups: Bool, availabilityPlatform: AvailabilityPlatform?) { + self.swiftAxis = VersionAxis( + versions: versions.compactMap { $0.keepingImages(carrying: .swift) }, + comparesImageGroups: comparesImageGroups, + availabilityPlatform: availabilityPlatform + ) + self.objcAxis = VersionAxis( + versions: versions.compactMap { $0.keepingImages(carrying: .objc) }, + comparesImageGroups: comparesImageGroups, + availabilityPlatform: availabilityPlatform + ) + } + + func axis(for language: MetadataLanguage) -> VersionAxis { + switch language { + case .swift: swiftAxis + case .objc: objcAxis + } + } +} diff --git a/Tests/IntegrationTests/InspectionDumps/VersionAxisDumpTests.swift b/Tests/IntegrationTests/InspectionDumps/VersionAxisDumpTests.swift new file mode 100644 index 000000000..9476c092f --- /dev/null +++ b/Tests/IntegrationTests/InspectionDumps/VersionAxisDumpTests.swift @@ -0,0 +1,35 @@ +import Foundation +import MachOKit +@testable import MachOSwiftSection +import ObjCMetadataSource +import ObjCIndexing +import ObjCInterface +import ObjCDiffing + +/// A dump over an ordered series of versions — a diff or an evolution. A +/// conforming suite supplies the axis each pipeline runs over, usually by +/// inheriting one of the axis base classes below. +protocol VersionAxisDumpTests: InspectionDumpTests { + func versionAxis(for language: MetadataLanguage) -> VersionAxis +} + +@available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) +extension VersionAxisDumpTests { + /// One image indexed the way `swift-section objc snapshot` indexes it and + /// frozen into a labeled snapshot document, round-tripped through the + /// persisted form: what a diff or an evolution consumes is exactly what a + /// saved baseline would decode to. + func objcSnapshotDocument(of image: AxisImage, label: String) async throws -> ObjCAPISnapshotDocument { + let indexer = try await preparedObjCIndexer(of: image.machOFile) + let document = ObjCAPISnapshotDocument( + provenance: ObjCAPIProvenance( + label: label, + binaryPath: image.machOFile.imagePath, + generatorVersion: "IntegrationTests", + createdAt: Date() + ), + snapshot: ObjCAPISnapshotBuilder(indexer: indexer).snapshot() + ) + return try ObjCAPISnapshotDocument.decode(from: document.encoded()) + } +} diff --git a/Tests/IntegrationTests/MachOSwiftSection/DyldCacheAssociatedTypeTests.swift b/Tests/IntegrationTests/MachOSwiftSection/DyldCacheAssociatedTypeTests.swift index 18c4c1afb..fcd1b280a 100644 --- a/Tests/IntegrationTests/MachOSwiftSection/DyldCacheAssociatedTypeTests.swift +++ b/Tests/IntegrationTests/MachOSwiftSection/DyldCacheAssociatedTypeTests.swift @@ -6,6 +6,9 @@ import Demangling import SwiftSectionFixtureSupport @_spi(Internals) @testable import SwiftSymbols @testable @_spi(Internals) import SwiftInspection +import MachOReading +import SwiftDeclaration +import MachOSwiftSection final class DyldCacheAssociatedTypeTests: DyldCacheTests, @unchecked Sendable { @MainActor diff --git a/Tests/IntegrationTests/MachOSwiftSection/MetadataAccessorTests.swift b/Tests/IntegrationTests/MachOSwiftSection/MetadataAccessorTests.swift index c5402f453..08f63bb93 100644 --- a/Tests/IntegrationTests/MachOSwiftSection/MetadataAccessorTests.swift +++ b/Tests/IntegrationTests/MachOSwiftSection/MetadataAccessorTests.swift @@ -12,6 +12,7 @@ import SwiftInspection #if canImport(SwiftUI) import SwiftUI +import Semantic #endif struct GenericStructNonRequirement { diff --git a/Tests/IntegrationTests/MachOSwiftSection/OpaqueTypeTests.swift b/Tests/IntegrationTests/MachOSwiftSection/OpaqueTypeTests.swift index 5ad3485c9..f30dee22d 100644 --- a/Tests/IntegrationTests/MachOSwiftSection/OpaqueTypeTests.swift +++ b/Tests/IntegrationTests/MachOSwiftSection/OpaqueTypeTests.swift @@ -9,6 +9,7 @@ import MachOSwiftSection @testable import SwiftDump @_spi(Internals) import SwiftSymbols @testable @_spi(Internals) import SwiftInspection +import Semantic protocol OpaqueTypeTests {} @@ -42,7 +43,7 @@ extension OpaqueTypeTests { } } -final class OpaqueTypeDyldCacheTests: DyldCacheTests, OpaqueTypeTests, @unchecked Sendable { +final class OpaqueTypeDyldCacheTests: DyldCacheTests, nonisolated OpaqueTypeTests, @unchecked Sendable { override class var cacheImageName: MachOImageName { .SwiftUI } @MainActor @@ -58,7 +59,7 @@ final class OpaqueTypeDyldCacheTests: DyldCacheTests, OpaqueTypeTests, @unchecke } } -final class OpaqueTypeMachOFileTests: MachOFileTests, OpaqueTypeTests, @unchecked Sendable { +final class OpaqueTypeMachOFileTests: MachOFileTests, nonisolated OpaqueTypeTests, @unchecked Sendable { override class var fileName: MachOFileName { .SymbolTestsCore } @MainActor @@ -67,7 +68,7 @@ final class OpaqueTypeMachOFileTests: MachOFileTests, OpaqueTypeTests, @unchecke } } -final class OpaqueTypeMachOImageTests: MachOImageTests, OpaqueTypeTests, @unchecked Sendable { +final class OpaqueTypeMachOImageTests: MachOImageTests, nonisolated OpaqueTypeTests, @unchecked Sendable { override class var imageName: MachOImageName { .SwiftUICore } @MainActor diff --git a/Tests/IntegrationTests/MachOSwiftSection/ProtocolGenericContextTests.swift b/Tests/IntegrationTests/MachOSwiftSection/ProtocolGenericContextTests.swift index 6c6ed9cee..aadbf0b86 100644 --- a/Tests/IntegrationTests/MachOSwiftSection/ProtocolGenericContextTests.swift +++ b/Tests/IntegrationTests/MachOSwiftSection/ProtocolGenericContextTests.swift @@ -4,6 +4,9 @@ import Testing @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport import SwiftInspection +import Demangling +import Semantic +import SwiftDeclarationRendering final class ProtocolGenericContextTests: MachOFileTests, @unchecked Sendable { override class var fileName: MachOFileName { .SymbolTestsCore } diff --git a/Tests/IntegrationTests/MachOSwiftSection/ProtocolRequirementSignatureTests.swift b/Tests/IntegrationTests/MachOSwiftSection/ProtocolRequirementSignatureTests.swift index 96a90eead..2fef5b994 100644 --- a/Tests/IntegrationTests/MachOSwiftSection/ProtocolRequirementSignatureTests.swift +++ b/Tests/IntegrationTests/MachOSwiftSection/ProtocolRequirementSignatureTests.swift @@ -4,6 +4,7 @@ import Testing @testable import SwiftDump @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import BinaryParseSupport final class ProtocolRequirementSignatureTests: MachOFileTests, @unchecked Sendable { override class var fileName: MachOFileName { .SymbolTestsCore } diff --git a/Tests/IntegrationTests/MachOSymbols/DyldCacheSymbolSimpleTests.swift b/Tests/IntegrationTests/MachOSymbols/DyldCacheSymbolSimpleTests.swift index c578f0778..111b439b9 100644 --- a/Tests/IntegrationTests/MachOSymbols/DyldCacheSymbolSimpleTests.swift +++ b/Tests/IntegrationTests/MachOSymbols/DyldCacheSymbolSimpleTests.swift @@ -35,7 +35,7 @@ final class DyldCacheSymbolSimpleTests: DyldCacheSymbolTests, @unchecked Sendabl let directoryURL = URL.documentsDirectory.appending(component: "SwiftSymbolExpanded") try directoryURL.createDirectoryIfNeeded() - try string.write(to: directoryURL.appending(components: "\(imageName.rawValue).txt"), atomically: true, encoding: .utf8) + try string.write(to: directoryURL.appending(components: "\(imageName.name).txt"), atomically: true, encoding: .utf8) } @Test func demangle() async throws { diff --git a/Tests/IntegrationTests/MachOSymbols/ExternalSymbolTests.swift b/Tests/IntegrationTests/MachOSymbols/ExternalSymbolTests.swift index 0b5c2e78a..0f02e9897 100644 --- a/Tests/IntegrationTests/MachOSymbols/ExternalSymbolTests.swift +++ b/Tests/IntegrationTests/MachOSymbols/ExternalSymbolTests.swift @@ -4,6 +4,9 @@ import Testing @testable import MachOSwiftSection @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import SwiftSymbols +import MachOKit +import Demangling final class ExternalSymbolTests: MachOFileTests, @unchecked Sendable { override class var fileName: MachOFileName { .iOS_18_5_Simulator_SwiftUI } diff --git a/Tests/IntegrationTests/MachOSymbols/SymbolIndexStoreBaselineTests.swift b/Tests/IntegrationTests/MachOSymbols/SymbolIndexStoreBaselineTests.swift index 54e6913c0..a3b3a01ef 100644 --- a/Tests/IntegrationTests/MachOSymbols/SymbolIndexStoreBaselineTests.swift +++ b/Tests/IntegrationTests/MachOSymbols/SymbolIndexStoreBaselineTests.swift @@ -6,6 +6,7 @@ import Demangling @_spi(Internals) @testable import SwiftSymbols @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import OrderedCollections /// Stage 0 of the NodeStore migration plan: capture per-image baseline /// metrics for `SwiftSymbolIndexStore.buildStorage` so Stage 1/4 can compare diff --git a/Tests/IntegrationTests/ObjCDiffing/ObjCAPIEvolutionTests.swift b/Tests/IntegrationTests/ObjCDiffing/ObjCAPIEvolutionTests.swift deleted file mode 100644 index bf756080b..000000000 --- a/Tests/IntegrationTests/ObjCDiffing/ObjCAPIEvolutionTests.swift +++ /dev/null @@ -1,496 +0,0 @@ -import Foundation -import Testing -import MachOKit -import SwiftSectionFixtureSupport -import SwiftSectionTestingSupport -@testable import MachOSwiftSection -import SwiftIndexing -import ObjCMetadataSource -import ObjCIndexing -import ObjCInterface -import ObjCDiffing - -/// One image indexed the way the `objc` subcommands index it: the Swift -/// classes that keep no class object supplied from Swift metadata. -@available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) -private func preparedObjCIndexer(of machO: MachOFile) async throws -> ObjCInterfaceIndexer { - let indexer = ObjCInterfaceIndexer( - machO: machO, - imagePath: machO.imagePath, - suppliedClasses: ObjCSuppliedClass.swiftClassesWithoutClassObjects(in: machO) - ) - try await indexer.prepare() - return indexer -} - -/// The Objective-C counterpart of ``ABIEvolutionDumpTests``. -/// -/// These index an *ordered series* of versions of one image — or of one -/// group of images per version (evolution proposal `image-group-evolution`) -/// — with MachOObjCSection's `ObjCInterfaceIndexer`, freeze each into an -/// `ObjCAPISnapshotDocument` (round-tripping through the persisted JSON form -/// so the codec and the format-version gate run on real-world data), and run -/// the series through `ObjCAPIEvolutionBuilder` + `ObjCAPIEvolutionReporter` — -/// the `swift-section objc evolution` pipeline. The annotated union header of -/// the same axis is ``ObjCEvolutionInterfaceDumpTests``, below. Like its -/// siblings it is a maintainer-inspection dump: it prints / writes results -/// without assertions. -protocol ObjCAPIEvolutionDumpTests: SwiftInterfaceDumpTests {} - -@available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) -extension ObjCAPIEvolutionDumpTests { - /// One image indexed the way `swift-section objc snapshot` indexes it and - /// frozen into a labeled snapshot document, round-tripped through the - /// persisted form: what the evolution consumes is exactly what a saved - /// baseline would decode to. - private func snapshotDocument(of machO: MachOFile, label: String) async throws -> ObjCAPISnapshotDocument { - let indexer = try await preparedObjCIndexer(of: machO) - let document = ObjCAPISnapshotDocument( - provenance: ObjCAPIProvenance( - label: label, - binaryPath: machO.imagePath, - generatorVersion: "IntegrationTests", - createdAt: Date() - ), - snapshot: ObjCAPISnapshotBuilder(indexer: indexer).snapshot() - ) - return try ObjCAPISnapshotDocument.decode(from: document.encoded()) - } - - /// Every version (oldest first) as `snapshotDocument(of:label:)`. The - /// timed step covers the whole preparation; the lineage math afterwards - /// takes seconds at most. - private func snapshotDocuments(of versions: [(label: String, machO: MachOFile)]) async throws -> [ObjCAPISnapshotDocument] { - var documents: [ObjCAPISnapshotDocument] = [] - try await measuringPreparation { - for version in versions { - documents.append(try await snapshotDocument(of: version.machO, label: version.label)) - } - } - return documents - } - - private func timelineReport(of evolution: ObjCAPIEvolution, documents: [ObjCAPISnapshotDocument]) -> String { - var report = ObjCAPIEvolutionReporter().report(evolution) - // For a two-version series the lineage events must match the - // two-sided differ verbatim — print both verdicts so the manual - // inspection can eyeball the consistency on real-world data. - if documents.count == 2, let oldDocument = documents.first, let newDocument = documents.last { - let diff = ObjCAPIDiffer().diff(old: oldDocument, new: newDocument) - report += "\n\nPairwise cross-check — evolution API-breaking: \(evolution.hasBreakingChange) · diff API-breaking: \(diff.hasBreakingChange)" - } - return report - } - - /// Console analogue of `evolutionFile`: prepares every version, then - /// prints the timeline report. - func evolutionString(versions: [(label: String, machO: MachOFile)]) async throws { - let documents = try await snapshotDocuments(of: versions) - let evolution = try ObjCAPIEvolutionBuilder().evolution(of: documents) - printResult(timelineReport(of: evolution, documents: documents)) - } - - /// Writes the timeline report (`-ObjCEvolution.txt`) and the - /// machine-readable form (`-ObjCEvolution.json`) next to the Swift - /// evolution dumps, both named after the *newest* version. - func evolutionFile(versions: [(label: String, machO: MachOFile)]) async throws { - let documents = try await snapshotDocuments(of: versions) - guard let newestVersion = versions.last else { return } - let evolution = try ObjCAPIEvolutionBuilder().evolution(of: documents) - try write(timelineReport(of: evolution, documents: documents), for: newestVersion.machO, suffix: "ObjCEvolution", fileExtension: "txt") - try write(String(decoding: ObjCAPIJSON.encoder().encode(evolution), as: UTF8.self), for: newestVersion.machO, suffix: "ObjCEvolution", fileExtension: "json") - } - - // MARK: - Groups of images - - /// Versions made up of groups of images (evolution proposal - /// `image-group-evolution`): every image of every version frozen as - /// `snapshotDocument(of:label:)` freezes one, under its image name. - private func imageGroupEvolution( - of imageGroupVersions: [(label: String, images: [(imageName: MachOImageName, machO: MachOFile)])] - ) async throws -> ObjCAPIEvolution { - var imageGroups: [[ObjCAPIImageSnapshot]] = [] - try await measuringPreparation { - for version in imageGroupVersions { - var imageSnapshots: [ObjCAPIImageSnapshot] = [] - for image in version.images { - let document = try await snapshotDocument(of: image.machO, label: version.label) - imageSnapshots.append(ObjCAPIImageSnapshot(imageName: image.imageName.rawValue, snapshot: document.snapshot)) - } - imageGroups.append(imageSnapshots) - } - } - return try ObjCAPIEvolutionBuilder().evolution( - ofImageGroups: imageGroups, - versions: imageGroupVersions.map { ObjCAPIVersionDescriptor(label: $0.label) } - ) - } - - /// Console analogue of `evolutionFile(imageGroupVersions:)`. - func evolutionString(imageGroupVersions: [(label: String, images: [(imageName: MachOImageName, machO: MachOFile)])]) async throws { - printResult(ObjCAPIEvolutionReporter().report(try await imageGroupEvolution(of: imageGroupVersions))) - } - - /// Writes the timeline report and the JSON of an evolution over groups of - /// images, named after the newest version's group - /// (`…-AppKit+UIFoundation+CollectionViewCore+CoreAutoLayout-ObjCEvolution.txt` - /// / `.json`). - func evolutionFile(imageGroupVersions: [(label: String, images: [(imageName: MachOImageName, machO: MachOFile)])]) async throws { - let evolution = try await imageGroupEvolution(of: imageGroupVersions) - guard let newestVersion = imageGroupVersions.last else { return } - try write(ObjCAPIEvolutionReporter().report(evolution), forImageGroup: newestVersion.images, suffix: "ObjCEvolution", fileExtension: "txt") - try write(String(decoding: ObjCAPIJSON.encoder().encode(evolution), as: UTF8.self), forImageGroup: newestVersion.images, suffix: "ObjCEvolution", fileExtension: "json") - } -} - -enum ObjCAPIEvolutionTestSuite { - /// AppKit's Objective-C metadata across an ordered series of dyld shared - /// caches. A version joins the axis when its image carries an `__objc_*` - /// section, which AppKit does in every cache — unlike its Swift sections, - /// which the Swift suites need and which only appear from macOS 14. - class MultiVersionDyldCacheImageTests: ABIEvolutionTestSuite.MultiVersionDyldCacheImageTests, @unchecked Sendable { - override class var cacheImageName: MachOImageName { .AppKit } - - override class func isOnAxis(_ machOFile: MachOFile) -> Bool { - machOFile.sections.contains(where: { $0.sectionName.hasPrefix("__objc_") }) - } - } - - /// AppKit across the three macOS caches the Swift evolution suites - /// default to (15.5 → 26.5.2 → 27.0), so the Objective-C report can be - /// read beside theirs. - final class DyldCacheTests: MultiVersionDyldCacheImageTests, ObjCAPIEvolutionDumpTests, @unchecked Sendable { - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionFile() async throws { - try await evolutionFile(versions: versions) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionString() async throws { - try await evolutionString(versions: versions) - } - } - - /// AppKit across every archived macOS cache, on the axis of the Swift - /// `SwiftEvolutionInterfaceBuilderTestSuite.ArchivedDyldCacheTests`: the - /// same versions under the same labels, listed there once for both. - /// - /// The method names of a macOS 11 cache read correctly only from - /// MachOObjCSection 0.8.202. Its relative method lists count a selector - /// from the name field itself, where later caches count it from a - /// selector base, and an earlier reader made every class and category - /// method of 11.x garbage — 11.7 → 12.0.1 then reported about 47,000 - /// removals and 53,000 additions instead of about 1,200 and 1,400. - final class ArchivedDyldCacheTests: MultiVersionDyldCacheImageTests, ObjCAPIEvolutionDumpTests, @unchecked Sendable { - override class var cachePaths: [DyldSharedCachePath] { - SwiftEvolutionInterfaceBuilderTestSuite.ArchivedDyldCacheTests.cachePaths - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionFile() async throws { - try await evolutionFile(versions: versions) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionString() async throws { - try await evolutionString(versions: versions) - } - } - - /// AppKit together with the frameworks Apple moved its classes into — - /// UIFoundation, CollectionViewCore, CoreAutoLayout — across the default - /// three caches (15.5 → 26.5.2 → 27.0), each version one group of images - /// (evolution proposal `image-group-evolution`). - final class AppKitImageGroupDyldCacheTests: MultiVersionDyldCacheImageTests, ObjCAPIEvolutionDumpTests, @unchecked Sendable { - override class var cacheImageNames: [MachOImageName] { [.AppKit, .UIFoundation, .CollectionViewCore, .CoreAutoLayout] } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionFile() async throws { - try await evolutionFile(imageGroupVersions: imageGroupVersions) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionString() async throws { - try await evolutionString(imageGroupVersions: imageGroupVersions) - } - } - - /// The same group across every archived macOS cache, on the axis of - /// ``ArchivedDyldCacheTests``: the classes that moved between AppKit, - /// UIFoundation and CollectionViewCore in 13.0 and 15.0 — where an - /// evolution of AppKit alone reads them as removed or added — read as - /// moved. CollectionViewCore joins the group in 13.0. - final class AppKitImageGroupArchivedDyldCacheTests: MultiVersionDyldCacheImageTests, ObjCAPIEvolutionDumpTests, @unchecked Sendable { - override class var cachePaths: [DyldSharedCachePath] { - ArchivedDyldCacheTests.cachePaths - } - - override class var cacheImageNames: [MachOImageName] { AppKitImageGroupDyldCacheTests.cacheImageNames } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionFile() async throws { - try await evolutionFile(imageGroupVersions: imageGroupVersions) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionString() async throws { - try await evolutionString(imageGroupVersions: imageGroupVersions) - } - } - - /// SwiftUI together with SwiftUICore across the default three caches — - /// the Objective-C side of `ABIEvolutionTestSuite.SwiftUIImageGroupDyldCacheTests`. - final class SwiftUIImageGroupDyldCacheTests: MultiVersionDyldCacheImageTests, ObjCAPIEvolutionDumpTests, @unchecked Sendable { - override class var cacheImageNames: [MachOImageName] { [.SwiftUI, .SwiftUICore] } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionFile() async throws { - try await evolutionFile(imageGroupVersions: imageGroupVersions) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionString() async throws { - try await evolutionString(imageGroupVersions: imageGroupVersions) - } - } - - /// The same group across every archived macOS cache: SwiftUI alone until - /// 14.8, SwiftUICore joining it in 15.0. - final class SwiftUIImageGroupArchivedDyldCacheTests: MultiVersionDyldCacheImageTests, ObjCAPIEvolutionDumpTests, @unchecked Sendable { - override class var cachePaths: [DyldSharedCachePath] { - ArchivedDyldCacheTests.cachePaths - } - - override class var cacheImageNames: [MachOImageName] { SwiftUIImageGroupDyldCacheTests.cacheImageNames } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionFile() async throws { - try await evolutionFile(imageGroupVersions: imageGroupVersions) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionString() async throws { - try await evolutionString(imageGroupVersions: imageGroupVersions) - } - } -} - -/// The annotated-union-header analogue of ``ObjCAPIEvolutionDumpTests``, and -/// the Objective-C counterpart of ``SwiftEvolutionInterfaceDumpTests``. -/// -/// These run the same series through MachOObjCSection's -/// `ObjCEvolutionInterfaceBuilder` — the `swift-section objc evolution -/// --interface` pipeline: every declaration rendered the way `objc dump` -/// renders it, the versions merged into one header, and each declaration's -/// lifecycle annotated. Read the header against the lineage report of the -/// same axis — the annotations are the same lineages. Like its siblings it is -/// a maintainer-inspection dump: it prints / writes results without -/// assertions. -protocol ObjCEvolutionInterfaceDumpTests: SwiftInterfaceDumpTests {} - -@available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) -extension ObjCEvolutionInterfaceDumpTests { - /// Indexes every version (oldest first) the way `objc evolution - /// --interface` does and hands it to the builder, which keeps what it - /// rendered and snapshotted, never the indexer. The timed step covers the - /// indexing and rendering of every version. - private func evolutionInterface( - of versions: [(label: String, machO: MachOFile)], - availabilityPlatform: String? - ) async throws -> ObjCEvolutionInterface { - var builder = ObjCEvolutionInterfaceBuilder() - try await measuringPreparation { - for version in versions { - let indexer = try await preparedObjCIndexer(of: version.machO) - builder.addVersion(indexer: indexer, machO: version.machO, version: ObjCAPIVersionDescriptor(label: version.label)) - } - } - return try builder.build(availabilityPlatform: availabilityPlatform) - } - - /// `evolutionInterface(of:availabilityPlatform:)` over versions made up - /// of groups of images (evolution proposal `image-group-evolution`): each - /// version's images handed to the builder together, the primary image - /// first, so a class that moved between them stays one declaration. - private func evolutionInterface( - ofImageGroups imageGroupVersions: [(label: String, images: [(imageName: MachOImageName, machO: MachOFile)])], - availabilityPlatform: String? - ) async throws -> ObjCEvolutionInterface { - var builder = ObjCEvolutionInterfaceBuilder() - try await measuringPreparation { - for version in imageGroupVersions { - var images: [ObjCEvolutionInterfaceImage] = [] - for image in version.images { - let indexer = try await preparedObjCIndexer(of: image.machO) - images.append(ObjCEvolutionInterfaceImage(imageName: image.imageName.rawValue, indexer: indexer, machO: image.machO)) - } - builder.addVersion(images: images, version: ObjCAPIVersionDescriptor(label: version.label)) - } - } - return try builder.build(availabilityPlatform: availabilityPlatform) - } - - /// The annotated header plus the per-axis verdict line, so the manual - /// inspection can eyeball the CI-gate input next to the rendering. - private func annotatedHeaderReport(of evolutionInterface: ObjCEvolutionInterface) -> String { - evolutionInterface.interface.string + "\n\n// API-breaking on this axis: \(evolutionInterface.evolution.hasBreakingChange)" - } - - /// Console analogue of `evolutionInterfaceFile`. A platform adds the - /// availability macros, as `objc evolution --interface --emit-available - /// --platform` does. - func evolutionInterfaceString(versions: [(label: String, machO: MachOFile)], availabilityPlatform: String? = nil) async throws { - let evolutionInterface = try await evolutionInterface(of: versions, availabilityPlatform: availabilityPlatform) - printResult(annotatedHeaderReport(of: evolutionInterface)) - } - - /// Writes the annotated header (`-ObjCEvolutionInterface.h`) next to the - /// lineage report, named after the *newest* version. - func evolutionInterfaceFile(versions: [(label: String, machO: MachOFile)], availabilityPlatform: String? = nil) async throws { - let evolutionInterface = try await evolutionInterface(of: versions, availabilityPlatform: availabilityPlatform) - guard let newestVersion = versions.last else { return } - try write(annotatedHeaderReport(of: evolutionInterface), for: newestVersion.machO, suffix: "ObjCEvolutionInterface", fileExtension: "h") - } - - /// Console analogue of - /// `evolutionInterfaceFile(imageGroupVersions:availabilityPlatform:)`. - func evolutionInterfaceString( - imageGroupVersions: [(label: String, images: [(imageName: MachOImageName, machO: MachOFile)])], - availabilityPlatform: String? = nil - ) async throws { - let evolutionInterface = try await evolutionInterface(ofImageGroups: imageGroupVersions, availabilityPlatform: availabilityPlatform) - printResult(annotatedHeaderReport(of: evolutionInterface)) - } - - /// Writes the annotated header of versions made up of groups of images, - /// named after the newest version's group - /// (`…-AppKit+UIFoundation+CollectionViewCore+CoreAutoLayout-ObjCEvolutionInterface.h`). - func evolutionInterfaceFile( - imageGroupVersions: [(label: String, images: [(imageName: MachOImageName, machO: MachOFile)])], - availabilityPlatform: String? = nil - ) async throws { - let evolutionInterface = try await evolutionInterface(ofImageGroups: imageGroupVersions, availabilityPlatform: availabilityPlatform) - guard let newestVersion = imageGroupVersions.last else { return } - try write(annotatedHeaderReport(of: evolutionInterface), forImageGroup: newestVersion.images, suffix: "ObjCEvolutionInterface", fileExtension: "h") - } -} - -enum ObjCEvolutionInterfaceTestSuite { - /// AppKit across the three macOS caches the evolution suites default to - /// (15.5 → 26.5.2 → 27.0) — the axis of - /// `ObjCAPIEvolutionTestSuite.DyldCacheTests`, so the header and the - /// report can be read side by side. - final class DyldCacheTests: ObjCAPIEvolutionTestSuite.MultiVersionDyldCacheImageTests, ObjCEvolutionInterfaceDumpTests, @unchecked Sendable { - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionInterfaceFile() async throws { - try await evolutionInterfaceFile(versions: versions) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionInterfaceString() async throws { - try await evolutionInterfaceString(versions: versions) - } - } - - /// AppKit across every archived macOS cache, on the axis of - /// `ObjCAPIEvolutionTestSuite.ArchivedDyldCacheTests`. Every label is a - /// version number, so the header also spells each lifecycle one macro can - /// express as `API_AVAILABLE` / `API_OBSOLETED`. - final class ArchivedDyldCacheTests: ObjCAPIEvolutionTestSuite.MultiVersionDyldCacheImageTests, ObjCEvolutionInterfaceDumpTests, @unchecked Sendable { - override class var cachePaths: [DyldSharedCachePath] { - ObjCAPIEvolutionTestSuite.ArchivedDyldCacheTests.cachePaths - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionInterfaceFile() async throws { - try await evolutionInterfaceFile(versions: versions, availabilityPlatform: "macos") - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionInterfaceString() async throws { - try await evolutionInterfaceString(versions: versions, availabilityPlatform: "macos") - } - } - - /// AppKit with UIFoundation, CollectionViewCore and CoreAutoLayout across - /// the default three caches — the axis of - /// `ObjCAPIEvolutionTestSuite.AppKitImageGroupDyldCacheTests`. - final class AppKitImageGroupDyldCacheTests: ObjCAPIEvolutionTestSuite.MultiVersionDyldCacheImageTests, ObjCEvolutionInterfaceDumpTests, @unchecked Sendable { - override class var cacheImageNames: [MachOImageName] { - ObjCAPIEvolutionTestSuite.AppKitImageGroupDyldCacheTests.cacheImageNames - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionInterfaceFile() async throws { - try await evolutionInterfaceFile(imageGroupVersions: imageGroupVersions) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionInterfaceString() async throws { - try await evolutionInterfaceString(imageGroupVersions: imageGroupVersions) - } - } - - /// The same group across every archived macOS cache, on the axis of - /// `ObjCAPIEvolutionTestSuite.AppKitImageGroupArchivedDyldCacheTests`, - /// with the availability macros. - final class AppKitImageGroupArchivedDyldCacheTests: ObjCAPIEvolutionTestSuite.MultiVersionDyldCacheImageTests, ObjCEvolutionInterfaceDumpTests, @unchecked Sendable { - override class var cachePaths: [DyldSharedCachePath] { - ObjCAPIEvolutionTestSuite.ArchivedDyldCacheTests.cachePaths - } - - override class var cacheImageNames: [MachOImageName] { - ObjCAPIEvolutionTestSuite.AppKitImageGroupDyldCacheTests.cacheImageNames - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionInterfaceFile() async throws { - try await evolutionInterfaceFile(imageGroupVersions: imageGroupVersions, availabilityPlatform: "macos") - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionInterfaceString() async throws { - try await evolutionInterfaceString(imageGroupVersions: imageGroupVersions, availabilityPlatform: "macos") - } - } - - /// SwiftUI with SwiftUICore across the default three caches — the axis - /// of `ObjCAPIEvolutionTestSuite.SwiftUIImageGroupDyldCacheTests`. - final class SwiftUIImageGroupDyldCacheTests: ObjCAPIEvolutionTestSuite.MultiVersionDyldCacheImageTests, ObjCEvolutionInterfaceDumpTests, @unchecked Sendable { - override class var cacheImageNames: [MachOImageName] { - ObjCAPIEvolutionTestSuite.SwiftUIImageGroupDyldCacheTests.cacheImageNames - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionInterfaceFile() async throws { - try await evolutionInterfaceFile(imageGroupVersions: imageGroupVersions) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionInterfaceString() async throws { - try await evolutionInterfaceString(imageGroupVersions: imageGroupVersions) - } - } - - /// The same group across every archived macOS cache, with the - /// availability macros. - final class SwiftUIImageGroupArchivedDyldCacheTests: ObjCAPIEvolutionTestSuite.MultiVersionDyldCacheImageTests, ObjCEvolutionInterfaceDumpTests, @unchecked Sendable { - override class var cachePaths: [DyldSharedCachePath] { - ObjCAPIEvolutionTestSuite.ArchivedDyldCacheTests.cachePaths - } - - override class var cacheImageNames: [MachOImageName] { - ObjCAPIEvolutionTestSuite.SwiftUIImageGroupDyldCacheTests.cacheImageNames - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionInterfaceFile() async throws { - try await evolutionInterfaceFile(imageGroupVersions: imageGroupVersions, availabilityPlatform: "macos") - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionInterfaceString() async throws { - try await evolutionInterfaceString(imageGroupVersions: imageGroupVersions, availabilityPlatform: "macos") - } - } -} diff --git a/Tests/IntegrationTests/SwiftDiffing/ABIEvolutionTests.swift b/Tests/IntegrationTests/SwiftDiffing/ABIEvolutionTests.swift deleted file mode 100644 index c68b38014..000000000 --- a/Tests/IntegrationTests/SwiftDiffing/ABIEvolutionTests.swift +++ /dev/null @@ -1,293 +0,0 @@ -import Foundation -import Testing -import SwiftDeclarationRendering -import MachOKit -import SwiftSectionFixtureSupport -import SwiftSectionTestingSupport -@testable import MachOSwiftSection -@testable import SwiftInterface -@_spi(Support) @testable import SwiftIndexing -import SwiftDiffing - -/// The N-version analogue of ``SwiftDiffableInterfaceBuilderTests``. -/// -/// Where the diffable-interface tests index a *pair* of binaries and diff -/// them, these index an *ordered series* of versions of one module, freeze -/// each into an `ABISnapshotDocument` (round-tripping through the persisted -/// JSON form so the codec and the format-version gate run on real-world -/// data), and run the series through `ABIEvolutionBuilder` + -/// `ABIEvolutionReporter` — the `swift-section evolution` pipeline. Like its -/// siblings it is a maintainer-inspection dump: it prints / writes results -/// without assertions. -protocol ABIEvolutionDumpTests: SwiftInterfaceDumpTests {} - -@available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) -extension ABIEvolutionDumpTests { - var indexConfiguration: SwiftDeclarationIndexConfiguration { - .init(showCImportedTypes: false) - } - - /// Indexes every version (oldest first) and freezes it into a labeled, - /// persistence-round-tripped snapshot document. The timed step covers the - /// whole preparation — indexing N binaries is the real cost; the lineage - /// math afterwards is milliseconds. - private func snapshotDocuments( - of versions: [(label: String, machO: some MachOFieldLayoutRenderable)] - ) async throws -> [ABISnapshotDocument] { - var documents: [ABISnapshotDocument] = [] - try await measuringPreparation { - for version in versions { - let builder = SwiftDiffableInterfaceBuilder(configuration: indexConfiguration, in: version.machO) - try await builder.prepare() - let document = ABISnapshotDocument( - provenance: ABIProvenance( - label: version.label, - binaryPath: version.machO.imagePath, - generatorVersion: "IntegrationTests", - createdAt: Date() - ), - snapshot: builder.snapshot() - ) - // Round-trip through the persisted form: what the evolution - // consumes is exactly what a saved baseline would decode to. - documents.append(try ABISnapshotDocument.decode(from: document.encoded())) - } - } - return documents - } - - private func timelineReport(of documents: [ABISnapshotDocument]) throws -> String { - let evolution = try ABIEvolutionBuilder().evolution(of: documents) - var report = ABIEvolutionReporter().report(evolution) - // For a two-version series the lineage events must match the - // two-sided differ verbatim — print both verdicts so the manual - // inspection can eyeball the consistency on real-world data. - if documents.count == 2, let oldDocument = documents.first, let newDocument = documents.last { - let diff = ABIDiffer().diff(old: oldDocument, new: newDocument) - report += "\n\nPairwise cross-check — evolution ABI-breaking: \(evolution.hasBreakingChange) · diff ABI-breaking: \(diff.hasBreakingChange)" - } - return report - } - - /// Console analogue of `diffString`: prepares every version, then prints - /// the timeline report. - func evolutionString(versions: [(label: String, machO: some MachOFieldLayoutRenderable)]) async throws { - let documents = try await snapshotDocuments(of: versions) - printResult(try timelineReport(of: documents)) - } - - /// File analogue of `diffFile`: writes the timeline report - /// (`-Evolution.txt`) and the machine-readable form (`-Evolution.json`) - /// next to the interface/diff dumps, both named after the *newest* - /// version. - func evolutionFile(versions: [(label: String, machO: some MachOFieldLayoutRenderable)]) async throws { - let documents = try await snapshotDocuments(of: versions) - guard let newestVersion = versions.last else { return } - try write(try timelineReport(of: documents), for: newestVersion.machO, suffix: "Evolution", fileExtension: "txt") - let evolution = try ABIEvolutionBuilder().evolution(of: documents) - try write(String(decoding: ABIJSON.encoder().encode(evolution), as: UTF8.self), for: newestVersion.machO, suffix: "Evolution", fileExtension: "json") - } - - // MARK: - Groups of images - - /// Versions made up of groups of images (evolution proposal - /// `image-group-evolution`): every image of every version indexed and - /// frozen as `snapshotDocuments(of:)` freezes one, round-tripped through - /// the persisted form, under its image name. - private func imageGroupEvolution( - of imageGroupVersions: [(label: String, images: [(imageName: MachOImageName, machO: MachOFile)])] - ) async throws -> ABIEvolution { - var imageGroups: [[ABIImageSnapshot]] = [] - try await measuringPreparation { - for version in imageGroupVersions { - var imageSnapshots: [ABIImageSnapshot] = [] - for image in version.images { - let builder = SwiftDiffableInterfaceBuilder(configuration: indexConfiguration, in: image.machO) - try await builder.prepare() - let document = ABISnapshotDocument( - provenance: ABIProvenance( - label: version.label, - binaryPath: image.machO.imagePath, - generatorVersion: "IntegrationTests", - createdAt: Date() - ), - snapshot: builder.snapshot() - ) - imageSnapshots.append(ABIImageSnapshot( - imageName: image.imageName.rawValue, - snapshot: try ABISnapshotDocument.decode(from: document.encoded()).snapshot - )) - } - imageGroups.append(imageSnapshots) - } - } - return try ABIEvolutionBuilder().evolution( - ofImageGroups: imageGroups, - versions: imageGroupVersions.map { ABIVersionDescriptor(label: $0.label) } - ) - } - - /// Console analogue of `evolutionFile(imageGroupVersions:)`. - func evolutionString(imageGroupVersions: [(label: String, images: [(imageName: MachOImageName, machO: MachOFile)])]) async throws { - printResult(ABIEvolutionReporter().report(try await imageGroupEvolution(of: imageGroupVersions))) - } - - /// Writes the timeline report and the JSON of an evolution over groups of - /// images, named after the newest version's group - /// (`…-SwiftUI+SwiftUICore-Evolution.txt` / `.json`). - func evolutionFile(imageGroupVersions: [(label: String, images: [(imageName: MachOImageName, machO: MachOFile)])]) async throws { - let evolution = try await imageGroupEvolution(of: imageGroupVersions) - guard let newestVersion = imageGroupVersions.last else { return } - try write(ABIEvolutionReporter().report(evolution), forImageGroup: newestVersion.images, suffix: "Evolution", fileExtension: "txt") - try write(String(decoding: ABIJSON.encoder().encode(evolution), as: UTF8.self), forImageGroup: newestVersion.images, suffix: "Evolution", fileExtension: "json") - } -} - -enum ABIEvolutionTestSuite { - /// Extracts the same image from an *ordered series* of dyld shared caches — - /// the N-version counterpart of - /// `SwiftDiffableInterfaceBuilderTestSuite.CrossVersionDyldCacheImageTests`. - /// The caches are retained because the extracted `MachOFile`s resolve - /// cross-image references through them while indexing. - /// - /// A version whose cache lacks the image, or whose image lacks the metadata - /// a suite reads (`isOnAxis(_:)`), is left off the axis: there is nothing - /// to index. For the Swift suites that is an image with no `__swift5_*` - /// section, and indexing it anyway logs four extraction failures. AppKit - /// kept its Swift API in `libswiftAppKit.dylib` until macOS 14, so a Swift - /// AppKit axis reaching further back starts at 14.0. A cache that cannot - /// be opened still throws. - /// - /// Each cache is opened whole, the way `swift-section --dyld-shared-cache` - /// opens it, so the dumps match what the command line prints. Opened from - /// its main file alone, every read into another sub-cache file mapped that - /// file once more until MachOObjCSection 0.8.109, and an evolution over - /// every archived macOS minor ran past 5 GB. - /// - /// A suite comparing a group of images per version (evolution proposal - /// `image-group-evolution`) lists them in `cacheImageNames`, the primary - /// image first: AppKit with the frameworks Apple moved its classes into, - /// SwiftUI with SwiftUICore. A version joins the axis when its cache has - /// the primary image on the axis; each other image joins its group where - /// the cache has it on the axis — CollectionViewCore is in the macOS - /// caches from 13.0 on, SwiftUICore from 15.0 on. - @TestActor - class MultiVersionDyldCacheImageTests: Sendable { - let caches: [FullDyldCache] - /// Each version's primary image. - let versions: [(label: String, machO: MachOFile)] - /// Each version's group of images, the primary image first. - let imageGroupVersions: [(label: String, images: [(imageName: MachOImageName, machO: MachOFile)])] - - /// Oldest first; each cache's `versionLabel` labels it on the axis. - class var cachePaths: [DyldSharedCachePath] { [.macOS_15_5, .macOS_26_5_2, .macOS_27_0] } - class var cacheImageName: MachOImageName { .SwiftUI } - - /// The images whose declarations make up one version, the primary - /// image first; by default the primary image alone. - class var cacheImageNames: [MachOImageName] { [cacheImageName] } - - /// Whether a version's image belongs on the axis: it must carry the - /// metadata the suite indexes, which for the Swift suites is a - /// `__swift5_*` section. - class func isOnAxis(_ machOFile: MachOFile) -> Bool { - machOFile.sections.contains(where: { $0.sectionName.hasPrefix("__swift5_") }) - } - - init() async throws { - var caches: [FullDyldCache] = [] - var versions: [(label: String, machO: MachOFile)] = [] - var imageGroupVersions: [(label: String, images: [(imageName: MachOImageName, machO: MachOFile)])] = [] - for cachePath in Self.cachePaths { - let cache = try FullDyldCache(path: cachePath) - let images = Self.cacheImageNames.compactMap { imageName -> (imageName: MachOImageName, machO: MachOFile)? in - guard let machOFile = cache.machOFile(named: imageName), Self.isOnAxis(machOFile) else { return nil } - return (imageName, machOFile) - } - guard let primaryImage = images.first, primaryImage.imageName == Self.cacheImageNames.first else { - continue - } - caches.append(cache) - versions.append((cachePath.versionLabel, primaryImage.machO)) - imageGroupVersions.append((cachePath.versionLabel, images)) - } - self.caches = caches - self.versions = versions - self.imageGroupVersions = imageGroupVersions - } - } - - /// AppKit across three macOS caches (15.5 → 26.5.1 → 27.0 beta 1) — the - /// flagship N == 3 lineage: introduced/modified/removed/re-added stories - /// only visible with more than two versions. - final class DyldCacheTests: MultiVersionDyldCacheImageTests, ABIEvolutionDumpTests, @unchecked Sendable { - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionFile() async throws { - try await evolutionFile(versions: versions) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionString() async throws { - try await evolutionString(versions: versions) - } - } - - /// SwiftUI together with SwiftUICore across the default three caches - /// (15.5 → 26.5.2 → 27.0), each version one group of images (evolution - /// proposal `image-group-evolution`): what moved between the two images - /// after the split reads as moved, not as removed and added. - final class SwiftUIImageGroupDyldCacheTests: MultiVersionDyldCacheImageTests, ABIEvolutionDumpTests, @unchecked Sendable { - override class var cacheImageNames: [MachOImageName] { [.SwiftUI, .SwiftUICore] } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionFile() async throws { - try await evolutionFile(imageGroupVersions: imageGroupVersions) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionString() async throws { - try await evolutionString(imageGroupVersions: imageGroupVersions) - } - } - - /// The same group across every archived macOS cache, on the axis of - /// `SwiftEvolutionInterfaceBuilderTestSuite.ArchivedDyldCacheTests`: - /// SwiftUI alone until 14.8, SwiftUICore joining it in 15.0 — where an - /// evolution of SwiftUI alone reads every declaration moved into - /// SwiftUICore as removed. - final class SwiftUIImageGroupArchivedDyldCacheTests: MultiVersionDyldCacheImageTests, ABIEvolutionDumpTests, @unchecked Sendable { - override class var cachePaths: [DyldSharedCachePath] { - SwiftEvolutionInterfaceBuilderTestSuite.ArchivedDyldCacheTests.cachePaths - } - - override class var cacheImageNames: [MachOImageName] { [.SwiftUI, .SwiftUICore] } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionFile() async throws { - try await evolutionFile(imageGroupVersions: imageGroupVersions) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionString() async throws { - try await evolutionString(imageGroupVersions: imageGroupVersions) - } - } - - /// SwiftUICore across two simulator runtimes (iOS 18.5 → 26.5) — the - /// N == 2 case, whose printed pairwise cross-check line must agree with - /// the two-sided differ. - final class SwiftUICoreTests: SwiftDiffableInterfaceBuilderTestSuite.CrossVersionMachOFileTests, ABIEvolutionDumpTests, @unchecked Sendable { - override class var oldFileName: MachOFileName { .iOS_18_5_Simulator_SwiftUICore } - override class var newFileName: MachOFileName { .iOS_26_5_Simulator_SwiftUICore } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionFile() async throws { - try await evolutionFile(versions: [("18.5", oldMachOFile), ("26.5", newMachOFile)]) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionString() async throws { - try await evolutionString(versions: [("18.5", oldMachOFile), ("26.5", newMachOFile)]) - } - } -} diff --git a/Tests/IntegrationTests/SwiftInterface/RenderingVerificationTests.swift b/Tests/IntegrationTests/SwiftInterface/RenderingVerificationTests.swift index 56bb26a37..cfe1bf826 100644 --- a/Tests/IntegrationTests/SwiftInterface/RenderingVerificationTests.swift +++ b/Tests/IntegrationTests/SwiftInterface/RenderingVerificationTests.swift @@ -8,6 +8,8 @@ import SwiftDeclarationRendering import SwiftInterface import SwiftSectionFixtureSupport import Demangling +import Semantic +import SwiftPrinting /// Maintainer-only rendering-verification harness (no assertions — like the rest /// of `IntegrationTests`). @@ -107,7 +109,7 @@ struct RenderingVerificationTests { } private static func cacheFile(named framework: String) -> MachOFile? { - guard let cache = try? FullDyldCache(path: .current) else { return nil } + guard let cache = FullDyldCache.cachedHost else { return nil } return cache.machOFile(by: .name(framework)) } diff --git a/Tests/IntegrationTests/SwiftInterface/SwiftDiffableInterfaceBuilderTests.swift b/Tests/IntegrationTests/SwiftInterface/SwiftDiffableInterfaceBuilderTests.swift deleted file mode 100644 index c475fbf98..000000000 --- a/Tests/IntegrationTests/SwiftInterface/SwiftDiffableInterfaceBuilderTests.swift +++ /dev/null @@ -1,263 +0,0 @@ -import Foundation -import Testing -import SwiftDeclarationRendering -import MachOKit -import SwiftSectionFixtureSupport -import SwiftSectionTestingSupport -@testable import MachOSwiftSection -@testable import SwiftInterface -@_spi(Support) @testable import SwiftIndexing -import SwiftDiffing - -/// The ABI-diff analogue of ``SwiftInterfaceBuilderTests``. -/// -/// Where the interface builder tests index *one* binary and render it, these -/// index a *pair* of binaries and run them through the diff pipeline: -/// `ABIDiffer` (the machine-readable change list) and -/// `SwiftDiffableInterfaceRenderer` (the full interface annotated with inline -/// `+`/`-` markers). Like its sibling it is a maintainer-inspection dump — it -/// prints / writes results without assertions. -protocol SwiftDiffableInterfaceBuilderTests: SwiftInterfaceDumpTests {} - -@available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) -extension SwiftDiffableInterfaceBuilderTests { - var indexConfiguration: SwiftDeclarationIndexConfiguration { - .init(showCImportedTypes: false) - } - - /// Builds and `prepare()`s both binaries in one timed step — the differ needs - /// both sides indexed before it can compare them, so the printed duration - /// covers the whole preparation. - private func preparedBuilders( - old: Old, - new: New, - ) async throws -> (old: SwiftDiffableInterfaceBuilder, new: SwiftDiffableInterfaceBuilder) { - let oldBuilder = SwiftDiffableInterfaceBuilder(configuration: indexConfiguration, in: old) - let newBuilder = SwiftDiffableInterfaceBuilder(configuration: indexConfiguration, in: new) - try await measuringPreparation { - try await oldBuilder.prepare() - try await newBuilder.prepare() - } - return (oldBuilder, newBuilder) - } - - /// The machine-readable change list plus the one-line compatibility verdict, - /// mirroring `swift-section diff`'s text report. - private func changeListReport( - old: SwiftDiffableInterfaceBuilder, - new: SwiftDiffableInterfaceBuilder, - ) -> String { - let diff = ABIDiffer().diff(old: old.abiModule(), new: new.abiModule()) - let verdict = "ABI-breaking: \(diff.hasBreakingChange) · backward-compatible: \(diff.isBackwardCompatible)" - return ABIDiffReporter().report(diff) + "\n\n" + verdict - } - - /// The full interface annotated with inline `+`/`-` markers, mirroring - /// `swift-section diff --interface`. - private func annotatedInterface( - old: SwiftDiffableInterfaceBuilder, - new: SwiftDiffableInterfaceBuilder, - format: DiffFormat = .inline, - ) async -> String { - await SwiftDiffableInterfaceRenderer(old: old, new: new).printAnnotatedInterface(format: format).string - } - - /// Console analogue of `buildString`: prepares both binaries, then prints the - /// change list and the annotated interface. - func diffString( - old: some MachOFieldLayoutRenderable, - new: some MachOFieldLayoutRenderable, - ) async throws { - let (oldBuilder, newBuilder) = try await preparedBuilders(old: old, new: new) - printResult(changeListReport(old: oldBuilder, new: newBuilder)) - await printResult(annotatedInterface(old: oldBuilder, new: newBuilder)) - } - - /// File analogue of `buildFile`: writes the change list (`-Diff.txt`) and the - /// annotated interface (`-AnnotatedInterface.swiftinterface`) next to the - /// single-binary interface dumps, both named after the *new* binary. - func diffFile( - old: some MachOFieldLayoutRenderable, - new: some MachOFieldLayoutRenderable, - ) async throws { - let (oldBuilder, newBuilder) = try await preparedBuilders(old: old, new: new) - try write(changeListReport(old: oldBuilder, new: newBuilder), for: newBuilder.machO, suffix: "Diff", fileExtension: "txt") - try await write(annotatedInterface(old: oldBuilder, new: newBuilder, format: .inline), for: newBuilder.machO, suffix: "AnnotatedInterface-Inline") - try await write(annotatedInterface(old: oldBuilder, new: newBuilder, format: .unified()), for: newBuilder.machO, suffix: "AnnotatedInterface-Unified") - } -} - -/// Selects the preferred-architecture slice from a loaded `File`, mirroring the -/// loading convention of `SwiftSectionTestingSupport`'s single-binary base classes. -/// Shared by every cross-version base class below so the fat/thin handling lives -/// in one place. -private func selectMachOFile(from file: File, architecture: CPUType) throws -> MachOFile { - switch file { - case .fat(let fatFile): - return try required(fatFile.machOFiles().first(where: { $0.header.cpuType == architecture }) ?? fatFile.machOFiles().first) - case .machO(let machO): - return machO - @unknown default: - fatalError() - } -} - -enum SwiftDiffableInterfaceBuilderTestSuite { - /// Loads a fixed `(old, new)` pair of `MachOFile`s by name — the two-binary - /// counterpart of `SwiftSectionTestingSupport.MachOFileTests`, which only loads one. - @TestActor - class CrossVersionMachOFileTests: Sendable { - let oldMachOFile: MachOFile - let newMachOFile: MachOFile - - class var oldFileName: MachOFileName { .iOS_18_5_Simulator_SwiftUICore } - class var newFileName: MachOFileName { .iOS_26_5_Simulator_SwiftUICore } - class var preferredArchitecture: CPUType { .arm64 } - - init() async throws { - self.oldMachOFile = try selectMachOFile(from: loadFromFile(named: Self.oldFileName), architecture: Self.preferredArchitecture) - self.newMachOFile = try selectMachOFile(from: loadFromFile(named: Self.newFileName), architecture: Self.preferredArchitecture) - } - } - - /// Extracts the same image from two dyld shared caches — the two-binary, - /// two-cache counterpart of `SwiftSectionTestingSupport.DyldCacheTests`. The caches are - /// retained because the extracted `MachOFile`s resolve cross-image references - /// (into Foundation, libswiftCore, …) through them while indexing. - @TestActor - class CrossVersionDyldCacheImageTests: Sendable { - let oldCache: DyldCache - let newCache: DyldCache - let oldMachOFileInCache: MachOFile - let newMachOFileInCache: MachOFile - - class var oldCachePath: DyldSharedCachePath { .macOS_26_5_1 } - class var newCachePath: DyldSharedCachePath { .macOS_27_0 } - class var cacheImageName: MachOImageName { .AppKit } - - init() async throws { - let oldCache = try DyldCache(path: Self.oldCachePath) - let newCache = try DyldCache(path: Self.newCachePath) - self.oldCache = oldCache - self.newCache = newCache - self.oldMachOFileInCache = try #require(oldCache.machOFile(named: Self.cacheImageName)) - self.newMachOFileInCache = try #require(newCache.machOFile(named: Self.cacheImageName)) - } - } - - /// Loads the same shared framework from two installed Xcode applications. The - /// shared `XcodeMachOFileName` fixture hardcodes a single Xcode, so this loads - /// by path directly — the local-loading counterpart that lets the diff compare - /// two Xcode versions without changing the fixture. - @TestActor - class CrossVersionXcodeFrameworkTests: Sendable { - let oldMachOFile: MachOFile - let newMachOFile: MachOFile - - class var oldXcodeApplicationPath: String { "/Applications/Xcode-26.3.0.app" } - class var newXcodeApplicationPath: String { "/Applications/Xcode-26.4.0.app" } - class var sharedFrameworkName: String { "DVTProductsUI" } - class var preferredArchitecture: CPUType { .arm64 } - - init() async throws { - self.oldMachOFile = try Self.loadSharedFramework(inXcodeAt: Self.oldXcodeApplicationPath) - self.newMachOFile = try Self.loadSharedFramework(inXcodeAt: Self.newXcodeApplicationPath) - } - - private class func loadSharedFramework(inXcodeAt xcodeApplicationPath: String) throws -> MachOFile { - let name = sharedFrameworkName - let binaryPath = "\(xcodeApplicationPath)/Contents/SharedFrameworks/\(name).framework/Versions/A/\(name)" - return try selectMachOFile(from: File.loadFromFile(url: URL(fileURLWithPath: binaryPath)), architecture: preferredArchitecture) - } - } - - /// SwiftUICore across two simulator runtimes (iOS 18.5 → 26.2). - final class SwiftUICoreTests: CrossVersionMachOFileTests, SwiftDiffableInterfaceBuilderTests, @unchecked Sendable { - override class var oldFileName: MachOFileName { .iOS_18_5_Simulator_SwiftUICore } - override class var newFileName: MachOFileName { .iOS_26_5_Simulator_SwiftUICore } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func `diff file`() async throws { - try await diffFile(old: oldMachOFile, new: newMachOFile) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func `diff string`() async throws { - try await diffString(old: oldMachOFile, new: newMachOFile) - } - } - - /// SwiftUI across two simulator runtimes (iOS 18.5 → 26.2). - final class SwiftUITests: CrossVersionMachOFileTests, SwiftDiffableInterfaceBuilderTests, @unchecked Sendable { - override class var oldFileName: MachOFileName { .iOS_18_5_Simulator_SwiftUI } - override class var newFileName: MachOFileName { .iOS_26_5_Simulator_SwiftUI } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func diffFile() async throws { - try await diffFile(old: oldMachOFile, new: newMachOFile) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func diffString() async throws { - try await diffString(old: oldMachOFile, new: newMachOFile) - } - } - - /// The same macOS image (SwiftUI) extracted from two dyld shared caches - /// (macOS 15.5 → current). Cross-image references resolve through each cache. - final class DyldCacheTests: CrossVersionDyldCacheImageTests, SwiftDiffableInterfaceBuilderTests, @unchecked Sendable { - override class var oldCachePath: DyldSharedCachePath { .macOS_26_5_1 } - override class var newCachePath: DyldSharedCachePath { .macOS_27_0 } - override class var cacheImageName: MachOImageName { .AppKit } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func diffFile() async throws { - try await diffFile(old: oldMachOFileInCache, new: newMachOFileInCache) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func diffString() async throws { - try await diffString(old: oldMachOFileInCache, new: newMachOFileInCache) - } - } - - /// The same image from two archived macOS caches, picked by version: point - /// the two versions at any directories under `/Volumes/DyldSharedCaches/macOS` - /// that hold a cache. - final class ArchivedDyldCacheTests: CrossVersionDyldCacheImageTests, SwiftDiffableInterfaceBuilderTests, @unchecked Sendable { - class var oldCacheVersion: String { "26.6" } - class var newCacheVersion: String { "27.0" } - override class var oldCachePath: DyldSharedCachePath { .macOS(oldCacheVersion) } - override class var newCachePath: DyldSharedCachePath { .macOS(newCacheVersion) } - override class var cacheImageName: MachOImageName { .AppKit } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func diffFile() async throws { - try await diffFile(old: oldMachOFileInCache, new: newMachOFileInCache) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func diffString() async throws { - try await diffString(old: oldMachOFileInCache, new: newMachOFileInCache) - } - } - - /// The DVTProductsUI shared framework across two installed Xcode versions - /// (26.3 → 26.4) — mirrors the framework the interface builder tests use, - /// loaded by path so the diff can compare two Xcodes. - final class XcodeFrameworkTests: CrossVersionXcodeFrameworkTests, SwiftDiffableInterfaceBuilderTests, @unchecked Sendable { - override class var oldXcodeApplicationPath: String { "/Applications/Xcode-26.3.0.app" } - override class var newXcodeApplicationPath: String { "/Applications/Xcode-26.4.0.app" } - override class var sharedFrameworkName: String { "DVTProductsUI" } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func diffFile() async throws { - try await diffFile(old: oldMachOFile, new: newMachOFile) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func diffString() async throws { - try await diffString(old: oldMachOFile, new: newMachOFile) - } - } -} diff --git a/Tests/IntegrationTests/SwiftInterface/SwiftEvolutionInterfaceBuilderTests.swift b/Tests/IntegrationTests/SwiftInterface/SwiftEvolutionInterfaceBuilderTests.swift deleted file mode 100644 index cce847f5c..000000000 --- a/Tests/IntegrationTests/SwiftInterface/SwiftEvolutionInterfaceBuilderTests.swift +++ /dev/null @@ -1,320 +0,0 @@ -import Foundation -import Testing -import SwiftDeclarationRendering -import MachOKit -import SwiftSectionFixtureSupport -import SwiftSectionTestingSupport -@testable import MachOSwiftSection -@_spi(Support) @testable import SwiftInterface -@_spi(Support) @testable import SwiftIndexing -import SwiftDiffing - -/// The annotated-union-interface analogue of ``ABIEvolutionDumpTests``. -/// -/// Where the evolution dump tests run an ordered series of versions through -/// the lineage-report pipeline (`ABIEvolutionBuilder` + `ABIEvolutionReporter`), -/// these run the same series through `AnySwiftEvolutionInterfaceBuilder` — -/// the `swift-section evolution --interface` pipeline — and dump the union -/// interface with lifecycle annotations. Like its siblings it is a -/// maintainer-inspection dump: it prints / writes results without assertions. -/// Inspect the output against the lineage report the `ABIEvolutionTests` -/// dumps produce for the same axis — the two views must tell one story -/// (annotation facts are the same lineages). -/// -/// Every axis here has three versions or more, on -/// `MultiVersionDyldCacheImageTests`: an evolution over fewer than three -/// images is what `diff --interface` already covers, and the stories this -/// view exists for — introduced mid-axis, removed mid-axis, modified twice, -/// gone-and-back bitmaps — only appear from three versions up. -protocol SwiftEvolutionInterfaceDumpTests: SwiftInterfaceDumpTests {} - -@available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) -extension SwiftEvolutionInterfaceDumpTests { - var indexConfiguration: SwiftDeclarationIndexConfiguration { - .init(showCImportedTypes: false) - } - - /// Builds and `prepare()`s the whole axis in one timed step — indexing N - /// binaries is the real cost; the lineage join and rendering afterwards - /// are cheap by comparison. - private func preparedBuilder( - versions: [(label: String, machO: some MachOFieldLayoutRenderable)], - availabilityAnnotationPlatform: String? - ) async throws -> AnySwiftEvolutionInterfaceBuilder { - let builder = try AnySwiftEvolutionInterfaceBuilder( - configuration: indexConfiguration, - versions: versions.map(\.machO), - labels: versions.map(\.label), - availabilityAnnotationPlatform: availabilityAnnotationPlatform - ) - try await measuringPreparation { - try await builder.prepare() - } - return builder - } - - /// The annotated union interface plus the per-axis verdict line, so the - /// manual inspection can eyeball the CI-gate input next to the rendering. - private func annotatedInterfaceReport(of builder: AnySwiftEvolutionInterfaceBuilder) async throws -> String { - var report = try await builder.printAnnotatedInterface().string - if let evolution = builder.evolution { - report += "\n\n// ABI-breaking on this axis: \(evolution.hasBreakingChange)" - } - return report - } - - /// Console analogue of `evolutionString`: prepares every version, then - /// prints the annotated union interface. A platform adds the genuine - /// `@available` lines, as `evolution --interface --emit-available - /// --platform` does. - func evolutionInterfaceString( - versions: [(label: String, machO: some MachOFieldLayoutRenderable)], - availabilityAnnotationPlatform: String? = nil - ) async throws { - let builder = try await preparedBuilder(versions: versions, availabilityAnnotationPlatform: availabilityAnnotationPlatform) - printResult(try await annotatedInterfaceReport(of: builder)) - } - - /// File analogue of `evolutionFile`: writes the annotated union interface - /// (`-EvolutionInterface.swiftinterface`) next to the lineage-report and - /// diff dumps, named after the *newest* version. - func evolutionInterfaceFile( - versions: [(label: String, machO: some MachOFieldLayoutRenderable)], - availabilityAnnotationPlatform: String? = nil - ) async throws { - let builder = try await preparedBuilder(versions: versions, availabilityAnnotationPlatform: availabilityAnnotationPlatform) - guard let newestVersion = versions.last else { return } - try await write(annotatedInterfaceReport(of: builder), for: newestVersion.machO, suffix: "EvolutionInterface") - } - - // MARK: - Groups of images - - /// Versions made up of groups of images (evolution proposal - /// `image-group-evolution`): each version's images render as one - /// interface, every declaration through the image that indexed it. - private func preparedBuilder( - imageGroupVersions: [(label: String, images: [(imageName: MachOImageName, machO: MachOFile)])], - availabilityAnnotationPlatform: String? - ) async throws -> AnySwiftEvolutionInterfaceBuilder { - let builder = try AnySwiftEvolutionInterfaceBuilder( - configuration: indexConfiguration, - imageGroups: imageGroupVersions.map { version in - version.images.map { SwiftEvolutionInterfaceImage(imageName: $0.imageName.rawValue, machO: $0.machO) } - }, - labels: imageGroupVersions.map(\.label), - availabilityAnnotationPlatform: availabilityAnnotationPlatform - ) - try await measuringPreparation { - try await builder.prepare() - } - return builder - } - - /// Console analogue of `evolutionInterfaceFile(imageGroupVersions:availabilityAnnotationPlatform:)`. - func evolutionInterfaceString( - imageGroupVersions: [(label: String, images: [(imageName: MachOImageName, machO: MachOFile)])], - availabilityAnnotationPlatform: String? = nil - ) async throws { - let builder = try await preparedBuilder(imageGroupVersions: imageGroupVersions, availabilityAnnotationPlatform: availabilityAnnotationPlatform) - printResult(try await annotatedInterfaceReport(of: builder)) - } - - /// Writes the annotated union interface of an evolution over groups of - /// images, named after the newest version's group - /// (`…-SwiftUI+SwiftUICore-EvolutionInterface.swiftinterface`). - func evolutionInterfaceFile( - imageGroupVersions: [(label: String, images: [(imageName: MachOImageName, machO: MachOFile)])], - availabilityAnnotationPlatform: String? = nil - ) async throws { - let builder = try await preparedBuilder(imageGroupVersions: imageGroupVersions, availabilityAnnotationPlatform: availabilityAnnotationPlatform) - guard let newestVersion = imageGroupVersions.last else { return } - try await write(annotatedInterfaceReport(of: builder), forImageGroup: newestVersion.images, suffix: "EvolutionInterface") - } -} - -enum SwiftEvolutionInterfaceBuilderTestSuite { - /// AppKit across three macOS caches (15.5 → 26.5.1 → 27.0 beta 1) — the - /// same axis as `ABIEvolutionTestSuite.DyldCacheTests`' lineage dumps, so - /// the interface and the report can be inspected side by side. - final class DyldCacheTests: ABIEvolutionTestSuite.MultiVersionDyldCacheImageTests, SwiftEvolutionInterfaceDumpTests, @unchecked Sendable { - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionInterfaceFile() async throws { - try await evolutionInterfaceFile(versions: versions) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionInterfaceString() async throws { - try await evolutionInterfaceString(versions: versions) - } - - /// The pack-generic façade on the same three real images: the axis - /// through `SwiftEvolutionInterfaceBuilder` (compile-time arity), dumped for eyeball comparison - /// against the erased builder's output above — the two must be - /// byte-identical. - @available(macOS 14.0, iOS 17.0, tvOS 17.0, watchOS 10.0, *) - @Test func evolutionInterfaceStringViaPackFacade() async throws { - let builder = try SwiftEvolutionInterfaceBuilder( - configuration: indexConfiguration, - versions: versions[0].machO, versions[1].machO, versions[2].machO, - labels: versions.map(\.label) - ) - // No `measuringPreparation` here: this @Test runs on the suite's - // @TestActor, and handing it an actor-isolated closure trips - // region-isolation checking (the extension helpers avoid this by - // being nonisolated themselves). - try await builder.prepare() - printResult(try await builder.printAnnotatedInterface().string) - } - } - - /// SwiftUICore across the same three macOS caches — the Swift-rich axis - /// (AppKit's Swift section is comparatively thin), exercising the union - /// interface over heavy generics, opaque returns, and extension blocks. - final class SwiftUICoreDyldCacheTests: ABIEvolutionTestSuite.MultiVersionDyldCacheImageTests, SwiftEvolutionInterfaceDumpTests, @unchecked Sendable { - override class var cacheImageName: MachOImageName { .SwiftUICore } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionInterfaceFile() async throws { - try await evolutionInterfaceFile(versions: versions) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionInterfaceString() async throws { - try await evolutionInterfaceString(versions: versions) - } - } - - /// The same image across archived macOS caches, picked by version: list - /// in `cacheVersions` the directories under - /// `/Volumes/DyldSharedCaches/macOS` that hold a cache, oldest first. A - /// cache is labeled with its version, or with the major release - /// `versionLabelsByCacheVersion` names for it, so every label is a - /// version number and the union interface also spells each lifecycle one - /// attribute can express as `@available(macOS, …)`. A version whose image - /// carries no Swift metadata drops off the axis (see - /// `MultiVersionDyldCacheImageTests`). - final class ArchivedDyldCacheTests: ABIEvolutionTestSuite.MultiVersionDyldCacheImageTests, SwiftEvolutionInterfaceDumpTests, @unchecked Sendable { - - class var cacheVersions: [String] { [ - "11.0.1", - "11.1", - "11.2", - "11.3", - "11.4", - "11.5", - "11.6", - "11.7", - "12.0.1", - "12.1", - "12.2", - "12.3", - "12.4", - "12.5", - "12.6", - "12.7", - "13.0", - "13.1", - "13.2", - "13.3", - "13.4", - "13.5", - "13.6", - "13.7", - "14.0", - "14.1", - "14.2", - "14.3", - "14.4", - "14.5", - "14.6", - "14.7", - "14.8", - "15.0", - "15.1", - "15.2", - "15.3", - "15.4", - "15.5", - "15.6", - "15.7", - "15.8", - "26.0", - "26.1", - "26.2", - "26.3", - "26.4", - "26.5", - "26.6", - "26.7", - "27.0", - ] } - - /// AppleDB offers no macOS 11.0 or 12.0 image, only 11.0.1 and - /// 12.0.1, so those are the directories the volume has; the axis - /// still labels them 11.0 and 12.0, the versions an SDK's - /// `@available` attributes name. - class var versionLabelsByCacheVersion: [String: String] { ["11.0.1": "11.0", "12.0.1": "12.0"] } - - override class var cachePaths: [DyldSharedCachePath] { - cacheVersions.map { cacheVersion in - let cachePath = DyldSharedCachePath.macOS(cacheVersion) - guard let versionLabel = versionLabelsByCacheVersion[cacheVersion] else { return cachePath } - return DyldSharedCachePath(rawValue: cachePath.rawValue, versionLabel: versionLabel) - } - } - - override class var cacheImageName: MachOImageName { .SwiftUI } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionInterfaceFile() async throws { - try await evolutionInterfaceFile(versions: versions, availabilityAnnotationPlatform: "macOS") - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionInterfaceString() async throws { - try await evolutionInterfaceString(versions: versions, availabilityAnnotationPlatform: "macOS") - } - } - - /// SwiftUI together with SwiftUICore across the default three caches - /// (15.5 → 26.5.2 → 27.0), each version one group of images (evolution - /// proposal `image-group-evolution`) — the axis of - /// `ABIEvolutionTestSuite.SwiftUIImageGroupDyldCacheTests`, so the - /// interface and the report can be read side by side. - final class SwiftUIImageGroupDyldCacheTests: ABIEvolutionTestSuite.MultiVersionDyldCacheImageTests, SwiftEvolutionInterfaceDumpTests, @unchecked Sendable { - override class var cacheImageNames: [MachOImageName] { [.SwiftUI, .SwiftUICore] } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionInterfaceFile() async throws { - try await evolutionInterfaceFile(imageGroupVersions: imageGroupVersions) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionInterfaceString() async throws { - try await evolutionInterfaceString(imageGroupVersions: imageGroupVersions) - } - } - - /// The same group across every archived macOS cache (`ArchivedDyldCacheTests`' - /// axis): SwiftUI alone until 14.8, SwiftUICore joining it in 15.0. Every - /// label is a version number, so the interface also spells each - /// lifecycle one attribute can express as `@available(macOS, …)`. - final class SwiftUIImageGroupArchivedDyldCacheTests: ABIEvolutionTestSuite.MultiVersionDyldCacheImageTests, SwiftEvolutionInterfaceDumpTests, @unchecked Sendable { - override class var cachePaths: [DyldSharedCachePath] { - ArchivedDyldCacheTests.cachePaths - } - - override class var cacheImageNames: [MachOImageName] { [.SwiftUI, .SwiftUICore] } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionInterfaceFile() async throws { - try await evolutionInterfaceFile(imageGroupVersions: imageGroupVersions, availabilityAnnotationPlatform: "macOS") - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func evolutionInterfaceString() async throws { - try await evolutionInterfaceString(imageGroupVersions: imageGroupVersions, availabilityAnnotationPlatform: "macOS") - } - } -} diff --git a/Tests/IntegrationTests/SwiftInterface/SwiftInterfaceBuilderTests.swift b/Tests/IntegrationTests/SwiftInterface/SwiftInterfaceBuilderTests.swift deleted file mode 100644 index dffd7785c..000000000 --- a/Tests/IntegrationTests/SwiftInterface/SwiftInterfaceBuilderTests.swift +++ /dev/null @@ -1,188 +0,0 @@ -@_spi(Support) @testable import SwiftDeclaration -@_spi(Support) @testable import SwiftIndexing -@_spi(Support) @testable import SwiftPrinting -import Foundation -import Testing -import SwiftDeclarationRendering -import MachOKit -import Dependencies -@testable import MachOSwiftSection -@testable import SwiftSectionTestingSupport -import SwiftSectionFixtureSupport -@testable import SwiftInterface -@_spi(Internals) @testable import SwiftSymbols -@_spi(Internals) @testable import MachOCaches - -protocol SwiftInterfaceBuilderTests: SwiftInterfaceDumpTests { - var builderConfiguration: SwiftInterfaceBuilderConfiguration { get } -} - -@available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) -extension SwiftInterfaceBuilderTests { - var builderConfiguration: SwiftInterfaceBuilderConfiguration { - SwiftInterfaceBuilderConfiguration( - indexConfiguration: .init( - showCImportedTypes: false, - ), - printConfiguration: .init( - printStrippedSymbolicItem: true, - printFieldOffset: true, - printExpandedFieldOffsets: true, - printMemberAddress: true, - printVTableOffset: true, - printPWTOffset: true, - infersObjCOverridesFromSelectorNames: true, - usesModuleSelectors: true, - protocolRequirementPlacement: .associatedTypes, - memberSortOrder: .byOffset, - printTypeLayout: true, - printEnumLayout: true, - ), - ) - } - - private func makeBuilder(in machO: MachO) throws -> SwiftInterfaceBuilder { - let builder = try SwiftInterfaceBuilder(configuration: builderConfiguration, eventHandlers: [], in: machO) - builder.addExtraDataProvider(SwiftInterfaceBuilderOpaqueTypeProvider(machO: machO)) - return builder - } - - /// Builds the interface (timed) and returns the rendered source. The two - /// `@Test` entry points below only differ in where they send this string. - private func buildInterfaceString(in machO: some MachOFieldLayoutRenderable) async throws -> String { - let builder = try makeBuilder(in: machO) - try await measuringPreparation { try await builder.prepare() } - return try await builder.printRoot().string - } - - func buildString(in machO: some MachOFieldLayoutRenderable) async throws { - try await printResult(buildInterfaceString(in: machO)) - } - - func buildFile(in machO: some MachOFieldLayoutRenderable) async throws { - // Preserve the historical `-FileDump` / `-ImageDump` naming so the file - // tells you which reader produced it. - let suffix = machO is MachOImage ? "ImageDump" : "FileDump" - try await write(buildInterfaceString(in: machO), for: machO, suffix: suffix) - } -} - -enum SwiftInterfaceBuilderTestSuite { - class DyldCacheTests: SwiftSectionTestingSupport.DyldCacheTests, SwiftInterfaceBuilderTests, @unchecked Sendable { - override class var cacheImageName: MachOImageName { - .AppKit - } - - override class var cachePath: DyldSharedCachePath { - .current - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func buildFile() async throws { - try await buildFile(in: machOFileInCache) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func buildString() async throws { - try await buildString(in: machOFileInCache) - } - } - - /// The same image from an archived macOS cache, picked by version: point - /// `cacheVersion` at any directory under `/Volumes/DyldSharedCaches/macOS` - /// that holds a cache. - class ArchivedDyldCacheTests: SwiftSectionTestingSupport.DyldCacheTests, SwiftInterfaceBuilderTests, @unchecked Sendable { - class var cacheVersion: String { - "26.6" - } - - override class var cachePath: DyldSharedCachePath { - .macOS(cacheVersion) - } - - override class var cacheImageName: MachOImageName { - .AppKit - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func buildFile() async throws { - try await buildFile(in: machOFileInCache) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func buildString() async throws { - try await buildString(in: machOFileInCache) - } - } - - class MachOFileTests: SwiftSectionTestingSupport.MachOFileTests, SwiftInterfaceBuilderTests, @unchecked Sendable { - override class var fileName: MachOFileName { - .SymbolTestsCore - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func buildFile() async throws { - try await buildFile(in: machOFile) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func buildString() async throws { - try await buildString(in: machOFile) - } - } - - class MachOImageTests: SwiftSectionTestingSupport.MachOImageTests, SwiftInterfaceBuilderTests, @unchecked Sendable { - override class var imageName: MachOImageName { - .SwiftUICore - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func buildFile() async throws { - try await buildFile(in: machOImage) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func buildString() async throws { - try await buildString(in: machOImage) - } - } - - class XcodeMachOFileTests: SwiftSectionTestingSupport.XcodeMachOFileTests, SwiftInterfaceBuilderTests { - var builderConfiguration: SwiftInterfaceBuilderConfiguration { - SwiftInterfaceBuilderConfiguration( - indexConfiguration: .init( - showCImportedTypes: false, - ), - printConfiguration: .init( - printStrippedSymbolicItem: true, - printFieldOffset: true, - printExpandedFieldOffsets: true, - printMemberAddress: true, - printVTableOffset: true, - printPWTOffset: true, - printExportedDeclarationsOnly: true, - infersObjCOverridesFromSelectorNames: true, - usesModuleSelectors: true, - protocolRequirementPlacement: .associatedTypes, - memberSortOrder: .byOffset, - printTypeLayout: true, - printEnumLayout: true, - ), - ) - } - - override class var fileName: XcodeMachOFileName { - .sharedFrameworks(.SourceEditor) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func buildFile() async throws { - try await buildFile(in: machOFile) - } - - @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) - @Test func buildString() async throws { - try await buildString(in: machOFile) - } - } -} diff --git a/Tests/IntegrationTests/SwiftInterface/SwiftInterfaceIndexerTests.swift b/Tests/IntegrationTests/SwiftInterface/SwiftInterfaceIndexerTests.swift index d9661cbe0..cd0d2c272 100644 --- a/Tests/IntegrationTests/SwiftInterface/SwiftInterfaceIndexerTests.swift +++ b/Tests/IntegrationTests/SwiftInterface/SwiftInterfaceIndexerTests.swift @@ -11,6 +11,7 @@ import Dependencies @testable import MachOSwiftSection @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import OrderedCollections final class SwiftDeclarationIndexerTests: MachOImageTests, @unchecked Sendable { override class var imageName: MachOImageName { .SwiftUICore } diff --git a/Tests/IntegrationTests/SwiftInterface/SwiftInterfaceTestSupport.swift b/Tests/IntegrationTests/SwiftInterface/SwiftInterfaceTestSupport.swift deleted file mode 100644 index 1a30807cb..000000000 --- a/Tests/IntegrationTests/SwiftInterface/SwiftInterfaceTestSupport.swift +++ /dev/null @@ -1,136 +0,0 @@ -import Foundation -import MachOKit -import SwiftSectionFixtureSupport -@testable import MachOSwiftSection - -/// Shared scaffolding for the `SwiftInterface`-level integration dumps. -/// -/// Both the single-binary interface builder tests and the two-binary diffable -/// builder tests follow the same shape — index a binary (timed), render it to a -/// `String`, then either print it or write it next to the others — so that -/// common machinery (the output directory, the `prepare()` timer, the -/// console/file sinks, and the binary-identifying file name) lives here once. -protocol SwiftInterfaceDumpTests {} - -@available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) -extension SwiftInterfaceDumpTests { - /// The directory every dump is written under, shared so the interface and - /// diff artifacts of the same binary co-locate for manual inspection. - var rootDirectory: URL { - .documentsDirectory.appending(path: "SwiftInterfaceTests") - } - - /// Runs `prepare` and prints how long it took (unless running silently). - /// Callers pass the whole preparation step — for the differ that means - /// preparing *both* binaries — so the printed duration covers the real work. - func measuringPreparation(_ prepare: () async throws -> Void) async rethrows { - let clock = ContinuousClock() - let duration = try await clock.measure { try await prepare() } - #if !SILENT_TEST - print(duration) - #endif - } - - /// Prints a rendered dump to the console, unless running silently. - func printResult(_ string: String) { - #if !SILENT_TEST - print(string) - #endif - } - - /// Writes a rendered dump into `rootDirectory` under a name that identifies - /// the binary by its build version and file name, so repeated runs overwrite - /// in place and different binaries never collide. - func write( - _ string: String, - for machO: some MachOSwiftSectionRepresentableWithCache, - suffix: String, - fileExtension: String = "swiftinterface" - ) throws { - try rootDirectory.createDirectoryIfNeeded() - let fileName = "\(machO.loadCommands.buildVersionCommand!)-\(machO.imagePath.lastPathComponent)-\(suffix).\(fileExtension)" - try string.write(to: rootDirectory.appending(path: fileName), atomically: true, encoding: .utf8) - } - - /// `write(_:for:suffix:fileExtension:)` for a version made up of a group - /// of images (evolution proposal `image-group-evolution`): named after - /// the primary image's build version and every image of the group, - /// joined by `+` (`…-SwiftUI+SwiftUICore-Evolution.txt`). - func write( - _ string: String, - forImageGroup images: [(imageName: MachOImageName, machO: MachOFile)], - suffix: String, - fileExtension: String = "swiftinterface" - ) throws { - guard let primaryImage = images.first else { return } - try rootDirectory.createDirectoryIfNeeded() - let imageGroupName = images.map { $0.machO.imagePath.lastPathComponent }.joined(separator: "+") - let fileName = "\(primaryImage.machO.loadCommands.buildVersionCommand!)-\(imageGroupName)-\(suffix).\(fileExtension)" - try string.write(to: rootDirectory.appending(path: fileName), atomically: true, encoding: .utf8) - } -} - -extension BuildVersionCommand: @retroactive CustomStringConvertible { - public var description: String { - "\(platform.stringValue)-\(sdk)" - } -} - -extension MachOKit.Platform { - var stringValue: String { - switch self { - case .unknown: - "Unknown" - case .any: - "Any" - case .macOS: - "macOS" - case .iOS: - "iOS" - case .tvOS: - "tvOS" - case .watchOS: - "watchOS" - case .bridgeOS: - "bridgeOS" - case .macCatalyst: - "macCatalyst" - case .iOSSimulator: - "iOSSimulator" - case .tvOSSimulator: - "tvOSSimulator" - case .watchOSSimulator: - "watchOSSimulator" - case .driverKit: - "DriverKit" - case .visionOS: - "visionOS" - case .visionOSSimulator: - "visionOSSimulator" - case .firmware: - "Firmware" - case .sepOS: - "sepOS" - case .macOSExclaveCore: - "macOSExclaveCore" - case .macOSExclaveKit: - "macOSExclaveKit" - case .iOSExclaveCore: - "iOSExclaveCore" - case .iOSExclaveKit: - "iOSExclaveKit" - case .tvOSExclaveCore: - "tvOSExclaveCore" - case .tvOSExclaveKit: - "tvOSExclaveKit" - case .watchOSExclaveCore: - "watchOSExclaveCore" - case .watchOSExclaveKit: - "watchOSExclaveKit" - case .visionOSExclaveCore: - "visionOSExclaveCore" - case .visionOSExclaveKit: - "visionOSExclaveKit" - } - } -} diff --git a/Tests/IntegrationTests/TypeIndexing/TypeNameProviderTests.swift b/Tests/IntegrationTests/TypeIndexing/TypeNameProviderTests.swift index 8ab542beb..dbb26c3d9 100644 --- a/Tests/IntegrationTests/TypeIndexing/TypeNameProviderTests.swift +++ b/Tests/IntegrationTests/TypeIndexing/TypeNameProviderTests.swift @@ -6,17 +6,22 @@ import MachOKit import MachOSwiftSection import SwiftInterface import Testing -import TypeIndexing +import SwiftTypeNameResolution @testable import SwiftSectionTestingSupport +import MachODependencies +import SwiftPrinting +import SwiftIndexing +import Semantic -/// Maintainer-run end-to-end for the TypeIndexing provider (evolution -/// proposal 0008): builds the fixture's interface with and without +/// Maintainer-run end-to-end for the `__C` type-name provider (evolution +/// proposal 0008, moved onto swift-type-indexing by proposal +/// swift-type-indexing-package): builds the fixture's interface with and without /// `SwiftInterfaceBuilderTypeNameProvider` attached and prints every line the /// provider changed, plus any `__C.` reference left unresolved. /// /// The first run per SDK build generates the linked modules' interfaces /// through sourcekitd (tens of seconds) and caches the extraction under -/// `Application Support/MachOSwiftSection/SDKIndexer/`. +/// `Application Support/swift-type-indexing/SDKIndexer/`. final class TypeNameProviderMachOFileTests: MachOFileTests, @unchecked Sendable { override class var fileName: MachOFileName { .SymbolTestsCore } diff --git a/Tests/MachOSwiftSectionTests/FileMappingTests.swift b/Tests/MachOSwiftSectionTests/FileMappingTests.swift index ae739fa01..b52e77926 100644 --- a/Tests/MachOSwiftSectionTests/FileMappingTests.swift +++ b/Tests/MachOSwiftSectionTests/FileMappingTests.swift @@ -26,7 +26,7 @@ import SwiftSectionFixtureSupport @Suite struct FileMappingTests { private static var isHostDyldCacheAvailable: Bool { - FileManager.default.fileExists(atPath: DyldSharedCachePath.current.rawValue) + FileManager.default.fileExists(atPath: DyldSharedCachePath.current.path) } /// More Swift images than an XPC service may hold descriptors: mapped per @@ -62,7 +62,8 @@ struct FileMappingTests { guard setrlimit(RLIMIT_NOFILE, &limit) == 0 else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EINVAL) } - let cache = try FullDyldCache(url: URL(fileURLWithPath: DyldSharedCachePath.current.rawValue)) + // A fresh instance, not `FullDyldCache.cachedHost`: its files have to be opened under the lowered descriptor limit. + let cache = try FullDyldCache(url: URL(fileURLWithPath: DyldSharedCachePath.current.path)) let swiftImages = Array( cache.machOFiles() .lazy diff --git a/Tests/MachOSwiftSectionTests/Fixtures/AccessibleFunction/AccessibleFunctionRecordTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/AccessibleFunction/AccessibleFunctionRecordTests.swift index 4ff2ef24f..1b42df110 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/AccessibleFunction/AccessibleFunctionRecordTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/AccessibleFunction/AccessibleFunctionRecordTests.swift @@ -4,6 +4,7 @@ import MachOFoundation @testable import MachOSwiftSection @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import BinaryParseSupport /// Fixture-based Suite for `AccessibleFunctionRecord`. /// @@ -13,12 +14,8 @@ import SwiftSectionFixtureSupport /// environment pointer is null, and the one generic target, whose is not, so /// the nullable pointer is exercised in both states. @Suite -final class AccessibleFunctionRecordTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "AccessibleFunctionRecord" - static var registeredTestMethodNames: Set { - AccessibleFunctionRecordBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class AccessibleFunctionRecordTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private struct Carrier { let label: String let file: AccessibleFunctionRecord @@ -45,10 +42,7 @@ final class AccessibleFunctionRecordTests: MachOSwiftSectionFixtureTests, Fixtur @Test func offset() async throws { for carrier in try allCarriers() { - let result = try acrossAllReaders( - file: { carrier.file.offset }, - image: { carrier.image.offset } - ) + let result = try acrossAllReaders(carrier.file, carrier.image) { $0.offset } #expect(result == carrier.expected.offset, "\(carrier.label)") } @@ -65,26 +59,19 @@ final class AccessibleFunctionRecordTests: MachOSwiftSectionFixtureTests, Fixtur @Test func layout() async throws { for carrier in try allCarriers() { - let flagsRaw = try acrossAllReaders( - file: { carrier.file.layout.flags.rawValue }, - image: { carrier.image.layout.flags.rawValue } - ) + let flagsRaw = try acrossAllReaders(carrier.file, carrier.image) { $0.layout.flags.rawValue } #expect(flagsRaw == carrier.expected.flagsRawValue, "\(carrier.label)") } // Four relative pointers plus a flag word, no padding. #expect(MemoryLayout.size == 20) for carrier in try allCarriers() { - let functionOffset = try acrossAllReaders( - file: { carrier.file.resolvedDirectOffset(from: \.function) }, - image: { carrier.image.resolvedDirectOffset(from: \.function) } - ) + let functionOffset = try acrossAllReaders(carrier.file, carrier.image) { $0.resolvedDirectOffset(from: \.function) } #expect(functionOffset == carrier.expected.functionOffset, "\(carrier.label)") - let genericEnvironmentOffset = try acrossAllReaders( - file: { carrier.file.resolvedDirectOffset(from: \.genericEnvironment) }, - image: { carrier.image.resolvedDirectOffset(from: \.genericEnvironment) } - ) + let genericEnvironmentOffset = try acrossAllReaders(carrier.file, carrier.image) { record in + record.resolvedDirectOffset(from: \.genericEnvironment) + } #expect(genericEnvironmentOffset == carrier.expected.genericEnvironmentOffset, "\(carrier.label)") } // The carriers are only worth having as a pair if they genuinely @@ -94,10 +81,7 @@ final class AccessibleFunctionRecordTests: MachOSwiftSectionFixtureTests, Fixtur @Test func isDistributed() async throws { for carrier in try allCarriers() { - let result = try acrossAllReaders( - file: { carrier.file.isDistributed }, - image: { carrier.image.isDistributed } - ) + let result = try acrossAllReaders(carrier.file, carrier.image) { $0.isDistributed } #expect(result == carrier.expected.isDistributed, "\(carrier.label)") } } @@ -132,10 +116,9 @@ final class AccessibleFunctionRecordTests: MachOSwiftSectionFixtureTests, Fixtur @Test func genericEnvironment() async throws { for carrier in try allCarriers() { - let resolvedOffset = try acrossAllContexts( - file: { try carrier.file.genericEnvironment(in: fileContext)?.offset }, - image: { try carrier.image.genericEnvironment(in: imageContext)?.offset } - ) + let resolvedOffset = try acrossAllContexts(carrier.file, carrier.image) { record, context in + try record.genericEnvironment(in: context)?.offset + } #expect(resolvedOffset == carrier.expected.genericEnvironmentOffset, "\(carrier.label)") } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Anonymous/AnonymousContextDescriptorFlagsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Anonymous/AnonymousContextDescriptorFlagsTests.swift index 2a92540ab..835b17822 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Anonymous/AnonymousContextDescriptorFlagsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Anonymous/AnonymousContextDescriptorFlagsTests.swift @@ -13,12 +13,8 @@ import SwiftSectionFixtureSupport /// descriptor and assert the `rawValue` and the derived `hasMangledName` /// match the baseline; we also verify the `init(rawValue:)` round-trip. @Suite -final class AnonymousContextDescriptorFlagsTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "AnonymousContextDescriptorFlags" - static var registeredTestMethodNames: Set { - AnonymousContextDescriptorFlagsBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class AnonymousContextDescriptorFlagsTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Helper: extract the `AnonymousContextDescriptorFlags` from the /// fixture's first anonymous descriptor against both readers. private func loadFirstFlags() throws -> (file: AnonymousContextDescriptorFlags, image: AnonymousContextDescriptorFlags) { @@ -31,10 +27,7 @@ final class AnonymousContextDescriptorFlagsTests: MachOSwiftSectionFixtureTests, @Test func rawValue() async throws { let flags = try loadFirstFlags() - let result = try acrossAllReaders( - file: { flags.file.rawValue }, - image: { flags.image.rawValue } - ) + let result = try acrossAllReaders(flags.file, flags.image) { $0.rawValue } #expect(result == AnonymousContextDescriptorFlagsBaseline.firstAnonymous.rawValue) } @@ -51,10 +44,7 @@ final class AnonymousContextDescriptorFlagsTests: MachOSwiftSectionFixtureTests, @Test func hasMangledName() async throws { let flags = try loadFirstFlags() - let result = try acrossAllReaders( - file: { flags.file.hasMangledName }, - image: { flags.image.hasMangledName } - ) + let result = try acrossAllReaders(flags.file, flags.image) { $0.hasMangledName } #expect(result == AnonymousContextDescriptorFlagsBaseline.firstAnonymous.hasMangledName) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Anonymous/AnonymousContextDescriptorProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Anonymous/AnonymousContextDescriptorProtocolTests.swift index d6ce2a62e..595911b57 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Anonymous/AnonymousContextDescriptorProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Anonymous/AnonymousContextDescriptorProtocolTests.swift @@ -12,22 +12,15 @@ import SwiftSectionFixtureSupport /// The MangledName payload is a deep ABI tree we don't embed as a literal; /// instead we verify cross-reader-consistent results at runtime. @Suite -final class AnonymousContextDescriptorProtocolTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "AnonymousContextDescriptorProtocol" - static var registeredTestMethodNames: Set { - AnonymousContextDescriptorProtocolBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class AnonymousContextDescriptorProtocolTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func hasMangledName() async throws { let fileDescriptor = try BaselineFixturePicker.anonymous_first(in: machOFile) let imageDescriptor = try BaselineFixturePicker.anonymous_first(in: machOImage) // `hasMangledName` is a pure-derivation getter on the protocol; // every reader must agree. - let result = try acrossAllReaders( - file: { fileDescriptor.hasMangledName }, - image: { imageDescriptor.hasMangledName } - ) + let result = try acrossAllReaders(fileDescriptor, imageDescriptor) { $0.hasMangledName } // The presence flag's value is recorded against the same picker // (`anonymous_first`) on this Suite's own baseline. #expect(result == AnonymousContextDescriptorProtocolBaseline.firstAnonymous.hasMangledName) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Anonymous/AnonymousContextDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Anonymous/AnonymousContextDescriptorTests.swift index 02b15b6bb..07d0f9fd4 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Anonymous/AnonymousContextDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Anonymous/AnonymousContextDescriptorTests.swift @@ -13,20 +13,13 @@ import SwiftSectionFixtureSupport /// `hasMangledName`) live on `AnonymousContextDescriptorProtocol` and are /// covered by `AnonymousContextDescriptorProtocolTests`. @Suite -final class AnonymousContextDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "AnonymousContextDescriptor" - static var registeredTestMethodNames: Set { - AnonymousContextDescriptorBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class AnonymousContextDescriptorTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func offset() async throws { let fileSubject = try BaselineFixturePicker.anonymous_first(in: machOFile) let imageSubject = try BaselineFixturePicker.anonymous_first(in: machOImage) - let result = try acrossAllReaders( - file: { fileSubject.offset }, - image: { imageSubject.offset } - ) + let result = try acrossAllReaders(fileSubject, imageSubject) { $0.offset } #expect(result == AnonymousContextDescriptorBaseline.firstAnonymous.offset) } @@ -37,10 +30,7 @@ final class AnonymousContextDescriptorTests: MachOSwiftSectionFixtureTests, Fixt // Cross-reader equality on the only stable scalar field // (`flags.rawValue`); `parent` is a relative pointer whose value // varies by reader. - let flagsRaw = try acrossAllReaders( - file: { fileSubject.layout.flags.rawValue }, - image: { imageSubject.layout.flags.rawValue } - ) + let flagsRaw = try acrossAllReaders(fileSubject, imageSubject) { $0.layout.flags.rawValue } #expect(flagsRaw == AnonymousContextDescriptorBaseline.firstAnonymous.layoutFlagsRawValue) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Anonymous/AnonymousContextTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Anonymous/AnonymousContextTests.swift index a147b3958..663b8e26d 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Anonymous/AnonymousContextTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Anonymous/AnonymousContextTests.swift @@ -17,12 +17,8 @@ import SwiftSectionFixtureSupport /// established presence-flag pattern (`MangledName` and `GenericContext` /// aren't cheaply Equatable). @Suite -final class AnonymousContextTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "AnonymousContext" - static var registeredTestMethodNames: Set { - AnonymousContextBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class AnonymousContextTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Helper: instantiate the `AnonymousContext` wrapper against both /// readers through their reading contexts. private func loadFirstAnonymousContexts() throws -> (file: AnonymousContext, image: AnonymousContext) { @@ -65,28 +61,19 @@ final class AnonymousContextTests: MachOSwiftSectionFixtureTests, FixtureSuite, @Test func descriptor() async throws { let contexts = try loadFirstAnonymousContexts() - let descriptorOffsets = try acrossAllReaders( - file: { contexts.file.descriptor.offset }, - image: { contexts.image.descriptor.offset } - ) + let descriptorOffsets = try acrossAllReaders(contexts.file, contexts.image) { $0.descriptor.offset } #expect(descriptorOffsets == AnonymousContextBaseline.firstAnonymous.descriptorOffset) } @Test func genericContext() async throws { let contexts = try loadFirstAnonymousContexts() - let presence = try acrossAllReaders( - file: { contexts.file.genericContext != nil }, - image: { contexts.image.genericContext != nil } - ) + let presence = try acrossAllReaders(contexts.file, contexts.image) { $0.genericContext != nil } #expect(presence == AnonymousContextBaseline.firstAnonymous.hasGenericContext) } @Test func mangledName() async throws { let contexts = try loadFirstAnonymousContexts() - let presence = try acrossAllReaders( - file: { contexts.file.mangledName != nil }, - image: { contexts.image.mangledName != nil } - ) + let presence = try acrossAllReaders(contexts.file, contexts.image) { $0.mangledName != nil } #expect(presence == AnonymousContextBaseline.firstAnonymous.hasMangledName) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/AssociatedType/AssociatedTypeDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/AssociatedType/AssociatedTypeDescriptorTests.swift index 172b3554a..f7b86a060 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/AssociatedType/AssociatedTypeDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/AssociatedType/AssociatedTypeDescriptorTests.swift @@ -18,12 +18,8 @@ import SwiftSectionFixtureSupport /// to `AssociatedTypeWitnessPatterns.AssociatedPatternProtocol` (5 concrete /// witnesses). @Suite -final class AssociatedTypeDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "AssociatedTypeDescriptor" - static var registeredTestMethodNames: Set { - AssociatedTypeDescriptorBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class AssociatedTypeDescriptorTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { // MARK: - Helpers private func loadDescriptors() throws -> (file: AssociatedTypeDescriptor, image: AssociatedTypeDescriptor) { @@ -36,26 +32,17 @@ final class AssociatedTypeDescriptorTests: MachOSwiftSectionFixtureTests, Fixtur @Test func offset() async throws { let descriptors = try loadDescriptors() - let result = try acrossAllReaders( - file: { descriptors.file.offset }, - image: { descriptors.image.offset } - ) + let result = try acrossAllReaders(descriptors.file, descriptors.image) { $0.offset } #expect(result == AssociatedTypeDescriptorBaseline.concreteWitnessTest.offset) } @Test func layout() async throws { // Cross-reader equality on the per-descriptor layout values. let descriptors = try loadDescriptors() - let numAssociatedTypes = try acrossAllReaders( - file: { descriptors.file.layout.numAssociatedTypes }, - image: { descriptors.image.layout.numAssociatedTypes } - ) + let numAssociatedTypes = try acrossAllReaders(descriptors.file, descriptors.image) { $0.layout.numAssociatedTypes } #expect(numAssociatedTypes == AssociatedTypeDescriptorBaseline.concreteWitnessTest.layoutNumAssociatedTypes) - let recordSize = try acrossAllReaders( - file: { descriptors.file.layout.associatedTypeRecordSize }, - image: { descriptors.image.layout.associatedTypeRecordSize } - ) + let recordSize = try acrossAllReaders(descriptors.file, descriptors.image) { $0.layout.associatedTypeRecordSize } #expect(recordSize == AssociatedTypeDescriptorBaseline.concreteWitnessTest.layoutAssociatedTypeRecordSize) } @@ -63,10 +50,7 @@ final class AssociatedTypeDescriptorTests: MachOSwiftSectionFixtureTests, Fixtur @Test func actualSize() async throws { let descriptors = try loadDescriptors() - let result = try acrossAllReaders( - file: { descriptors.file.actualSize }, - image: { descriptors.image.actualSize } - ) + let result = try acrossAllReaders(descriptors.file, descriptors.image) { $0.actualSize } #expect(result == AssociatedTypeDescriptorBaseline.concreteWitnessTest.actualSize) } @@ -74,28 +58,25 @@ final class AssociatedTypeDescriptorTests: MachOSwiftSectionFixtureTests, Fixtur @Test func conformingTypeName() async throws { let descriptors = try loadDescriptors() - let presence = try acrossAllContexts( - file: { (try? descriptors.file.conformingTypeName(in: fileContext)) != nil }, - image: { (try? descriptors.image.conformingTypeName(in: imageContext)) != nil } - ) + let presence = try acrossAllContexts(descriptors.file, descriptors.image) { descriptor, context in + (try? descriptor.conformingTypeName(in: context)) != nil + } #expect(presence == AssociatedTypeDescriptorBaseline.concreteWitnessTest.hasConformingTypeName) } @Test func protocolTypeName() async throws { let descriptors = try loadDescriptors() - let presence = try acrossAllContexts( - file: { (try? descriptors.file.protocolTypeName(in: fileContext)) != nil }, - image: { (try? descriptors.image.protocolTypeName(in: imageContext)) != nil } - ) + let presence = try acrossAllContexts(descriptors.file, descriptors.image) { descriptor, context in + (try? descriptor.protocolTypeName(in: context)) != nil + } #expect(presence == AssociatedTypeDescriptorBaseline.concreteWitnessTest.hasProtocolTypeName) } @Test func associatedTypeRecords() async throws { let descriptors = try loadDescriptors() - let count = try acrossAllContexts( - file: { try descriptors.file.associatedTypeRecords(in: fileContext).count }, - image: { try descriptors.image.associatedTypeRecords(in: imageContext).count } - ) + let count = try acrossAllContexts(descriptors.file, descriptors.image) { descriptor, context in + try descriptor.associatedTypeRecords(in: context).count + } #expect(count == AssociatedTypeDescriptorBaseline.concreteWitnessTest.recordsCount) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/AssociatedType/AssociatedTypeRecordTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/AssociatedType/AssociatedTypeRecordTests.swift index 9e6539e46..816465a7c 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/AssociatedType/AssociatedTypeRecordTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/AssociatedType/AssociatedTypeRecordTests.swift @@ -17,12 +17,8 @@ import SwiftSectionFixtureSupport /// `AssociatedTypeWitnessPatterns.ConcreteWitnessTest`'s /// `AssociatedTypeDescriptor` (witnessing `First = Int`). @Suite -final class AssociatedTypeRecordTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "AssociatedTypeRecord" - static var registeredTestMethodNames: Set { - AssociatedTypeRecordBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class AssociatedTypeRecordTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { // MARK: - Helpers private func loadFirstRecord() throws -> (file: AssociatedTypeRecord, image: AssociatedTypeRecord) { @@ -39,10 +35,7 @@ final class AssociatedTypeRecordTests: MachOSwiftSectionFixtureTests, FixtureSui @Test func offset() async throws { let records = try loadFirstRecord() - let result = try acrossAllReaders( - file: { records.file.offset }, - image: { records.image.offset } - ) + let result = try acrossAllReaders(records.file, records.image) { $0.offset } #expect(result == AssociatedTypeRecordBaseline.firstRecord.offset) } @@ -53,10 +46,9 @@ final class AssociatedTypeRecordTests: MachOSwiftSectionFixtureTests, FixtureSui // structural-presence anchor — it just verifies the layout // accessor is available and consistent across readers. let records = try loadFirstRecord() - let nameStringMatches = try acrossAllContexts( - file: { try records.file.name(in: fileContext) }, - image: { try records.image.name(in: imageContext) } - ) + let nameStringMatches = try acrossAllContexts(records.file, records.image) { record, context in + try record.name(in: context) + } #expect(nameStringMatches == AssociatedTypeRecordBaseline.firstRecord.name) } @@ -64,19 +56,15 @@ final class AssociatedTypeRecordTests: MachOSwiftSectionFixtureTests, FixtureSui @Test func name() async throws { let records = try loadFirstRecord() - let result = try acrossAllContexts( - file: { try records.file.name(in: fileContext) }, - image: { try records.image.name(in: imageContext) } - ) + let result = try acrossAllContexts(records.file, records.image) { record, context in try record.name(in: context) } #expect(result == AssociatedTypeRecordBaseline.firstRecord.name) } @Test func substitutedTypeName() async throws { let records = try loadFirstRecord() - let presence = try acrossAllContexts( - file: { (try? records.file.substitutedTypeName(in: fileContext)) != nil }, - image: { (try? records.image.substitutedTypeName(in: imageContext)) != nil } - ) + let presence = try acrossAllContexts(records.file, records.image) { record, context in + (try? record.substitutedTypeName(in: context)) != nil + } #expect(presence == AssociatedTypeRecordBaseline.firstRecord.hasSubstitutedTypeName) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/AssociatedType/AssociatedTypeTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/AssociatedType/AssociatedTypeTests.swift index 02a0164f6..fa9ab9c19 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/AssociatedType/AssociatedTypeTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/AssociatedType/AssociatedTypeTests.swift @@ -19,12 +19,8 @@ import SwiftSectionFixtureSupport /// to `AssociatedTypeWitnessPatterns.AssociatedPatternProtocol` (5 concrete /// witnesses). @Suite -final class AssociatedTypeTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "AssociatedType" - static var registeredTestMethodNames: Set { - AssociatedTypeBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class AssociatedTypeTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { // MARK: - Helpers private func loadAssociatedTypes() throws -> (file: AssociatedType, image: AssociatedType) { @@ -64,37 +60,27 @@ final class AssociatedTypeTests: MachOSwiftSectionFixtureTests, FixtureSuite, @u @Test func descriptor() async throws { let associatedTypes = try loadAssociatedTypes() - let result = try acrossAllReaders( - file: { associatedTypes.file.descriptor.offset }, - image: { associatedTypes.image.descriptor.offset } - ) + let result = try acrossAllReaders(associatedTypes.file, associatedTypes.image) { $0.descriptor.offset } #expect(result == AssociatedTypeBaseline.concreteWitnessTest.descriptorOffset) } @Test func conformingTypeName() async throws { let associatedTypes = try loadAssociatedTypes() - let presence = try acrossAllReaders( - file: { !associatedTypes.file.conformingTypeName.elements.isEmpty }, - image: { !associatedTypes.image.conformingTypeName.elements.isEmpty } - ) + let presence = try acrossAllReaders(associatedTypes.file, associatedTypes.image) { associatedType in + !associatedType.conformingTypeName.elements.isEmpty + } #expect(presence == AssociatedTypeBaseline.concreteWitnessTest.hasConformingTypeName) } @Test func protocolTypeName() async throws { let associatedTypes = try loadAssociatedTypes() - let presence = try acrossAllReaders( - file: { !associatedTypes.file.protocolTypeName.elements.isEmpty }, - image: { !associatedTypes.image.protocolTypeName.elements.isEmpty } - ) + let presence = try acrossAllReaders(associatedTypes.file, associatedTypes.image) { !$0.protocolTypeName.elements.isEmpty } #expect(presence == AssociatedTypeBaseline.concreteWitnessTest.hasProtocolTypeName) } @Test func records() async throws { let associatedTypes = try loadAssociatedTypes() - let count = try acrossAllReaders( - file: { associatedTypes.file.records.count }, - image: { associatedTypes.image.records.count } - ) + let count = try acrossAllReaders(associatedTypes.file, associatedTypes.image) { $0.records.count } #expect(count == AssociatedTypeBaseline.concreteWitnessTest.recordsCount) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/BuiltinType/BuiltinTypeDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/BuiltinType/BuiltinTypeDescriptorTests.swift index 089e852bf..ba5547063 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/BuiltinType/BuiltinTypeDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/BuiltinType/BuiltinTypeDescriptorTests.swift @@ -15,12 +15,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class BuiltinTypeDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "BuiltinTypeDescriptor" - static var registeredTestMethodNames: Set { - BuiltinTypeDescriptorBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class BuiltinTypeDescriptorTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadDescriptors() throws -> (file: BuiltinTypeDescriptor, image: BuiltinTypeDescriptor) { let file = try BaselineFixturePicker.builtinTypeDescriptor_first(in: machOFile) let image = try BaselineFixturePicker.builtinTypeDescriptor_first(in: machOImage) @@ -29,31 +25,16 @@ final class BuiltinTypeDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSu @Test func offset() async throws { let descriptors = try loadDescriptors() - let result = try acrossAllReaders( - file: { descriptors.file.offset }, - image: { descriptors.image.offset } - ) + let result = try acrossAllReaders(descriptors.file, descriptors.image) { $0.offset } #expect(result == BuiltinTypeDescriptorBaseline.firstBuiltin.descriptorOffset) } @Test func layout() async throws { let descriptors = try loadDescriptors() - let size = try acrossAllReaders( - file: { descriptors.file.layout.size }, - image: { descriptors.image.layout.size } - ) - let stride = try acrossAllReaders( - file: { descriptors.file.layout.stride }, - image: { descriptors.image.layout.stride } - ) - let alignmentAndFlags = try acrossAllReaders( - file: { descriptors.file.layout.alignmentAndFlags }, - image: { descriptors.image.layout.alignmentAndFlags } - ) - let numExtraInhabitants = try acrossAllReaders( - file: { descriptors.file.layout.numExtraInhabitants }, - image: { descriptors.image.layout.numExtraInhabitants } - ) + let size = try acrossAllReaders(descriptors.file, descriptors.image) { $0.layout.size } + let stride = try acrossAllReaders(descriptors.file, descriptors.image) { $0.layout.stride } + let alignmentAndFlags = try acrossAllReaders(descriptors.file, descriptors.image) { $0.layout.alignmentAndFlags } + let numExtraInhabitants = try acrossAllReaders(descriptors.file, descriptors.image) { $0.layout.numExtraInhabitants } #expect(size == BuiltinTypeDescriptorBaseline.firstBuiltin.size) #expect(stride == BuiltinTypeDescriptorBaseline.firstBuiltin.stride) @@ -63,28 +44,19 @@ final class BuiltinTypeDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSu @Test func alignment() async throws { let descriptors = try loadDescriptors() - let result = try acrossAllReaders( - file: { descriptors.file.alignment }, - image: { descriptors.image.alignment } - ) + let result = try acrossAllReaders(descriptors.file, descriptors.image) { $0.alignment } #expect(result == BuiltinTypeDescriptorBaseline.firstBuiltin.alignment) } @Test func isBitwiseTakable() async throws { let descriptors = try loadDescriptors() - let result = try acrossAllReaders( - file: { descriptors.file.isBitwiseTakable }, - image: { descriptors.image.isBitwiseTakable } - ) + let result = try acrossAllReaders(descriptors.file, descriptors.image) { $0.isBitwiseTakable } #expect(result == BuiltinTypeDescriptorBaseline.firstBuiltin.isBitwiseTakable) } @Test func hasMangledName() async throws { let descriptors = try loadDescriptors() - let result = try acrossAllReaders( - file: { descriptors.file.hasMangledName }, - image: { descriptors.image.hasMangledName } - ) + let result = try acrossAllReaders(descriptors.file, descriptors.image) { $0.hasMangledName } #expect(result == BuiltinTypeDescriptorBaseline.firstBuiltin.hasMangledName) } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/BuiltinType/BuiltinTypeTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/BuiltinType/BuiltinTypeTests.swift index 92c962445..824966492 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/BuiltinType/BuiltinTypeTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/BuiltinType/BuiltinTypeTests.swift @@ -12,12 +12,8 @@ import SwiftSectionFixtureSupport /// `__swift5_builtin` section (matches `BuiltinTypeDescriptorBaseline`'s /// carrier). @Suite -final class BuiltinTypeTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "BuiltinType" - static var registeredTestMethodNames: Set { - BuiltinTypeBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class BuiltinTypeTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadBuiltins() throws -> (file: BuiltinType, image: BuiltinType) { let fileDescriptor = try BaselineFixturePicker.builtinTypeDescriptor_first(in: machOFile) let imageDescriptor = try BaselineFixturePicker.builtinTypeDescriptor_first(in: machOImage) @@ -50,19 +46,13 @@ final class BuiltinTypeTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unch @Test func descriptor() async throws { let builtins = try loadBuiltins() - let result = try acrossAllReaders( - file: { builtins.file.descriptor.offset }, - image: { builtins.image.descriptor.offset } - ) + let result = try acrossAllReaders(builtins.file, builtins.image) { $0.descriptor.offset } #expect(result == BuiltinTypeBaseline.firstBuiltin.descriptorOffset) } @Test func typeName() async throws { let builtins = try loadBuiltins() - let presence = try acrossAllReaders( - file: { builtins.file.typeName != nil }, - image: { builtins.image.typeName != nil } - ) + let presence = try acrossAllReaders(builtins.file, builtins.image) { $0.typeName != nil } #expect(presence == BuiltinTypeBaseline.firstBuiltin.hasTypeName) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Capture/CaptureDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Capture/CaptureDescriptorTests.swift index 27371b800..080935bd0 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Capture/CaptureDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Capture/CaptureDescriptorTests.swift @@ -12,12 +12,8 @@ import SwiftSectionFixtureSupport /// non-generic closure's context, a closure in a one-parameter generic /// function, and one in a two-parameter generic function. @Suite -final class CaptureDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "CaptureDescriptor" - static var registeredTestMethodNames: Set { - CaptureDescriptorBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class CaptureDescriptorTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private struct Carrier { let label: String let file: CaptureDescriptor @@ -52,20 +48,16 @@ final class CaptureDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @Test func offset() async throws { for carrier in try allCarriers() { - let result = try acrossAllReaders( - file: { carrier.file.offset }, - image: { carrier.image.offset } - ) + let result = try acrossAllReaders(carrier.file, carrier.image) { $0.offset } #expect(result == carrier.expected.offset, "\(carrier.label)") } } @Test func layout() async throws { for carrier in try allCarriers() { - let counts = try acrossAllReaders( - file: { [carrier.file.layout.numberOfCaptureTypes, carrier.file.layout.numberOfMetadataSources, carrier.file.layout.numberOfBindings] }, - image: { [carrier.image.layout.numberOfCaptureTypes, carrier.image.layout.numberOfMetadataSources, carrier.image.layout.numberOfBindings] } - ) + let counts = try acrossAllReaders(carrier.file, carrier.image) { descriptor in + [descriptor.layout.numberOfCaptureTypes, descriptor.layout.numberOfMetadataSources, descriptor.layout.numberOfBindings] + } #expect(counts.map(Int.init) == [carrier.expected.numberOfCaptureTypes, carrier.expected.numberOfMetadataSources, carrier.expected.numberOfBindings], "\(carrier.label)") } #expect(MemoryLayout.size == 12) @@ -80,10 +72,7 @@ final class CaptureDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, /// whole section is the real assertion here. @Test func actualSize() async throws { for carrier in try allCarriers() { - let result = try acrossAllReaders( - file: { carrier.file.actualSize }, - image: { carrier.image.actualSize } - ) + let result = try acrossAllReaders(carrier.file, carrier.image) { $0.actualSize } #expect(result == carrier.expected.actualSize, "\(carrier.label)") #expect( result == MemoryLayout.size @@ -102,30 +91,23 @@ final class CaptureDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @Test func captureTypeRecordsOffset() async throws { for carrier in try allCarriers() { - let result = try acrossAllReaders( - file: { carrier.file.captureTypeRecordsOffset }, - image: { carrier.image.captureTypeRecordsOffset } - ) + let result = try acrossAllReaders(carrier.file, carrier.image) { $0.captureTypeRecordsOffset } #expect(result == carrier.expected.captureTypeRecordsOffset, "\(carrier.label)") } } @Test func metadataSourceRecordsOffset() async throws { for carrier in try allCarriers() { - let result = try acrossAllReaders( - file: { carrier.file.metadataSourceRecordsOffset }, - image: { carrier.image.metadataSourceRecordsOffset } - ) + let result = try acrossAllReaders(carrier.file, carrier.image) { $0.metadataSourceRecordsOffset } #expect(result == carrier.expected.metadataSourceRecordsOffset, "\(carrier.label)") } } @Test func captureTypeRecords() async throws { for carrier in try allCarriers() { - let offsets = try acrossAllContexts( - file: { try carrier.file.captureTypeRecords(in: fileContext).map(\.offset) }, - image: { try carrier.image.captureTypeRecords(in: imageContext).map(\.offset) } - ) + let offsets = try acrossAllContexts(carrier.file, carrier.image) { descriptor, context in + try descriptor.captureTypeRecords(in: context).map(\.offset) + } #expect(offsets.count == carrier.expected.numberOfCaptureTypes, "\(carrier.label)") #expect(offsets.first == carrier.expected.captureTypeRecordsOffset, "\(carrier.label)") @@ -138,10 +120,9 @@ final class CaptureDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @Test func metadataSourceRecords() async throws { for carrier in try allCarriers() { - let sources = try acrossAllContexts( - file: { try carrier.file.metadataSourceRecords(in: fileContext).map { try $0.mangledMetadataSource(in: fileContext).rawString } }, - image: { try carrier.image.metadataSourceRecords(in: imageContext).map { try $0.mangledMetadataSource(in: imageContext).rawString } } - ) + let sources = try acrossAllContexts(carrier.file, carrier.image) { descriptor, context in + try descriptor.metadataSourceRecords(in: context).map { try $0.mangledMetadataSource(in: context).rawString } + } #expect(sources == carrier.expected.mangledMetadataSources, "\(carrier.label)") let inProcess = try carrier.image.asPointerWrapper(in: machOImage).metadataSourceRecords(in: inProcessContext) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Capture/CaptureTypeRecordTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Capture/CaptureTypeRecordTests.swift index 4b5a0d2a3..b50aedfe1 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Capture/CaptureTypeRecordTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Capture/CaptureTypeRecordTests.swift @@ -12,12 +12,8 @@ import SwiftSectionFixtureSupport /// the record's location and the fact that the payload resolves; the payload /// itself is only required to agree across readers. @Suite -final class CaptureTypeRecordTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "CaptureTypeRecord" - static var registeredTestMethodNames: Set { - CaptureTypeRecordBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class CaptureTypeRecordTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private struct Carrier { let index: Int let file: CaptureTypeRecord @@ -40,20 +36,14 @@ final class CaptureTypeRecordTests: MachOSwiftSectionFixtureTests, FixtureSuite, @Test func offset() async throws { for carrier in try allCarriers() { - let result = try acrossAllReaders( - file: { carrier.file.offset }, - image: { carrier.image.offset } - ) + let result = try acrossAllReaders(carrier.file, carrier.image) { $0.offset } #expect(result == carrier.expected.offset, "record \(carrier.index)") } } @Test func layout() async throws { for carrier in try allCarriers() { - let relativeOffset = try acrossAllReaders( - file: { carrier.file.layout.mangledTypeName.relativeOffset }, - image: { carrier.image.layout.mangledTypeName.relativeOffset } - ) + let relativeOffset = try acrossAllReaders(carrier.file, carrier.image) { $0.layout.mangledTypeName.relativeOffset } #expect(relativeOffset != 0, "record \(carrier.index)") } // A capture type record is exactly one relative pointer; the whole diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Capture/MetadataSourceRecordTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Capture/MetadataSourceRecordTests.swift index 810f4369c..fbfe22805 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Capture/MetadataSourceRecordTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Capture/MetadataSourceRecordTests.swift @@ -15,12 +15,8 @@ import SwiftSectionFixtureSupport /// in the metadata source grammar, not in Swift's type mangling, and this /// library deliberately reports it unparsed. @Suite -final class MetadataSourceRecordTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "MetadataSourceRecord" - static var registeredTestMethodNames: Set { - MetadataSourceRecordBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class MetadataSourceRecordTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private struct Carrier { let index: Int let file: MetadataSourceRecord @@ -43,20 +39,16 @@ final class MetadataSourceRecordTests: MachOSwiftSectionFixtureTests, FixtureSui @Test func offset() async throws { for carrier in try allCarriers() { - let result = try acrossAllReaders( - file: { carrier.file.offset }, - image: { carrier.image.offset } - ) + let result = try acrossAllReaders(carrier.file, carrier.image) { $0.offset } #expect(result == carrier.expected.offset, "record \(carrier.index)") } } @Test func layout() async throws { for carrier in try allCarriers() { - let relativeOffsets = try acrossAllReaders( - file: { [carrier.file.layout.mangledTypeName.relativeOffset, carrier.file.layout.mangledMetadataSource.relativeOffset] }, - image: { [carrier.image.layout.mangledTypeName.relativeOffset, carrier.image.layout.mangledMetadataSource.relativeOffset] } - ) + let relativeOffsets = try acrossAllReaders(carrier.file, carrier.image) { record in + [record.layout.mangledTypeName.relativeOffset, record.layout.mangledMetadataSource.relativeOffset] + } #expect(relativeOffsets.allSatisfy { $0 != 0 }, "record \(carrier.index)") } #expect(MemoryLayout.size == 8) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorFlagsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorFlagsTests.swift index 383857a58..f48642ce5 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorFlagsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorFlagsTests.swift @@ -14,12 +14,8 @@ import SwiftSectionFixtureSupport /// name-only key; we register one entry per name and exercise the /// instance-derivation path here. @Suite -final class ContextDescriptorFlagsTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ContextDescriptorFlags" - static var registeredTestMethodNames: Set { - ContextDescriptorFlagsBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ContextDescriptorFlagsTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Helper: extract the `ContextDescriptorFlags` from /// `Structs.StructTest`'s descriptor against both readers. private func loadStructTestFlags() throws -> (file: ContextDescriptorFlags, image: ContextDescriptorFlags) { @@ -30,10 +26,7 @@ final class ContextDescriptorFlagsTests: MachOSwiftSectionFixtureTests, FixtureS @Test func rawValue() async throws { let flags = try loadStructTestFlags() - let result = try acrossAllReaders( - file: { flags.file.rawValue }, - image: { flags.image.rawValue } - ) + let result = try acrossAllReaders(flags.file, flags.image) { $0.rawValue } #expect(result == ContextDescriptorFlagsBaseline.structTest.rawValue) } @@ -55,28 +48,19 @@ final class ContextDescriptorFlagsTests: MachOSwiftSectionFixtureTests, FixtureS @Test func kind() async throws { let flags = try loadStructTestFlags() - let result = try acrossAllReaders( - file: { flags.file.kind.rawValue }, - image: { flags.image.kind.rawValue } - ) + let result = try acrossAllReaders(flags.file, flags.image) { $0.kind.rawValue } #expect(result == ContextDescriptorFlagsBaseline.structTest.kindRawValue) } @Test func version() async throws { let flags = try loadStructTestFlags() - let result = try acrossAllReaders( - file: { flags.file.version }, - image: { flags.image.version } - ) + let result = try acrossAllReaders(flags.file, flags.image) { $0.version } #expect(result == ContextDescriptorFlagsBaseline.structTest.version) } @Test func kindSpecificFlagsRawValue() async throws { let flags = try loadStructTestFlags() - let result = try acrossAllReaders( - file: { flags.file.kindSpecificFlagsRawValue }, - image: { flags.image.kindSpecificFlagsRawValue } - ) + let result = try acrossAllReaders(flags.file, flags.image) { $0.kindSpecificFlagsRawValue } #expect(result == ContextDescriptorFlagsBaseline.structTest.kindSpecificFlagsRawValue) } @@ -84,37 +68,25 @@ final class ContextDescriptorFlagsTests: MachOSwiftSectionFixtureTests, FixtureS let flags = try loadStructTestFlags() // `kindSpecificFlags` returns `ContextDescriptorKindSpecificFlags?`, // which isn't trivially Equatable. Use presence-only assertion. - let presence = try acrossAllReaders( - file: { flags.file.kindSpecificFlags != nil }, - image: { flags.image.kindSpecificFlags != nil } - ) + let presence = try acrossAllReaders(flags.file, flags.image) { $0.kindSpecificFlags != nil } #expect(presence == ContextDescriptorFlagsBaseline.structTest.hasKindSpecificFlags) } @Test func hasInvertibleProtocols() async throws { let flags = try loadStructTestFlags() - let result = try acrossAllReaders( - file: { flags.file.hasInvertibleProtocols }, - image: { flags.image.hasInvertibleProtocols } - ) + let result = try acrossAllReaders(flags.file, flags.image) { $0.hasInvertibleProtocols } #expect(result == ContextDescriptorFlagsBaseline.structTest.hasInvertibleProtocols) } @Test func isUnique() async throws { let flags = try loadStructTestFlags() - let result = try acrossAllReaders( - file: { flags.file.isUnique }, - image: { flags.image.isUnique } - ) + let result = try acrossAllReaders(flags.file, flags.image) { $0.isUnique } #expect(result == ContextDescriptorFlagsBaseline.structTest.isUnique) } @Test func isGeneric() async throws { let flags = try loadStructTestFlags() - let result = try acrossAllReaders( - file: { flags.file.isGeneric }, - image: { flags.image.isGeneric } - ) + let result = try acrossAllReaders(flags.file, flags.image) { $0.isGeneric } #expect(result == ContextDescriptorFlagsBaseline.structTest.isGeneric) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorKindSpecificFlagsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorKindSpecificFlagsTests.swift index 56a1660be..6d6253356 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorKindSpecificFlagsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorKindSpecificFlagsTests.swift @@ -14,12 +14,8 @@ import SwiftSectionFixtureSupport /// other two `nil`). PublicMemberScanner does NOT emit MethodKey entries /// for enum cases. @Suite -final class ContextDescriptorKindSpecificFlagsTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ContextDescriptorKindSpecificFlags" - static var registeredTestMethodNames: Set { - ContextDescriptorKindSpecificFlagsBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ContextDescriptorKindSpecificFlagsTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Helper: extract the `ContextDescriptorKindSpecificFlags` from /// `Structs.StructTest`'s descriptor against both readers. private func loadStructTestKindSpecificFlags() throws -> (file: ContextDescriptorKindSpecificFlags, image: ContextDescriptorKindSpecificFlags) { @@ -32,28 +28,19 @@ final class ContextDescriptorKindSpecificFlagsTests: MachOSwiftSectionFixtureTes @Test func protocolFlags() async throws { let flags = try loadStructTestKindSpecificFlags() - let presence = try acrossAllReaders( - file: { flags.file.protocolFlags != nil }, - image: { flags.image.protocolFlags != nil } - ) + let presence = try acrossAllReaders(flags.file, flags.image) { $0.protocolFlags != nil } #expect(presence == ContextDescriptorKindSpecificFlagsBaseline.structTest.hasProtocolFlags) } @Test func typeFlags() async throws { let flags = try loadStructTestKindSpecificFlags() - let presence = try acrossAllReaders( - file: { flags.file.typeFlags != nil }, - image: { flags.image.typeFlags != nil } - ) + let presence = try acrossAllReaders(flags.file, flags.image) { $0.typeFlags != nil } #expect(presence == ContextDescriptorKindSpecificFlagsBaseline.structTest.hasTypeFlags) } @Test func anonymousFlags() async throws { let flags = try loadStructTestKindSpecificFlags() - let presence = try acrossAllReaders( - file: { flags.file.anonymousFlags != nil }, - image: { flags.image.anonymousFlags != nil } - ) + let presence = try acrossAllReaders(flags.file, flags.image) { $0.anonymousFlags != nil } #expect(presence == ContextDescriptorKindSpecificFlagsBaseline.structTest.hasAnonymousFlags) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorKindTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorKindTests.swift index a05f3496a..954a9a9e0 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorKindTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorKindTests.swift @@ -14,12 +14,8 @@ import SwiftSectionFixtureSupport /// The kind value is sampled off `Structs.StructTest`'s descriptor — a /// `.struct` kind whose `description == "struct"` and `mangledType == "V"`. @Suite -final class ContextDescriptorKindTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ContextDescriptorKind" - static var registeredTestMethodNames: Set { - ContextDescriptorKindBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ContextDescriptorKindTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Helper: extract the `ContextDescriptorKind` from /// `Structs.StructTest`'s descriptor against both readers. private func loadStructTestKinds() throws -> (file: ContextDescriptorKind, image: ContextDescriptorKind) { @@ -30,19 +26,13 @@ final class ContextDescriptorKindTests: MachOSwiftSectionFixtureTests, FixtureSu @Test func description() async throws { let kinds = try loadStructTestKinds() - let result = try acrossAllReaders( - file: { kinds.file.description }, - image: { kinds.image.description } - ) + let result = try acrossAllReaders(kinds.file, kinds.image) { $0.description } #expect(result == ContextDescriptorKindBaseline.structTest.description) } @Test func mangledType() async throws { let kinds = try loadStructTestKinds() - let result = try acrossAllReaders( - file: { kinds.file.mangledType }, - image: { kinds.image.mangledType } - ) + let result = try acrossAllReaders(kinds.file, kinds.image) { $0.mangledType } #expect(result == ContextDescriptorKindBaseline.structTest.mangledType) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorProtocolTests.swift index 3df35e1a5..0fa65ac0e 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorProtocolTests.swift @@ -18,20 +18,15 @@ import SwiftSectionFixtureSupport /// `GenericContext?`, etc.) aren't trivially Equatable, so we assert on /// presence flags recorded in the baseline. @Suite -final class ContextDescriptorProtocolTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ContextDescriptorProtocol" - static var registeredTestMethodNames: Set { - ContextDescriptorProtocolBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ContextDescriptorProtocolTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func parent() async throws { let fileDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOImage) - let presence = try acrossAllContexts( - file: { (try fileDescriptor.parent(in: fileContext)) != nil }, - image: { (try imageDescriptor.parent(in: imageContext)) != nil } - ) + let presence = try acrossAllContexts(fileDescriptor, imageDescriptor) { descriptor, context in + (try descriptor.parent(in: context)) != nil + } #expect(presence == ContextDescriptorProtocolBaseline.structTest.hasParent) } @@ -39,10 +34,9 @@ final class ContextDescriptorProtocolTests: MachOSwiftSectionFixtureTests, Fixtu let fileDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOImage) - let presence = try acrossAllContexts( - file: { (try fileDescriptor.genericContext(in: fileContext)) != nil }, - image: { (try imageDescriptor.genericContext(in: imageContext)) != nil } - ) + let presence = try acrossAllContexts(fileDescriptor, imageDescriptor) { descriptor, context in + (try descriptor.genericContext(in: context)) != nil + } #expect(presence == ContextDescriptorProtocolBaseline.structTest.hasGenericContext) } @@ -50,10 +44,9 @@ final class ContextDescriptorProtocolTests: MachOSwiftSectionFixtureTests, Fixtu let fileDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOImage) - let presence = try acrossAllContexts( - file: { (try fileDescriptor.moduleContextDescriptor(in: fileContext)) != nil }, - image: { (try imageDescriptor.moduleContextDescriptor(in: imageContext)) != nil } - ) + let presence = try acrossAllContexts(fileDescriptor, imageDescriptor) { descriptor, context in + (try descriptor.moduleContextDescriptor(in: context)) != nil + } #expect(presence == ContextDescriptorProtocolBaseline.structTest.hasModuleContextDescriptor) } @@ -61,10 +54,9 @@ final class ContextDescriptorProtocolTests: MachOSwiftSectionFixtureTests, Fixtu let fileDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOImage) - let result = try acrossAllContexts( - file: { try fileDescriptor.isCImportedContextDescriptor(in: fileContext) }, - image: { try imageDescriptor.isCImportedContextDescriptor(in: imageContext) } - ) + let result = try acrossAllContexts(fileDescriptor, imageDescriptor) { descriptor, context in + try descriptor.isCImportedContextDescriptor(in: context) + } #expect(result == ContextDescriptorProtocolBaseline.structTest.isCImportedContextDescriptor) } @@ -76,10 +68,7 @@ final class ContextDescriptorProtocolTests: MachOSwiftSectionFixtureTests, Fixtu // through `layout.flags`. Exercise the path by reading `kind` (a stable // scalar `ContextDescriptorKind`) via the dot-access syntax that triggers // dynamic-member lookup. - let result = try acrossAllReaders( - file: { fileDescriptor.kind.rawValue }, - image: { imageDescriptor.kind.rawValue } - ) + let result = try acrossAllReaders(fileDescriptor, imageDescriptor) { $0.kind.rawValue } #expect(result == ContextDescriptorProtocolBaseline.structTest.subscriptKindRawValue) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorTests.swift index a64e5d332..9b3b5dd8a 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorTests.swift @@ -18,12 +18,8 @@ import SwiftSectionFixtureSupport /// offset of `Structs.StructTest` (the same path `ContextDescriptorWrapper.resolve` /// uses to dispatch on the `kind` byte). @Suite -final class ContextDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ContextDescriptor" - static var registeredTestMethodNames: Set { - ContextDescriptorBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ContextDescriptorTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Helper: read the bare `ContextDescriptor` header at the /// `Structs.StructTest` offset against both readers. private func loadStructTestContextDescriptors() throws -> (file: ContextDescriptor, image: ContextDescriptor) { @@ -36,10 +32,7 @@ final class ContextDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @Test func offset() async throws { let descriptors = try loadStructTestContextDescriptors() - let result = try acrossAllReaders( - file: { descriptors.file.offset }, - image: { descriptors.image.offset } - ) + let result = try acrossAllReaders(descriptors.file, descriptors.image) { $0.offset } #expect(result == ContextDescriptorBaseline.structTest.offset) } @@ -48,10 +41,7 @@ final class ContextDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, // Cross-reader equality on the only stable scalar field // (`flags.rawValue`); `parent` is a relative pointer whose value // varies by reader. - let flagsRaw = try acrossAllReaders( - file: { descriptors.file.layout.flags.rawValue }, - image: { descriptors.image.layout.flags.rawValue } - ) + let flagsRaw = try acrossAllReaders(descriptors.file, descriptors.image) { $0.layout.flags.rawValue } #expect(flagsRaw == ContextDescriptorBaseline.structTest.layoutFlagsRawValue) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorWrapperTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorWrapperTests.swift index 948c02350..3345df426 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorWrapperTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorWrapperTests.swift @@ -13,12 +13,8 @@ import SwiftSectionFixtureSupport /// accessor `false`, `hasTypeContextDescriptor: true`, etc. Broader kind /// coverage lives in the dedicated concrete-kind Suites in Tasks 7-11. @Suite -final class ContextDescriptorWrapperTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ContextDescriptorWrapper" - static var registeredTestMethodNames: Set { - ContextDescriptorWrapperBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ContextDescriptorWrapperTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Helper: build a `ContextDescriptorWrapper` of the /// `Structs.StructTest` descriptor against both readers. private func loadStructTestWrappers() throws -> (file: ContextDescriptorWrapper, image: ContextDescriptorWrapper) { @@ -31,46 +27,31 @@ final class ContextDescriptorWrapperTests: MachOSwiftSectionFixtureTests, Fixtur @Test func protocolDescriptor() async throws { let wrappers = try loadStructTestWrappers() - let presence = try acrossAllReaders( - file: { wrappers.file.protocolDescriptor != nil }, - image: { wrappers.image.protocolDescriptor != nil } - ) + let presence = try acrossAllReaders(wrappers.file, wrappers.image) { $0.protocolDescriptor != nil } #expect(presence == ContextDescriptorWrapperBaseline.structTest.hasProtocolDescriptor) } @Test func extensionContextDescriptor() async throws { let wrappers = try loadStructTestWrappers() - let presence = try acrossAllReaders( - file: { wrappers.file.extensionContextDescriptor != nil }, - image: { wrappers.image.extensionContextDescriptor != nil } - ) + let presence = try acrossAllReaders(wrappers.file, wrappers.image) { $0.extensionContextDescriptor != nil } #expect(presence == ContextDescriptorWrapperBaseline.structTest.hasExtensionContextDescriptor) } @Test func opaqueTypeDescriptor() async throws { let wrappers = try loadStructTestWrappers() - let presence = try acrossAllReaders( - file: { wrappers.file.opaqueTypeDescriptor != nil }, - image: { wrappers.image.opaqueTypeDescriptor != nil } - ) + let presence = try acrossAllReaders(wrappers.file, wrappers.image) { $0.opaqueTypeDescriptor != nil } #expect(presence == ContextDescriptorWrapperBaseline.structTest.hasOpaqueTypeDescriptor) } @Test func moduleContextDescriptor() async throws { let wrappers = try loadStructTestWrappers() - let presence = try acrossAllReaders( - file: { wrappers.file.moduleContextDescriptor != nil }, - image: { wrappers.image.moduleContextDescriptor != nil } - ) + let presence = try acrossAllReaders(wrappers.file, wrappers.image) { $0.moduleContextDescriptor != nil } #expect(presence == ContextDescriptorWrapperBaseline.structTest.hasModuleContextDescriptor) } @Test func anonymousContextDescriptor() async throws { let wrappers = try loadStructTestWrappers() - let presence = try acrossAllReaders( - file: { wrappers.file.anonymousContextDescriptor != nil }, - image: { wrappers.image.anonymousContextDescriptor != nil } - ) + let presence = try acrossAllReaders(wrappers.file, wrappers.image) { $0.anonymousContextDescriptor != nil } #expect(presence == ContextDescriptorWrapperBaseline.structTest.hasAnonymousContextDescriptor) } @@ -78,82 +59,55 @@ final class ContextDescriptorWrapperTests: MachOSwiftSectionFixtureTests, Fixtur @Test func isType() async throws { let wrappers = try loadStructTestWrappers() - let result = try acrossAllReaders( - file: { wrappers.file.isType }, - image: { wrappers.image.isType } - ) + let result = try acrossAllReaders(wrappers.file, wrappers.image) { $0.isType } #expect(result == ContextDescriptorWrapperBaseline.structTest.isType) } @Test func isEnum() async throws { let wrappers = try loadStructTestWrappers() - let result = try acrossAllReaders( - file: { wrappers.file.isEnum }, - image: { wrappers.image.isEnum } - ) + let result = try acrossAllReaders(wrappers.file, wrappers.image) { $0.isEnum } #expect(result == ContextDescriptorWrapperBaseline.structTest.isEnum) } @Test func isStruct() async throws { let wrappers = try loadStructTestWrappers() - let result = try acrossAllReaders( - file: { wrappers.file.isStruct }, - image: { wrappers.image.isStruct } - ) + let result = try acrossAllReaders(wrappers.file, wrappers.image) { $0.isStruct } #expect(result == ContextDescriptorWrapperBaseline.structTest.isStruct) } @Test func isClass() async throws { let wrappers = try loadStructTestWrappers() - let result = try acrossAllReaders( - file: { wrappers.file.isClass }, - image: { wrappers.image.isClass } - ) + let result = try acrossAllReaders(wrappers.file, wrappers.image) { $0.isClass } #expect(result == ContextDescriptorWrapperBaseline.structTest.isClass) } @Test func isProtocol() async throws { let wrappers = try loadStructTestWrappers() - let result = try acrossAllReaders( - file: { wrappers.file.isProtocol }, - image: { wrappers.image.isProtocol } - ) + let result = try acrossAllReaders(wrappers.file, wrappers.image) { $0.isProtocol } #expect(result == ContextDescriptorWrapperBaseline.structTest.isProtocol) } @Test func isAnonymous() async throws { let wrappers = try loadStructTestWrappers() - let result = try acrossAllReaders( - file: { wrappers.file.isAnonymous }, - image: { wrappers.image.isAnonymous } - ) + let result = try acrossAllReaders(wrappers.file, wrappers.image) { $0.isAnonymous } #expect(result == ContextDescriptorWrapperBaseline.structTest.isAnonymous) } @Test func isExtension() async throws { let wrappers = try loadStructTestWrappers() - let result = try acrossAllReaders( - file: { wrappers.file.isExtension }, - image: { wrappers.image.isExtension } - ) + let result = try acrossAllReaders(wrappers.file, wrappers.image) { $0.isExtension } #expect(result == ContextDescriptorWrapperBaseline.structTest.isExtension) } @Test func isModule() async throws { let wrappers = try loadStructTestWrappers() - let result = try acrossAllReaders( - file: { wrappers.file.isModule }, - image: { wrappers.image.isModule } - ) + let result = try acrossAllReaders(wrappers.file, wrappers.image) { $0.isModule } #expect(result == ContextDescriptorWrapperBaseline.structTest.isModule) } @Test func isOpaqueType() async throws { let wrappers = try loadStructTestWrappers() - let result = try acrossAllReaders( - file: { wrappers.file.isOpaqueType }, - image: { wrappers.image.isOpaqueType } - ) + let result = try acrossAllReaders(wrappers.file, wrappers.image) { $0.isOpaqueType } #expect(result == ContextDescriptorWrapperBaseline.structTest.isOpaqueType) } @@ -163,37 +117,25 @@ final class ContextDescriptorWrapperTests: MachOSwiftSectionFixtureTests, Fixtur let wrappers = try loadStructTestWrappers() // `contextDescriptor` returns `any ContextDescriptorProtocol`; the // `offset` is the cross-reader-stable scalar. - let result = try acrossAllReaders( - file: { wrappers.file.contextDescriptor.offset }, - image: { wrappers.image.contextDescriptor.offset } - ) + let result = try acrossAllReaders(wrappers.file, wrappers.image) { $0.contextDescriptor.offset } #expect(result == ContextDescriptorWrapperBaseline.structTest.descriptorOffset) } @Test func namedContextDescriptor() async throws { let wrappers = try loadStructTestWrappers() - let presence = try acrossAllReaders( - file: { wrappers.file.namedContextDescriptor != nil }, - image: { wrappers.image.namedContextDescriptor != nil } - ) + let presence = try acrossAllReaders(wrappers.file, wrappers.image) { $0.namedContextDescriptor != nil } #expect(presence == ContextDescriptorWrapperBaseline.structTest.hasNamedContextDescriptor) } @Test func typeContextDescriptor() async throws { let wrappers = try loadStructTestWrappers() - let presence = try acrossAllReaders( - file: { wrappers.file.typeContextDescriptor != nil }, - image: { wrappers.image.typeContextDescriptor != nil } - ) + let presence = try acrossAllReaders(wrappers.file, wrappers.image) { $0.typeContextDescriptor != nil } #expect(presence == ContextDescriptorWrapperBaseline.structTest.hasTypeContextDescriptor) } @Test func typeContextDescriptorWrapper() async throws { let wrappers = try loadStructTestWrappers() - let presence = try acrossAllReaders( - file: { wrappers.file.typeContextDescriptorWrapper != nil }, - image: { wrappers.image.typeContextDescriptorWrapper != nil } - ) + let presence = try acrossAllReaders(wrappers.file, wrappers.image) { $0.typeContextDescriptorWrapper != nil } #expect(presence == ContextDescriptorWrapperBaseline.structTest.hasTypeContextDescriptorWrapper) } @@ -201,19 +143,17 @@ final class ContextDescriptorWrapperTests: MachOSwiftSectionFixtureTests, Fixtur @Test func parent() async throws { let wrappers = try loadStructTestWrappers() - let presence = try acrossAllContexts( - file: { (try wrappers.file.parent(in: fileContext)) != nil }, - image: { (try wrappers.image.parent(in: imageContext)) != nil } - ) + let presence = try acrossAllContexts(wrappers.file, wrappers.image) { wrapper, context in + (try wrapper.parent(in: context)) != nil + } #expect(presence == ContextDescriptorWrapperBaseline.structTest.hasParent) } @Test func genericContext() async throws { let wrappers = try loadStructTestWrappers() - let presence = try acrossAllContexts( - file: { (try wrappers.file.genericContext(in: fileContext)) != nil }, - image: { (try wrappers.image.genericContext(in: imageContext)) != nil } - ) + let presence = try acrossAllContexts(wrappers.file, wrappers.image) { wrapper, context in + (try wrapper.genericContext(in: context)) != nil + } #expect(presence == ContextDescriptorWrapperBaseline.structTest.hasGenericContext) } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextProtocolTests.swift index 527f81e43..30b5ea1ab 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextProtocolTests.swift @@ -15,22 +15,17 @@ import SwiftSectionFixtureSupport /// We exercise the protocol-extension method through a `Struct` context /// built off `Structs.StructTest`'s descriptor. @Suite -final class ContextProtocolTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ContextProtocol" - static var registeredTestMethodNames: Set { - ContextProtocolBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ContextProtocolTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func parent() async throws { let fileDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOImage) let fileContextWrapper = try Struct(descriptor: fileDescriptor, in: fileContext) let imageContextWrapper = try Struct(descriptor: imageDescriptor, in: imageContext) - let presence = try acrossAllContexts( - file: { (try fileContextWrapper.parent(in: fileContext)) != nil }, - image: { (try imageContextWrapper.parent(in: imageContext)) != nil } - ) + let presence = try acrossAllContexts(fileContextWrapper, imageContextWrapper) { contextWrapper, context in + (try contextWrapper.parent(in: context)) != nil + } #expect(presence == ContextProtocolBaseline.structTest.hasParent) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextWrapperTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextWrapperTests.swift index 5d4f7ce9f..797fca674 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextWrapperTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextWrapperTests.swift @@ -16,12 +16,8 @@ import SwiftSectionFixtureSupport /// `ContextWrapper.forContextDescriptorWrapper` to produce a /// `.type(.struct(...))` wrapper. @Suite -final class ContextWrapperTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ContextWrapper" - static var registeredTestMethodNames: Set { - ContextWrapperBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ContextWrapperTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Helper: build a `ContextWrapper` of the `Structs.StructTest` /// descriptor against both readers via /// `forContextDescriptorWrapper(_:in:)`. @@ -37,10 +33,7 @@ final class ContextWrapperTests: MachOSwiftSectionFixtureTests, FixtureSuite, @u let wrappers = try loadStructTestWrappers() // `context` projects to `any ContextProtocol`; the descriptor's // `offset` is the cross-reader-stable scalar. - let result = try acrossAllReaders( - file: { wrappers.file.context.descriptor.offset }, - image: { wrappers.image.context.descriptor.offset } - ) + let result = try acrossAllReaders(wrappers.file, wrappers.image) { $0.context.descriptor.offset } #expect(result == ContextWrapperBaseline.structTest.descriptorOffset) } @@ -61,10 +54,9 @@ final class ContextWrapperTests: MachOSwiftSectionFixtureTests, FixtureSuite, @u @Test func parent() async throws { let wrappers = try loadStructTestWrappers() - let presence = try acrossAllContexts( - file: { (try wrappers.file.parent(in: fileContext)) != nil }, - image: { (try wrappers.image.parent(in: imageContext)) != nil } - ) + let presence = try acrossAllContexts(wrappers.file, wrappers.image) { wrapper, context in + (try wrapper.parent(in: context)) != nil + } #expect(presence == ContextWrapperBaseline.structTest.hasParent) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/NamedContextDescriptorProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/NamedContextDescriptorProtocolTests.swift index 25ec4eb26..a4efb4ece 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/NamedContextDescriptorProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/NamedContextDescriptorProtocolTests.swift @@ -16,20 +16,15 @@ import SwiftSectionFixtureSupport /// `StructDescriptor`. The MangledName payload is a deep ABI tree we don't /// embed as a literal; we assert its presence and the stable `name` string. @Suite -final class NamedContextDescriptorProtocolTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "NamedContextDescriptorProtocol" - static var registeredTestMethodNames: Set { - NamedContextDescriptorProtocolBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class NamedContextDescriptorProtocolTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func name() async throws { let fileDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOImage) - let result = try acrossAllContexts( - file: { try fileDescriptor.name(in: fileContext) }, - image: { try imageDescriptor.name(in: imageContext) } - ) + let result = try acrossAllContexts(fileDescriptor, imageDescriptor) { descriptor, context in + try descriptor.name(in: context) + } #expect(result == NamedContextDescriptorProtocolBaseline.structTest.name) } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/DispatchClass/DispatchClassMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/DispatchClass/DispatchClassMetadataTests.swift index 52fa77c5d..bd26ac7e6 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/DispatchClass/DispatchClassMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/DispatchClass/DispatchClassMetadataTests.swift @@ -26,12 +26,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class DispatchClassMetadataTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "DispatchClassMetadata" - static var registeredTestMethodNames: Set { - DispatchClassMetadataBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class DispatchClassMetadataTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Mangled symbol of the metadata accessor for /// `SymbolTestsCore.Classes.ClassTest`. Used by `fixtureMetadata(symbol:)` /// to obtain the runtime-allocated class metadata pointer. diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExistentialMetatypeMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExistentialMetatypeMetadataTests.swift index 87fa4fd6c..8206eaf9a 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExistentialMetatypeMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExistentialMetatypeMetadataTests.swift @@ -17,12 +17,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class ExistentialMetatypeMetadataTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ExistentialMetatypeMetadata" - static var registeredTestMethodNames: Set { - ExistentialMetatypeMetadataBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ExistentialMetatypeMetadataTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func layout() async throws { let resolved = try usingInProcessOnly { context in try ExistentialMetatypeMetadata.resolve(at: InProcessMetadataPicker.stdlibAnyMetatype, in: context) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExistentialTypeFlagsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExistentialTypeFlagsTests.swift index cd1b7d76e..3ae4187a3 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExistentialTypeFlagsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExistentialTypeFlagsTests.swift @@ -16,12 +16,8 @@ import SwiftSectionFixtureSupport /// - `AnyObject.self` flags (`0x0`) — anchor `classConstraint` (`.class`); /// `Any.self` reading `.any` is pinned by `FlagWordDecodingTests`. @Suite -final class ExistentialTypeFlagsTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ExistentialTypeFlags" - static var registeredTestMethodNames: Set { - ExistentialTypeFlagsBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ExistentialTypeFlagsTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test("init(rawValue:)") func initializer() async throws { let result = try usingInProcessOnly { context in let metadata = try ExistentialTypeMetadata.resolve(at: InProcessMetadataPicker.stdlibAnyExistential, in: context) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExistentialTypeMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExistentialTypeMetadataTests.swift index eab4bce0c..a25a0ada7 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExistentialTypeMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExistentialTypeMetadataTests.swift @@ -24,12 +24,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class ExistentialTypeMetadataTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ExistentialTypeMetadata" - static var registeredTestMethodNames: Set { - ExistentialTypeMetadataBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ExistentialTypeMetadataTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func layout() async throws { let resolved = try usingInProcessOnly { context in try ExistentialTypeMetadata.resolve(at: InProcessMetadataPicker.stdlibAnyExistential, in: context) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExtendedExistentialTypeMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExtendedExistentialTypeMetadataTests.swift index 23cd23a64..6f92547da 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExtendedExistentialTypeMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExtendedExistentialTypeMetadataTests.swift @@ -23,12 +23,8 @@ import SwiftSectionFixtureSupport /// at the language-runtime level. Tests guard the in-process metadata /// access with `if #available` rather than annotating the suite class. @Suite -final class ExtendedExistentialTypeMetadataTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ExtendedExistentialTypeMetadata" - static var registeredTestMethodNames: Set { - ExtendedExistentialTypeMetadataBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ExtendedExistentialTypeMetadataTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func layout() async throws { guard #available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) else { return } // Returning a struct directly as a tuple is not Equatable, so diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExtendedExistentialTypeShapeFlagsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExtendedExistentialTypeShapeFlagsTests.swift index 5a8d1fffe..56df87886 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExtendedExistentialTypeShapeFlagsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExtendedExistentialTypeShapeFlagsTests.swift @@ -16,12 +16,8 @@ import SwiftSectionFixtureSupport /// at the language-runtime level. Tests guard the in-process metadata /// access with `if #available` rather than annotating the suite class. @Suite -final class ExtendedExistentialTypeShapeFlagsTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ExtendedExistentialTypeShapeFlags" - static var registeredTestMethodNames: Set { - ExtendedExistentialTypeShapeFlagsBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ExtendedExistentialTypeShapeFlagsTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test("init(rawValue:)") func initializer() async throws { guard #available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) else { return } let result = try usingInProcessOnly { context in diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExtendedExistentialTypeShapeTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExtendedExistentialTypeShapeTests.swift index f4392031e..9d75e8bb7 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExtendedExistentialTypeShapeTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/ExtendedExistentialTypeShapeTests.swift @@ -23,12 +23,8 @@ import SwiftSectionFixtureSupport /// at the language-runtime level. Tests guard the in-process metadata /// access with `if #available` rather than annotating the suite class. @Suite -final class ExtendedExistentialTypeShapeTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ExtendedExistentialTypeShape" - static var registeredTestMethodNames: Set { - ExtendedExistentialTypeShapeBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ExtendedExistentialTypeShapeTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func layout() async throws { guard #available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) else { return } let flagsRaw = try usingInProcessOnly { context in diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/NonUniqueExtendedExistentialTypeShapeTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/NonUniqueExtendedExistentialTypeShapeTests.swift index 0551e479e..2163876c8 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/NonUniqueExtendedExistentialTypeShapeTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ExistentialType/NonUniqueExtendedExistentialTypeShapeTests.swift @@ -15,12 +15,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class NonUniqueExtendedExistentialTypeShapeTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "NonUniqueExtendedExistentialTypeShape" - static var registeredTestMethodNames: Set { - NonUniqueExtendedExistentialTypeShapeBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class NonUniqueExtendedExistentialTypeShapeTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func syntheticShape() -> NonUniqueExtendedExistentialTypeShape { NonUniqueExtendedExistentialTypeShape( layout: .init( diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Extension/ExtensionContextDescriptorProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Extension/ExtensionContextDescriptorProtocolTests.swift index bdf7179e1..ed43c9f1b 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Extension/ExtensionContextDescriptorProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Extension/ExtensionContextDescriptorProtocolTests.swift @@ -13,12 +13,8 @@ import SwiftSectionFixtureSupport /// consistent results at runtime against the presence flag in the /// baseline. @Suite -final class ExtensionContextDescriptorProtocolTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ExtensionContextDescriptorProtocol" - static var registeredTestMethodNames: Set { - ExtensionContextDescriptorProtocolBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ExtensionContextDescriptorProtocolTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func extendedContext() async throws { let fileSubject = try BaselineFixturePicker.extension_first(in: machOFile) let imageSubject = try BaselineFixturePicker.extension_first(in: machOImage) @@ -27,10 +23,9 @@ final class ExtensionContextDescriptorProtocolTests: MachOSwiftSectionFixtureTes // mangled name. The MangledName tree itself is Hashable but we // record presence-only in the baseline for parity with the // wrapper Suite. - let presence = try acrossAllContexts( - file: { (try fileSubject.extendedContext(in: fileContext)) != nil }, - image: { (try imageSubject.extendedContext(in: imageContext)) != nil } - ) + let presence = try acrossAllContexts(fileSubject, imageSubject) { descriptor, context in + (try descriptor.extendedContext(in: context)) != nil + } #expect(presence == ExtensionContextDescriptorProtocolBaseline.firstExtension.hasExtendedContext) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Extension/ExtensionContextDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Extension/ExtensionContextDescriptorTests.swift index 154c6d7d7..c1c742dac 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Extension/ExtensionContextDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Extension/ExtensionContextDescriptorTests.swift @@ -14,20 +14,13 @@ import SwiftSectionFixtureSupport /// `PublicMemberScanner` and is covered by /// `ExtensionContextDescriptorProtocolTests`. @Suite -final class ExtensionContextDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ExtensionContextDescriptor" - static var registeredTestMethodNames: Set { - ExtensionContextDescriptorBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ExtensionContextDescriptorTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func offset() async throws { let fileSubject = try BaselineFixturePicker.extension_first(in: machOFile) let imageSubject = try BaselineFixturePicker.extension_first(in: machOImage) - let result = try acrossAllReaders( - file: { fileSubject.offset }, - image: { imageSubject.offset } - ) + let result = try acrossAllReaders(fileSubject, imageSubject) { $0.offset } #expect(result == ExtensionContextDescriptorBaseline.firstExtension.offset) } @@ -35,10 +28,7 @@ final class ExtensionContextDescriptorTests: MachOSwiftSectionFixtureTests, Fixt let fileSubject = try BaselineFixturePicker.extension_first(in: machOFile) let imageSubject = try BaselineFixturePicker.extension_first(in: machOImage) - let flagsRaw = try acrossAllReaders( - file: { fileSubject.layout.flags.rawValue }, - image: { imageSubject.layout.flags.rawValue } - ) + let flagsRaw = try acrossAllReaders(fileSubject, imageSubject) { $0.layout.flags.rawValue } #expect(flagsRaw == ExtensionContextDescriptorBaseline.firstExtension.layoutFlagsRawValue) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Extension/ExtensionContextTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Extension/ExtensionContextTests.swift index cee55c329..661dbd06c 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Extension/ExtensionContextTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Extension/ExtensionContextTests.swift @@ -13,12 +13,8 @@ import SwiftSectionFixtureSupport /// `__swift5_types`/`__swift5_types2` records. The optional `genericContext` /// and `extendedContextMangledName` ivars use the presence-flag pattern. @Suite -final class ExtensionContextTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ExtensionContext" - static var registeredTestMethodNames: Set { - ExtensionContextBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ExtensionContextTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Helper: instantiate the `ExtensionContext` wrapper for the /// fixture's first extension descriptor against both readers. private func loadFirstExtensionContexts() throws -> (file: ExtensionContext, image: ExtensionContext) { @@ -54,28 +50,19 @@ final class ExtensionContextTests: MachOSwiftSectionFixtureTests, FixtureSuite, @Test func descriptor() async throws { let contexts = try loadFirstExtensionContexts() - let descriptorOffsets = try acrossAllReaders( - file: { contexts.file.descriptor.offset }, - image: { contexts.image.descriptor.offset } - ) + let descriptorOffsets = try acrossAllReaders(contexts.file, contexts.image) { $0.descriptor.offset } #expect(descriptorOffsets == ExtensionContextBaseline.firstExtension.descriptorOffset) } @Test func genericContext() async throws { let contexts = try loadFirstExtensionContexts() - let presence = try acrossAllReaders( - file: { contexts.file.genericContext != nil }, - image: { contexts.image.genericContext != nil } - ) + let presence = try acrossAllReaders(contexts.file, contexts.image) { $0.genericContext != nil } #expect(presence == ExtensionContextBaseline.firstExtension.hasGenericContext) } @Test func extendedContextMangledName() async throws { let contexts = try loadFirstExtensionContexts() - let presence = try acrossAllReaders( - file: { contexts.file.extendedContextMangledName != nil }, - image: { contexts.image.extendedContextMangledName != nil } - ) + let presence = try acrossAllReaders(contexts.file, contexts.image) { $0.extendedContextMangledName != nil } #expect(presence == ExtensionContextBaseline.firstExtension.hasExtendedContextMangledName) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/FieldDescriptor/FieldDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/FieldDescriptor/FieldDescriptorTests.swift index 87ca2c077..e89ca041b 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/FieldDescriptor/FieldDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/FieldDescriptor/FieldDescriptorTests.swift @@ -20,12 +20,8 @@ import SwiftSectionFixtureSupport /// - `structTest` — zero records (StructTest declares only a computed /// property, no stored fields) @Suite -final class FieldDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "FieldDescriptor" - static var registeredTestMethodNames: Set { - FieldDescriptorBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class FieldDescriptorTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { // MARK: - Helpers private func loadGenericStructFieldDescriptors() throws -> (file: FieldDescriptor, image: FieldDescriptor) { @@ -48,10 +44,7 @@ final class FieldDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @ @Test func offset() async throws { let descriptors = try loadGenericStructFieldDescriptors() - let result = try acrossAllReaders( - file: { descriptors.file.offset }, - image: { descriptors.image.offset } - ) + let result = try acrossAllReaders(descriptors.file, descriptors.image) { $0.offset } #expect(result == FieldDescriptorBaseline.genericStructNonRequirement.offset) } @@ -59,22 +52,13 @@ final class FieldDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @ // Cross-reader equality on the per-field layout values // (numFields and fieldRecordSize, kind via raw value). let descriptors = try loadGenericStructFieldDescriptors() - let numFields = try acrossAllReaders( - file: { Int(descriptors.file.layout.numFields) }, - image: { Int(descriptors.image.layout.numFields) } - ) + let numFields = try acrossAllReaders(descriptors.file, descriptors.image) { Int($0.layout.numFields) } #expect(numFields == FieldDescriptorBaseline.genericStructNonRequirement.layoutNumFields) - let fieldRecordSize = try acrossAllReaders( - file: { Int(descriptors.file.layout.fieldRecordSize) }, - image: { Int(descriptors.image.layout.fieldRecordSize) } - ) + let fieldRecordSize = try acrossAllReaders(descriptors.file, descriptors.image) { Int($0.layout.fieldRecordSize) } #expect(fieldRecordSize == FieldDescriptorBaseline.genericStructNonRequirement.layoutFieldRecordSize) - let kindRaw = try acrossAllReaders( - file: { descriptors.file.layout.kind }, - image: { descriptors.image.layout.kind } - ) + let kindRaw = try acrossAllReaders(descriptors.file, descriptors.image) { $0.layout.kind } #expect(kindRaw == FieldDescriptorBaseline.genericStructNonRequirement.kindRawValue) } @@ -85,17 +69,11 @@ final class FieldDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @ /// whole section is the real assertion here. @Test func actualSize() async throws { let genericDescriptors = try loadGenericStructFieldDescriptors() - let genericSize = try acrossAllReaders( - file: { genericDescriptors.file.actualSize }, - image: { genericDescriptors.image.actualSize } - ) + let genericSize = try acrossAllReaders(genericDescriptors.file, genericDescriptors.image) { $0.actualSize } #expect(genericSize == FieldDescriptorBaseline.genericStructNonRequirement.actualSize) let structTestDescriptors = try loadStructTestFieldDescriptors() - let structTestSize = try acrossAllReaders( - file: { structTestDescriptors.file.actualSize }, - image: { structTestDescriptors.image.actualSize } - ) + let structTestSize = try acrossAllReaders(structTestDescriptors.file, structTestDescriptors.image) { $0.actualSize } #expect(structTestSize == FieldDescriptorBaseline.structTest.actualSize) #expect(structTestSize == MemoryLayout.size) @@ -112,10 +90,7 @@ final class FieldDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @ @Test func kind() async throws { let descriptors = try loadGenericStructFieldDescriptors() - let result = try acrossAllReaders( - file: { descriptors.file.kind.rawValue }, - image: { descriptors.image.kind.rawValue } - ) + let result = try acrossAllReaders(descriptors.file, descriptors.image) { $0.kind.rawValue } #expect(result == FieldDescriptorBaseline.genericStructNonRequirement.kindRawValue) } @@ -123,28 +98,25 @@ final class FieldDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @ @Test func mangledTypeName() async throws { let descriptors = try loadGenericStructFieldDescriptors() - let presence = try acrossAllContexts( - file: { (try? descriptors.file.mangledTypeName(in: fileContext)) != nil }, - image: { (try? descriptors.image.mangledTypeName(in: imageContext)) != nil } - ) + let presence = try acrossAllContexts(descriptors.file, descriptors.image) { descriptor, context in + (try? descriptor.mangledTypeName(in: context)) != nil + } #expect(presence == FieldDescriptorBaseline.genericStructNonRequirement.hasMangledTypeName) } @Test func records() async throws { // Fixture with non-empty records: GenericStructNonRequirement (3 fields). let genericDescriptors = try loadGenericStructFieldDescriptors() - let genericCount = try acrossAllContexts( - file: { try genericDescriptors.file.records(in: fileContext).count }, - image: { try genericDescriptors.image.records(in: imageContext).count } - ) + let genericCount = try acrossAllContexts(genericDescriptors.file, genericDescriptors.image) { descriptor, context in + try descriptor.records(in: context).count + } #expect(genericCount == FieldDescriptorBaseline.genericStructNonRequirement.recordsCount) // Fixture with empty records: StructTest (0 fields, only a computed body). let structTestDescriptors = try loadStructTestFieldDescriptors() - let structTestCount = try acrossAllContexts( - file: { try structTestDescriptors.file.records(in: fileContext).count }, - image: { try structTestDescriptors.image.records(in: imageContext).count } - ) + let structTestCount = try acrossAllContexts(structTestDescriptors.file, structTestDescriptors.image) { descriptor, context in + try descriptor.records(in: context).count + } #expect(structTestCount == FieldDescriptorBaseline.structTest.recordsCount) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/FieldRecord/FieldRecordFlagsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/FieldRecord/FieldRecordFlagsTests.swift index 3dc26ed71..c7656d243 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/FieldRecord/FieldRecordFlagsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/FieldRecord/FieldRecordFlagsTests.swift @@ -11,12 +11,8 @@ import SwiftSectionFixtureSupport /// exercises each membership predicate against synthetic raw values /// embedded in the baseline. @Suite -final class FieldRecordFlagsTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "FieldRecordFlags" - static var registeredTestMethodNames: Set { - FieldRecordFlagsBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class FieldRecordFlagsTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test("init(rawValue:)") func initializerWithRawValue() async throws { let flags = FieldRecordFlags(rawValue: FieldRecordFlagsBaseline.allBits.rawValue) #expect(flags.rawValue == FieldRecordFlagsBaseline.allBits.rawValue) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/FieldRecord/FieldRecordTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/FieldRecord/FieldRecordTests.swift index aace65319..29b20a235 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/FieldRecord/FieldRecordTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/FieldRecord/FieldRecordTests.swift @@ -18,12 +18,8 @@ import SwiftSectionFixtureSupport /// the first two to exercise both a concrete-type field and a /// generic-parameter field. @Suite -final class FieldRecordTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "FieldRecord" - static var registeredTestMethodNames: Set { - FieldRecordBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class FieldRecordTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { // MARK: - Helpers private func loadRecords() throws -> (file: [FieldRecord], image: [FieldRecord]) { @@ -47,10 +43,7 @@ final class FieldRecordTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unch @Test func offset() async throws { let records = try loadFirstRecord() - let result = try acrossAllReaders( - file: { records.file.offset }, - image: { records.image.offset } - ) + let result = try acrossAllReaders(records.file, records.image) { $0.offset } #expect(result == FieldRecordBaseline.firstRecord.offset) } @@ -59,10 +52,7 @@ final class FieldRecordTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unch // records all carry flags == 0x2 — `isVariadic` is set on stored // properties). let records = try loadFirstRecord() - let flagsRaw = try acrossAllReaders( - file: { records.file.layout.flags.rawValue }, - image: { records.image.layout.flags.rawValue } - ) + let flagsRaw = try acrossAllReaders(records.file, records.image) { $0.layout.flags.rawValue } #expect(flagsRaw == FieldRecordBaseline.firstRecord.layoutFlagsRawValue) } @@ -71,29 +61,24 @@ final class FieldRecordTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unch @Test func fieldName() async throws { // First record: field1. let firstRecords = try loadFirstRecord() - let firstName = try acrossAllContexts( - file: { try firstRecords.file.fieldName(in: fileContext) }, - image: { try firstRecords.image.fieldName(in: imageContext) } - ) + let firstName = try acrossAllContexts(firstRecords.file, firstRecords.image) { record, context in + try record.fieldName(in: context) + } #expect(firstName == FieldRecordBaseline.firstRecord.fieldName) // Second record: field2. let allRecords = try loadRecords() let fileSecond = try required(allRecords.file.dropFirst().first) let imageSecond = try required(allRecords.image.dropFirst().first) - let secondName = try acrossAllContexts( - file: { try fileSecond.fieldName(in: fileContext) }, - image: { try imageSecond.fieldName(in: imageContext) } - ) + let secondName = try acrossAllContexts(fileSecond, imageSecond) { record, context in try record.fieldName(in: context) } #expect(secondName == FieldRecordBaseline.secondRecord.fieldName) } @Test func mangledTypeName() async throws { let records = try loadFirstRecord() - let presence = try acrossAllContexts( - file: { (try? records.file.mangledTypeName(in: fileContext)) != nil }, - image: { (try? records.image.mangledTypeName(in: imageContext)) != nil } - ) + let presence = try acrossAllContexts(records.file, records.image) { record, context in + (try? record.mangledTypeName(in: context)) != nil + } #expect(presence == FieldRecordBaseline.firstRecord.hasMangledTypeName) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ForeignType/ForeignClassMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ForeignType/ForeignClassMetadataTests.swift index 4c37c8e7c..c13447218 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ForeignType/ForeignClassMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ForeignType/ForeignClassMetadataTests.swift @@ -27,12 +27,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class ForeignClassMetadataTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ForeignClassMetadata" - static var registeredTestMethodNames: Set { - ForeignClassMetadataBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ForeignClassMetadataTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func layout() async throws { let kindRaw = try usingInProcessOnly { context in let metadata = try ForeignClassMetadata.resolve( diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ForeignType/ForeignReferenceTypeMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ForeignType/ForeignReferenceTypeMetadataTests.swift index a7109dea3..ba81cdf6f 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ForeignType/ForeignReferenceTypeMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ForeignType/ForeignReferenceTypeMetadataTests.swift @@ -15,12 +15,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class ForeignReferenceTypeMetadataTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ForeignReferenceTypeMetadata" - static var registeredTestMethodNames: Set { - ForeignReferenceTypeMetadataBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ForeignReferenceTypeMetadataTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func syntheticForeignReference() -> ForeignReferenceTypeMetadata { ForeignReferenceTypeMetadata( layout: .init( diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Function/FunctionTypeFlagsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Function/FunctionTypeFlagsTests.swift index 07ff7dfbd..93aefd1a7 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Function/FunctionTypeFlagsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Function/FunctionTypeFlagsTests.swift @@ -14,12 +14,8 @@ import SwiftSectionFixtureSupport /// `isThrowing`, etc.) are pure raw-value bit decoders and are tracked /// via the sentinel allowlist (`pureDataUtilityEntries`). @Suite -final class FunctionTypeFlagsTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "FunctionTypeFlags" - static var registeredTestMethodNames: Set { - FunctionTypeFlagsBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class FunctionTypeFlagsTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func numberOfParameters() async throws { let result = try usingInProcessOnly { context in try FunctionTypeMetadata.resolve(at: InProcessMetadataPicker.stdlibFunctionIntToVoid, in: context) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Function/FunctionTypeMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Function/FunctionTypeMetadataTests.swift index 02278d74a..3ac51269e 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Function/FunctionTypeMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Function/FunctionTypeMetadataTests.swift @@ -20,12 +20,8 @@ import SwiftSectionFixtureSupport /// assertions strong: a mis-computed offset by even one word lands on /// something else entirely. @Suite -final class FunctionTypeMetadataTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "FunctionTypeMetadata" - static var registeredTestMethodNames: Set { - FunctionTypeMetadataBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class FunctionTypeMetadataTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private struct Carrier { let label: String let pointer: UnsafeRawPointer diff --git a/Tests/MachOSwiftSectionTests/Fixtures/FunctionPointer/AsyncFunctionPointerTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/FunctionPointer/AsyncFunctionPointerTests.swift index 3ece8a418..081d11893 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/FunctionPointer/AsyncFunctionPointerTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/FunctionPointer/AsyncFunctionPointerTests.swift @@ -13,12 +13,8 @@ import SwiftSectionFixtureSupport /// assertion runs across both readers, because everything the record exposes /// is either a raw word or pure relative-pointer arithmetic. @Suite -final class AsyncFunctionPointerTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "AsyncFunctionPointer" - static var registeredTestMethodNames: Set { - AsyncFunctionPointerBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class AsyncFunctionPointerTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private struct Carrier { let label: String let file: AsyncFunctionPointer @@ -53,26 +49,17 @@ final class AsyncFunctionPointerTests: MachOSwiftSectionFixtureTests, FixtureSui @Test func offset() async throws { for carrier in try allCarriers() { - let result = try acrossAllReaders( - file: { carrier.file.offset }, - image: { carrier.image.offset } - ) + let result = try acrossAllReaders(carrier.file, carrier.image) { $0.offset } #expect(result == carrier.expected.offset, "\(carrier.label)") } } @Test func layout() async throws { for carrier in try allCarriers() { - let relativeOffset = try acrossAllReaders( - file: { carrier.file.layout.function.relativeOffset }, - image: { carrier.image.layout.function.relativeOffset } - ) + let relativeOffset = try acrossAllReaders(carrier.file, carrier.image) { $0.layout.function.relativeOffset } #expect(Int(relativeOffset) == carrier.expected.functionOffset.map { $0 - carrier.expected.offset }, "\(carrier.label)") - let contextSize = try acrossAllReaders( - file: { carrier.file.layout.expectedContextSize }, - image: { carrier.image.layout.expectedContextSize } - ) + let contextSize = try acrossAllReaders(carrier.file, carrier.image) { $0.layout.expectedContextSize } #expect(contextSize == carrier.expected.expectedContextSize, "\(carrier.label)") } // The whole record is two words; a Swift struct that grew padding @@ -82,10 +69,7 @@ final class AsyncFunctionPointerTests: MachOSwiftSectionFixtureTests, FixtureSui // Resolving the function pointer is pure arithmetic, so it is // identical across readers and pinned as a literal. for carrier in try allCarriers() { - let functionOffset = try acrossAllReaders( - file: { carrier.file.resolvedDirectOffset(from: \.function) }, - image: { carrier.image.resolvedDirectOffset(from: \.function) } - ) + let functionOffset = try acrossAllReaders(carrier.file, carrier.image) { $0.resolvedDirectOffset(from: \.function) } #expect(functionOffset == carrier.expected.functionOffset, "\(carrier.label)") // The record never points at itself: the whole reason it exists // is that it is NOT the entry point. diff --git a/Tests/MachOSwiftSectionTests/Fixtures/FunctionPointer/CoroFunctionPointerTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/FunctionPointer/CoroFunctionPointerTests.swift index 23aeeeca0..975f5c7b9 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/FunctionPointer/CoroFunctionPointerTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/FunctionPointer/CoroFunctionPointerTests.swift @@ -34,17 +34,6 @@ final class CoroFunctionPointerTests: FixtureSuite, @unchecked Sendable { // MARK: - Fixture - private enum FixtureWorkingDirectoryCleanup { - nonisolated(unsafe) static var directories: [URL] = [] - static let registration: Void = { - atexit { - for directory in FixtureWorkingDirectoryCleanup.directories { - try? FileManager.default.removeItem(at: directory) - } - } - }() - } - /// `Anchor` keeps a `__DATA` segment in the dylib (see AGENTS.md, /// "On-the-fly-compiled fixture dylibs need a class"). `Holder.first` is /// the payload: a `_read` accessor, which under CoroutineAccessors lowers @@ -66,71 +55,40 @@ final class CoroFunctionPointerTests: FixtureSuite, @unchecked Sendable { } """ - private struct FixtureCompilationError: Swift.Error, CustomStringConvertible { - let diagnostics: String - var description: String { "coro-function-pointer fixture compilation failed:\n\(diagnostics)" } + /// Both compiles failed; carries what each one reported. + private struct BothCompilationsFailedError: Swift.Error, CustomStringConvertible { + let withFeatureFlagFailure: any Swift.Error + let withoutFeatureFlagFailure: any Swift.Error + var description: String { "coro-function-pointer fixture compilation failed:\n\(withFeatureFlagFailure)\n\(withoutFeatureFlagFailure)" } } - private static let fixtureCompilationResult: Result = { - Result { - let workingDirectory = FileManager.default.temporaryDirectory - .appendingPathComponent("CoroFunctionPointerFixture-\(UUID().uuidString)") - try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) - _ = FixtureWorkingDirectoryCleanup.registration - FixtureWorkingDirectoryCleanup.directories.append(workingDirectory) - - let sourceURL = workingDirectory.appendingPathComponent("CoroFunctionPointerFixture.swift") - let libraryURL = workingDirectory.appendingPathComponent("libCoroFunctionPointerFixture.dylib") - try fixtureSource.write(to: sourceURL, atomically: true, encoding: .utf8) - - // The feature is still experimental, so it must be requested by - // name; should it ever graduate, the flag becomes unknown and the - // compile fails, so fall back to building without it — the - // accessors lower to `yield_once_2` either way once it is on by - // default. `-enable-library-evolution` is what forces the - // accessors to be dispatched (and therefore emitted) at all. - var lastDiagnostics = "" - func compile(withCoroutineAccessorsFlag requestsFeature: Bool) throws -> Int32 { - let process = Process() - process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") - var arguments = [ - "swiftc", "-emit-library", - "-module-name", "CoroFunctionPointerFixture", - "-enable-library-evolution", - ] - if requestsFeature { - arguments += ["-enable-experimental-feature", "CoroutineAccessors"] - } - arguments += [sourceURL.path, "-o", libraryURL.path] - process.arguments = arguments - let standardErrorPipe = Pipe() - process.standardError = standardErrorPipe - try process.run() - // Drain BEFORE waitUntilExit — see LegacyDyldInfoBindTests. - lastDiagnostics = String(decoding: standardErrorPipe.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self) - process.waitUntilExit() - return process.terminationStatus - } - - if try compile(withCoroutineAccessorsFlag: true) != 0 { - let withFlagDiagnostics = lastDiagnostics - guard try compile(withCoroutineAccessorsFlag: false) == 0 else { - throw FixtureCompilationError(diagnostics: withFlagDiagnostics + lastDiagnostics) - } - } - return libraryURL + private func loadFixtureMachOFile() throws -> MachOFile { + // The feature is still experimental, so it must be requested by + // name; should it ever graduate, the flag becomes unknown and the + // compile fails, so fall back to building without it — the + // accessors lower to `yield_once_2` either way once it is on by + // default. `-enable-library-evolution` is what forces the + // accessors to be dispatched (and therefore emitted) at all. + func compile(withCoroutineAccessorsFlag requestsFeature: Bool) throws -> URL { + try FixtureCompiler.shared.dynamicLibrary( + named: "CoroFunctionPointerFixture", + language: .swift, + source: Self.fixtureSource, + arguments: ["-enable-library-evolution"] + (requestsFeature ? ["-enable-experimental-feature", "CoroutineAccessors"] : []) + ) } - }() - private func loadFixtureMachOFile() throws -> MachOFile { - let libraryURL = try Self.fixtureCompilationResult.get() - switch try MachOKit.loadFromFile(url: libraryURL) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") + let libraryURL: URL + do { + libraryURL = try compile(withCoroutineAccessorsFlag: true) + } catch let withFeatureFlagFailure { + do { + libraryURL = try compile(withCoroutineAccessorsFlag: false) + } catch let withoutFeatureFlagFailure { + throw BothCompilationsFailedError(withFeatureFlagFailure: withFeatureFlagFailure, withoutFeatureFlagFailure: withoutFeatureFlagFailure) + } } + return try HostSlice.machOFile(at: libraryURL) } /// The one `…Twc` record in the fixture, plus the file it came from. diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericContextDescriptorFlagsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericContextDescriptorFlagsTests.swift index 186e03d34..5538915e7 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericContextDescriptorFlagsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericContextDescriptorFlagsTests.swift @@ -13,12 +13,8 @@ import SwiftSectionFixtureSupport /// `init(rawValue:)` round-trip against synthetic raw values from the /// baseline. @Suite -final class GenericContextDescriptorFlagsTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "GenericContextDescriptorFlags" - static var registeredTestMethodNames: Set { - GenericContextDescriptorFlagsBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class GenericContextDescriptorFlagsTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test("init(rawValue:)") func initializerWithRawValue() async throws { let allFlags = GenericContextDescriptorFlags( rawValue: GenericContextDescriptorFlagsBaseline.all.rawValue diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericContextDescriptorHeaderTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericContextDescriptorHeaderTests.swift index 70419ae9e..e2a5dc4f6 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericContextDescriptorHeaderTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericContextDescriptorHeaderTests.swift @@ -14,12 +14,8 @@ import SwiftSectionFixtureSupport /// asserts cross-reader equality on `offset` and the four scalar layout /// fields (`numParams`, `numRequirements`, `numKeyArguments`, `flags`). @Suite -final class GenericContextDescriptorHeaderTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "GenericContextDescriptorHeader" - static var registeredTestMethodNames: Set { - GenericContextDescriptorHeaderBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class GenericContextDescriptorHeaderTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Helper: extract the `GenericContextDescriptorHeader` from the first /// generic extension context against both readers, mirroring the /// generator's pick logic. @@ -31,32 +27,17 @@ final class GenericContextDescriptorHeaderTests: MachOSwiftSectionFixtureTests, @Test func offset() async throws { let headers = try loadFirstExtensionGenericHeaders() - let result = try acrossAllReaders( - file: { headers.file.offset }, - image: { headers.image.offset } - ) + let result = try acrossAllReaders(headers.file, headers.image) { $0.offset } #expect(result == GenericContextDescriptorHeaderBaseline.firstExtensionGenericHeader.offset) } @Test func layout() async throws { let headers = try loadFirstExtensionGenericHeaders() - let numParams = try acrossAllReaders( - file: { headers.file.layout.numParams }, - image: { headers.image.layout.numParams } - ) - let numRequirements = try acrossAllReaders( - file: { headers.file.layout.numRequirements }, - image: { headers.image.layout.numRequirements } - ) - let numKeyArguments = try acrossAllReaders( - file: { headers.file.layout.numKeyArguments }, - image: { headers.image.layout.numKeyArguments } - ) - let flagsRawValue = try acrossAllReaders( - file: { headers.file.layout.flags.rawValue }, - image: { headers.image.layout.flags.rawValue } - ) + let numParams = try acrossAllReaders(headers.file, headers.image) { $0.layout.numParams } + let numRequirements = try acrossAllReaders(headers.file, headers.image) { $0.layout.numRequirements } + let numKeyArguments = try acrossAllReaders(headers.file, headers.image) { $0.layout.numKeyArguments } + let flagsRawValue = try acrossAllReaders(headers.file, headers.image) { $0.layout.flags.rawValue } #expect(numParams == GenericContextDescriptorHeaderBaseline.firstExtensionGenericHeader.layoutNumParams) #expect(numRequirements == GenericContextDescriptorHeaderBaseline.firstExtensionGenericHeader.layoutNumRequirements) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericContextTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericContextTests.swift index 6704677d1..d9ca9c8ae 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericContextTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericContextTests.swift @@ -27,12 +27,8 @@ import SwiftSectionFixtureSupport /// - `parameterPack` — typePackHeader/typePacks /// - `invertibleProtocol` — invertedProtocols requirement @Suite -final class GenericContextTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "TargetGenericContext" - static var registeredTestMethodNames: Set { - GenericContextBaseline.registeredTestMethodNames - } - +@FixtureSuite(testedTypeName: "TargetGenericContext") +final class GenericContextTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { // MARK: - Helpers private func loadContextsFromFile( @@ -106,28 +102,19 @@ final class GenericContextTests: MachOSwiftSectionFixtureTests, FixtureSuite, @u @Test func offset() async throws { let contexts = try layoutRequirementContexts() - let result = try acrossAllReaders( - file: { contexts.file.offset }, - image: { contexts.image.offset } - ) + let result = try acrossAllReaders(contexts.file, contexts.image) { $0.offset } #expect(result == GenericContextBaseline.layoutRequirement.offset) } @Test func size() async throws { let contexts = try layoutRequirementContexts() - let result = try acrossAllReaders( - file: { contexts.file.size }, - image: { contexts.image.size } - ) + let result = try acrossAllReaders(contexts.file, contexts.image) { $0.size } #expect(result == GenericContextBaseline.layoutRequirement.size) } @Test func depth() async throws { let contexts = try layoutRequirementContexts() - let result = try acrossAllReaders( - file: { contexts.file.depth }, - image: { contexts.image.depth } - ) + let result = try acrossAllReaders(contexts.file, contexts.image) { $0.depth } #expect(result == GenericContextBaseline.layoutRequirement.depth) } @@ -136,10 +123,7 @@ final class GenericContextTests: MachOSwiftSectionFixtureTests, FixtureSuite, @u // (i.e. the start of the generic-context payload). Cross-reader // equality is captured indirectly via the header's `numParams` ivar. let contexts = try layoutRequirementContexts() - let numParams = try acrossAllReaders( - file: { contexts.file.header.layout.numParams }, - image: { contexts.image.header.layout.numParams } - ) + let numParams = try acrossAllReaders(contexts.file, contexts.image) { $0.header.layout.numParams } #expect(Int(numParams) == GenericContextBaseline.layoutRequirement.parametersCount) } @@ -147,45 +131,30 @@ final class GenericContextTests: MachOSwiftSectionFixtureTests, FixtureSuite, @u @Test func parameters() async throws { let contexts = try layoutRequirementContexts() - let count = try acrossAllReaders( - file: { contexts.file.parameters.count }, - image: { contexts.image.parameters.count } - ) + let count = try acrossAllReaders(contexts.file, contexts.image) { $0.parameters.count } #expect(count == GenericContextBaseline.layoutRequirement.parametersCount) } @Test func requirements() async throws { let contexts = try layoutRequirementContexts() - let count = try acrossAllReaders( - file: { contexts.file.requirements.count }, - image: { contexts.image.requirements.count } - ) + let count = try acrossAllReaders(contexts.file, contexts.image) { $0.requirements.count } #expect(count == GenericContextBaseline.layoutRequirement.requirementsCount) } @Test func typePackHeader() async throws { // No type packs on layoutRequirement; presence true on parameterPack. let contexts = try layoutRequirementContexts() - let layoutPresence = try acrossAllReaders( - file: { contexts.file.typePackHeader != nil }, - image: { contexts.image.typePackHeader != nil } - ) + let layoutPresence = try acrossAllReaders(contexts.file, contexts.image) { $0.typePackHeader != nil } #expect(layoutPresence == GenericContextBaseline.layoutRequirement.hasTypePackHeader) let packContexts = try parameterPackContexts() - let packPresence = try acrossAllReaders( - file: { packContexts.file.typePackHeader != nil }, - image: { packContexts.image.typePackHeader != nil } - ) + let packPresence = try acrossAllReaders(packContexts.file, packContexts.image) { $0.typePackHeader != nil } #expect(packPresence == GenericContextBaseline.parameterPack.hasTypePackHeader) } @Test func typePacks() async throws { let packContexts = try parameterPackContexts() - let count = try acrossAllReaders( - file: { packContexts.file.typePacks.count }, - image: { packContexts.image.typePacks.count } - ) + let count = try acrossAllReaders(packContexts.file, packContexts.image) { $0.typePacks.count } #expect(count == GenericContextBaseline.parameterPack.typePacksCount) } @@ -194,19 +163,13 @@ final class GenericContextTests: MachOSwiftSectionFixtureTests, FixtureSuite, @u // parameters, so valueHeader is always nil. Check on the layout // fixture (a representative case). let contexts = try layoutRequirementContexts() - let presence = try acrossAllReaders( - file: { contexts.file.valueHeader != nil }, - image: { contexts.image.valueHeader != nil } - ) + let presence = try acrossAllReaders(contexts.file, contexts.image) { $0.valueHeader != nil } #expect(presence == GenericContextBaseline.layoutRequirement.hasValueHeader) } @Test func values() async throws { let contexts = try layoutRequirementContexts() - let count = try acrossAllReaders( - file: { contexts.file.values.count }, - image: { contexts.image.values.count } - ) + let count = try acrossAllReaders(contexts.file, contexts.image) { $0.values.count } #expect(count == GenericContextBaseline.layoutRequirement.valuesCount) } @@ -214,37 +177,25 @@ final class GenericContextTests: MachOSwiftSectionFixtureTests, FixtureSuite, @u @Test func parentParameters() async throws { let contexts = try layoutRequirementContexts() - let count = try acrossAllReaders( - file: { contexts.file.parentParameters.count }, - image: { contexts.image.parentParameters.count } - ) + let count = try acrossAllReaders(contexts.file, contexts.image) { $0.parentParameters.count } #expect(count == GenericContextBaseline.layoutRequirement.parentParametersCount) } @Test func parentRequirements() async throws { let contexts = try layoutRequirementContexts() - let count = try acrossAllReaders( - file: { contexts.file.parentRequirements.count }, - image: { contexts.image.parentRequirements.count } - ) + let count = try acrossAllReaders(contexts.file, contexts.image) { $0.parentRequirements.count } #expect(count == GenericContextBaseline.layoutRequirement.parentRequirementsCount) } @Test func parentTypePacks() async throws { let contexts = try layoutRequirementContexts() - let count = try acrossAllReaders( - file: { contexts.file.parentTypePacks.count }, - image: { contexts.image.parentTypePacks.count } - ) + let count = try acrossAllReaders(contexts.file, contexts.image) { $0.parentTypePacks.count } #expect(count == GenericContextBaseline.layoutRequirement.parentTypePacksCount) } @Test func parentValues() async throws { let contexts = try layoutRequirementContexts() - let count = try acrossAllReaders( - file: { contexts.file.parentValues.count }, - image: { contexts.image.parentValues.count } - ) + let count = try acrossAllReaders(contexts.file, contexts.image) { $0.parentValues.count } #expect(count == GenericContextBaseline.layoutRequirement.parentValuesCount) } @@ -258,28 +209,23 @@ final class GenericContextTests: MachOSwiftSectionFixtureTests, FixtureSuite, @u // requirement instead), so we check both fixtures register the // baseline-recorded presence. let invertible = try invertibleProtocolContexts() - let presence = try acrossAllReaders( - file: { invertible.file.conditionalInvertibleProtocolSet != nil }, - image: { invertible.image.conditionalInvertibleProtocolSet != nil } - ) + let presence = try acrossAllReaders(invertible.file, invertible.image) { $0.conditionalInvertibleProtocolSet != nil } #expect(presence == GenericContextBaseline.invertibleProtocol.hasConditionalInvertibleProtocolSet) } @Test func conditionalInvertibleProtocolsRequirementsCount() async throws { let invertible = try invertibleProtocolContexts() - let presence = try acrossAllReaders( - file: { invertible.file.conditionalInvertibleProtocolsRequirementsCount != nil }, - image: { invertible.image.conditionalInvertibleProtocolsRequirementsCount != nil } - ) + let presence = try acrossAllReaders(invertible.file, invertible.image) { genericContext in + genericContext.conditionalInvertibleProtocolsRequirementsCount != nil + } #expect(presence == GenericContextBaseline.invertibleProtocol.hasConditionalInvertibleProtocolsRequirementsCount) } @Test func conditionalInvertibleProtocolsRequirements() async throws { let invertible = try invertibleProtocolContexts() - let count = try acrossAllReaders( - file: { invertible.file.conditionalInvertibleProtocolsRequirements.count }, - image: { invertible.image.conditionalInvertibleProtocolsRequirements.count } - ) + let count = try acrossAllReaders(invertible.file, invertible.image) { genericContext in + genericContext.conditionalInvertibleProtocolsRequirements.count + } #expect(count == GenericContextBaseline.invertibleProtocol.conditionalInvertibleProtocolsRequirementsCount) } @@ -287,73 +233,49 @@ final class GenericContextTests: MachOSwiftSectionFixtureTests, FixtureSuite, @u @Test func currentParameters() async throws { let contexts = try layoutRequirementContexts() - let count = try acrossAllReaders( - file: { contexts.file.currentParameters.count }, - image: { contexts.image.currentParameters.count } - ) + let count = try acrossAllReaders(contexts.file, contexts.image) { $0.currentParameters.count } #expect(count == GenericContextBaseline.layoutRequirement.currentParametersCount) } @Test func currentRequirements() async throws { let contexts = try layoutRequirementContexts() - let count = try acrossAllReaders( - file: { contexts.file.currentRequirements.count }, - image: { contexts.image.currentRequirements.count } - ) + let count = try acrossAllReaders(contexts.file, contexts.image) { $0.currentRequirements.count } #expect(count == GenericContextBaseline.layoutRequirement.currentRequirementsCount) } @Test func currentTypePacks() async throws { let packContexts = try parameterPackContexts() - let count = try acrossAllReaders( - file: { packContexts.file.currentTypePacks.count }, - image: { packContexts.image.currentTypePacks.count } - ) + let count = try acrossAllReaders(packContexts.file, packContexts.image) { $0.currentTypePacks.count } #expect(count == GenericContextBaseline.parameterPack.currentTypePacksCount) } @Test func currentValues() async throws { let contexts = try layoutRequirementContexts() - let count = try acrossAllReaders( - file: { contexts.file.currentValues.count }, - image: { contexts.image.currentValues.count } - ) + let count = try acrossAllReaders(contexts.file, contexts.image) { $0.currentValues.count } #expect(count == GenericContextBaseline.layoutRequirement.currentValuesCount) } @Test func allParameters() async throws { let contexts = try layoutRequirementContexts() - let count = try acrossAllReaders( - file: { contexts.file.allParameters.count }, - image: { contexts.image.allParameters.count } - ) + let count = try acrossAllReaders(contexts.file, contexts.image) { $0.allParameters.count } #expect(count == GenericContextBaseline.layoutRequirement.allParametersCount) } @Test func allRequirements() async throws { let contexts = try layoutRequirementContexts() - let count = try acrossAllReaders( - file: { contexts.file.allRequirements.count }, - image: { contexts.image.allRequirements.count } - ) + let count = try acrossAllReaders(contexts.file, contexts.image) { $0.allRequirements.count } #expect(count == GenericContextBaseline.layoutRequirement.allRequirementsCount) } @Test func allTypePacks() async throws { let packContexts = try parameterPackContexts() - let count = try acrossAllReaders( - file: { packContexts.file.allTypePacks.count }, - image: { packContexts.image.allTypePacks.count } - ) + let count = try acrossAllReaders(packContexts.file, packContexts.image) { $0.allTypePacks.count } #expect(count == GenericContextBaseline.parameterPack.allTypePacksCount) } @Test func allValues() async throws { let contexts = try layoutRequirementContexts() - let count = try acrossAllReaders( - file: { contexts.file.allValues.count }, - image: { contexts.image.allValues.count } - ) + let count = try acrossAllReaders(contexts.file, contexts.image) { $0.allValues.count } #expect(count == GenericContextBaseline.layoutRequirement.allValuesCount) } @@ -363,10 +285,9 @@ final class GenericContextTests: MachOSwiftSectionFixtureTests, FixtureSuite, @u // Top-level type with no parent generic context: every requirement // is unique. Cross-reader equality on the count. let contexts = try layoutRequirementContexts() - let count = try acrossAllContexts( - file: { contexts.file.uniqueCurrentRequirements(in: fileContext).count }, - image: { contexts.image.uniqueCurrentRequirements(in: imageContext).count } - ) + let count = try acrossAllContexts(contexts.file, contexts.image) { genericContext, context in + genericContext.uniqueCurrentRequirements(in: context).count + } #expect(count == GenericContextBaseline.layoutRequirement.requirementsCount) } @@ -398,10 +319,7 @@ final class GenericContextTests: MachOSwiftSectionFixtureTests, FixtureSuite, @u @Test("parameters is cumulative across the parent chain (3-level fixture)") func nestedThreeLevelParametersIsCumulative() async throws { let contexts = try nestedThreeLevelContexts() - let count = try acrossAllReaders( - file: { contexts.file.parameters.count }, - image: { contexts.image.parameters.count } - ) + let count = try acrossAllReaders(contexts.file, contexts.image) { $0.parameters.count } // Outer + Middle + InnerMost cumulative = 3. // numParams in the binary header matches. #expect(count == 3) @@ -411,10 +329,7 @@ final class GenericContextTests: MachOSwiftSectionFixtureTests, FixtureSuite, @u @Test("requirements is cumulative across the parent chain (3-level fixture)") func nestedThreeLevelRequirementsIsCumulative() async throws { let contexts = try nestedThreeLevelContexts() - let count = try acrossAllReaders( - file: { contexts.file.requirements.count }, - image: { contexts.image.requirements.count } - ) + let count = try acrossAllReaders(contexts.file, contexts.image) { $0.requirements.count } // One protocol constraint per level: Outer:Hashable, Middle:Equatable, // InnerMost:Comparable. #expect(count == 3) @@ -423,10 +338,7 @@ final class GenericContextTests: MachOSwiftSectionFixtureTests, FixtureSuite, @u @Test("parentParameters stores cumulative counts per level — counter-example to a per-level-new interpretation") func nestedThreeLevelParentParametersAreCumulative() async throws { let contexts = try nestedThreeLevelContexts() - let parentCounts = try acrossAllReaders( - file: { contexts.file.parentParameters.map(\.count) }, - image: { contexts.image.parentParameters.map(\.count) } - ) + let parentCounts = try acrossAllReaders(contexts.file, contexts.image) { $0.parentParameters.map(\.count) } // Outer scope cumulative = [Outer]; Middle scope cumulative = [Outer, Middle]. // If parentParameters was per-level-new, this would be [1, 1] instead. #expect(parentCounts == [1, 2]) @@ -435,10 +347,7 @@ final class GenericContextTests: MachOSwiftSectionFixtureTests, FixtureSuite, @u @Test("parentRequirements stores cumulative counts per level — counter-example to a per-level-new interpretation") func nestedThreeLevelParentRequirementsAreCumulative() async throws { let contexts = try nestedThreeLevelContexts() - let parentCounts = try acrossAllReaders( - file: { contexts.file.parentRequirements.map(\.count) }, - image: { contexts.image.parentRequirements.map(\.count) } - ) + let parentCounts = try acrossAllReaders(contexts.file, contexts.image) { $0.parentRequirements.map(\.count) } // Outer scope cumulative requirements = [Outer:Hashable]; // Middle scope cumulative requirements = [Outer:Hashable, Middle:Equatable]. // Per-level-new would be [1, 1] — the assertion below distinguishes @@ -449,10 +358,7 @@ final class GenericContextTests: MachOSwiftSectionFixtureTests, FixtureSuite, @u @Test("currentParameters drops only the immediate-parent's cumulative count") func nestedThreeLevelCurrentParametersHardcoded() async throws { let contexts = try nestedThreeLevelContexts() - let count = try acrossAllReaders( - file: { contexts.file.currentParameters.count }, - image: { contexts.image.currentParameters.count } - ) + let count = try acrossAllReaders(contexts.file, contexts.image) { $0.currentParameters.count } // InnerMost adds exactly one new parameter (`InnerMost`). #expect(count == 1) } @@ -460,10 +366,7 @@ final class GenericContextTests: MachOSwiftSectionFixtureTests, FixtureSuite, @u @Test("currentRequirements must drop only the immediate-parent's count, not parentRequirements.flatMap.count") func nestedThreeLevelCurrentRequirementsHardcoded() async throws { let contexts = try nestedThreeLevelContexts() - let count = try acrossAllReaders( - file: { contexts.file.currentRequirements.count }, - image: { contexts.image.currentRequirements.count } - ) + let count = try acrossAllReaders(contexts.file, contexts.image) { $0.currentRequirements.count } // InnerMost adds exactly one new requirement (`InnerMost: Comparable`). // A regression that uses `parentRequirements.flatMap{$0}.count` // (= 1 + 2 = 3) instead of `parentRequirements.last?.count` (= 2) @@ -477,14 +380,10 @@ final class GenericContextTests: MachOSwiftSectionFixtureTests, FixtureSuite, @u @Test("flatMap-over-parents and last-of-parents diverge at depth ≥ 2 — invariant guarding the currentRequirements formula") func nestedThreeLevelFlatMapVsLastDivergence() async throws { let contexts = try nestedThreeLevelContexts() - let flatMapCount = try acrossAllReaders( - file: { contexts.file.parentRequirements.flatMap { $0 }.count }, - image: { contexts.image.parentRequirements.flatMap { $0 }.count } - ) - let lastCount = try acrossAllReaders( - file: { contexts.file.parentRequirements.last?.count ?? 0 }, - image: { contexts.image.parentRequirements.last?.count ?? 0 } - ) + let flatMapCount = try acrossAllReaders(contexts.file, contexts.image) { genericContext in + genericContext.parentRequirements.flatMap { $0 }.count + } + let lastCount = try acrossAllReaders(contexts.file, contexts.image) { $0.parentRequirements.last?.count ?? 0 } // 1 (Outer) + 2 (Middle cumulative) = 3; immediate parent's // cumulative count alone = 2. The two values must differ for a // 3-level-nested fixture; if they ever stop differing, this @@ -498,10 +397,9 @@ final class GenericContextTests: MachOSwiftSectionFixtureTests, FixtureSuite, @u @Test("uniqueCurrentRequirements deduplicates by content even when parents are cumulative") func nestedThreeLevelUniqueCurrentRequirements() async throws { let contexts = try nestedThreeLevelContexts() - let count = try acrossAllContexts( - file: { contexts.file.uniqueCurrentRequirements(in: fileContext).count }, - image: { contexts.image.uniqueCurrentRequirements(in: imageContext).count } - ) + let count = try acrossAllContexts(contexts.file, contexts.image) { genericContext, context in + genericContext.uniqueCurrentRequirements(in: context).count + } // InnerMost adds one requirement. uniqueCurrentRequirements walks // `parentRequirements.flatMap { $0 }` and uses `isContentEqual` to // skip inherited entries, so cumulative duplicates do not break it. @@ -511,10 +409,7 @@ final class GenericContextTests: MachOSwiftSectionFixtureTests, FixtureSuite, @u @Test("allParameters has one entry per nesting level (parents + own)") func nestedThreeLevelAllParametersLevelCount() async throws { let contexts = try nestedThreeLevelContexts() - let count = try acrossAllReaders( - file: { contexts.file.allParameters.count }, - image: { contexts.image.allParameters.count } - ) + let count = try acrossAllReaders(contexts.file, contexts.image) { $0.allParameters.count } // Two parent generic contexts (Outer, Middle) + the current scope. #expect(count == 3) } @@ -522,10 +417,7 @@ final class GenericContextTests: MachOSwiftSectionFixtureTests, FixtureSuite, @u @Test("allRequirements has one entry per nesting level (parents + own)") func nestedThreeLevelAllRequirementsLevelCount() async throws { let contexts = try nestedThreeLevelContexts() - let count = try acrossAllReaders( - file: { contexts.file.allRequirements.count }, - image: { contexts.image.allRequirements.count } - ) + let count = try acrossAllReaders(contexts.file, contexts.image) { $0.allRequirements.count } // Same shape as allParameters: 2 parent levels + current. If // currentRequirements regresses to empty, allRequirements collapses // back to `parentRequirements` (count 2) — this assertion catches diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericEnvironmentFlagsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericEnvironmentFlagsTests.swift index 8209b248e..7609c8669 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericEnvironmentFlagsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericEnvironmentFlagsTests.swift @@ -12,12 +12,8 @@ import SwiftSectionFixtureSupport /// synthetic raw values from the baseline (no live carrier exists in /// SymbolTestsCore — see the Generator's note). @Suite -final class GenericEnvironmentFlagsTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "GenericEnvironmentFlags" - static var registeredTestMethodNames: Set { - GenericEnvironmentFlagsBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class GenericEnvironmentFlagsTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test("init(rawValue:)") func initializerWithRawValue() async throws { let max = GenericEnvironmentFlags(rawValue: GenericEnvironmentFlagsBaseline.maxAll.rawValue) #expect(max.rawValue == GenericEnvironmentFlagsBaseline.maxAll.rawValue) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericEnvironmentTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericEnvironmentTests.swift index ab0c5e089..86e79a1c5 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericEnvironmentTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericEnvironmentTests.swift @@ -12,12 +12,8 @@ import SwiftSectionFixtureSupport /// surface (`offset`, `layout`) for the Coverage Invariant test and /// documents the missing runtime coverage. @Suite -final class GenericEnvironmentTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "GenericEnvironment" - static var registeredTestMethodNames: Set { - GenericEnvironmentBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class GenericEnvironmentTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func registrationOnly() async throws { // No live carrier surfaced by the static reader — see Generator note. #expect(GenericEnvironmentBaseline.registeredTestMethodNames.contains("layout")) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericPackShapeDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericPackShapeDescriptorTests.swift index 866b3b138..6e64cf494 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericPackShapeDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericPackShapeDescriptorTests.swift @@ -11,12 +11,8 @@ import SwiftSectionFixtureSupport /// `ParameterPackRequirementTest` generic struct's /// `typeGenericContext.typePacks` array. @Suite -final class GenericPackShapeDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "GenericPackShapeDescriptor" - static var registeredTestMethodNames: Set { - GenericPackShapeDescriptorBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class GenericPackShapeDescriptorTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadFirstPack() throws -> (file: GenericPackShapeDescriptor, image: GenericPackShapeDescriptor) { let fileDescriptor = try BaselineFixturePicker.struct_ParameterPackRequirementTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.struct_ParameterPackRequirementTest(in: machOImage) @@ -29,29 +25,17 @@ final class GenericPackShapeDescriptorTests: MachOSwiftSectionFixtureTests, Fixt @Test func offset() async throws { let packs = try loadFirstPack() - let result = try acrossAllReaders(file: { packs.file.offset }, image: { packs.image.offset }) + let result = try acrossAllReaders(packs.file, packs.image) { $0.offset } #expect(result == GenericPackShapeDescriptorBaseline.parameterPackFirstShape.offset) } @Test func layout() async throws { let packs = try loadFirstPack() - let kindRaw = try acrossAllReaders( - file: { packs.file.layout.kind }, - image: { packs.image.layout.kind } - ) - let index = try acrossAllReaders( - file: { packs.file.layout.index }, - image: { packs.image.layout.index } - ) - let shapeClass = try acrossAllReaders( - file: { packs.file.layout.shapeClass }, - image: { packs.image.layout.shapeClass } - ) - let unused = try acrossAllReaders( - file: { packs.file.layout.unused }, - image: { packs.image.layout.unused } - ) + let kindRaw = try acrossAllReaders(packs.file, packs.image) { $0.layout.kind } + let index = try acrossAllReaders(packs.file, packs.image) { $0.layout.index } + let shapeClass = try acrossAllReaders(packs.file, packs.image) { $0.layout.shapeClass } + let unused = try acrossAllReaders(packs.file, packs.image) { $0.layout.unused } #expect(kindRaw == GenericPackShapeDescriptorBaseline.parameterPackFirstShape.layoutKind) #expect(index == GenericPackShapeDescriptorBaseline.parameterPackFirstShape.layoutIndex) @@ -61,10 +45,7 @@ final class GenericPackShapeDescriptorTests: MachOSwiftSectionFixtureTests, Fixt @Test func kind() async throws { let packs = try loadFirstPack() - let result = try acrossAllReaders( - file: { packs.file.kind.rawValue }, - image: { packs.image.kind.rawValue } - ) + let result = try acrossAllReaders(packs.file, packs.image) { $0.kind.rawValue } #expect(result == GenericPackShapeDescriptorBaseline.parameterPackFirstShape.kindRawValue) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericPackShapeHeaderTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericPackShapeHeaderTests.swift index 6ace24aaa..1f795b5b0 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericPackShapeHeaderTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericPackShapeHeaderTests.swift @@ -11,12 +11,8 @@ import SwiftSectionFixtureSupport /// `ParameterPackRequirementTest` generic struct's /// `typeGenericContext.typePackHeader`. @Suite -final class GenericPackShapeHeaderTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "GenericPackShapeHeader" - static var registeredTestMethodNames: Set { - GenericPackShapeHeaderBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class GenericPackShapeHeaderTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadHeaders() throws -> (file: GenericPackShapeHeader, image: GenericPackShapeHeader) { let fileDescriptor = try BaselineFixturePicker.struct_ParameterPackRequirementTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.struct_ParameterPackRequirementTest(in: machOImage) @@ -29,21 +25,15 @@ final class GenericPackShapeHeaderTests: MachOSwiftSectionFixtureTests, FixtureS @Test func offset() async throws { let headers = try loadHeaders() - let result = try acrossAllReaders(file: { headers.file.offset }, image: { headers.image.offset }) + let result = try acrossAllReaders(headers.file, headers.image) { $0.offset } #expect(result == GenericPackShapeHeaderBaseline.parameterPackHeader.offset) } @Test func layout() async throws { let headers = try loadHeaders() - let numPacks = try acrossAllReaders( - file: { headers.file.layout.numPacks }, - image: { headers.image.layout.numPacks } - ) - let numShapeClasses = try acrossAllReaders( - file: { headers.file.layout.numShapeClasses }, - image: { headers.image.layout.numShapeClasses } - ) + let numPacks = try acrossAllReaders(headers.file, headers.image) { $0.layout.numPacks } + let numShapeClasses = try acrossAllReaders(headers.file, headers.image) { $0.layout.numShapeClasses } #expect(numPacks == GenericPackShapeHeaderBaseline.parameterPackHeader.layoutNumPacks) #expect(numShapeClasses == GenericPackShapeHeaderBaseline.parameterPackHeader.layoutNumShapeClasses) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericParamDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericParamDescriptorTests.swift index 2ed7e6a51..8da3abdbb 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericParamDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericParamDescriptorTests.swift @@ -13,12 +13,8 @@ import SwiftSectionFixtureSupport /// (`GenericStructLayoutRequirement.parameters[0]`), one for a typePack /// parameter (`ParameterPackRequirementTest.parameters[0]`). @Suite -final class GenericParamDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "GenericParamDescriptor" - static var registeredTestMethodNames: Set { - GenericParamDescriptorBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class GenericParamDescriptorTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { // MARK: - Helpers private func loadLayoutRequirementParam0() throws -> (file: GenericParamDescriptor, image: GenericParamDescriptor) { @@ -45,65 +41,41 @@ final class GenericParamDescriptorTests: MachOSwiftSectionFixtureTests, FixtureS @Test func offset() async throws { let layout = try loadLayoutRequirementParam0() - let layoutResult = try acrossAllReaders( - file: { layout.file.offset }, - image: { layout.image.offset } - ) + let layoutResult = try acrossAllReaders(layout.file, layout.image) { $0.offset } #expect(layoutResult == GenericParamDescriptorBaseline.layoutRequirementParam0.offset) let pack = try loadParameterPackParam0() - let packResult = try acrossAllReaders( - file: { pack.file.offset }, - image: { pack.image.offset } - ) + let packResult = try acrossAllReaders(pack.file, pack.image) { $0.offset } #expect(packResult == GenericParamDescriptorBaseline.parameterPackParam0.offset) } @Test func layout() async throws { let layout = try loadLayoutRequirementParam0() - let layoutRaw = try acrossAllReaders( - file: { layout.file.layout.rawValue }, - image: { layout.image.layout.rawValue } - ) + let layoutRaw = try acrossAllReaders(layout.file, layout.image) { $0.layout.rawValue } #expect(layoutRaw == GenericParamDescriptorBaseline.layoutRequirementParam0.layoutRawValue) let pack = try loadParameterPackParam0() - let packRaw = try acrossAllReaders( - file: { pack.file.layout.rawValue }, - image: { pack.image.layout.rawValue } - ) + let packRaw = try acrossAllReaders(pack.file, pack.image) { $0.layout.rawValue } #expect(packRaw == GenericParamDescriptorBaseline.parameterPackParam0.layoutRawValue) } @Test func hasKeyArgument() async throws { let layout = try loadLayoutRequirementParam0() - let layoutResult = try acrossAllReaders( - file: { layout.file.hasKeyArgument }, - image: { layout.image.hasKeyArgument } - ) + let layoutResult = try acrossAllReaders(layout.file, layout.image) { $0.hasKeyArgument } #expect(layoutResult == GenericParamDescriptorBaseline.layoutRequirementParam0.hasKeyArgument) let pack = try loadParameterPackParam0() - let packResult = try acrossAllReaders( - file: { pack.file.hasKeyArgument }, - image: { pack.image.hasKeyArgument } - ) + let packResult = try acrossAllReaders(pack.file, pack.image) { $0.hasKeyArgument } #expect(packResult == GenericParamDescriptorBaseline.parameterPackParam0.hasKeyArgument) } @Test func kind() async throws { let layout = try loadLayoutRequirementParam0() - let layoutResult = try acrossAllReaders( - file: { layout.file.kind.rawValue }, - image: { layout.image.kind.rawValue } - ) + let layoutResult = try acrossAllReaders(layout.file, layout.image) { $0.kind.rawValue } #expect(layoutResult == GenericParamDescriptorBaseline.layoutRequirementParam0.kindRawValue) let pack = try loadParameterPackParam0() - let packResult = try acrossAllReaders( - file: { pack.file.kind.rawValue }, - image: { pack.image.kind.rawValue } - ) + let packResult = try acrossAllReaders(pack.file, pack.image) { $0.kind.rawValue } #expect(packResult == GenericParamDescriptorBaseline.parameterPackParam0.kindRawValue) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericRequirementContentTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericRequirementContentTests.swift index b5b1632d6..226b30614 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericRequirementContentTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericRequirementContentTests.swift @@ -21,12 +21,8 @@ import SwiftSectionFixtureSupport /// `InvertibleProtocolRequirementTest: ~Copyable` /// generic struct, which surfaces a `.invertedProtocols` requirement. @Suite -final class GenericRequirementContentTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "InvertedProtocols" - static var registeredTestMethodNames: Set { - GenericRequirementContentBaseline.registeredTestMethodNames - } - +@FixtureSuite(testedTypeName: "InvertedProtocols") +final class GenericRequirementContentTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadInvertedProtocols() throws -> (file: GenericRequirementContent.InvertedProtocols, image: GenericRequirementContent.InvertedProtocols) { let fileDescriptor = try BaselineFixturePicker.struct_InvertibleProtocolRequirementTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.struct_InvertibleProtocolRequirementTest(in: machOImage) @@ -51,19 +47,13 @@ final class GenericRequirementContentTests: MachOSwiftSectionFixtureTests, Fixtu @Test func genericParamIndex() async throws { let payloads = try loadInvertedProtocols() - let result = try acrossAllReaders( - file: { payloads.file.genericParamIndex }, - image: { payloads.image.genericParamIndex } - ) + let result = try acrossAllReaders(payloads.file, payloads.image) { $0.genericParamIndex } #expect(result == GenericRequirementContentBaseline.invertibleProtocolRequirement.genericParamIndex) } @Test func protocols() async throws { let payloads = try loadInvertedProtocols() - let result = try acrossAllReaders( - file: { payloads.file.protocols.rawValue }, - image: { payloads.image.protocols.rawValue } - ) + let result = try acrossAllReaders(payloads.file, payloads.image) { $0.protocols.rawValue } #expect(result == GenericRequirementContentBaseline.invertibleProtocolRequirement.protocolsRawValue) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericRequirementDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericRequirementDescriptorTests.swift index 80d8c4bf3..5c4d80c9b 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericRequirementDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericRequirementDescriptorTests.swift @@ -17,12 +17,8 @@ import SwiftSectionFixtureSupport /// - baseClass (`Element: GenericBaseClassForRequirementTest`) /// - sameType (`First == Second`) @Suite -final class GenericRequirementDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "GenericRequirementDescriptor" - static var registeredTestMethodNames: Set { - GenericRequirementDescriptorBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class GenericRequirementDescriptorTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { // MARK: - Helpers private func loadFirstRequirement( @@ -77,35 +73,26 @@ final class GenericRequirementDescriptorTests: MachOSwiftSectionFixtureTests, Fi @Test func offset() async throws { let layout = try layoutRequirements() - let layoutOffset = try acrossAllReaders(file: { layout.file.offset }, image: { layout.image.offset }) + let layoutOffset = try acrossAllReaders(layout.file, layout.image) { $0.offset } #expect(layoutOffset == GenericRequirementDescriptorBaseline.layoutRequirement.offset) let swift = try swiftProtocolRequirements() - let swiftOffset = try acrossAllReaders(file: { swift.file.offset }, image: { swift.image.offset }) + let swiftOffset = try acrossAllReaders(swift.file, swift.image) { $0.offset } #expect(swiftOffset == GenericRequirementDescriptorBaseline.swiftProtocolRequirement.offset) } @Test func layout() async throws { // Layout-level rawValue cross-reader equality on each fixture. let layout = try layoutRequirements() - let layoutRaw = try acrossAllReaders( - file: { layout.file.layout.flags.rawValue }, - image: { layout.image.layout.flags.rawValue } - ) + let layoutRaw = try acrossAllReaders(layout.file, layout.image) { $0.layout.flags.rawValue } #expect(layoutRaw == GenericRequirementDescriptorBaseline.layoutRequirement.flagsRawValue) let baseClass = try baseClassRequirements() - let baseClassRaw = try acrossAllReaders( - file: { baseClass.file.layout.flags.rawValue }, - image: { baseClass.image.layout.flags.rawValue } - ) + let baseClassRaw = try acrossAllReaders(baseClass.file, baseClass.image) { $0.layout.flags.rawValue } #expect(baseClassRaw == GenericRequirementDescriptorBaseline.baseClassRequirement.flagsRawValue) let sameType = try sameTypeRequirements() - let sameTypeRaw = try acrossAllReaders( - file: { sameType.file.layout.flags.rawValue }, - image: { sameType.image.layout.flags.rawValue } - ) + let sameTypeRaw = try acrossAllReaders(sameType.file, sameType.image) { $0.layout.flags.rawValue } #expect(sameTypeRaw == GenericRequirementDescriptorBaseline.sameTypeRequirement.flagsRawValue) } @@ -113,38 +100,23 @@ final class GenericRequirementDescriptorTests: MachOSwiftSectionFixtureTests, Fi @Test func content() async throws { let layout = try layoutRequirements() - let layoutKind = try acrossAllReaders( - file: { describeContentKind(layout.file.content) }, - image: { describeContentKind(layout.image.content) } - ) + let layoutKind = try acrossAllReaders(layout.file, layout.image) { describeContentKind($0.content) } #expect(layoutKind == GenericRequirementDescriptorBaseline.layoutRequirement.contentKindCase) let swift = try swiftProtocolRequirements() - let swiftKind = try acrossAllReaders( - file: { describeContentKind(swift.file.content) }, - image: { describeContentKind(swift.image.content) } - ) + let swiftKind = try acrossAllReaders(swift.file, swift.image) { describeContentKind($0.content) } #expect(swiftKind == GenericRequirementDescriptorBaseline.swiftProtocolRequirement.contentKindCase) let objc = try objcProtocolRequirements() - let objcKind = try acrossAllReaders( - file: { describeContentKind(objc.file.content) }, - image: { describeContentKind(objc.image.content) } - ) + let objcKind = try acrossAllReaders(objc.file, objc.image) { describeContentKind($0.content) } #expect(objcKind == GenericRequirementDescriptorBaseline.objcProtocolRequirement.contentKindCase) let baseClass = try baseClassRequirements() - let baseClassKind = try acrossAllReaders( - file: { describeContentKind(baseClass.file.content) }, - image: { describeContentKind(baseClass.image.content) } - ) + let baseClassKind = try acrossAllReaders(baseClass.file, baseClass.image) { describeContentKind($0.content) } #expect(baseClassKind == GenericRequirementDescriptorBaseline.baseClassRequirement.contentKindCase) let sameType = try sameTypeRequirements() - let sameTypeKind = try acrossAllReaders( - file: { describeContentKind(sameType.file.content) }, - image: { describeContentKind(sameType.image.content) } - ) + let sameTypeKind = try acrossAllReaders(sameType.file, sameType.image) { describeContentKind($0.content) } #expect(sameTypeKind == GenericRequirementDescriptorBaseline.sameTypeRequirement.contentKindCase) } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericRequirementFlagsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericRequirementFlagsTests.swift index 6d14e0d38..2f9b0f78f 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericRequirementFlagsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericRequirementFlagsTests.swift @@ -11,12 +11,8 @@ import SwiftSectionFixtureSupport /// `hasKeyArgument`, `isValueRequirement`). The Suite exercises each /// branch against synthetic raw values from the baseline. @Suite -final class GenericRequirementFlagsTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "GenericRequirementFlags" - static var registeredTestMethodNames: Set { - GenericRequirementFlagsBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class GenericRequirementFlagsTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test("init(rawValue:)") func initializerWithRawValue() async throws { let flags = GenericRequirementFlags(rawValue: GenericRequirementFlagsBaseline.protocolWithKey.rawValue) #expect(flags.rawValue == GenericRequirementFlagsBaseline.protocolWithKey.rawValue) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericRequirementTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericRequirementTests.swift index 9e1858f32..923532550 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericRequirementTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericRequirementTests.swift @@ -15,12 +15,8 @@ import SwiftSectionFixtureSupport /// baseClass / sameType) and asserts cross-reader equality of the /// resolved content discriminant against the baseline. @Suite -final class GenericRequirementTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "GenericRequirement" - static var registeredTestMethodNames: Set { - GenericRequirementBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class GenericRequirementTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { // MARK: - Helpers private func loadFirstRequirement( @@ -108,10 +104,7 @@ final class GenericRequirementTests: MachOSwiftSectionFixtureTests, FixtureSuite @Test func descriptor() async throws { let layout = try layoutRequirements() - let result = try acrossAllReaders( - file: { layout.file.descriptor.offset }, - image: { layout.image.descriptor.offset } - ) + let result = try acrossAllReaders(layout.file, layout.image) { $0.descriptor.offset } #expect(result == GenericRequirementBaseline.layoutRequirement.descriptorOffset) } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericValueDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericValueDescriptorTests.swift index 23d8c2e6d..5e8fbe93f 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericValueDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericValueDescriptorTests.swift @@ -15,12 +15,8 @@ import SwiftSectionFixtureSupport /// (Phase B7) and asserts cross-reader equality on `offset`, /// `layout.type`, and `type.rawValue`. @Suite -final class GenericValueDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "GenericValueDescriptor" - static var registeredTestMethodNames: Set { - GenericValueDescriptorBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class GenericValueDescriptorTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Helper: extract the first `GenericValueDescriptor` from /// `FixedSizeArray`'s generic context against both readers. private func loadFirstValue() throws -> (file: GenericValueDescriptor, image: GenericValueDescriptor) { @@ -35,28 +31,19 @@ final class GenericValueDescriptorTests: MachOSwiftSectionFixtureTests, FixtureS @Test func offset() async throws { let values = try loadFirstValue() - let result = try acrossAllReaders( - file: { values.file.offset }, - image: { values.image.offset } - ) + let result = try acrossAllReaders(values.file, values.image) { $0.offset } #expect(result == GenericValueDescriptorBaseline.fixedSizeArrayFirstValue.offset) } @Test func layout() async throws { let values = try loadFirstValue() - let layoutType = try acrossAllReaders( - file: { values.file.layout.type }, - image: { values.image.layout.type } - ) + let layoutType = try acrossAllReaders(values.file, values.image) { $0.layout.type } #expect(layoutType == GenericValueDescriptorBaseline.fixedSizeArrayFirstValue.layoutType) } @Test func type() async throws { let values = try loadFirstValue() - let typeRaw = try acrossAllReaders( - file: { values.file.type.rawValue }, - image: { values.image.type.rawValue } - ) + let typeRaw = try acrossAllReaders(values.file, values.image) { $0.type.rawValue } #expect(typeRaw == GenericValueDescriptorBaseline.fixedSizeArrayFirstValue.typeRawValue) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericValueHeaderTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericValueHeaderTests.swift index d0c10ee51..377958887 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericValueHeaderTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericValueHeaderTests.swift @@ -15,12 +15,8 @@ import SwiftSectionFixtureSupport /// (Phase B7) and asserts cross-reader equality on `offset` and /// `layout.numValues`. @Suite -final class GenericValueHeaderTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "GenericValueHeader" - static var registeredTestMethodNames: Set { - GenericValueHeaderBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class GenericValueHeaderTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Helper: extract the `GenericValueHeader` from `FixedSizeArray`'s /// generic context against both readers. private func loadValueHeaders() throws -> (file: GenericValueHeader, image: GenericValueHeader) { @@ -35,19 +31,13 @@ final class GenericValueHeaderTests: MachOSwiftSectionFixtureTests, FixtureSuite @Test func offset() async throws { let headers = try loadValueHeaders() - let result = try acrossAllReaders( - file: { headers.file.offset }, - image: { headers.image.offset } - ) + let result = try acrossAllReaders(headers.file, headers.image) { $0.offset } #expect(result == GenericValueHeaderBaseline.fixedSizeArrayHeader.offset) } @Test func layout() async throws { let headers = try loadValueHeaders() - let numValues = try acrossAllReaders( - file: { headers.file.layout.numValues }, - image: { headers.image.layout.numValues } - ) + let numValues = try acrossAllReaders(headers.file, headers.image) { $0.layout.numValues } #expect(numValues == GenericValueHeaderBaseline.fixedSizeArrayHeader.layoutNumValues) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericWitnessTableTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericWitnessTableTests.swift index 785924a26..38b4ad061 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericWitnessTableTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericWitnessTableTests.swift @@ -15,12 +15,8 @@ import SwiftSectionFixtureSupport /// `layout`) for the Coverage Invariant test and documents the missing /// runtime coverage. @Suite -final class GenericWitnessTableTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "GenericWitnessTable" - static var registeredTestMethodNames: Set { - GenericWitnessTableBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class GenericWitnessTableTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func registrationOnly() async throws { // No live carrier surfaced by the current public API — see // Generator note. diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericClassMetadataPatternTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericClassMetadataPatternTests.swift index 4f8e6e029..e3f489785 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericClassMetadataPatternTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericClassMetadataPatternTests.swift @@ -4,6 +4,7 @@ import MachOFoundation @testable import MachOSwiftSection @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import BinaryParseSupport /// Fixture-based Suite for `GenericClassMetadataPattern`. /// @@ -11,12 +12,8 @@ import SwiftSectionFixtureSupport /// simplest generic class in the fixture, and the only pattern that trails a /// partial pattern. @Suite -final class GenericClassMetadataPatternTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "GenericClassMetadataPattern" - static var registeredTestMethodNames: Set { - GenericClassMetadataPatternBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class GenericClassMetadataPatternTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadPatterns() throws -> (file: GenericClassMetadataPattern, image: GenericClassMetadataPattern) { ( file: try BaselineFixturePicker.genericClassMetadataPattern_classNonRequirement(in: machOFile), @@ -26,48 +23,30 @@ final class GenericClassMetadataPatternTests: MachOSwiftSectionFixtureTests, Fix @Test func offset() async throws { let patterns = try loadPatterns() - let result = try acrossAllReaders( - file: { patterns.file.offset }, - image: { patterns.image.offset } - ) + let result = try acrossAllReaders(patterns.file, patterns.image) { $0.offset } #expect(result == GenericClassMetadataPatternBaseline.offset) } @Test func layout() async throws { let patterns = try loadPatterns() - let flagsRaw = try acrossAllReaders( - file: { patterns.file.layout.patternFlags.rawValue }, - image: { patterns.image.layout.patternFlags.rawValue } - ) + let flagsRaw = try acrossAllReaders(patterns.file, patterns.image) { $0.layout.patternFlags.rawValue } #expect(flagsRaw == GenericClassMetadataPatternBaseline.patternFlagsRawValue) // Three header words, two function pointers, the class flag word and // four half-words of interop offsets. #expect(MemoryLayout.size == 32) - let classFlags = try acrossAllReaders( - file: { patterns.file.layout.classFlags }, - image: { patterns.image.layout.classFlags } - ) + let classFlags = try acrossAllReaders(patterns.file, patterns.image) { $0.layout.classFlags } #expect(classFlags == GenericClassMetadataPatternBaseline.classFlags) // Where the runtime-built class_ro_t and metaclass land inside the // extra data block, counted in WORDS. - let interopOffsetsInWords = try acrossAllReaders( - file: { - [ - patterns.file.layout.classReadOnlyDataOffsetInWords, - patterns.file.layout.metaclassObjectOffsetInWords, - patterns.file.layout.metaclassReadOnlyDataOffsetInWords, - ] - }, - image: { - [ - patterns.image.layout.classReadOnlyDataOffsetInWords, - patterns.image.layout.metaclassObjectOffsetInWords, - patterns.image.layout.metaclassReadOnlyDataOffsetInWords, - ] - } - ) + let interopOffsetsInWords = try acrossAllReaders(patterns.file, patterns.image) { pattern in + [ + pattern.layout.classReadOnlyDataOffsetInWords, + pattern.layout.metaclassObjectOffsetInWords, + pattern.layout.metaclassReadOnlyDataOffsetInWords, + ] + } #expect(interopOffsetsInWords.map(Int.init) == [ GenericClassMetadataPatternBaseline.classReadOnlyDataOffsetInWords, GenericClassMetadataPatternBaseline.metaclassObjectOffsetInWords, @@ -82,10 +61,7 @@ final class GenericClassMetadataPatternTests: MachOSwiftSectionFixtureTests, Fix (\GenericClassMetadataPattern.Layout.destroy, GenericClassMetadataPatternBaseline.destroyOffset), (\GenericClassMetadataPattern.Layout.instanceVariableDestroyer, GenericClassMetadataPatternBaseline.instanceVariableDestroyerOffset), ] { - let resolved = try acrossAllReaders( - file: { patterns.file.resolvedDirectOffset(from: keyPath) }, - image: { patterns.image.resolvedDirectOffset(from: keyPath) } - ) + let resolved = try acrossAllReaders(patterns.file, patterns.image) { $0.resolvedDirectOffset(from: keyPath) } #expect(resolved == expected) } } @@ -96,10 +72,7 @@ final class GenericClassMetadataPatternTests: MachOSwiftSectionFixtureTests, Fix /// value carrier is checked here too. @Test func hasImmediateMembersPattern() async throws { let patterns = try loadPatterns() - let result = try acrossAllReaders( - file: { patterns.file.hasImmediateMembersPattern }, - image: { patterns.image.hasImmediateMembersPattern } - ) + let result = try acrossAllReaders(patterns.file, patterns.image) { $0.hasImmediateMembersPattern } #expect(result == GenericClassMetadataPatternBaseline.hasImmediateMembersPattern) let valuePattern = try BaselineFixturePicker.genericValueMetadataPattern_structNonRequirement(in: machOFile) @@ -109,20 +82,16 @@ final class GenericClassMetadataPatternTests: MachOSwiftSectionFixtureTests, Fix @Test func numberOfTrailingPartialPatterns() async throws { let patterns = try loadPatterns() - let result = try acrossAllReaders( - file: { patterns.file.numberOfTrailingPartialPatterns }, - image: { patterns.image.numberOfTrailingPartialPatterns } - ) + let result = try acrossAllReaders(patterns.file, patterns.image) { $0.numberOfTrailingPartialPatterns } #expect(result == GenericClassMetadataPatternBaseline.numberOfTrailingPartialPatterns) #expect(result == (patterns.file.hasExtraDataPattern ? 1 : 0) + (patterns.file.hasImmediateMembersPattern ? 1 : 0)) } @Test func immediateMembersPattern() async throws { let patterns = try loadPatterns() - let result = try acrossAllContexts( - file: { try patterns.file.immediateMembersPattern(in: fileContext)?.offset }, - image: { try patterns.image.immediateMembersPattern(in: imageContext)?.offset } - ) + let result = try acrossAllContexts(patterns.file, patterns.image) { pattern, context in + try pattern.immediateMembersPattern(in: context)?.offset + } // This carrier has no immediate-members pattern; the accessor must // answer nil rather than hand back the extra-data one. #expect(result == nil) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericMetadataPartialPatternTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericMetadataPartialPatternTests.swift index cd1094c8c..c04f7ffb9 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericMetadataPartialPatternTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericMetadataPartialPatternTests.swift @@ -11,12 +11,8 @@ import SwiftSectionFixtureSupport /// `GenericClassNonRequirement`'s class pattern — the one partial pattern /// the fixture contains. @Suite -final class GenericMetadataPartialPatternTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "GenericMetadataPartialPattern" - static var registeredTestMethodNames: Set { - GenericMetadataPartialPatternBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class GenericMetadataPartialPatternTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadPartialPatterns() throws -> (file: GenericMetadataPartialPattern, image: GenericMetadataPartialPattern) { let filePattern = try BaselineFixturePicker.genericClassMetadataPattern_classNonRequirement(in: machOFile) let imagePattern = try BaselineFixturePicker.genericClassMetadataPattern_classNonRequirement(in: machOImage) @@ -28,37 +24,31 @@ final class GenericMetadataPartialPatternTests: MachOSwiftSectionFixtureTests, F @Test func offset() async throws { let partialPatterns = try loadPartialPatterns() - let result = try acrossAllReaders( - file: { partialPatterns.file.offset }, - image: { partialPatterns.image.offset } - ) + let result = try acrossAllReaders(partialPatterns.file, partialPatterns.image) { $0.offset } #expect(result == GenericMetadataPartialPatternBaseline.offset) } @Test func layout() async throws { let partialPatterns = try loadPartialPatterns() - let relativeOffset = try acrossAllReaders( - file: { partialPatterns.file.layout.pattern.relativeOffset }, - image: { partialPatterns.image.layout.pattern.relativeOffset } - ) + let relativeOffset = try acrossAllReaders(partialPatterns.file, partialPatterns.image) { partialPattern in + partialPattern.layout.pattern.relativeOffset + } #expect(relativeOffset != 0) // One relative pointer plus two half-words; the pattern's own size // arithmetic depends on it. #expect(MemoryLayout.size == 8) - let patternOffset = try acrossAllReaders( - file: { partialPatterns.file.resolvedDirectOffset(from: \.pattern) }, - image: { partialPatterns.image.resolvedDirectOffset(from: \.pattern) } - ) + let patternOffset = try acrossAllReaders(partialPatterns.file, partialPatterns.image) { partialPattern in + partialPattern.resolvedDirectOffset(from: \.pattern) + } #expect(patternOffset == GenericMetadataPartialPatternBaseline.patternOffset) // Both quantities are counted in WORDS, not bytes — reading them as // bytes would place the block eight times too close to the metadata's // start. - let wordCounts = try acrossAllReaders( - file: { [partialPatterns.file.layout.offsetInWords, partialPatterns.file.layout.sizeInWords] }, - image: { [partialPatterns.image.layout.offsetInWords, partialPatterns.image.layout.sizeInWords] } - ) + let wordCounts = try acrossAllReaders(partialPatterns.file, partialPatterns.image) { partialPattern in + [partialPattern.layout.offsetInWords, partialPattern.layout.sizeInWords] + } #expect(wordCounts.map(Int.init) == [ GenericMetadataPartialPatternBaseline.offsetInWords, GenericMetadataPartialPatternBaseline.sizeInWords, diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericMetadataPatternProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericMetadataPatternProtocolTests.swift index 9e617f360..0d6e77804 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericMetadataPatternProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericMetadataPatternProtocolTests.swift @@ -12,12 +12,8 @@ import SwiftSectionFixtureSupport /// is the one part of the two layouts that must agree, and the class carrier /// is the only one with a trailing partial pattern. @Suite -final class GenericMetadataPatternProtocolTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "GenericMetadataPatternProtocol" - static var registeredTestMethodNames: Set { - GenericMetadataPatternProtocolBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class GenericMetadataPatternProtocolTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private struct Carrier { let label: String let file: any GenericMetadataPatternProtocol @@ -44,10 +40,7 @@ final class GenericMetadataPatternProtocolTests: MachOSwiftSectionFixtureTests, @Test func hasExtraDataPattern() async throws { for carrier in try allCarriers() { - let result = try acrossAllReaders( - file: { carrier.file.hasExtraDataPattern }, - image: { carrier.image.hasExtraDataPattern } - ) + let result = try acrossAllReaders(carrier.file, carrier.image) { $0.hasExtraDataPattern } #expect(result == carrier.expected.hasExtraDataPattern, "\(carrier.label)") } // The two carriers differ here, which is what makes the trailing @@ -57,40 +50,30 @@ final class GenericMetadataPatternProtocolTests: MachOSwiftSectionFixtureTests, @Test func hasTrailingFlags() async throws { for carrier in try allCarriers() { - let result = try acrossAllReaders( - file: { carrier.file.hasTrailingFlags }, - image: { carrier.image.hasTrailingFlags } - ) + let result = try acrossAllReaders(carrier.file, carrier.image) { $0.hasTrailingFlags } #expect(result == carrier.expected.hasTrailingFlags, "\(carrier.label)") } } @Test func partialPatternsOffset() async throws { for carrier in try allCarriers() { - let result = try acrossAllReaders( - file: { carrier.file.partialPatternsOffset }, - image: { carrier.image.partialPatternsOffset } - ) + let result = try acrossAllReaders(carrier.file, carrier.image) { $0.partialPatternsOffset } #expect(result == carrier.expected.partialPatternsOffset, "\(carrier.label)") } } @Test func size() async throws { for carrier in try allCarriers() { - let result = try acrossAllReaders( - file: { carrier.file.size }, - image: { carrier.image.size } - ) + let result = try acrossAllReaders(carrier.file, carrier.image) { $0.size } #expect(result == carrier.expected.size, "\(carrier.label)") } } @Test func partialPatterns() async throws { for carrier in try allCarriers() { - let offsets = try acrossAllContexts( - file: { try carrier.file.partialPatterns(in: fileContext).map(\.offset) }, - image: { try carrier.image.partialPatterns(in: imageContext).map(\.offset) } - ) + let offsets = try acrossAllContexts(carrier.file, carrier.image) { pattern, context in + try pattern.partialPatterns(in: context).map(\.offset) + } #expect(offsets.count == carrier.expected.partialPatternCount, "\(carrier.label)") #expect(offsets.first == (carrier.expected.partialPatternCount > 0 ? carrier.expected.partialPatternsOffset : nil), "\(carrier.label)") } @@ -98,10 +81,9 @@ final class GenericMetadataPatternProtocolTests: MachOSwiftSectionFixtureTests, @Test func extraDataPattern() async throws { for carrier in try allCarriers() { - let result = try acrossAllContexts( - file: { try carrier.file.extraDataPattern(in: fileContext)?.offset }, - image: { try carrier.image.extraDataPattern(in: imageContext)?.offset } - ) + let result = try acrossAllContexts(carrier.file, carrier.image) { pattern, context in + try pattern.extraDataPattern(in: context)?.offset + } let expected = carrier.expected.hasExtraDataPattern ? carrier.expected.partialPatternsOffset : nil #expect(result == expected, "\(carrier.label)") } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericValueMetadataPatternTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericValueMetadataPatternTests.swift index 610819016..f7abafab5 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericValueMetadataPatternTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericValueMetadataPatternTests.swift @@ -12,12 +12,8 @@ import SwiftSectionFixtureSupport /// context header — so the picker itself exercises /// `TypeGenericContextDescriptorHeader.defaultInstantiationPatternOffset`. @Suite -final class GenericValueMetadataPatternTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "GenericValueMetadataPattern" - static var registeredTestMethodNames: Set { - GenericValueMetadataPatternBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class GenericValueMetadataPatternTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadPatterns() throws -> (file: GenericValueMetadataPattern, image: GenericValueMetadataPattern) { ( file: try BaselineFixturePicker.genericValueMetadataPattern_structNonRequirement(in: machOFile), @@ -27,33 +23,25 @@ final class GenericValueMetadataPatternTests: MachOSwiftSectionFixtureTests, Fix @Test func offset() async throws { let patterns = try loadPatterns() - let result = try acrossAllReaders( - file: { patterns.file.offset }, - image: { patterns.image.offset } - ) + let result = try acrossAllReaders(patterns.file, patterns.image) { $0.offset } #expect(result == GenericValueMetadataPatternBaseline.offset) } @Test func layout() async throws { let patterns = try loadPatterns() - let flagsRaw = try acrossAllReaders( - file: { patterns.file.layout.patternFlags.rawValue }, - image: { patterns.image.layout.patternFlags.rawValue } - ) + let flagsRaw = try acrossAllReaders(patterns.file, patterns.image) { $0.layout.patternFlags.rawValue } #expect(flagsRaw == GenericValueMetadataPatternBaseline.patternFlagsRawValue) // Three header words plus the value witness pointer. #expect(MemoryLayout.size == 16) - let instantiationFunctionOffset = try acrossAllReaders( - file: { patterns.file.resolvedDirectOffset(from: \.instantiationFunction) }, - image: { patterns.image.resolvedDirectOffset(from: \.instantiationFunction) } - ) + let instantiationFunctionOffset = try acrossAllReaders(patterns.file, patterns.image) { pattern in + pattern.resolvedDirectOffset(from: \.instantiationFunction) + } #expect(instantiationFunctionOffset == GenericValueMetadataPatternBaseline.instantiationFunctionOffset) - let completionFunctionOffset = try acrossAllReaders( - file: { patterns.file.resolvedDirectOffset(from: \.completionFunction) }, - image: { patterns.image.resolvedDirectOffset(from: \.completionFunction) } - ) + let completionFunctionOffset = try acrossAllReaders(patterns.file, patterns.image) { pattern in + pattern.resolvedDirectOffset(from: \.completionFunction) + } #expect(completionFunctionOffset == GenericValueMetadataPatternBaseline.completionFunctionOffset) } @@ -62,20 +50,14 @@ final class GenericValueMetadataPatternTests: MachOSwiftSectionFixtureTests, Fix /// mistake this accessor exists to prevent. @Test func metadataKind() async throws { let patterns = try loadPatterns() - let result = try acrossAllReaders( - file: { patterns.file.metadataKind?.rawValue }, - image: { patterns.image.metadataKind?.rawValue } - ) + let result = try acrossAllReaders(patterns.file, patterns.image) { $0.metadataKind?.rawValue } #expect(result == GenericValueMetadataPatternBaseline.metadataKindRawValue) #expect(patterns.file.metadataKind == .struct) } @Test func numberOfTrailingPartialPatterns() async throws { let patterns = try loadPatterns() - let result = try acrossAllReaders( - file: { patterns.file.numberOfTrailingPartialPatterns }, - image: { patterns.image.numberOfTrailingPartialPatterns } - ) + let result = try acrossAllReaders(patterns.file, patterns.image) { $0.numberOfTrailingPartialPatterns } #expect(result == GenericValueMetadataPatternBaseline.numberOfTrailingPartialPatterns) // A value pattern never counts the class-only immediate-members bit, // which on this carrier is set as part of the metadata kind. @@ -87,19 +69,13 @@ final class GenericValueMetadataPatternTests: MachOSwiftSectionFixtureTests, Fix /// answer for size, stride, alignment and extra inhabitants. @Test func valueWitnessesOffset() async throws { let patterns = try loadPatterns() - let result = try acrossAllReaders( - file: { patterns.file.valueWitnessesOffset }, - image: { patterns.image.valueWitnessesOffset } - ) + let result = try acrossAllReaders(patterns.file, patterns.image) { $0.valueWitnessesOffset } #expect(result == GenericValueMetadataPatternBaseline.valueWitnessesOffset) } @Test func valueWitnessesIsIndirect() async throws { let patterns = try loadPatterns() - let result = try acrossAllReaders( - file: { patterns.file.valueWitnessesIsIndirect }, - image: { patterns.image.valueWitnessesIsIndirect } - ) + let result = try acrossAllReaders(patterns.file, patterns.image) { $0.valueWitnessesIsIndirect } #expect(result == GenericValueMetadataPatternBaseline.valueWitnessesIsIndirect) // The two readings are mutually exclusive: an indirect pointer names // no offset within this image. diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/ResilientClassMetadataPatternTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/ResilientClassMetadataPatternTests.swift index bd7dfb8e0..4e6012aed 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/ResilientClassMetadataPatternTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/ResilientClassMetadataPatternTests.swift @@ -13,12 +13,8 @@ import SwiftSectionFixtureSupport /// field, not through a generic context — that route is what this Suite /// exercises end to end. @Suite -final class ResilientClassMetadataPatternTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ResilientClassMetadataPattern" - static var registeredTestMethodNames: Set { - ResilientClassMetadataPatternBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ResilientClassMetadataPatternTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadPatterns() throws -> (file: ResilientClassMetadataPattern, image: ResilientClassMetadataPattern) { ( file: try BaselineFixturePicker.resilientClassMetadataPattern_resilientChild(in: machOFile), @@ -28,10 +24,7 @@ final class ResilientClassMetadataPatternTests: MachOSwiftSectionFixtureTests, F @Test func offset() async throws { let patterns = try loadPatterns() - let result = try acrossAllReaders( - file: { patterns.file.offset }, - image: { patterns.image.offset } - ) + let result = try acrossAllReaders(patterns.file, patterns.image) { $0.offset } #expect(result == ResilientClassMetadataPatternBaseline.offset) // The pattern is reached through the singleton record's union field, @@ -45,10 +38,7 @@ final class ResilientClassMetadataPatternTests: MachOSwiftSectionFixtureTests, F @Test func layout() async throws { let patterns = try loadPatterns() - let classFlags = try acrossAllReaders( - file: { patterns.file.layout.classFlags }, - image: { patterns.image.layout.classFlags } - ) + let classFlags = try acrossAllReaders(patterns.file, patterns.image) { $0.layout.classFlags } #expect(classFlags == ResilientClassMetadataPatternBaseline.classFlags) // Three function pointers, the class flag word and two interop // pointers. @@ -64,10 +54,7 @@ final class ResilientClassMetadataPatternTests: MachOSwiftSectionFixtureTests, F (\ResilientClassMetadataPattern.Layout.data, ResilientClassMetadataPatternBaseline.dataOffset), (\ResilientClassMetadataPattern.Layout.metaclass, ResilientClassMetadataPatternBaseline.metaclassOffset), ] { - let resolved = try acrossAllReaders( - file: { patterns.file.resolvedDirectOffset(from: keyPath) }, - image: { patterns.image.resolvedDirectOffset(from: keyPath) } - ) + let resolved = try acrossAllReaders(patterns.file, patterns.image) { $0.resolvedDirectOffset(from: keyPath) } #expect(resolved == expected) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/TypeGenericContextDescriptorHeaderTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/TypeGenericContextDescriptorHeaderTests.swift index 444bb1037..af8eb19cc 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/TypeGenericContextDescriptorHeaderTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/TypeGenericContextDescriptorHeaderTests.swift @@ -16,12 +16,8 @@ import SwiftSectionFixtureSupport /// on `offset` and the four scalar fields exposed via the /// `GenericContextDescriptorHeaderLayout` protocol. @Suite -final class TypeGenericContextDescriptorHeaderTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "TypeGenericContextDescriptorHeader" - static var registeredTestMethodNames: Set { - TypeGenericContextDescriptorHeaderBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class TypeGenericContextDescriptorHeaderTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Helper: extract the `TypeGenericContextDescriptorHeader` from /// `GenericStructLayoutRequirement` against both readers. private func loadGenericStructLayoutRequirementHeaders() throws -> (file: TypeGenericContextDescriptorHeader, image: TypeGenericContextDescriptorHeader) { @@ -34,32 +30,17 @@ final class TypeGenericContextDescriptorHeaderTests: MachOSwiftSectionFixtureTes @Test func offset() async throws { let headers = try loadGenericStructLayoutRequirementHeaders() - let result = try acrossAllReaders( - file: { headers.file.offset }, - image: { headers.image.offset } - ) + let result = try acrossAllReaders(headers.file, headers.image) { $0.offset } #expect(result == TypeGenericContextDescriptorHeaderBaseline.genericStructLayoutRequirement.offset) } @Test func layout() async throws { let headers = try loadGenericStructLayoutRequirementHeaders() - let numParams = try acrossAllReaders( - file: { headers.file.layout.numParams }, - image: { headers.image.layout.numParams } - ) - let numRequirements = try acrossAllReaders( - file: { headers.file.layout.numRequirements }, - image: { headers.image.layout.numRequirements } - ) - let numKeyArguments = try acrossAllReaders( - file: { headers.file.layout.numKeyArguments }, - image: { headers.image.layout.numKeyArguments } - ) - let flagsRawValue = try acrossAllReaders( - file: { headers.file.layout.flags.rawValue }, - image: { headers.image.layout.flags.rawValue } - ) + let numParams = try acrossAllReaders(headers.file, headers.image) { $0.layout.numParams } + let numRequirements = try acrossAllReaders(headers.file, headers.image) { $0.layout.numRequirements } + let numKeyArguments = try acrossAllReaders(headers.file, headers.image) { $0.layout.numKeyArguments } + let flagsRawValue = try acrossAllReaders(headers.file, headers.image) { $0.layout.flags.rawValue } #expect(numParams == TypeGenericContextDescriptorHeaderBaseline.genericStructLayoutRequirement.layoutNumParams) #expect(numRequirements == TypeGenericContextDescriptorHeaderBaseline.genericStructLayoutRequirement.layoutNumRequirements) @@ -68,19 +49,17 @@ final class TypeGenericContextDescriptorHeaderTests: MachOSwiftSectionFixtureTes // The instantiation cache is mutable runtime state and reads as zero // in the file; only where it sits is a static fact. - let instantiationCacheOffset = try acrossAllReaders( - file: { headers.file.resolvedDirectOffset(from: \.instantiationCache) }, - image: { headers.image.resolvedDirectOffset(from: \.instantiationCache) } - ) + let instantiationCacheOffset = try acrossAllReaders(headers.file, headers.image) { header in + header.resolvedDirectOffset(from: \.instantiationCache) + } #expect(instantiationCacheOffset == TypeGenericContextDescriptorHeaderBaseline.genericStructLayoutRequirement.instantiationCacheOffset) // The entry point to the whole generic-pattern family. The pattern // Suites reach their carriers through exactly this field, so a wrong // answer here would surface there too. - let patternOffset = try acrossAllReaders( - file: { headers.file.resolvedDirectOffset(from: \.defaultInstantiationPattern) }, - image: { headers.image.resolvedDirectOffset(from: \.defaultInstantiationPattern) } - ) + let patternOffset = try acrossAllReaders(headers.file, headers.image) { header in + header.resolvedDirectOffset(from: \.defaultInstantiationPattern) + } #expect(patternOffset == TypeGenericContextDescriptorHeaderBaseline.genericStructLayoutRequirement.defaultInstantiationPatternOffset) // Resolving what it points at must produce a struct pattern, since diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Heap/GenericBoxHeapMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Heap/GenericBoxHeapMetadataTests.swift index 9b76321d4..f73273ae6 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Heap/GenericBoxHeapMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Heap/GenericBoxHeapMetadataTests.swift @@ -13,12 +13,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class GenericBoxHeapMetadataTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "GenericBoxHeapMetadata" - static var registeredTestMethodNames: Set { - GenericBoxHeapMetadataBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class GenericBoxHeapMetadataTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func offset() async throws { let metadata = GenericBoxHeapMetadata( layout: .init( diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Heap/HeapLocalVariableMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Heap/HeapLocalVariableMetadataTests.swift index 7081a0f00..fa7a0b96a 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Heap/HeapLocalVariableMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Heap/HeapLocalVariableMetadataTests.swift @@ -13,12 +13,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class HeapLocalVariableMetadataTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "HeapLocalVariableMetadata" - static var registeredTestMethodNames: Set { - HeapLocalVariableMetadataBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class HeapLocalVariableMetadataTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func offset() async throws { let metadata = HeapLocalVariableMetadata( layout: .init( diff --git a/Tests/MachOSwiftSectionTests/Fixtures/KeyPath/KeyPathComponentHeaderTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/KeyPath/KeyPathComponentHeaderTests.swift index e4c57be04..a690df699 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/KeyPath/KeyPathComponentHeaderTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/KeyPath/KeyPathComponentHeaderTests.swift @@ -15,12 +15,8 @@ import SwiftSectionFixtureSupport /// path pattern, and the header models the pattern encoding too (evolution /// proposal 0025). @Suite -final class KeyPathComponentHeaderTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "KeyPathComponentHeader" - static var registeredTestMethodNames: Set { - KeyPathComponentHeaderBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class KeyPathComponentHeaderTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private struct Shape { let label: String let file: KeyPathComponentHeader @@ -59,11 +55,7 @@ final class KeyPathComponentHeaderTests: MachOSwiftSectionFixtureTests, FixtureS sourceLocation: SourceLocation = #_sourceLocation ) throws { for shape in try liveShapes() { - let result = try acrossAllReaders( - file: { accessor(shape.file) }, - image: { accessor(shape.image) }, - sourceLocation: sourceLocation - ) + let result = try acrossAllReaders(shape.file, shape.image, sourceLocation: sourceLocation) { accessor($0) } #expect(result == expectation(shape.expected), "\(shape.label)", sourceLocation: sourceLocation) } for shape in synthesizedShapes() { diff --git a/Tests/MachOSwiftSectionTests/Fixtures/KeyPath/KeyPathComputedPropertyBodyTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/KeyPath/KeyPathComputedPropertyBodyTests.swift index 2cff7d2b0..302b61200 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/KeyPath/KeyPathComputedPropertyBodyTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/KeyPath/KeyPathComputedPropertyBodyTests.swift @@ -13,12 +13,8 @@ import SwiftSectionFixtureSupport /// relative-pointer arithmetic off the body's own location, so both readers /// must agree, and the values are pinned as literals. @Suite -final class KeyPathComputedPropertyBodyTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "KeyPathComputedPropertyBody" - static var registeredTestMethodNames: Set { - KeyPathComputedPropertyBodyBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class KeyPathComputedPropertyBodyTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private var expected: KeyPathComputedPropertyBodyBaseline.Entry { KeyPathComputedPropertyBodyBaseline.codableClassIdentifier } @@ -38,11 +34,7 @@ final class KeyPathComputedPropertyBodyTests: MachOSwiftSectionFixtureTests, Fix sourceLocation: SourceLocation = #_sourceLocation ) throws { let bodies = try loadBodies() - let result = try acrossAllReaders( - file: { accessor(bodies.file) }, - image: { accessor(bodies.image) }, - sourceLocation: sourceLocation - ) + let result = try acrossAllReaders(bodies.file, bodies.image, sourceLocation: sourceLocation) { accessor($0) } #expect(result == expectation, sourceLocation: sourceLocation) } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/KeyPath/KeyPathStoredFieldOffsetTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/KeyPath/KeyPathStoredFieldOffsetTests.swift index 592364666..513c9c6c3 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/KeyPath/KeyPathStoredFieldOffsetTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/KeyPath/KeyPathStoredFieldOffsetTests.swift @@ -14,12 +14,8 @@ import SwiftSectionFixtureSupport /// exists to make, so both are asserted here. The two remaining cases have no /// fixture carrier and are constructed directly. @Suite -final class KeyPathStoredFieldOffsetTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "KeyPathStoredFieldOffset" - static var registeredTestMethodNames: Set { - KeyPathStoredFieldOffsetBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class KeyPathStoredFieldOffsetTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private struct Shape { let label: String let file: KeyPathStoredFieldOffset @@ -63,11 +59,7 @@ final class KeyPathStoredFieldOffsetTests: MachOSwiftSectionFixtureTests, Fixtur sourceLocation: SourceLocation = #_sourceLocation ) throws { for shape in try liveShapes() { - let result = try acrossAllReaders( - file: { accessor(shape.file) }, - image: { accessor(shape.image) }, - sourceLocation: sourceLocation - ) + let result = try acrossAllReaders(shape.file, shape.image, sourceLocation: sourceLocation) { accessor($0) } #expect(result == expectation(shape.expected), "\(shape.label)", sourceLocation: sourceLocation) } for shape in synthesizedShapes() { diff --git a/Tests/MachOSwiftSectionTests/Fixtures/KeyPath/PropertyDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/KeyPath/PropertyDescriptorTests.swift index e1b553516..cb24591b4 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/KeyPath/PropertyDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/KeyPath/PropertyDescriptorTests.swift @@ -14,12 +14,8 @@ import SwiftSectionFixtureSupport /// offset only lives in the metadata, and a resilient class's settable /// computed property. Every assertion runs across both readers. @Suite -final class PropertyDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "PropertyDescriptor" - static var registeredTestMethodNames: Set { - PropertyDescriptorBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class PropertyDescriptorTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private struct Shape { let label: String let file: PropertyDescriptor @@ -60,30 +56,21 @@ final class PropertyDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite @Test func offset() async throws { for shape in try allShapes() { - let result = try acrossAllReaders( - file: { shape.file.offset }, - image: { shape.image.offset } - ) + let result = try acrossAllReaders(shape.file, shape.image) { $0.offset } #expect(result == shape.expected.offset, "\(shape.label)") } } @Test func layout() async throws { for shape in try allShapes() { - let result = try acrossAllReaders( - file: { shape.file.layout.header.rawValue }, - image: { shape.image.layout.header.rawValue } - ) + let result = try acrossAllReaders(shape.file, shape.image) { $0.layout.header.rawValue } #expect(result == shape.expected.headerRawValue, "\(shape.label)") } } @Test func header() async throws { for shape in try allShapes() { - let result = try acrossAllReaders( - file: { shape.file.header.rawValue }, - image: { shape.image.header.rawValue } - ) + let result = try acrossAllReaders(shape.file, shape.image) { $0.header.rawValue } #expect(result == shape.expected.headerRawValue, "\(shape.label)") #expect(shape.file.header == shape.file.layout.header, "\(shape.label)") } @@ -91,10 +78,7 @@ final class PropertyDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite @Test func isTrivial() async throws { for shape in try allShapes() { - let result = try acrossAllReaders( - file: { shape.file.isTrivial }, - image: { shape.image.isTrivial } - ) + let result = try acrossAllReaders(shape.file, shape.image) { $0.isTrivial } #expect(result == shape.expected.isTrivial, "\(shape.label)") } // Exactly one of the four carriers is the shared trivial descriptor; @@ -106,20 +90,14 @@ final class PropertyDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite @Test func bodySize() async throws { for shape in try allShapes() { - let result = try acrossAllReaders( - file: { shape.file.bodySize }, - image: { shape.image.bodySize } - ) + let result = try acrossAllReaders(shape.file, shape.image) { $0.bodySize } #expect(result == shape.expected.bodySize, "\(shape.label)") } } @Test func size() async throws { for shape in try allShapes() { - let result = try acrossAllReaders( - file: { shape.file.size }, - image: { shape.image.size } - ) + let result = try acrossAllReaders(shape.file, shape.image) { $0.size } #expect(result == shape.expected.size, "\(shape.label)") #expect(result == MemoryLayout.size + shape.expected.bodySize, "\(shape.label)") } @@ -127,10 +105,7 @@ final class PropertyDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite @Test func bodyOffset() async throws { for shape in try allShapes() { - let result = try acrossAllReaders( - file: { shape.file.bodyOffset }, - image: { shape.image.bodyOffset } - ) + let result = try acrossAllReaders(shape.file, shape.image) { $0.bodyOffset } #expect(result == shape.expected.bodyOffset, "\(shape.label)") #expect(result == shape.expected.offset + MemoryLayout.size, "\(shape.label)") } @@ -138,10 +113,7 @@ final class PropertyDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite @Test func inlineStoredFieldOffset() async throws { for shape in try allShapes() { - let result = try acrossAllReaders( - file: { shape.file.inlineStoredFieldOffset?.rawValue }, - image: { shape.image.inlineStoredFieldOffset?.rawValue } - ) + let result = try acrossAllReaders(shape.file, shape.image) { $0.inlineStoredFieldOffset?.rawValue } #expect(result == shape.expected.inlineStoredFieldOffsetRawValue, "\(shape.label)") } } @@ -164,10 +136,9 @@ final class PropertyDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite /// so it is identical across readers and pinned as a literal. @Test func computedPropertyBody() async throws { for shape in try allShapes() { - let result = try acrossAllContexts( - file: { try shape.file.computedPropertyBody(in: fileContext)?.getterOffset }, - image: { try shape.image.computedPropertyBody(in: imageContext)?.getterOffset } - ) + let result = try acrossAllContexts(shape.file, shape.image) { descriptor, context in + try descriptor.computedPropertyBody(in: context)?.getterOffset + } #expect(result == shape.expected.computedGetterOffset, "\(shape.label)") // The in-process leg reads through a pointer, so its offsets are diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Mangling/MangledNameTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Mangling/MangledNameTests.swift index 4c807e9f8..896e7f7d7 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Mangling/MangledNameTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Mangling/MangledNameTests.swift @@ -13,12 +13,8 @@ import SwiftSectionFixtureSupport /// element-array isn't deep-compared because it carries reader- /// specific offset values). @Suite -final class MangledNameTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "MangledName" - static var registeredTestMethodNames: Set { - MangledNameBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class MangledNameTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadMangledNames() throws -> (file: MangledName, image: MangledName) { let fileDescriptor = try BaselineFixturePicker.multiPayloadEnumDescriptor_MultiPayloadEnumTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.multiPayloadEnumDescriptor_MultiPayloadEnumTest(in: machOImage) @@ -29,19 +25,13 @@ final class MangledNameTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unch @Test func isEmpty() async throws { let names = try loadMangledNames() - let result = try acrossAllReaders( - file: { names.file.isEmpty }, - image: { names.image.isEmpty } - ) + let result = try acrossAllReaders(names.file, names.image) { $0.isEmpty } #expect(result == MangledNameBaseline.multiPayloadEnumName.isEmpty) } @Test func rawString() async throws { let names = try loadMangledNames() - let result = try acrossAllReaders( - file: { names.file.rawString }, - image: { names.image.rawString } - ) + let result = try acrossAllReaders(names.file, names.image) { $0.rawString } #expect(result == MangledNameBaseline.multiPayloadEnumName.rawString) } @@ -49,20 +39,14 @@ final class MangledNameTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unch let names = try loadMangledNames() // symbolString applies prefix-insertion if the raw string isn't // already a Swift symbol; the result is reader-independent. - let result = try acrossAllReaders( - file: { names.file.symbolString }, - image: { names.image.symbolString } - ) + let result = try acrossAllReaders(names.file, names.image) { $0.symbolString } #expect(!result.isEmpty) } @Test func typeString() async throws { let names = try loadMangledNames() // typeString strips the prefix if present; reader-independent. - let result = try acrossAllReaders( - file: { names.file.typeString }, - image: { names.image.typeString } - ) + let result = try acrossAllReaders(names.file, names.image) { $0.typeString } #expect(!result.isEmpty) } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/BorrowTypeMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/BorrowTypeMetadataTests.swift index ad25f6021..5aeeb4e53 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/BorrowTypeMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/BorrowTypeMetadataTests.swift @@ -18,12 +18,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class BorrowTypeMetadataTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "BorrowTypeMetadata" - static var registeredTestMethodNames: Set { - BorrowTypeMetadataBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class BorrowTypeMetadataTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func offset() async throws { let metadata = BorrowTypeMetadata( layout: .init(kind: 0x309, referent: .init(address: 0)), diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/CanonicalSpecializedMetadataAccessorsListEntryTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/CanonicalSpecializedMetadataAccessorsListEntryTests.swift index e2edefa1e..96e508f41 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/CanonicalSpecializedMetadataAccessorsListEntryTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/CanonicalSpecializedMetadataAccessorsListEntryTests.swift @@ -18,12 +18,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class CanonicalSpecializedMetadataAccessorsListEntryTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "CanonicalSpecializedMetadataAccessorsListEntry" - static var registeredTestMethodNames: Set { - CanonicalSpecializedMetadataAccessorsListEntryBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class CanonicalSpecializedMetadataAccessorsListEntryTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// `offset` is set by the memberwise initialiser; cross-reader /// agreement is trivial (no MachO read is involved). @Test func offset() async throws { diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/CanonicalSpecializedMetadatasCachingOnceTokenTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/CanonicalSpecializedMetadatasCachingOnceTokenTests.swift index 1f5a630e5..1b311b8e0 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/CanonicalSpecializedMetadatasCachingOnceTokenTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/CanonicalSpecializedMetadatasCachingOnceTokenTests.swift @@ -15,12 +15,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class CanonicalSpecializedMetadatasCachingOnceTokenTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "CanonicalSpecializedMetadatasCachingOnceToken" - static var registeredTestMethodNames: Set { - CanonicalSpecializedMetadatasCachingOnceTokenBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class CanonicalSpecializedMetadatasCachingOnceTokenTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func offset() async throws { let token = CanonicalSpecializedMetadatasCachingOnceToken( layout: .init(token: .init(relativeOffset: 0)), diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/CanonicalSpecializedMetadatasListCountTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/CanonicalSpecializedMetadatasListCountTests.swift index 4493f7209..651c5a550 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/CanonicalSpecializedMetadatasListCountTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/CanonicalSpecializedMetadatasListCountTests.swift @@ -11,12 +11,8 @@ import SwiftSectionFixtureSupport /// `SymbolTestsCore` fixture declares no prespecializations, so the type is /// exercised via constant round-trip through `init(rawValue:)` / `rawValue`. @Suite -final class CanonicalSpecializedMetadatasListCountTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "CanonicalSpecializedMetadatasListCount" - static var registeredTestMethodNames: Set { - CanonicalSpecializedMetadatasListCountBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class CanonicalSpecializedMetadatasListCountTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// `init(rawValue:)` constructs the wrapper from a raw `UInt32`. @Test("init(rawValue:)") func initializerWithRawValue() async throws { let count = CanonicalSpecializedMetadatasListCount( diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/CanonicalSpecializedMetadatasListEntryTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/CanonicalSpecializedMetadatasListEntryTests.swift index 26a0db65f..509c990aa 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/CanonicalSpecializedMetadatasListEntryTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/CanonicalSpecializedMetadatasListEntryTests.swift @@ -13,12 +13,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class CanonicalSpecializedMetadatasListEntryTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "CanonicalSpecializedMetadatasListEntry" - static var registeredTestMethodNames: Set { - CanonicalSpecializedMetadatasListEntryBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class CanonicalSpecializedMetadatasListEntryTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func offset() async throws { let entry = CanonicalSpecializedMetadatasListEntry( layout: .init(metadata: .init(relativeOffset: 0)), diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/FixedArrayTypeMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/FixedArrayTypeMetadataTests.swift index ce3a4f1f9..855725230 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/FixedArrayTypeMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/FixedArrayTypeMetadataTests.swift @@ -16,12 +16,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class FixedArrayTypeMetadataTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "FixedArrayTypeMetadata" - static var registeredTestMethodNames: Set { - FixedArrayTypeMetadataBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class FixedArrayTypeMetadataTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func offset() async throws { let metadata = FixedArrayTypeMetadata( layout: .init(kind: 0x308, count: 0, element: .init(address: 0)), diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/FullMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/FullMetadataTests.swift index 26837d627..d54e37c53 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/FullMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/FullMetadataTests.swift @@ -19,12 +19,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class FullMetadataTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "FullMetadata" - static var registeredTestMethodNames: Set { - FullMetadataBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class FullMetadataTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Materialize a `FullMetadata` for `Structs.StructTest` /// from a MachOImage metadata accessor. private func loadFullStructMetadata() throws -> FullMetadata { diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/HeapMetadataHeaderPrefixTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/HeapMetadataHeaderPrefixTests.swift index c7f7529a3..af0d707e5 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/HeapMetadataHeaderPrefixTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/HeapMetadataHeaderPrefixTests.swift @@ -4,6 +4,7 @@ import MachOFoundation @testable import MachOSwiftSection @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import BinaryParseSupport /// Fixture-based Suite for `HeapMetadataHeaderPrefix`. /// @@ -24,12 +25,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class HeapMetadataHeaderPrefixTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "HeapMetadataHeaderPrefix" - static var registeredTestMethodNames: Set { - HeapMetadataHeaderPrefixBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class HeapMetadataHeaderPrefixTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Materialise a `HeapMetadataHeaderPrefix` for `Classes.ClassTest` from /// the loaded MachOImage. The class metadata is loaded as /// `ClassMetadataObjCInterop`; the heap-header prefix lives at diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/HeapMetadataHeaderTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/HeapMetadataHeaderTests.swift index 0bd74276a..fc387a48d 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/HeapMetadataHeaderTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/HeapMetadataHeaderTests.swift @@ -4,6 +4,7 @@ import MachOFoundation @testable import MachOSwiftSection @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import BinaryParseSupport /// Fixture-based Suite for `HeapMetadataHeader`. /// @@ -16,12 +17,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class HeapMetadataHeaderTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "HeapMetadataHeader" - static var registeredTestMethodNames: Set { - HeapMetadataHeaderBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class HeapMetadataHeaderTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Materialise a `HeapMetadataHeader` for `Classes.ClassTest` from the /// loaded MachOImage's metadata accessor. The class metadata is loaded /// as `ClassMetadataObjCInterop`; the heap header lives at diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/TypeMetadataHeaderBaseTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/TypeMetadataHeaderBaseTests.swift index 4b0349658..2fda78e1a 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/TypeMetadataHeaderBaseTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/TypeMetadataHeaderBaseTests.swift @@ -15,12 +15,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class TypeMetadataHeaderBaseTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "TypeMetadataHeaderBase" - static var registeredTestMethodNames: Set { - TypeMetadataHeaderBaseBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class TypeMetadataHeaderBaseTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func offset() async throws { let base = TypeMetadataHeaderBase( layout: .init(valueWitnesses: .init(address: 0)), diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/TypeMetadataHeaderTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/TypeMetadataHeaderTests.swift index c4d176165..22525bf28 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/TypeMetadataHeaderTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/TypeMetadataHeaderTests.swift @@ -16,12 +16,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class TypeMetadataHeaderTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "TypeMetadataHeader" - static var registeredTestMethodNames: Set { - TypeMetadataHeaderBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class TypeMetadataHeaderTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Materialise a `TypeMetadataHeader` for `Structs.StructTest` from /// the loaded MachOImage's metadata accessor via the full-metadata /// header projection. diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/TypeMetadataLayoutPrefixTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/TypeMetadataLayoutPrefixTests.swift index cb43f8f52..e0cdf694c 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/TypeMetadataLayoutPrefixTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/TypeMetadataLayoutPrefixTests.swift @@ -15,12 +15,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class TypeMetadataLayoutPrefixTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "TypeMetadataLayoutPrefix" - static var registeredTestMethodNames: Set { - TypeMetadataLayoutPrefixBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class TypeMetadataLayoutPrefixTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func offset() async throws { let prefix = TypeMetadataLayoutPrefix( layout: .init(layoutString: .init(address: 0)), diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataAccessorFunctionTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataAccessorFunctionTests.swift index ceab142f0..072ac7afc 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataAccessorFunctionTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataAccessorFunctionTests.swift @@ -20,12 +20,8 @@ import SwiftSectionFixtureSupport /// `init(ptr:)` is `package`-scoped and not visited by `PublicMemberScanner`; /// the six `callAsFunction` overloads collapse to a single `MethodKey`. @Suite -final class MetadataAccessorFunctionTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "MetadataAccessorFunction" - static var registeredTestMethodNames: Set { - MetadataAccessorFunctionBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class MetadataAccessorFunctionTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// `callAsFunction(request:)` invokes the accessor with no metadata or /// witness-table arguments and returns a complete metadata response. @Test func callAsFunction() async throws { diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataBoundsProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataBoundsProtocolTests.swift index e8d9545f8..7a87375b9 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataBoundsProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataBoundsProtocolTests.swift @@ -16,12 +16,8 @@ import SwiftSectionFixtureSupport /// `totalSizeInBytes = (neg + pos) * sizeof(UnsafeRawPointer)` /// `addressPointInBytes = neg * sizeof(UnsafeRawPointer)` @Suite -final class MetadataBoundsProtocolTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "MetadataBoundsProtocol" - static var registeredTestMethodNames: Set { - MetadataBoundsProtocolBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class MetadataBoundsProtocolTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func makeBounds() -> MetadataBounds { MetadataBounds( layout: .init( diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataBoundsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataBoundsTests.swift index 9de65fa26..89e0ea1f5 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataBoundsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataBoundsTests.swift @@ -17,12 +17,8 @@ import SwiftSectionFixtureSupport /// derived sizes (`totalSizeInBytes`, `addressPointInBytes`) are inherited /// from `MetadataBoundsProtocol` and covered by that Suite. @Suite -final class MetadataBoundsTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "MetadataBounds" - static var registeredTestMethodNames: Set { - MetadataBoundsBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class MetadataBoundsTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func offset() async throws { let bounds = MetadataBounds( layout: .init( diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataInitialization/ForeignMetadataInitializationTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataInitialization/ForeignMetadataInitializationTests.swift index 938a2c587..6780b6aeb 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataInitialization/ForeignMetadataInitializationTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataInitialization/ForeignMetadataInitializationTests.swift @@ -16,12 +16,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class ForeignMetadataInitializationTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ForeignMetadataInitialization" - static var registeredTestMethodNames: Set { - ForeignMetadataInitializationBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ForeignMetadataInitializationTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func offset() async throws { let initialization = ForeignMetadataInitialization( layout: .init(completionFunction: .init(relativeOffset: 0)), diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataInitialization/SingletonMetadataInitializationTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataInitialization/SingletonMetadataInitializationTests.swift index d6f6fe7ad..3b04bcf7e 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataInitialization/SingletonMetadataInitializationTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataInitialization/SingletonMetadataInitializationTests.swift @@ -15,12 +15,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class SingletonMetadataInitializationTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "SingletonMetadataInitialization" - static var registeredTestMethodNames: Set { - SingletonMetadataInitializationBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class SingletonMetadataInitializationTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Helper: load the picked class descriptor and its /// SingletonMetadataInitialization payload from both readers. private func loadInits() throws -> (file: SingletonMetadataInitialization, image: SingletonMetadataInitialization) { @@ -38,28 +34,16 @@ final class SingletonMetadataInitializationTests: MachOSwiftSectionFixtureTests, let inits = try loadInits() // Both readers must agree on the absolute offset within the // descriptor's trailing-objects layout. - let result = try acrossAllReaders( - file: { inits.file.offset }, - image: { inits.image.offset } - ) + let result = try acrossAllReaders(inits.file, inits.image) { $0.offset } #expect(result > 0) } @Test func layout() async throws { let inits = try loadInits() // Cross-reader equality on each of the three relative pointers. - let cacheOffset = try acrossAllReaders( - file: { inits.file.layout.initializationCacheOffset.relativeOffset }, - image: { inits.image.layout.initializationCacheOffset.relativeOffset } - ) - let incompleteOffset = try acrossAllReaders( - file: { inits.file.layout.incompleteMetadata.relativeOffset }, - image: { inits.image.layout.incompleteMetadata.relativeOffset } - ) - let completionOffset = try acrossAllReaders( - file: { inits.file.layout.completionFunction.relativeOffset }, - image: { inits.image.layout.completionFunction.relativeOffset } - ) + let cacheOffset = try acrossAllReaders(inits.file, inits.image) { $0.layout.initializationCacheOffset.relativeOffset } + let incompleteOffset = try acrossAllReaders(inits.file, inits.image) { $0.layout.incompleteMetadata.relativeOffset } + let completionOffset = try acrossAllReaders(inits.file, inits.image) { $0.layout.completionFunction.relativeOffset } // Recover the signed Int32 values from the UInt64 baseline bits. let expectedCache = Int32(truncatingIfNeeded: SingletonMetadataInitializationBaseline.firstSingletonInit.initializationCacheRelativeOffsetBits) @@ -73,16 +57,14 @@ final class SingletonMetadataInitializationTests: MachOSwiftSectionFixtureTests, // for this carrier, a class WITHOUT a resilient superclass, it holds // the incomplete metadata; `ResilientClassMetadataPatternTests` reads // the same word on a carrier where it is a pattern instead. - let resolvedIncomplete = try acrossAllReaders( - file: { inits.file.resolvedDirectOffset(from: \.incompleteMetadata) }, - image: { inits.image.resolvedDirectOffset(from: \.incompleteMetadata) } - ) + let resolvedIncomplete = try acrossAllReaders(inits.file, inits.image) { initialization in + initialization.resolvedDirectOffset(from: \.incompleteMetadata) + } #expect(resolvedIncomplete == SingletonMetadataInitializationBaseline.firstSingletonInit.incompleteMetadataOffset) - let resolvedCompletion = try acrossAllReaders( - file: { inits.file.resolvedDirectOffset(from: \.completionFunction) }, - image: { inits.image.resolvedDirectOffset(from: \.completionFunction) } - ) + let resolvedCompletion = try acrossAllReaders(inits.file, inits.image) { initialization in + initialization.resolvedDirectOffset(from: \.completionFunction) + } #expect(resolvedCompletion == SingletonMetadataInitializationBaseline.firstSingletonInit.completionFunctionOffset) } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataProtocolTests.swift index 2394bfb33..f81000117 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataProtocolTests.swift @@ -18,12 +18,8 @@ import SwiftSectionFixtureSupport /// accessor; `MachOFile` cannot invoke metadata accessors. Members are /// exercised via the carrier's imageContext / in-process paths. @Suite -final class MetadataProtocolTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "MetadataProtocol" - static var registeredTestMethodNames: Set { - MetadataProtocolBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class MetadataProtocolTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Materialise a `StructMetadata`-conforming carrier for /// `Structs.StructTest` from a MachOImage metadata accessor. private func loadStructTestStructMetadata() throws -> StructMetadata { diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataRequestTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataRequestTests.swift index 66165e08b..8e9da2d49 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataRequestTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataRequestTests.swift @@ -14,12 +14,8 @@ import SwiftSectionFixtureSupport /// (rather than `.sentinel`). The `InProcessContext` is unused; the /// assertions exercise the flag-set bit-packing accessors directly. @Suite -final class MetadataRequestTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "MetadataRequest" - static var registeredTestMethodNames: Set { - MetadataRequestBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class MetadataRequestTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Default `init()` produces a zero-valued request (`.complete` state, /// non-blocking). @Test("init") func defaultInitializer() async throws { diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataResponseTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataResponseTests.swift index 983deb0cc..52ae2b128 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataResponseTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataResponseTests.swift @@ -17,12 +17,8 @@ import SwiftSectionFixtureSupport /// **Reader asymmetry:** the response originates from MachOImage's accessor /// invocation; `MachOFile` cannot invoke runtime functions. @Suite -final class MetadataResponseTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "MetadataResponse" - static var registeredTestMethodNames: Set { - MetadataResponseBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class MetadataResponseTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadStructTestResponse() throws -> MetadataResponse { let descriptor = try BaselineFixturePicker.struct_StructTest(in: machOImage) let accessor = try required(try descriptor.metadataAccessorFunction(in: imageContext)) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataTests.swift index 384fc16a7..5080598e5 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataTests.swift @@ -18,12 +18,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class MetadataTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "Metadata" - static var registeredTestMethodNames: Set { - MetadataBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class MetadataTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Materialize a kind-erased `Metadata` for `Structs.StructTest`. private func loadStructTestMetadata() throws -> Metadata { let descriptor = try BaselineFixturePicker.struct_StructTest(in: machOImage) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataWrapperTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataWrapperTests.swift index 7c811a6a8..791a3bf0f 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataWrapperTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataWrapperTests.swift @@ -20,12 +20,8 @@ import SwiftSectionFixtureSupport /// metadata accessor (`StructTest.metadataAccessorFunction`); `MachOFile` /// cannot invoke runtime functions. @Suite -final class MetadataWrapperTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "MetadataWrapper" - static var registeredTestMethodNames: Set { - MetadataWrapperBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class MetadataWrapperTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Materialise an image-relative wrapper for the imageContext code /// paths. private func loadStructTestImageWrapper() throws -> MetadataWrapper { diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetatypeMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetatypeMetadataTests.swift index 3c62f0804..bb8f9d800 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetatypeMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetatypeMetadataTests.swift @@ -16,12 +16,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class MetatypeMetadataTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "MetatypeMetadata" - static var registeredTestMethodNames: Set { - MetatypeMetadataBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class MetatypeMetadataTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func layout() async throws { let resolved = try usingInProcessOnly { context in try MetatypeMetadata.resolve(at: InProcessMetadataPicker.stdlibIntMetatype, in: context) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/SingletonMetadataPointerTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/SingletonMetadataPointerTests.swift index c02546c6e..544de0a58 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/SingletonMetadataPointerTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/SingletonMetadataPointerTests.swift @@ -16,12 +16,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class SingletonMetadataPointerTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "SingletonMetadataPointer" - static var registeredTestMethodNames: Set { - SingletonMetadataPointerBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class SingletonMetadataPointerTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func offset() async throws { let pointer = SingletonMetadataPointer( layout: .init(metadata: .init(relativeOffset: 0)), diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Module/ModuleContextDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Module/ModuleContextDescriptorTests.swift index f65c42127..65a6238da 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Module/ModuleContextDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Module/ModuleContextDescriptorTests.swift @@ -13,20 +13,13 @@ import SwiftSectionFixtureSupport /// surface is exercised through the wrapper Suite (`ModuleContextTests`) /// to avoid duplicating coverage here. @Suite -final class ModuleContextDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ModuleContextDescriptor" - static var registeredTestMethodNames: Set { - ModuleContextDescriptorBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ModuleContextDescriptorTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func offset() async throws { let fileSubject = try BaselineFixturePicker.module_SymbolTestsCore(in: machOFile) let imageSubject = try BaselineFixturePicker.module_SymbolTestsCore(in: machOImage) - let result = try acrossAllReaders( - file: { fileSubject.offset }, - image: { imageSubject.offset } - ) + let result = try acrossAllReaders(fileSubject, imageSubject) { $0.offset } #expect(result == ModuleContextDescriptorBaseline.symbolTestsCore.offset) } @@ -34,10 +27,7 @@ final class ModuleContextDescriptorTests: MachOSwiftSectionFixtureTests, Fixture let fileSubject = try BaselineFixturePicker.module_SymbolTestsCore(in: machOFile) let imageSubject = try BaselineFixturePicker.module_SymbolTestsCore(in: machOImage) - let flagsRaw = try acrossAllReaders( - file: { fileSubject.layout.flags.rawValue }, - image: { imageSubject.layout.flags.rawValue } - ) + let flagsRaw = try acrossAllReaders(fileSubject, imageSubject) { $0.layout.flags.rawValue } #expect(flagsRaw == ModuleContextDescriptorBaseline.symbolTestsCore.layoutFlagsRawValue) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Module/ModuleContextTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Module/ModuleContextTests.swift index 96e7575dc..f41a29268 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Module/ModuleContextTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Module/ModuleContextTests.swift @@ -11,12 +11,8 @@ import SwiftSectionFixtureSupport /// `ModuleContext` only carries `descriptor` and `name`; `name` is a /// stable string literal we embed in the baseline. @Suite -final class ModuleContextTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ModuleContext" - static var registeredTestMethodNames: Set { - ModuleContextBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ModuleContextTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Helper: instantiate the `ModuleContext` wrapper for the /// `SymbolTestsCore` module against both readers. private func loadSymbolTestsCoreContexts() throws -> (file: ModuleContext, image: ModuleContext) { @@ -54,19 +50,13 @@ final class ModuleContextTests: MachOSwiftSectionFixtureTests, FixtureSuite, @un @Test func descriptor() async throws { let contexts = try loadSymbolTestsCoreContexts() - let descriptorOffsets = try acrossAllReaders( - file: { contexts.file.descriptor.offset }, - image: { contexts.image.descriptor.offset } - ) + let descriptorOffsets = try acrossAllReaders(contexts.file, contexts.image) { $0.descriptor.offset } #expect(descriptorOffsets == ModuleContextBaseline.symbolTestsCore.descriptorOffset) } @Test func name() async throws { let contexts = try loadSymbolTestsCoreContexts() - let result = try acrossAllReaders( - file: { contexts.file.name }, - image: { contexts.image.name } - ) + let result = try acrossAllReaders(contexts.file, contexts.image) { $0.name } #expect(result == ModuleContextBaseline.symbolTestsCore.name) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/OpaqueType/OpaqueMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/OpaqueType/OpaqueMetadataTests.swift index c43bda67d..2fc06bd75 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/OpaqueType/OpaqueMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/OpaqueType/OpaqueMetadataTests.swift @@ -13,12 +13,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class OpaqueMetadataTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "OpaqueMetadata" - static var registeredTestMethodNames: Set { - OpaqueMetadataBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class OpaqueMetadataTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func offset() async throws { let metadata = OpaqueMetadata( layout: .init(kind: 0x300), diff --git a/Tests/MachOSwiftSectionTests/Fixtures/OpaqueType/OpaqueTypeDescriptorProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/OpaqueType/OpaqueTypeDescriptorProtocolTests.swift index 39afc7d22..f46a67eae 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/OpaqueType/OpaqueTypeDescriptorProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/OpaqueType/OpaqueTypeDescriptorProtocolTests.swift @@ -16,12 +16,8 @@ import SwiftSectionFixtureSupport /// `OpaqueTypeDescriptor` instances whose `ContextDescriptorFlags` /// kind-specific bits encode known counts. @Suite -final class OpaqueTypeDescriptorProtocolTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "OpaqueTypeDescriptorProtocol" - static var registeredTestMethodNames: Set { - OpaqueTypeDescriptorProtocolBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class OpaqueTypeDescriptorProtocolTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func descriptor(withUnderlyingTypeArguments count: UInt16) -> OpaqueTypeDescriptor { // ContextDescriptorFlags kind in low 5 bits + kindSpecificFlagsRawValue // in upper 16 bits. We pack `count` into the upper 16 bits to diff --git a/Tests/MachOSwiftSectionTests/Fixtures/OpaqueType/OpaqueTypeDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/OpaqueType/OpaqueTypeDescriptorTests.swift index 43c6697f0..2c7301b6e 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/OpaqueType/OpaqueTypeDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/OpaqueType/OpaqueTypeDescriptorTests.swift @@ -13,12 +13,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class OpaqueTypeDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "OpaqueTypeDescriptor" - static var registeredTestMethodNames: Set { - OpaqueTypeDescriptorBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class OpaqueTypeDescriptorTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func syntheticDescriptor() -> OpaqueTypeDescriptor { OpaqueTypeDescriptor( layout: .init( diff --git a/Tests/MachOSwiftSectionTests/Fixtures/OpaqueType/OpaqueTypeFixtureTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/OpaqueType/OpaqueTypeFixtureTests.swift index 8fedfdcdc..4efd20086 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/OpaqueType/OpaqueTypeFixtureTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/OpaqueType/OpaqueTypeFixtureTests.swift @@ -15,12 +15,8 @@ import SwiftSectionFixtureSupport /// public surface and exercises members against a synthetic memberwise /// instance. @Suite -final class OpaqueTypeFixtureTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "OpaqueType" - static var registeredTestMethodNames: Set { - OpaqueTypeBaseline.registeredTestMethodNames - } - +@FixtureSuite(testedTypeName: "OpaqueType", baseline: OpaqueTypeBaseline.self) +final class OpaqueTypeFixtureTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Synthetic descriptor — flags layout uses /// `ContextDescriptorKind.opaqueType` (4) with no kind-specific /// flags, so `numUnderlyingTypeArguments == 0`. diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/Invertible/InvertibleProtocolSetTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/Invertible/InvertibleProtocolSetTests.swift index bfd1bb76e..f4e903be5 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/Invertible/InvertibleProtocolSetTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/Invertible/InvertibleProtocolSetTests.swift @@ -12,12 +12,8 @@ import SwiftSectionFixtureSupport /// `RequirementInSignature`), so the Suite exercises the accessors /// against the synthetic raw values embedded in the baseline. @Suite -final class InvertibleProtocolSetTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "InvertibleProtocolSet" - static var registeredTestMethodNames: Set { - InvertibleProtocolSetBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class InvertibleProtocolSetTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test("init(rawValue:)") func initializerWithRawValue() async throws { let set = InvertibleProtocolSet(rawValue: InvertibleProtocolSetBaseline.both.rawValue) #expect(set.rawValue == InvertibleProtocolSetBaseline.both.rawValue) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/Invertible/InvertibleProtocolsRequirementCountTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/Invertible/InvertibleProtocolsRequirementCountTests.swift index 20a73c213..c251fac98 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/Invertible/InvertibleProtocolsRequirementCountTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/Invertible/InvertibleProtocolsRequirementCountTests.swift @@ -12,12 +12,8 @@ import SwiftSectionFixtureSupport /// exercises the round-trip via the synthetic raw values embedded in /// the baseline. @Suite -final class InvertibleProtocolsRequirementCountTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "InvertibleProtocolsRequirementCount" - static var registeredTestMethodNames: Set { - InvertibleProtocolsRequirementCountBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class InvertibleProtocolsRequirementCountTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test("init(rawValue:)") func initializerWithRawValue() async throws { let zero = InvertibleProtocolsRequirementCount(rawValue: InvertibleProtocolsRequirementCountBaseline.zero.rawValue) #expect(zero.rawValue == InvertibleProtocolsRequirementCountBaseline.zero.rawValue) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ObjC/ObjCProtocolPrefixTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ObjC/ObjCProtocolPrefixTests.swift index 459cc2bdc..048cf6698 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ObjC/ObjCProtocolPrefixTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ObjC/ObjCProtocolPrefixTests.swift @@ -11,12 +11,8 @@ import SwiftSectionFixtureSupport /// `Protocols.ObjCInheritingProtocolTest: NSObjectProtocol` requirement, /// which surfaces an `ObjCProtocolPrefix` resolving to `NSObject`. @Suite -final class ObjCProtocolPrefixTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ObjCProtocolPrefix" - static var registeredTestMethodNames: Set { - ObjCProtocolPrefixBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ObjCProtocolPrefixTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadFirstPrefixes() throws -> (file: ObjCProtocolPrefix, image: ObjCProtocolPrefix) { let file = try BaselineFixturePicker.objcProtocolPrefix_first(in: machOFile) let image = try BaselineFixturePicker.objcProtocolPrefix_first(in: machOImage) @@ -49,10 +45,7 @@ final class ObjCProtocolPrefixTests: MachOSwiftSectionFixtureTests, FixtureSuite @Test func name() async throws { let (file, image) = try loadFirstPrefixes() - let result = try acrossAllContexts( - file: { try file.name(in: fileContext) }, - image: { try image.name(in: imageContext) } - ) + let result = try acrossAllContexts(file, image) { prefix, context in try prefix.name(in: context) } #expect(result == ObjCProtocolPrefixBaseline.firstPrefix.name) } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ObjC/RelativeObjCProtocolPrefixTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ObjC/RelativeObjCProtocolPrefixTests.swift index 304c808f8..96a84cd84 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ObjC/RelativeObjCProtocolPrefixTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ObjC/RelativeObjCProtocolPrefixTests.swift @@ -13,12 +13,8 @@ import SwiftSectionFixtureSupport /// (`offset`, `layout`, `mangledName`) for the Coverage Invariant test /// and documents the missing runtime coverage. @Suite -final class RelativeObjCProtocolPrefixTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "RelativeObjCProtocolPrefix" - static var registeredTestMethodNames: Set { - RelativeObjCProtocolPrefixBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class RelativeObjCProtocolPrefixTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func registrationOnly() async throws { // No live instance available in SymbolTestsCore; the Suite registers // the public surface (offset, layout, mangledName) for the Coverage diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolBaseRequirementTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolBaseRequirementTests.swift index 449139050..9406e1e31 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolBaseRequirementTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolBaseRequirementTests.swift @@ -12,12 +12,8 @@ import SwiftSectionFixtureSupport /// We pick a live instance via `Protocols.ProtocolWitnessTableTest`'s /// `baseRequirement` slot. @Suite -final class ProtocolBaseRequirementTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ProtocolBaseRequirement" - static var registeredTestMethodNames: Set { - ProtocolBaseRequirementBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ProtocolBaseRequirementTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadBaseRequirements() throws -> (file: ProtocolBaseRequirement, image: ProtocolBaseRequirement) { let fileDescriptor = try BaselineFixturePicker.protocol_ProtocolWitnessTableTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.protocol_ProtocolWitnessTableTest(in: machOImage) @@ -30,10 +26,7 @@ final class ProtocolBaseRequirementTests: MachOSwiftSectionFixtureTests, Fixture @Test func offset() async throws { let (file, image) = try loadBaseRequirements() - let result = try acrossAllReaders( - file: { file.offset }, - image: { image.offset } - ) + let result = try acrossAllReaders(file, image) { $0.offset } #expect(result == ProtocolBaseRequirementBaseline.witnessTableTest.offset) } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolContextDescriptorFlagsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolContextDescriptorFlagsTests.swift index 65c380888..e8948df13 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolContextDescriptorFlagsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolContextDescriptorFlagsTests.swift @@ -12,12 +12,8 @@ import SwiftSectionFixtureSupport /// We exercise it against `Protocols.ProtocolTest` whose kind-specific /// flags slot resolves to a real value. @Suite -final class ProtocolContextDescriptorFlagsTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ProtocolContextDescriptorFlags" - static var registeredTestMethodNames: Set { - ProtocolContextDescriptorFlagsBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ProtocolContextDescriptorFlagsTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadProtocolTestFlags() throws -> (file: ProtocolContextDescriptorFlags, image: ProtocolContextDescriptorFlags) { let fileDescriptor = try BaselineFixturePicker.protocol_ProtocolTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.protocol_ProtocolTest(in: machOImage) @@ -28,10 +24,7 @@ final class ProtocolContextDescriptorFlagsTests: MachOSwiftSectionFixtureTests, @Test func rawValue() async throws { let flags = try loadProtocolTestFlags() - let result = try acrossAllReaders( - file: { flags.file.rawValue }, - image: { flags.image.rawValue } - ) + let result = try acrossAllReaders(flags.file, flags.image) { $0.rawValue } #expect(result == ProtocolContextDescriptorFlagsBaseline.protocolTest.rawValue) } @@ -49,28 +42,19 @@ final class ProtocolContextDescriptorFlagsTests: MachOSwiftSectionFixtureTests, @Test func isResilient() async throws { let flags = try loadProtocolTestFlags() - let result = try acrossAllReaders( - file: { flags.file.isResilient }, - image: { flags.image.isResilient } - ) + let result = try acrossAllReaders(flags.file, flags.image) { $0.isResilient } #expect(result == ProtocolContextDescriptorFlagsBaseline.protocolTest.isResilient) } @Test func classConstraint() async throws { let flags = try loadProtocolTestFlags() - let result = try acrossAllReaders( - file: { flags.file.classConstraint.rawValue }, - image: { flags.image.classConstraint.rawValue } - ) + let result = try acrossAllReaders(flags.file, flags.image) { $0.classConstraint.rawValue } #expect(result == ProtocolContextDescriptorFlagsBaseline.protocolTest.classConstraintRawValue) } @Test func specialProtocolKind() async throws { let flags = try loadProtocolTestFlags() - let result = try acrossAllReaders( - file: { flags.file.specialProtocolKind?.rawValue }, - image: { flags.image.specialProtocolKind?.rawValue } - ) + let result = try acrossAllReaders(flags.file, flags.image) { $0.specialProtocolKind?.rawValue } #expect(result == ProtocolContextDescriptorFlagsBaseline.protocolTest.specialProtocolKindRawValue) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolDescriptorFlagsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolDescriptorFlagsTests.swift index 183b28116..7f70ce8ec 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolDescriptorFlagsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolDescriptorFlagsTests.swift @@ -12,12 +12,8 @@ import SwiftSectionFixtureSupport /// the Suite exercises the flag accessors against synthetic raw values /// embedded in the baseline. @Suite -final class ProtocolDescriptorFlagsTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ProtocolDescriptorFlags" - static var registeredTestMethodNames: Set { - ProtocolDescriptorFlagsBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ProtocolDescriptorFlagsTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test("init(rawValue:)") func initializerWithRawValue() async throws { let flags = ProtocolDescriptorFlags(rawValue: ProtocolDescriptorFlagsBaseline.swift.rawValue) #expect(flags.rawValue == ProtocolDescriptorFlagsBaseline.swift.rawValue) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolDescriptorRefTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolDescriptorRefTests.swift index fc079c5a0..340e85794 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolDescriptorRefTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolDescriptorRefTests.swift @@ -14,12 +14,8 @@ import SwiftSectionFixtureSupport /// from the baseline, plus exercises `name(in:)` end-to-end via the /// fixture's ObjC inheriting protocol. @Suite -final class ProtocolDescriptorRefTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ProtocolDescriptorRef" - static var registeredTestMethodNames: Set { - ProtocolDescriptorRefBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ProtocolDescriptorRefTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { // MARK: - Synthetic Swift / ObjC factories @Test("init(storage:)") func initializerWithStorage() async throws { diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolDescriptorTests.swift index f12a07435..f234f6464 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolDescriptorTests.swift @@ -13,12 +13,8 @@ import SwiftSectionFixtureSupport /// on `NamedContextDescriptorProtocol` and are exercised in Task 6 under /// `NamedContextDescriptorProtocolTests`. @Suite -final class ProtocolDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ProtocolDescriptor" - static var registeredTestMethodNames: Set { - ProtocolDescriptorBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ProtocolDescriptorTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadProtocolTestDescriptors() throws -> (file: ProtocolDescriptor, image: ProtocolDescriptor) { let file = try BaselineFixturePicker.protocol_ProtocolTest(in: machOFile) let image = try BaselineFixturePicker.protocol_ProtocolTest(in: machOImage) @@ -27,27 +23,15 @@ final class ProtocolDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite @Test func offset() async throws { let (file, image) = try loadProtocolTestDescriptors() - let result = try acrossAllReaders( - file: { file.offset }, - image: { image.offset } - ) + let result = try acrossAllReaders(file, image) { $0.offset } #expect(result == ProtocolDescriptorBaseline.protocolTest.offset) } @Test func layout() async throws { let (file, image) = try loadProtocolTestDescriptors() - let numRequirementsInSignature = try acrossAllReaders( - file: { file.layout.numRequirementsInSignature }, - image: { image.layout.numRequirementsInSignature } - ) - let numRequirements = try acrossAllReaders( - file: { file.layout.numRequirements }, - image: { image.layout.numRequirements } - ) - let flagsRaw = try acrossAllReaders( - file: { file.layout.flags.rawValue }, - image: { image.layout.flags.rawValue } - ) + let numRequirementsInSignature = try acrossAllReaders(file, image) { $0.layout.numRequirementsInSignature } + let numRequirements = try acrossAllReaders(file, image) { $0.layout.numRequirements } + let flagsRaw = try acrossAllReaders(file, image) { $0.layout.flags.rawValue } #expect(numRequirementsInSignature == ProtocolDescriptorBaseline.protocolTest.layoutNumRequirementsInSignature) #expect(numRequirements == ProtocolDescriptorBaseline.protocolTest.layoutNumRequirements) @@ -60,10 +44,7 @@ final class ProtocolDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite /// the ReadingContext overload over both readers here. @Test func associatedTypes() async throws { let (file, image) = try loadProtocolTestDescriptors() - let result = try acrossAllContexts( - file: { try file.associatedTypes(in: fileContext) }, - image: { try image.associatedTypes(in: imageContext) } - ) + let result = try acrossAllContexts(file, image) { descriptor, context in try descriptor.associatedTypes(in: context) } #expect(result == ProtocolDescriptorBaseline.protocolTest.associatedTypes) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolRecordTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolRecordTests.swift index c571eefa3..78d1cbc1d 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolRecordTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolRecordTests.swift @@ -11,12 +11,8 @@ import SwiftSectionFixtureSupport /// `__swift5_protos` section. We pick the first record from the fixture /// and verify its offset and resolved descriptor offset/name. @Suite -final class ProtocolRecordTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ProtocolRecord" - static var registeredTestMethodNames: Set { - ProtocolRecordBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ProtocolRecordTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadFirstRecords() throws -> (file: ProtocolRecord, image: ProtocolRecord) { let file = try BaselineFixturePicker.protocolRecord_first(in: machOFile) let image = try BaselineFixturePicker.protocolRecord_first(in: machOImage) @@ -25,10 +21,7 @@ final class ProtocolRecordTests: MachOSwiftSectionFixtureTests, FixtureSuite, @u @Test func offset() async throws { let (file, image) = try loadFirstRecords() - let result = try acrossAllReaders( - file: { file.offset }, - image: { image.offset } - ) + let result = try acrossAllReaders(file, image) { $0.offset } #expect(result == ProtocolRecordBaseline.firstRecord.offset) } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolRequirementFlagsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolRequirementFlagsTests.swift index aac9fee00..5dc7222bd 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolRequirementFlagsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolRequirementFlagsTests.swift @@ -13,12 +13,8 @@ import SwiftSectionFixtureSupport /// for the `kind = .method` branch and synthetic raw values for the /// remaining branches. @Suite -final class ProtocolRequirementFlagsTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ProtocolRequirementFlags" - static var registeredTestMethodNames: Set { - ProtocolRequirementFlagsBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ProtocolRequirementFlagsTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadFirstRequirementFlags() throws -> (file: ProtocolRequirementFlags, image: ProtocolRequirementFlags) { let fileDescriptor = try BaselineFixturePicker.protocol_ProtocolWitnessTableTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.protocol_ProtocolWitnessTableTest(in: machOImage) @@ -36,28 +32,19 @@ final class ProtocolRequirementFlagsTests: MachOSwiftSectionFixtureTests, Fixtur @Test func rawValue() async throws { let (file, image) = try loadFirstRequirementFlags() - let result = try acrossAllReaders( - file: { file.rawValue }, - image: { image.rawValue } - ) + let result = try acrossAllReaders(file, image) { $0.rawValue } #expect(result == ProtocolRequirementFlagsBaseline.witnessTableMethod.rawValue) } @Test func kind() async throws { let (file, image) = try loadFirstRequirementFlags() - let result = try acrossAllReaders( - file: { file.kind?.rawValue }, - image: { image.kind?.rawValue } - ) + let result = try acrossAllReaders(file, image) { $0.kind?.rawValue } #expect(result == ProtocolRequirementFlagsBaseline.witnessTableMethod.kindRawValue) } @Test func isCoroutine() async throws { let (file, image) = try loadFirstRequirementFlags() - let result = try acrossAllReaders( - file: { file.isCoroutine }, - image: { image.isCoroutine } - ) + let result = try acrossAllReaders(file, image) { $0.isCoroutine } #expect(result == ProtocolRequirementFlagsBaseline.witnessTableMethod.isCoroutine) // Synthetic: read coroutine kind sets isCoroutine. @@ -67,10 +54,7 @@ final class ProtocolRequirementFlagsTests: MachOSwiftSectionFixtureTests, Fixtur @Test func isAsync() async throws { let (file, image) = try loadFirstRequirementFlags() - let result = try acrossAllReaders( - file: { file.isAsync }, - image: { image.isAsync } - ) + let result = try acrossAllReaders(file, image) { $0.isAsync } #expect(result == ProtocolRequirementFlagsBaseline.witnessTableMethod.isAsync) // Synthetic: method + maybeAsync sets isAsync. @@ -80,10 +64,7 @@ final class ProtocolRequirementFlagsTests: MachOSwiftSectionFixtureTests, Fixtur @Test func isInstance() async throws { let (file, image) = try loadFirstRequirementFlags() - let result = try acrossAllReaders( - file: { file.isInstance }, - image: { image.isInstance } - ) + let result = try acrossAllReaders(file, image) { $0.isInstance } #expect(result == ProtocolRequirementFlagsBaseline.witnessTableMethod.isInstance) } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolRequirementKindTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolRequirementKindTests.swift index 434fb2596..ce36b7dca 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolRequirementKindTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolRequirementKindTests.swift @@ -11,12 +11,8 @@ import SwiftSectionFixtureSupport /// themselves are out of scope for `PublicMemberScanner`. We assert the /// description string for every case to exercise the switch coverage. @Suite -final class ProtocolRequirementKindTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ProtocolRequirementKind" - static var registeredTestMethodNames: Set { - ProtocolRequirementKindBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ProtocolRequirementKindTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func description() async throws { #expect(ProtocolRequirementKind.baseProtocol.description == ProtocolRequirementKindBaseline.baseProtocolDescription) #expect(ProtocolRequirementKind.method.description == ProtocolRequirementKindBaseline.methodDescription) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolRequirementTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolRequirementTests.swift index 20350d1af..2f09fc89a 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolRequirementTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolRequirementTests.swift @@ -18,12 +18,8 @@ import SwiftSectionFixtureSupport /// `ProtocolBaseRequirement` (the second struct in the same file) gets /// its own Suite (`ProtocolBaseRequirementTests`). @Suite -final class ProtocolRequirementTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ProtocolRequirement" - static var registeredTestMethodNames: Set { - ProtocolRequirementBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ProtocolRequirementTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadFirstRequirements() throws -> (file: ProtocolRequirement, image: ProtocolRequirement) { let fileDescriptor = try BaselineFixturePicker.protocol_ProtocolWitnessTableTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.protocol_ProtocolWitnessTableTest(in: machOImage) @@ -46,19 +42,13 @@ final class ProtocolRequirementTests: MachOSwiftSectionFixtureTests, FixtureSuit @Test func offset() async throws { let (file, image) = try loadFirstRequirements() - let result = try acrossAllReaders( - file: { file.offset }, - image: { image.offset } - ) + let result = try acrossAllReaders(file, image) { $0.offset } #expect(result == ProtocolRequirementBaseline.firstRequirement.offset) } @Test func layout() async throws { let (file, image) = try loadFirstRequirements() - let result = try acrossAllReaders( - file: { file.layout.flags.rawValue }, - image: { image.layout.flags.rawValue } - ) + let result = try acrossAllReaders(file, image) { $0.layout.flags.rawValue } #expect(result == ProtocolRequirementBaseline.firstRequirement.layoutFlagsRawValue) } @@ -67,18 +57,12 @@ final class ProtocolRequirementTests: MachOSwiftSectionFixtureTests, FixtureSuit /// real offset for a defaulted one — and identical across readers. @Test func defaultImplementationOffset() async throws { let (file, image) = try loadFirstRequirements() - let result = try acrossAllReaders( - file: { file.defaultImplementationOffset }, - image: { image.defaultImplementationOffset } - ) + let result = try acrossAllReaders(file, image) { $0.defaultImplementationOffset } #expect(result == nil) #expect(result == ProtocolRequirementBaseline.firstRequirement.defaultImplementationOffset) let (defaultedFile, defaultedImage) = try loadFirstDefaultedRequirements() - let defaultedResult = try acrossAllReaders( - file: { defaultedFile.defaultImplementationOffset }, - image: { defaultedImage.defaultImplementationOffset } - ) + let defaultedResult = try acrossAllReaders(defaultedFile, defaultedImage) { $0.defaultImplementationOffset } #expect(defaultedResult != nil) #expect(defaultedResult == ProtocolRequirementBaseline.firstDefaultedRequirement.defaultImplementationOffset) // The literal is the resolved target, never the pointer field's own diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolTests.swift index 282f6cc10..246432478 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolTests.swift @@ -13,12 +13,8 @@ import SwiftSectionFixtureSupport /// `Protocols.ProtocolWitnessTableTest` (5 method requirements, no /// requirement-in-signature). @Suite -final class ProtocolTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "Protocol" - static var registeredTestMethodNames: Set { - ProtocolBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ProtocolTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadProtocolTestProtocols() throws -> (file: MachOSwiftSection.`Protocol`, image: MachOSwiftSection.`Protocol`) { let fileDescriptor = try BaselineFixturePicker.protocol_ProtocolTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.protocol_ProtocolTest(in: machOImage) @@ -39,55 +35,37 @@ final class ProtocolTests: MachOSwiftSectionFixtureTests, FixtureSuite, @uncheck @Test func name() async throws { let (file, image) = try loadProtocolTestProtocols() - let result = try acrossAllReaders( - file: { file.name }, - image: { image.name } - ) + let result = try acrossAllReaders(file, image) { $0.name } #expect(result == ProtocolBaseline.protocolTest.name) } @Test func descriptor() async throws { let (file, image) = try loadProtocolTestProtocols() - let result = try acrossAllReaders( - file: { file.descriptor.offset }, - image: { image.descriptor.offset } - ) + let result = try acrossAllReaders(file, image) { $0.descriptor.offset } #expect(result == ProtocolBaseline.protocolTest.descriptorOffset) } @Test func protocolFlags() async throws { let (file, image) = try loadProtocolTestProtocols() - let result = try acrossAllReaders( - file: { file.protocolFlags.rawValue }, - image: { image.protocolFlags.rawValue } - ) + let result = try acrossAllReaders(file, image) { $0.protocolFlags.rawValue } #expect(result == ProtocolBaseline.protocolTest.protocolFlagsRawValue) } @Test func baseRequirement() async throws { let (file, image) = try loadProtocolTestProtocols() - let result = try acrossAllReaders( - file: { file.baseRequirement != nil }, - image: { image.baseRequirement != nil } - ) + let result = try acrossAllReaders(file, image) { $0.baseRequirement != nil } #expect(result == ProtocolBaseline.protocolTest.hasBaseRequirement) } @Test func requirementInSignatures() async throws { let (file, image) = try loadProtocolTestProtocols() - let result = try acrossAllReaders( - file: { file.requirementInSignatures.count }, - image: { image.requirementInSignatures.count } - ) + let result = try acrossAllReaders(file, image) { $0.requirementInSignatures.count } #expect(result == ProtocolBaseline.protocolTest.requirementInSignaturesCount) } @Test func requirements() async throws { let (file, image) = try loadWitnessTableTestProtocols() - let result = try acrossAllReaders( - file: { file.requirements.count }, - image: { image.requirements.count } - ) + let result = try acrossAllReaders(file, image) { $0.requirements.count } #expect(result == ProtocolBaseline.protocolWitnessTableTest.requirementsCount) } @@ -95,19 +73,13 @@ final class ProtocolTests: MachOSwiftSectionFixtureTests, FixtureSuite, @uncheck @Test func numberOfRequirements() async throws { let (file, image) = try loadWitnessTableTestProtocols() - let result = try acrossAllReaders( - file: { file.numberOfRequirements }, - image: { image.numberOfRequirements } - ) + let result = try acrossAllReaders(file, image) { $0.numberOfRequirements } #expect(result == ProtocolBaseline.protocolWitnessTableTest.numberOfRequirements) } @Test func numberOfRequirementsInSignature() async throws { let (file, image) = try loadProtocolTestProtocols() - let result = try acrossAllReaders( - file: { file.numberOfRequirementsInSignature }, - image: { image.numberOfRequirementsInSignature } - ) + let result = try acrossAllReaders(file, image) { $0.numberOfRequirementsInSignature } #expect(result == ProtocolBaseline.protocolTest.numberOfRequirementsInSignature) } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolWitnessTableTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolWitnessTableTests.swift index 6869cd005..c47ded713 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolWitnessTableTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolWitnessTableTests.swift @@ -13,12 +13,8 @@ import SwiftSectionFixtureSupport /// `ProtocolConformance` in the fixture that surfaces one and verify /// the offset equals the baseline. @Suite -final class ProtocolWitnessTableTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ProtocolWitnessTable" - static var registeredTestMethodNames: Set { - ProtocolWitnessTableBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ProtocolWitnessTableTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadFirstWitnessTables() throws -> (file: ProtocolWitnessTable, image: ProtocolWitnessTable) { let fileConformance = try required( try machOFile.swift.protocolConformances.first(where: { $0.witnessTablePattern != nil }) @@ -33,10 +29,7 @@ final class ProtocolWitnessTableTests: MachOSwiftSectionFixtureTests, FixtureSui @Test func offset() async throws { let (file, image) = try loadFirstWitnessTables() - let result = try acrossAllReaders( - file: { file.offset }, - image: { image.offset } - ) + let result = try acrossAllReaders(file, image) { $0.offset } #expect(result == ProtocolWitnessTableBaseline.firstWitnessTable.offset) } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ResilientWitnessTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ResilientWitnessTests.swift index 5f80acdde..3bf2f70e5 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ResilientWitnessTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ResilientWitnessTests.swift @@ -16,12 +16,8 @@ import SwiftSectionFixtureSupport /// MachO-only debug formatter `implementationAddressString(in:)` must /// produce a non-empty hex string. @Suite -final class ResilientWitnessTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ResilientWitness" - static var registeredTestMethodNames: Set { - ResilientWitnessBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ResilientWitnessTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadFirstWitnesses() throws -> (file: ResilientWitness, image: ResilientWitness) { let fileConformance = try BaselineFixturePicker.protocolConformance_resilientWitnessFirst(in: machOFile) let imageConformance = try BaselineFixturePicker.protocolConformance_resilientWitnessFirst(in: machOImage) @@ -32,10 +28,7 @@ final class ResilientWitnessTests: MachOSwiftSectionFixtureTests, FixtureSuite, @Test func offset() async throws { let (file, image) = try loadFirstWitnesses() - let result = try acrossAllReaders( - file: { file.offset }, - image: { image.offset } - ) + let result = try acrossAllReaders(file, image) { $0.offset } #expect(result == ResilientWitnessBaseline.firstWitness.offset) } @@ -50,19 +43,13 @@ final class ResilientWitnessTests: MachOSwiftSectionFixtureTests, FixtureSuite, @Test func requirement() async throws { let (file, image) = try loadFirstWitnesses() - let result = try acrossAllContexts( - file: { (try file.requirement(in: fileContext)) != nil }, - image: { (try image.requirement(in: imageContext)) != nil } - ) + let result = try acrossAllContexts(file, image) { witness, context in (try witness.requirement(in: context)) != nil } #expect(result == ResilientWitnessBaseline.firstWitness.hasRequirement) } @Test func implementationOffset() async throws { let (file, image) = try loadFirstWitnesses() - let result = try acrossAllReaders( - file: { file.implementationOffset }, - image: { image.implementationOffset } - ) + let result = try acrossAllReaders(file, image) { $0.implementationOffset } #expect(result == ResilientWitnessBaseline.firstWitness.implementationOffset) } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ResilientWitnessesHeaderTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ResilientWitnessesHeaderTests.swift index 025627642..3f4056dd9 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ResilientWitnessesHeaderTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ResilientWitnessesHeaderTests.swift @@ -10,12 +10,8 @@ import SwiftSectionFixtureSupport /// Picker: the first `ProtocolConformance` from the fixture with a /// non-empty `resilientWitnesses` array (so the header materializes). @Suite -final class ResilientWitnessesHeaderTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ResilientWitnessesHeader" - static var registeredTestMethodNames: Set { - ResilientWitnessesHeaderBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ResilientWitnessesHeaderTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadFirstHeaders() throws -> (file: ResilientWitnessesHeader, image: ResilientWitnessesHeader) { let fileConformance = try BaselineFixturePicker.protocolConformance_resilientWitnessFirst(in: machOFile) let imageConformance = try BaselineFixturePicker.protocolConformance_resilientWitnessFirst(in: machOImage) @@ -26,19 +22,13 @@ final class ResilientWitnessesHeaderTests: MachOSwiftSectionFixtureTests, Fixtur @Test func offset() async throws { let (file, image) = try loadFirstHeaders() - let result = try acrossAllReaders( - file: { file.offset }, - image: { image.offset } - ) + let result = try acrossAllReaders(file, image) { $0.offset } #expect(result == ResilientWitnessesHeaderBaseline.firstHeader.offset) } @Test func layout() async throws { let (file, image) = try loadFirstHeaders() - let result = try acrossAllReaders( - file: { file.layout.numWitnesses }, - image: { image.layout.numWitnesses } - ) + let result = try acrossAllReaders(file, image) { $0.layout.numWitnesses } #expect(result == ResilientWitnessesHeaderBaseline.firstHeader.layoutNumWitnesses) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ProtocolConformance/GlobalActorReferenceTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ProtocolConformance/GlobalActorReferenceTests.swift index dba9dbce4..5246de535 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ProtocolConformance/GlobalActorReferenceTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ProtocolConformance/GlobalActorReferenceTests.swift @@ -19,12 +19,8 @@ import SwiftSectionFixtureSupport /// collapses to a single MethodKey under PublicMemberScanner's name-based /// deduplication; the Suite exercises both reader paths. @Suite -final class GlobalActorReferenceTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "GlobalActorReference" - static var registeredTestMethodNames: Set { - GlobalActorReferenceBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class GlobalActorReferenceTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadFirstReferences() throws -> (file: GlobalActorReference, image: GlobalActorReference) { let fileConformance = try BaselineFixturePicker.protocolConformance_globalActorFirst(in: machOFile) let imageConformance = try BaselineFixturePicker.protocolConformance_globalActorFirst(in: machOImage) @@ -35,10 +31,7 @@ final class GlobalActorReferenceTests: MachOSwiftSectionFixtureTests, FixtureSui @Test func offset() async throws { let (file, image) = try loadFirstReferences() - let result = try acrossAllReaders( - file: { file.offset }, - image: { image.offset } - ) + let result = try acrossAllReaders(file, image) { $0.offset } #expect(result == GlobalActorReferenceBaseline.firstReference.offset) } @@ -57,10 +50,7 @@ final class GlobalActorReferenceTests: MachOSwiftSectionFixtureTests, FixtureSui /// overload over both readers here. @Test func typeName() async throws { let (file, image) = try loadFirstReferences() - let result = try acrossAllContexts( - file: { try file.typeName(in: fileContext).symbolString }, - image: { try image.typeName(in: imageContext).symbolString } - ) + let result = try acrossAllContexts(file, image) { reference, context in try reference.typeName(in: context).symbolString } #expect(result == GlobalActorReferenceBaseline.firstReference.typeNameSymbolString) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ProtocolConformance/ProtocolConformanceDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ProtocolConformance/ProtocolConformanceDescriptorTests.swift index f767935f3..fc84a5055 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ProtocolConformance/ProtocolConformanceDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ProtocolConformance/ProtocolConformanceDescriptorTests.swift @@ -22,12 +22,8 @@ import SwiftSectionFixtureSupport /// — non-retroactive, no global-actor isolation, simplest path with a /// resolvable witness table and a `directTypeDescriptor` type reference. @Suite -final class ProtocolConformanceDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ProtocolConformanceDescriptor" - static var registeredTestMethodNames: Set { - ProtocolConformanceDescriptorBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ProtocolConformanceDescriptorTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadStructTestProtocolTestDescriptors() throws -> (file: ProtocolConformanceDescriptor, image: ProtocolConformanceDescriptor) { let fileConformance = try BaselineFixturePicker.protocolConformance_StructTestProtocolTest(in: machOFile) let imageConformance = try BaselineFixturePicker.protocolConformance_StructTestProtocolTest(in: machOImage) @@ -36,19 +32,13 @@ final class ProtocolConformanceDescriptorTests: MachOSwiftSectionFixtureTests, F @Test func offset() async throws { let (file, image) = try loadStructTestProtocolTestDescriptors() - let result = try acrossAllReaders( - file: { file.offset }, - image: { image.offset } - ) + let result = try acrossAllReaders(file, image) { $0.offset } #expect(result == ProtocolConformanceDescriptorBaseline.structTestProtocolTest.offset) } @Test func layout() async throws { let (file, image) = try loadStructTestProtocolTestDescriptors() - let flagsRawValue = try acrossAllReaders( - file: { file.layout.flags.rawValue }, - image: { image.layout.flags.rawValue } - ) + let flagsRawValue = try acrossAllReaders(file, image) { $0.layout.flags.rawValue } #expect(flagsRawValue == ProtocolConformanceDescriptorBaseline.structTestProtocolTest.layoutFlagsRawValue) } @@ -56,10 +46,7 @@ final class ProtocolConformanceDescriptorTests: MachOSwiftSectionFixtureTests, F /// `layout.flags.typeReferenceKind` + `layout.typeReference`. @Test func typeReference() async throws { let (file, image) = try loadStructTestProtocolTestDescriptors() - let kindRawValue = try acrossAllReaders( - file: { file.layout.flags.typeReferenceKind?.rawValue }, - image: { image.layout.flags.typeReferenceKind?.rawValue } - ) + let kindRawValue = try acrossAllReaders(file, image) { $0.layout.flags.typeReferenceKind?.rawValue } #expect(kindRawValue == ProtocolConformanceDescriptorBaseline.structTestProtocolTest.typeReferenceKindRawValue) // The TypeReference enum case must match the kind. @@ -77,10 +64,9 @@ final class ProtocolConformanceDescriptorTests: MachOSwiftSectionFixtureTests, F /// here. @Test func protocolDescriptor() async throws { let (file, image) = try loadStructTestProtocolTestDescriptors() - let result = try acrossAllContexts( - file: { (try file.protocolDescriptor(in: fileContext)) != nil }, - image: { (try image.protocolDescriptor(in: imageContext)) != nil } - ) + let result = try acrossAllContexts(file, image) { descriptor, context in + (try descriptor.protocolDescriptor(in: context)) != nil + } #expect(result == ProtocolConformanceDescriptorBaseline.structTestProtocolTest.hasProtocolDescriptor) } @@ -110,10 +96,9 @@ final class ProtocolConformanceDescriptorTests: MachOSwiftSectionFixtureTests, F /// here. @Test func witnessTablePattern() async throws { let (file, image) = try loadStructTestProtocolTestDescriptors() - let result = try acrossAllContexts( - file: { (try file.witnessTablePattern(in: fileContext)) != nil }, - image: { (try image.witnessTablePattern(in: imageContext)) != nil } - ) + let result = try acrossAllContexts(file, image) { descriptor, context in + (try descriptor.witnessTablePattern(in: context)) != nil + } #expect(result == ProtocolConformanceDescriptorBaseline.structTestProtocolTest.hasWitnessTablePattern) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ProtocolConformance/ProtocolConformanceFlagsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ProtocolConformance/ProtocolConformanceFlagsTests.swift index c7cdc2219..7d5175cf6 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ProtocolConformance/ProtocolConformanceFlagsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ProtocolConformance/ProtocolConformanceFlagsTests.swift @@ -13,12 +13,8 @@ import SwiftSectionFixtureSupport /// asserts each accessor against the baseline literal — this validates both /// the bitfield parsing and the `init(rawValue:)`/`rawValue` round-trip. @Suite -final class ProtocolConformanceFlagsTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ProtocolConformanceFlags" - static var registeredTestMethodNames: Set { - ProtocolConformanceFlagsBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ProtocolConformanceFlagsTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test("init(rawValue:)") func initializerWithRawValue() async throws { let flags = ProtocolConformanceFlags(rawValue: ProtocolConformanceFlagsBaseline.structTestProtocolTest.rawValue) #expect(flags.rawValue == ProtocolConformanceFlagsBaseline.structTestProtocolTest.rawValue) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ProtocolConformance/ProtocolConformanceTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ProtocolConformance/ProtocolConformanceTests.swift index 2f894c46d..e580092ed 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ProtocolConformance/ProtocolConformanceTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ProtocolConformance/ProtocolConformanceTests.swift @@ -25,12 +25,8 @@ import SwiftSectionFixtureSupport /// - The first resilient-witness conformance — surfaces /// `resilientWitnessesHeader` and `resilientWitnesses`. @Suite -final class ProtocolConformanceTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ProtocolConformance" - static var registeredTestMethodNames: Set { - ProtocolConformanceBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ProtocolConformanceTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadStructTestProtocolTest() throws -> (file: ProtocolConformance, image: ProtocolConformance) { let file = try BaselineFixturePicker.protocolConformance_StructTestProtocolTest(in: machOFile) let image = try BaselineFixturePicker.protocolConformance_StructTestProtocolTest(in: machOImage) @@ -59,28 +55,19 @@ final class ProtocolConformanceTests: MachOSwiftSectionFixtureTests, FixtureSuit @Test func descriptor() async throws { let (file, image) = try loadStructTestProtocolTest() - let result = try acrossAllReaders( - file: { file.descriptor.offset }, - image: { image.descriptor.offset } - ) + let result = try acrossAllReaders(file, image) { $0.descriptor.offset } #expect(result == ProtocolConformanceBaseline.structTestProtocolTest.descriptorOffset) } @Test func flags() async throws { let (file, image) = try loadStructTestProtocolTest() - let result = try acrossAllReaders( - file: { file.flags.rawValue }, - image: { image.flags.rawValue } - ) + let result = try acrossAllReaders(file, image) { $0.flags.rawValue } #expect(result == ProtocolConformanceBaseline.structTestProtocolTest.flagsRawValue) } @Test("protocol") func conformedProtocol() async throws { let (file, image) = try loadStructTestProtocolTest() - let result = try acrossAllReaders( - file: { file.protocol != nil }, - image: { image.protocol != nil } - ) + let result = try acrossAllReaders(file, image) { $0.protocol != nil } #expect(result == ProtocolConformanceBaseline.structTestProtocolTest.hasProtocol) } @@ -101,19 +88,13 @@ final class ProtocolConformanceTests: MachOSwiftSectionFixtureTests, FixtureSuit @Test func witnessTablePattern() async throws { let (file, image) = try loadStructTestProtocolTest() - let result = try acrossAllReaders( - file: { file.witnessTablePattern != nil }, - image: { image.witnessTablePattern != nil } - ) + let result = try acrossAllReaders(file, image) { $0.witnessTablePattern != nil } #expect(result == ProtocolConformanceBaseline.structTestProtocolTest.hasWitnessTablePattern) } @Test func retroactiveContextDescriptor() async throws { let (file, image) = try loadStructTestProtocolTest() - let result = try acrossAllReaders( - file: { file.retroactiveContextDescriptor != nil }, - image: { image.retroactiveContextDescriptor != nil } - ) + let result = try acrossAllReaders(file, image) { $0.retroactiveContextDescriptor != nil } #expect(result == ProtocolConformanceBaseline.structTestProtocolTest.hasRetroactiveContextDescriptor) } @@ -121,55 +102,37 @@ final class ProtocolConformanceTests: MachOSwiftSectionFixtureTests, FixtureSuit @Test func conditionalRequirements() async throws { let (file, image) = try loadConditionalFirst() - let result = try acrossAllReaders( - file: { file.conditionalRequirements.count }, - image: { image.conditionalRequirements.count } - ) + let result = try acrossAllReaders(file, image) { $0.conditionalRequirements.count } #expect(result == ProtocolConformanceBaseline.conditionalFirst.conditionalRequirementsCount) } @Test func conditionalPackShapeDescriptors() async throws { let (file, image) = try loadStructTestProtocolTest() - let result = try acrossAllReaders( - file: { file.conditionalPackShapeDescriptors.count }, - image: { image.conditionalPackShapeDescriptors.count } - ) + let result = try acrossAllReaders(file, image) { $0.conditionalPackShapeDescriptors.count } #expect(result == ProtocolConformanceBaseline.structTestProtocolTest.conditionalPackShapeDescriptorsCount) } @Test func resilientWitnessesHeader() async throws { let (file, image) = try loadResilientFirst() - let result = try acrossAllReaders( - file: { file.resilientWitnessesHeader != nil }, - image: { image.resilientWitnessesHeader != nil } - ) + let result = try acrossAllReaders(file, image) { $0.resilientWitnessesHeader != nil } #expect(result == ProtocolConformanceBaseline.resilientFirst.hasResilientWitnessesHeader) } @Test func resilientWitnesses() async throws { let (file, image) = try loadResilientFirst() - let result = try acrossAllReaders( - file: { file.resilientWitnesses.count }, - image: { image.resilientWitnesses.count } - ) + let result = try acrossAllReaders(file, image) { $0.resilientWitnesses.count } #expect(result == ProtocolConformanceBaseline.resilientFirst.resilientWitnessesCount) } @Test func genericWitnessTable() async throws { let (file, image) = try loadStructTestProtocolTest() - let result = try acrossAllReaders( - file: { file.genericWitnessTable != nil }, - image: { image.genericWitnessTable != nil } - ) + let result = try acrossAllReaders(file, image) { $0.genericWitnessTable != nil } #expect(result == ProtocolConformanceBaseline.structTestProtocolTest.hasGenericWitnessTable) } @Test func globalActorReference() async throws { let (file, image) = try loadGlobalActorFirst() - let result = try acrossAllReaders( - file: { file.globalActorReference != nil }, - image: { image.globalActorReference != nil } - ) + let result = try acrossAllReaders(file, image) { $0.globalActorReference != nil } #expect(result == ProtocolConformanceBaseline.globalActorFirst.hasGlobalActorReference) } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/TupleType/TupleTypeMetadataElementTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/TupleType/TupleTypeMetadataElementTests.swift index 71c100be4..f27e48407 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/TupleType/TupleTypeMetadataElementTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/TupleType/TupleTypeMetadataElementTests.swift @@ -18,12 +18,8 @@ import SwiftSectionFixtureSupport /// keys nested types by their inner struct name, so the /// `testedTypeName` here is `"Element"`. @Suite -final class TupleTypeMetadataElementTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "Element" - static var registeredTestMethodNames: Set { - TupleTypeMetadataElementBaseline.registeredTestMethodNames - } - +@FixtureSuite(testedTypeName: "Element") +final class TupleTypeMetadataElementTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func type() async throws { let address = try usingInProcessOnly { context in let tuple = try TupleTypeMetadata.resolve(at: InProcessMetadataPicker.stdlibTupleIntString, in: context) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/TupleType/TupleTypeMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/TupleType/TupleTypeMetadataTests.swift index b706dc56a..4f63ba95b 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/TupleType/TupleTypeMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/TupleType/TupleTypeMetadataTests.swift @@ -17,12 +17,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class TupleTypeMetadataTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "TupleTypeMetadata" - static var registeredTestMethodNames: Set { - TupleTypeMetadataBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class TupleTypeMetadataTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func layout() async throws { let resolved = try usingInProcessOnly { context in try TupleTypeMetadata.resolve(at: InProcessMetadataPicker.stdlibTupleIntString, in: context) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/ClassDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/ClassDescriptorTests.swift index aea1d755a..91bf3aa97 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/ClassDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/ClassDescriptorTests.swift @@ -16,12 +16,8 @@ import SwiftSectionFixtureSupport /// Two pickers feed the assertions: `Classes.ClassTest` (no superclass) /// and `Classes.SubclassTest` (has a superclass mangled name). @Suite -final class ClassDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ClassDescriptor" - static var registeredTestMethodNames: Set { - ClassDescriptorBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ClassDescriptorTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadClassTestDescriptors() throws -> (file: ClassDescriptor, image: ClassDescriptor) { let file = try BaselineFixturePicker.class_ClassTest(in: machOFile) let image = try BaselineFixturePicker.class_ClassTest(in: machOImage) @@ -39,32 +35,17 @@ final class ClassDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @ @Test func offset() async throws { let (fileSubject, imageSubject) = try loadClassTestDescriptors() - let result = try acrossAllReaders( - file: { fileSubject.offset }, - image: { imageSubject.offset } - ) + let result = try acrossAllReaders(fileSubject, imageSubject) { $0.offset } #expect(result == ClassDescriptorBaseline.classTest.offset) } @Test func layout() async throws { let (fileSubject, imageSubject) = try loadClassTestDescriptors() - let numFields = try acrossAllReaders( - file: { fileSubject.layout.numFields }, - image: { imageSubject.layout.numFields } - ) - let fieldOffsetVectorOffset = try acrossAllReaders( - file: { fileSubject.layout.fieldOffsetVectorOffset }, - image: { imageSubject.layout.fieldOffsetVectorOffset } - ) - let numImmediateMembers = try acrossAllReaders( - file: { fileSubject.layout.numImmediateMembers }, - image: { imageSubject.layout.numImmediateMembers } - ) - let flagsRaw = try acrossAllReaders( - file: { fileSubject.layout.flags.rawValue }, - image: { imageSubject.layout.flags.rawValue } - ) + let numFields = try acrossAllReaders(fileSubject, imageSubject) { $0.layout.numFields } + let fieldOffsetVectorOffset = try acrossAllReaders(fileSubject, imageSubject) { $0.layout.fieldOffsetVectorOffset } + let numImmediateMembers = try acrossAllReaders(fileSubject, imageSubject) { $0.layout.numImmediateMembers } + let flagsRaw = try acrossAllReaders(fileSubject, imageSubject) { $0.layout.flags.rawValue } #expect(Int(numFields) == ClassDescriptorBaseline.classTest.layoutNumFields) #expect(Int(fieldOffsetVectorOffset) == ClassDescriptorBaseline.classTest.layoutFieldOffsetVectorOffset) @@ -76,83 +57,56 @@ final class ClassDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @ @Test func hasFieldOffsetVector() async throws { let (fileSubject, imageSubject) = try loadClassTestDescriptors() - let result = try acrossAllReaders( - file: { fileSubject.hasFieldOffsetVector }, - image: { imageSubject.hasFieldOffsetVector } - ) + let result = try acrossAllReaders(fileSubject, imageSubject) { $0.hasFieldOffsetVector } #expect(result == ClassDescriptorBaseline.classTest.hasFieldOffsetVector) } @Test func hasDefaultOverrideTable() async throws { let (fileSubject, imageSubject) = try loadClassTestDescriptors() - let result = try acrossAllReaders( - file: { fileSubject.hasDefaultOverrideTable }, - image: { imageSubject.hasDefaultOverrideTable } - ) + let result = try acrossAllReaders(fileSubject, imageSubject) { $0.hasDefaultOverrideTable } #expect(result == ClassDescriptorBaseline.classTest.hasDefaultOverrideTable) } @Test func isActor() async throws { let (fileSubject, imageSubject) = try loadClassTestDescriptors() - let result = try acrossAllReaders( - file: { fileSubject.isActor }, - image: { imageSubject.isActor } - ) + let result = try acrossAllReaders(fileSubject, imageSubject) { $0.isActor } #expect(result == ClassDescriptorBaseline.classTest.isActor) } @Test func isDefaultActor() async throws { let (fileSubject, imageSubject) = try loadClassTestDescriptors() - let result = try acrossAllReaders( - file: { fileSubject.isDefaultActor }, - image: { imageSubject.isDefaultActor } - ) + let result = try acrossAllReaders(fileSubject, imageSubject) { $0.isDefaultActor } #expect(result == ClassDescriptorBaseline.classTest.isDefaultActor) } @Test func hasVTable() async throws { let (fileSubject, imageSubject) = try loadClassTestDescriptors() - let result = try acrossAllReaders( - file: { fileSubject.hasVTable }, - image: { imageSubject.hasVTable } - ) + let result = try acrossAllReaders(fileSubject, imageSubject) { $0.hasVTable } #expect(result == ClassDescriptorBaseline.classTest.hasVTable) } @Test func hasOverrideTable() async throws { // Use SubclassTest here — the override table is exclusive to subclasses. let (fileSubject, imageSubject) = try loadSubclassTestDescriptors() - let result = try acrossAllReaders( - file: { fileSubject.hasOverrideTable }, - image: { imageSubject.hasOverrideTable } - ) + let result = try acrossAllReaders(fileSubject, imageSubject) { $0.hasOverrideTable } #expect(result == ClassDescriptorBaseline.subclassTest.hasOverrideTable) } @Test func hasResilientSuperclass() async throws { let (fileSubject, imageSubject) = try loadClassTestDescriptors() - let result = try acrossAllReaders( - file: { fileSubject.hasResilientSuperclass }, - image: { imageSubject.hasResilientSuperclass } - ) + let result = try acrossAllReaders(fileSubject, imageSubject) { $0.hasResilientSuperclass } #expect(result == ClassDescriptorBaseline.classTest.hasResilientSuperclass) } @Test func areImmediateMembersNegative() async throws { let (fileSubject, imageSubject) = try loadClassTestDescriptors() - let result = try acrossAllReaders( - file: { fileSubject.areImmediateMembersNegative }, - image: { imageSubject.areImmediateMembersNegative } - ) + let result = try acrossAllReaders(fileSubject, imageSubject) { $0.areImmediateMembersNegative } #expect(result == ClassDescriptorBaseline.classTest.areImmediateMembersNegative) } @Test func hasObjCResilientClassStub() async throws { let (fileSubject, imageSubject) = try loadClassTestDescriptors() - let result = try acrossAllReaders( - file: { fileSubject.hasObjCResilientClassStub }, - image: { imageSubject.hasObjCResilientClassStub } - ) + let result = try acrossAllReaders(fileSubject, imageSubject) { $0.hasObjCResilientClassStub } #expect(result == ClassDescriptorBaseline.classTest.hasObjCResilientClassStub) } @@ -160,19 +114,13 @@ final class ClassDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @ @Test func immediateMemberSize() async throws { let (fileSubject, imageSubject) = try loadClassTestDescriptors() - let result = try acrossAllReaders( - file: { fileSubject.immediateMemberSize }, - image: { imageSubject.immediateMemberSize } - ) + let result = try acrossAllReaders(fileSubject, imageSubject) { $0.immediateMemberSize } #expect(UInt(result) == ClassDescriptorBaseline.classTest.immediateMemberSize) } @Test func nonResilientImmediateMembersOffset() async throws { let (fileSubject, imageSubject) = try loadClassTestDescriptors() - let result = try acrossAllReaders( - file: { fileSubject.nonResilientImmediateMembersOffset }, - image: { imageSubject.nonResilientImmediateMembersOffset } - ) + let result = try acrossAllReaders(fileSubject, imageSubject) { $0.nonResilientImmediateMembersOffset } #expect(result == ClassDescriptorBaseline.classTest.nonResilientImmediateMembersOffset) } @@ -186,10 +134,9 @@ final class ClassDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @ /// cross-reader equality on the rawValue. @Test func resilientSuperclassReferenceKind() async throws { let (fileSubject, imageSubject) = try loadClassTestDescriptors() - let result = try acrossAllReaders( - file: { fileSubject.resilientSuperclassReferenceKind?.rawValue ?? UInt8.max }, - image: { imageSubject.resilientSuperclassReferenceKind?.rawValue ?? UInt8.max } - ) + let result = try acrossAllReaders(fileSubject, imageSubject) { descriptor in + descriptor.resilientSuperclassReferenceKind?.rawValue ?? UInt8.max + } // The chain always resolves for class kind; the value should be // a valid TypeReferenceKind raw byte. #expect(result != UInt8.max) @@ -211,17 +158,15 @@ final class ClassDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @ /// non-nil mangled name for `SubclassTest`. @Test func superclassTypeMangledName() async throws { let (classTestFile, classTestImage) = try loadClassTestDescriptors() - let classTestPresence = try acrossAllContexts( - file: { (try classTestFile.superclassTypeMangledName(in: fileContext)) != nil }, - image: { (try classTestImage.superclassTypeMangledName(in: imageContext)) != nil } - ) + let classTestPresence = try acrossAllContexts(classTestFile, classTestImage) { descriptor, context in + (try descriptor.superclassTypeMangledName(in: context)) != nil + } #expect(classTestPresence == ClassDescriptorBaseline.classTest.hasSuperclassTypeMangledName) let (subclassFile, subclassImage) = try loadSubclassTestDescriptors() - let subclassPresence = try acrossAllContexts( - file: { (try subclassFile.superclassTypeMangledName(in: fileContext)) != nil }, - image: { (try subclassImage.superclassTypeMangledName(in: imageContext)) != nil } - ) + let subclassPresence = try acrossAllContexts(subclassFile, subclassImage) { descriptor, context in + (try descriptor.superclassTypeMangledName(in: context)) != nil + } #expect(subclassPresence == ClassDescriptorBaseline.subclassTest.hasSuperclassTypeMangledName) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/ClassFlagsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/ClassFlagsTests.swift index 48e72e9cc..7945778c6 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/ClassFlagsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/ClassFlagsTests.swift @@ -12,12 +12,8 @@ import SwiftSectionFixtureSupport /// records no member names because neither the `Flag` cases nor the /// statics `@FlagSet` generates are scanner-visible as method-keyed members. @Suite -final class ClassFlagsTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ClassFlags" - static var registeredTestMethodNames: Set { - ClassFlagsBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ClassFlagsTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func rawValuesMatchBaseline() async throws { #expect(ClassFlags.isSwiftPreStableABI.rawValue == ClassFlagsBaseline.isSwiftPreStableABI) #expect(ClassFlags.usesSwiftRefcounting.rawValue == ClassFlagsBaseline.usesSwiftRefcounting) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/ClassTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/ClassTests.swift index 2581befcc..5b95b1101 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/ClassTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/ClassTests.swift @@ -17,12 +17,8 @@ import SwiftSectionFixtureSupport /// `init(descriptor:in:)` is exercised by dedicated tests over the file /// and image contexts and over the in-process context. @Suite -final class ClassTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "Class" - static var registeredTestMethodNames: Set { - ClassBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ClassTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Helper: instantiate the `Class` wrapper for `Classes.ClassTest` /// against both readers through their reading contexts. private func loadClassTestClasses() throws -> (file: Class, image: Class) { @@ -69,164 +65,112 @@ final class ClassTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked @Test func descriptor() async throws { let classes = try loadClassTestClasses() - let descriptorOffsets = try acrossAllReaders( - file: { classes.file.descriptor.offset }, - image: { classes.image.descriptor.offset } - ) + let descriptorOffsets = try acrossAllReaders(classes.file, classes.image) { $0.descriptor.offset } #expect(descriptorOffsets == ClassBaseline.classTest.descriptorOffset) } @Test func genericContext() async throws { let classes = try loadClassTestClasses() - let presence = try acrossAllReaders( - file: { classes.file.genericContext != nil }, - image: { classes.image.genericContext != nil } - ) + let presence = try acrossAllReaders(classes.file, classes.image) { $0.genericContext != nil } #expect(presence == ClassBaseline.classTest.hasGenericContext) } @Test func resilientSuperclass() async throws { let classes = try loadClassTestClasses() - let presence = try acrossAllReaders( - file: { classes.file.resilientSuperclass != nil }, - image: { classes.image.resilientSuperclass != nil } - ) + let presence = try acrossAllReaders(classes.file, classes.image) { $0.resilientSuperclass != nil } #expect(presence == ClassBaseline.classTest.hasResilientSuperclass) } @Test func foreignMetadataInitialization() async throws { let classes = try loadClassTestClasses() - let presence = try acrossAllReaders( - file: { classes.file.foreignMetadataInitialization != nil }, - image: { classes.image.foreignMetadataInitialization != nil } - ) + let presence = try acrossAllReaders(classes.file, classes.image) { $0.foreignMetadataInitialization != nil } #expect(presence == ClassBaseline.classTest.hasForeignMetadataInitialization) } @Test func singletonMetadataInitialization() async throws { let classes = try loadClassTestClasses() - let presence = try acrossAllReaders( - file: { classes.file.singletonMetadataInitialization != nil }, - image: { classes.image.singletonMetadataInitialization != nil } - ) + let presence = try acrossAllReaders(classes.file, classes.image) { $0.singletonMetadataInitialization != nil } #expect(presence == ClassBaseline.classTest.hasSingletonMetadataInitialization) } @Test func vTableDescriptorHeader() async throws { let classes = try loadClassTestClasses() - let presence = try acrossAllReaders( - file: { classes.file.vTableDescriptorHeader != nil }, - image: { classes.image.vTableDescriptorHeader != nil } - ) + let presence = try acrossAllReaders(classes.file, classes.image) { $0.vTableDescriptorHeader != nil } #expect(presence == ClassBaseline.classTest.hasVTableDescriptorHeader) } @Test func methodDescriptors() async throws { let classes = try loadClassTestClasses() - let count = try acrossAllReaders( - file: { classes.file.methodDescriptors.count }, - image: { classes.image.methodDescriptors.count } - ) + let count = try acrossAllReaders(classes.file, classes.image) { $0.methodDescriptors.count } #expect(count == ClassBaseline.classTest.methodDescriptorsCount) } @Test func overrideTableHeader() async throws { // SubclassTest is the path that exercises this ivar. let classes = try loadSubclassTestClasses() - let presence = try acrossAllReaders( - file: { classes.file.overrideTableHeader != nil }, - image: { classes.image.overrideTableHeader != nil } - ) + let presence = try acrossAllReaders(classes.file, classes.image) { $0.overrideTableHeader != nil } #expect(presence == ClassBaseline.subclassTest.hasOverrideTableHeader) } @Test func methodOverrideDescriptors() async throws { let classes = try loadSubclassTestClasses() - let count = try acrossAllReaders( - file: { classes.file.methodOverrideDescriptors.count }, - image: { classes.image.methodOverrideDescriptors.count } - ) + let count = try acrossAllReaders(classes.file, classes.image) { $0.methodOverrideDescriptors.count } #expect(count == ClassBaseline.subclassTest.methodOverrideDescriptorsCount) } @Test func objcResilientClassStubInfo() async throws { let classes = try loadClassTestClasses() - let presence = try acrossAllReaders( - file: { classes.file.objcResilientClassStubInfo != nil }, - image: { classes.image.objcResilientClassStubInfo != nil } - ) + let presence = try acrossAllReaders(classes.file, classes.image) { $0.objcResilientClassStubInfo != nil } #expect(presence == ClassBaseline.classTest.hasObjCResilientClassStubInfo) } @Test func canonicalSpecializedMetadatasListCount() async throws { let classes = try loadClassTestClasses() - let presence = try acrossAllReaders( - file: { classes.file.canonicalSpecializedMetadatasListCount != nil }, - image: { classes.image.canonicalSpecializedMetadatasListCount != nil } - ) + let presence = try acrossAllReaders(classes.file, classes.image) { $0.canonicalSpecializedMetadatasListCount != nil } #expect(presence == ClassBaseline.classTest.hasCanonicalSpecializedMetadatasListCount) } @Test func canonicalSpecializedMetadatas() async throws { let classes = try loadClassTestClasses() - let count = try acrossAllReaders( - file: { classes.file.canonicalSpecializedMetadatas.count }, - image: { classes.image.canonicalSpecializedMetadatas.count } - ) + let count = try acrossAllReaders(classes.file, classes.image) { $0.canonicalSpecializedMetadatas.count } #expect(count == ClassBaseline.classTest.canonicalSpecializedMetadatasCount) } @Test func canonicalSpecializedMetadataAccessors() async throws { let classes = try loadClassTestClasses() - let count = try acrossAllReaders( - file: { classes.file.canonicalSpecializedMetadataAccessors.count }, - image: { classes.image.canonicalSpecializedMetadataAccessors.count } - ) + let count = try acrossAllReaders(classes.file, classes.image) { $0.canonicalSpecializedMetadataAccessors.count } #expect(count == ClassBaseline.classTest.canonicalSpecializedMetadataAccessorsCount) } @Test func canonicalSpecializedMetadatasCachingOnceToken() async throws { let classes = try loadClassTestClasses() - let presence = try acrossAllReaders( - file: { classes.file.canonicalSpecializedMetadatasCachingOnceToken != nil }, - image: { classes.image.canonicalSpecializedMetadatasCachingOnceToken != nil } - ) + let presence = try acrossAllReaders(classes.file, classes.image) { swiftClass in + swiftClass.canonicalSpecializedMetadatasCachingOnceToken != nil + } #expect(presence == ClassBaseline.classTest.hasCanonicalSpecializedMetadatasCachingOnceToken) } @Test func invertibleProtocolSet() async throws { let classes = try loadClassTestClasses() - let presence = try acrossAllReaders( - file: { classes.file.invertibleProtocolSet != nil }, - image: { classes.image.invertibleProtocolSet != nil } - ) + let presence = try acrossAllReaders(classes.file, classes.image) { $0.invertibleProtocolSet != nil } #expect(presence == ClassBaseline.classTest.hasInvertibleProtocolSet) } @Test func singletonMetadataPointer() async throws { let classes = try loadClassTestClasses() - let presence = try acrossAllReaders( - file: { classes.file.singletonMetadataPointer != nil }, - image: { classes.image.singletonMetadataPointer != nil } - ) + let presence = try acrossAllReaders(classes.file, classes.image) { $0.singletonMetadataPointer != nil } #expect(presence == ClassBaseline.classTest.hasSingletonMetadataPointer) } @Test func methodDefaultOverrideTableHeader() async throws { let classes = try loadClassTestClasses() - let presence = try acrossAllReaders( - file: { classes.file.methodDefaultOverrideTableHeader != nil }, - image: { classes.image.methodDefaultOverrideTableHeader != nil } - ) + let presence = try acrossAllReaders(classes.file, classes.image) { $0.methodDefaultOverrideTableHeader != nil } #expect(presence == ClassBaseline.classTest.hasMethodDefaultOverrideTableHeader) } @Test func methodDefaultOverrideDescriptors() async throws { let classes = try loadClassTestClasses() - let count = try acrossAllReaders( - file: { classes.file.methodDefaultOverrideDescriptors.count }, - image: { classes.image.methodDefaultOverrideDescriptors.count } - ) + let count = try acrossAllReaders(classes.file, classes.image) { $0.methodDefaultOverrideDescriptors.count } #expect(count == ClassBaseline.classTest.methodDefaultOverrideDescriptorsCount) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/ExtraClassDescriptorFlagsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/ExtraClassDescriptorFlagsTests.swift index e027b4ece..a36a466b3 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/ExtraClassDescriptorFlagsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/ExtraClassDescriptorFlagsTests.swift @@ -11,12 +11,8 @@ import SwiftSectionFixtureSupport /// resilient ObjC stub, so we exercise the flag derivation by /// constructing instances with known raw values. @Suite -final class ExtraClassDescriptorFlagsTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ExtraClassDescriptorFlags" - static var registeredTestMethodNames: Set { - ExtraClassDescriptorFlagsBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ExtraClassDescriptorFlagsTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func rawValue() async throws { let zero = ExtraClassDescriptorFlags(rawValue: ExtraClassDescriptorFlagsBaseline.zeroRawValue) #expect(zero.rawValue == ExtraClassDescriptorFlagsBaseline.zeroRawValue) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadata/AnyClassMetadataProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadata/AnyClassMetadataProtocolTests.swift index 1953498c6..d940ebfea 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadata/AnyClassMetadataProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadata/AnyClassMetadataProtocolTests.swift @@ -20,12 +20,8 @@ import SwiftSectionFixtureSupport /// /// **Reader asymmetry:** the metadata source originates from MachOImage. @Suite -final class AnyClassMetadataProtocolTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "AnyClassMetadataProtocol" - static var registeredTestMethodNames: Set { - AnyClassMetadataProtocolBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class AnyClassMetadataProtocolTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Helper: load `ClassMetadataObjCInterop` for `ClassTest`, then /// re-resolve at the same offset as a slim `AnyClassMetadata`. private func loadAnyClassMetadata() throws -> AnyClassMetadata { diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadata/AnyClassMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadata/AnyClassMetadataTests.swift index fdfafdda4..326d8bfab 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadata/AnyClassMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadata/AnyClassMetadataTests.swift @@ -24,12 +24,8 @@ import SwiftSectionFixtureSupport /// down via the protocol's `asFinalClassMetadata(in:)` helper, then /// performing structural checks on the slim header. @Suite -final class AnyClassMetadataTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "AnyClassMetadata" - static var registeredTestMethodNames: Set { - AnyClassMetadataBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class AnyClassMetadataTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Helper: load the `ClassMetadataObjCInterop` for `ClassTest` and /// re-resolve at the same offset as an `AnyClassMetadata` slim view. /// The two layouts overlap in their leading fields (kind + diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadataObjCInterop/AnyClassMetadataObjCInteropProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadataObjCInterop/AnyClassMetadataObjCInteropProtocolTests.swift index 34e27a45d..6499f756c 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadataObjCInterop/AnyClassMetadataObjCInteropProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadataObjCInterop/AnyClassMetadataObjCInteropProtocolTests.swift @@ -14,12 +14,8 @@ import SwiftSectionFixtureSupport /// /// **Reader asymmetry:** the source metadata originates from MachOImage. @Suite -final class AnyClassMetadataObjCInteropProtocolTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "AnyClassMetadataObjCInteropProtocol" - static var registeredTestMethodNames: Set { - AnyClassMetadataObjCInteropProtocolBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class AnyClassMetadataObjCInteropProtocolTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadInteropMetadata() throws -> ClassMetadataObjCInterop { let descriptor = try BaselineFixturePicker.class_ClassTest(in: machOImage) let accessor = try required(try descriptor.metadataAccessorFunction(in: imageContext)) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadataObjCInterop/AnyClassMetadataObjCInteropTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadataObjCInterop/AnyClassMetadataObjCInteropTests.swift index df9a163eb..ea0a4fbf8 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadataObjCInterop/AnyClassMetadataObjCInteropTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadataObjCInterop/AnyClassMetadataObjCInteropTests.swift @@ -14,12 +14,8 @@ import SwiftSectionFixtureSupport /// /// **Reader asymmetry:** the metadata source originates from MachOImage. @Suite -final class AnyClassMetadataObjCInteropTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "AnyClassMetadataObjCInterop" - static var registeredTestMethodNames: Set { - AnyClassMetadataObjCInteropBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class AnyClassMetadataObjCInteropTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Helper: load `ClassMetadataObjCInterop` for ClassTest, then take /// its superclass to get an `AnyClassMetadataObjCInterop` slim view. private func loadAnyInteropSuperclass() throws -> AnyClassMetadataObjCInterop { diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/Bounds/ClassMetadataBoundsProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/Bounds/ClassMetadataBoundsProtocolTests.swift index ca7fcf794..f60340c7e 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/Bounds/ClassMetadataBoundsProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/Bounds/ClassMetadataBoundsProtocolTests.swift @@ -11,12 +11,8 @@ import SwiftSectionFixtureSupport /// two static factories (`forAddressPointAndSize`, `forSwiftRootClass`). /// We exercise them on `ClassMetadataBounds` with known inputs. @Suite -final class ClassMetadataBoundsProtocolTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ClassMetadataBoundsProtocol" - static var registeredTestMethodNames: Set { - ClassMetadataBoundsProtocolBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ClassMetadataBoundsProtocolTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// `forAddressPointAndSize(addressPoint:totalSize:offset:)` derives /// negative/positive sizes from a (pointer-aligned) address point and /// total size. Use known multiples of pointer size to verify the diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/Bounds/ClassMetadataBoundsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/Bounds/ClassMetadataBoundsTests.swift index 23a9ff351..8266d229e 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/Bounds/ClassMetadataBoundsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/Bounds/ClassMetadataBoundsTests.swift @@ -11,12 +11,8 @@ import SwiftSectionFixtureSupport /// the static factories on `ClassMetadataBoundsProtocol`. We construct /// instances with known scalars and verify the layout fields round-trip. @Suite -final class ClassMetadataBoundsTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ClassMetadataBounds" - static var registeredTestMethodNames: Set { - ClassMetadataBoundsBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ClassMetadataBoundsTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func offset() async throws { // Construct a deterministic instance and verify the `offset` ivar // is set as supplied. (Default-init through the public layout diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/Bounds/StoredClassMetadataBoundsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/Bounds/StoredClassMetadataBoundsTests.swift index a3b7681da..ec214fb76 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/Bounds/StoredClassMetadataBoundsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/Bounds/StoredClassMetadataBoundsTests.swift @@ -4,6 +4,7 @@ import MachOFoundation @testable import MachOSwiftSection @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import BinaryParseSupport /// Fixture-based Suite for `StoredClassMetadataBounds`. /// @@ -25,12 +26,8 @@ import SwiftSectionFixtureSupport /// successfully and is the canonical path the Swift runtime takes. /// Phase B2 settled on InProcess-only coverage for this Suite. @Suite -final class StoredClassMetadataBoundsTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "StoredClassMetadataBounds" - static var registeredTestMethodNames: Set { - StoredClassMetadataBoundsBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class StoredClassMetadataBoundsTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Mangled symbol of the nominal type descriptor for /// `SymbolTestsCore.ResilientClassFixtures.ResilientChild`. Used by /// `fixtureSymbol(_:)` to obtain the descriptor pointer directly. diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/ClassMetadata/ClassMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/ClassMetadata/ClassMetadataTests.swift index 1bc4c3d33..7389d2e6f 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/ClassMetadata/ClassMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/ClassMetadata/ClassMetadataTests.swift @@ -15,12 +15,8 @@ import SwiftSectionFixtureSupport /// /// **Reader asymmetry:** the metadata source originates from MachOImage. @Suite -final class ClassMetadataTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ClassMetadata" - static var registeredTestMethodNames: Set { - ClassMetadataBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ClassMetadataTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Helper: load `ClassTest`'s metadata via the accessor (returned as /// `ClassMetadataObjCInterop`); the related `descriptorOffset` is a /// static lookup on `ClassMetadata`. diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/ClassMetadataObjCInterop/ClassMetadataObjCInteropTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/ClassMetadataObjCInterop/ClassMetadataObjCInteropTests.swift index 7d2118698..07b0ce389 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/ClassMetadataObjCInterop/ClassMetadataObjCInteropTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/ClassMetadataObjCInterop/ClassMetadataObjCInteropTests.swift @@ -14,12 +14,8 @@ import SwiftSectionFixtureSupport /// /// **Reader asymmetry:** the metadata source originates from MachOImage. @Suite -final class ClassMetadataObjCInteropTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ClassMetadataObjCInterop" - static var registeredTestMethodNames: Set { - ClassMetadataObjCInteropBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ClassMetadataObjCInteropTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadInteropMetadata() throws -> ClassMetadataObjCInterop { let descriptor = try BaselineFixturePicker.class_ClassTest(in: machOImage) let accessor = try required(try descriptor.metadataAccessorFunction(in: imageContext)) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/FinalClassMetadataProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/FinalClassMetadataProtocolTests.swift index 14c8dee8f..460f2b010 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/FinalClassMetadataProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/FinalClassMetadataProtocolTests.swift @@ -16,12 +16,8 @@ import SwiftSectionFixtureSupport /// the protocol methods accept any `ReadingContext` so we exercise the /// ReadingContext overloads here. @Suite -final class FinalClassMetadataProtocolTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "FinalClassMetadataProtocol" - static var registeredTestMethodNames: Set { - FinalClassMetadataProtocolBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class FinalClassMetadataProtocolTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadInteropMetadata() throws -> ClassMetadataObjCInterop { let descriptor = try BaselineFixturePicker.class_ClassTest(in: machOImage) let accessor = try required(try descriptor.metadataAccessorFunction(in: imageContext)) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/ObjCClassWrapperMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/ObjCClassWrapperMetadataTests.swift index 3a39d1626..8a3c73f62 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/ObjCClassWrapperMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/ObjCClassWrapperMetadataTests.swift @@ -23,12 +23,8 @@ import SwiftSectionFixtureSupport /// (reached via `Foundation`'s in-process metadata) is the canonical /// `ObjCClassWrapperMetadata` carrier. @Suite -final class ObjCClassWrapperMetadataTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ObjCClassWrapperMetadata" - static var registeredTestMethodNames: Set { - ObjCClassWrapperMetadataBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ObjCClassWrapperMetadataTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func layout() async throws { let kindRaw = try usingInProcessOnly { context in let metadata = try ObjCClassWrapperMetadata.resolve( diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDefaultOverrideDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDefaultOverrideDescriptorTests.swift index 849f38ece..eba9d440b 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDefaultOverrideDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDefaultOverrideDescriptorTests.swift @@ -12,12 +12,8 @@ import SwiftSectionFixtureSupport /// cannot be sourced. The Suite documents the missing runtime coverage /// and registers the public surface for the Coverage Invariant test. @Suite -final class MethodDefaultOverrideDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "MethodDefaultOverrideDescriptor" - static var registeredTestMethodNames: Set { - MethodDefaultOverrideDescriptorBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class MethodDefaultOverrideDescriptorTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Sentinel test ensuring the Suite is loaded by swift-testing. The /// real coverage will land when a fixture surfaces a default-override /// table. diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDefaultOverrideTableHeaderTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDefaultOverrideTableHeaderTests.swift index fa5880186..33cad1b98 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDefaultOverrideTableHeaderTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDefaultOverrideTableHeaderTests.swift @@ -10,12 +10,8 @@ import SwiftSectionFixtureSupport /// default-override table, so a live header cannot be sourced. The Suite /// documents the missing runtime coverage. @Suite -final class MethodDefaultOverrideTableHeaderTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "MethodDefaultOverrideTableHeader" - static var registeredTestMethodNames: Set { - MethodDefaultOverrideTableHeaderBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class MethodDefaultOverrideTableHeaderTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func registrationOnly() async throws { // No live instance available in SymbolTestsCore; the Suite registers // the public surface (offset, layout) for the Coverage Invariant diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDescriptorFlagsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDescriptorFlagsTests.swift index eefa3bbbb..0e6af6548 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDescriptorFlagsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDescriptorFlagsTests.swift @@ -13,12 +13,8 @@ import SwiftSectionFixtureSupport /// `instanceVariable` getter — kind `.getter`, isInstance `true`, /// other bits clear. @Suite -final class MethodDescriptorFlagsTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "MethodDescriptorFlags" - static var registeredTestMethodNames: Set { - MethodDescriptorFlagsBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class MethodDescriptorFlagsTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Helper: load the first vtable entry's flags from each reader. private func loadFirstFlags() throws -> (file: MethodDescriptorFlags, image: MethodDescriptorFlags) { let fileDescriptor = try BaselineFixturePicker.class_ClassTest(in: machOFile) @@ -32,10 +28,7 @@ final class MethodDescriptorFlagsTests: MachOSwiftSectionFixtureTests, FixtureSu @Test func rawValue() async throws { let flags = try loadFirstFlags() - let result = try acrossAllReaders( - file: { flags.file.rawValue }, - image: { flags.image.rawValue } - ) + let result = try acrossAllReaders(flags.file, flags.image) { $0.rawValue } #expect(result == MethodDescriptorFlagsBaseline.firstClassTestMethod.rawValue) } @@ -51,82 +44,55 @@ final class MethodDescriptorFlagsTests: MachOSwiftSectionFixtureTests, FixtureSu @Test func kind() async throws { let flags = try loadFirstFlags() - let result = try acrossAllReaders( - file: { flags.file.kind?.rawValue }, - image: { flags.image.kind?.rawValue } - ) + let result = try acrossAllReaders(flags.file, flags.image) { $0.kind?.rawValue } #expect(result == MethodDescriptorFlagsBaseline.firstClassTestMethod.kindRawValue) } @Test func isDynamic() async throws { let flags = try loadFirstFlags() - let result = try acrossAllReaders( - file: { flags.file.isDynamic }, - image: { flags.image.isDynamic } - ) + let result = try acrossAllReaders(flags.file, flags.image) { $0.isDynamic } #expect(result == MethodDescriptorFlagsBaseline.firstClassTestMethod.isDynamic) } @Test func isInstance() async throws { let flags = try loadFirstFlags() - let result = try acrossAllReaders( - file: { flags.file.isInstance }, - image: { flags.image.isInstance } - ) + let result = try acrossAllReaders(flags.file, flags.image) { $0.isInstance } #expect(result == MethodDescriptorFlagsBaseline.firstClassTestMethod.isInstance) } @Test func _hasAsyncBitSet() async throws { let flags = try loadFirstFlags() - let result = try acrossAllReaders( - file: { flags.file._hasAsyncBitSet }, - image: { flags.image._hasAsyncBitSet } - ) + let result = try acrossAllReaders(flags.file, flags.image) { $0._hasAsyncBitSet } #expect(result == MethodDescriptorFlagsBaseline.firstClassTestMethod.hasAsyncBitSet) } @Test func isAsync() async throws { let flags = try loadFirstFlags() - let result = try acrossAllReaders( - file: { flags.file.isAsync }, - image: { flags.image.isAsync } - ) + let result = try acrossAllReaders(flags.file, flags.image) { $0.isAsync } #expect(result == MethodDescriptorFlagsBaseline.firstClassTestMethod.isAsync) } @Test func isCoroutine() async throws { let flags = try loadFirstFlags() - let result = try acrossAllReaders( - file: { flags.file.isCoroutine }, - image: { flags.image.isCoroutine } - ) + let result = try acrossAllReaders(flags.file, flags.image) { $0.isCoroutine } #expect(result == MethodDescriptorFlagsBaseline.firstClassTestMethod.isCoroutine) } @Test func isCalleeAllocatedCoroutine() async throws { let flags = try loadFirstFlags() - let result = try acrossAllReaders( - file: { flags.file.isCalleeAllocatedCoroutine }, - image: { flags.image.isCalleeAllocatedCoroutine } - ) + let result = try acrossAllReaders(flags.file, flags.image) { $0.isCalleeAllocatedCoroutine } #expect(result == MethodDescriptorFlagsBaseline.firstClassTestMethod.isCalleeAllocatedCoroutine) } @Test func isData() async throws { let flags = try loadFirstFlags() - let result = try acrossAllReaders( - file: { flags.file.isData }, - image: { flags.image.isData } - ) + let result = try acrossAllReaders(flags.file, flags.image) { $0.isData } #expect(result == MethodDescriptorFlagsBaseline.firstClassTestMethod.isData) } @Test func extraDiscriminator() async throws { let flags = try loadFirstFlags() - let result = try acrossAllReaders( - file: { flags.file.extraDiscriminator }, - image: { flags.image.extraDiscriminator } - ) + let result = try acrossAllReaders(flags.file, flags.image) { $0.extraDiscriminator } #expect(result == MethodDescriptorFlagsBaseline.firstClassTestMethod.extraDiscriminator) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDescriptorKindTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDescriptorKindTests.swift index a95f19738..80654a5d0 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDescriptorKindTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDescriptorKindTests.swift @@ -10,12 +10,8 @@ import SwiftSectionFixtureSupport /// Suite pins both the raw values and the `description` strings, so any /// accidental renumbering or display tweak fails a test. @Suite -final class MethodDescriptorKindTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "MethodDescriptorKind" - static var registeredTestMethodNames: Set { - MethodDescriptorKindBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class MethodDescriptorKindTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func description() async throws { // Pin raw values + descriptions per case. #expect(MethodDescriptorKind.method.rawValue == MethodDescriptorKindBaseline.method.rawValue) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDescriptorTests.swift index b25045a81..a1e93f436 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDescriptorTests.swift @@ -15,12 +15,8 @@ import SwiftSectionFixtureSupport /// resolves to (pinned as a baseline literal; the ReadingContext leg must /// report the same location as a context address). @Suite -final class MethodDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "MethodDescriptor" - static var registeredTestMethodNames: Set { - MethodDescriptorBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class MethodDescriptorTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Helper: load the first vtable entry of `Classes.ClassTest` from /// each reader. private func loadFirstMethods() throws -> (file: MethodDescriptor, image: MethodDescriptor) { @@ -35,19 +31,13 @@ final class MethodDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @Test func offset() async throws { let methods = try loadFirstMethods() - let result = try acrossAllReaders( - file: { methods.file.offset }, - image: { methods.image.offset } - ) + let result = try acrossAllReaders(methods.file, methods.image) { $0.offset } #expect(result == MethodDescriptorBaseline.firstClassTestMethod.offset) } @Test func layout() async throws { let methods = try loadFirstMethods() - let flagsRaw = try acrossAllReaders( - file: { methods.file.layout.flags.rawValue }, - image: { methods.image.layout.flags.rawValue } - ) + let flagsRaw = try acrossAllReaders(methods.file, methods.image) { $0.layout.flags.rawValue } #expect(flagsRaw == MethodDescriptorBaseline.firstClassTestMethod.layoutFlagsRawValue) } @@ -55,10 +45,7 @@ final class MethodDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, /// a literal and identical across readers. @Test func implementationOffset() async throws { let methods = try loadFirstMethods() - let result = try acrossAllReaders( - file: { methods.file.implementationOffset }, - image: { methods.image.implementationOffset } - ) + let result = try acrossAllReaders(methods.file, methods.image) { $0.implementationOffset } #expect(result == MethodDescriptorBaseline.firstClassTestMethod.implementationOffset) } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodOverrideDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodOverrideDescriptorTests.swift index d287ef8f2..d856e4a14 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodOverrideDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodOverrideDescriptorTests.swift @@ -12,12 +12,8 @@ import SwiftSectionFixtureSupport /// implementation offset, and presence-flags for the resolved class/method /// pointers. @Suite -final class MethodOverrideDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "MethodOverrideDescriptor" - static var registeredTestMethodNames: Set { - MethodOverrideDescriptorBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class MethodOverrideDescriptorTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Helper: load the first override entry of `Classes.SubclassTest` /// from each reader. private func loadFirstOverrides() throws -> (file: MethodOverrideDescriptor, image: MethodOverrideDescriptor) { @@ -32,10 +28,7 @@ final class MethodOverrideDescriptorTests: MachOSwiftSectionFixtureTests, Fixtur @Test func offset() async throws { let overrides = try loadFirstOverrides() - let result = try acrossAllReaders( - file: { overrides.file.offset }, - image: { overrides.image.offset } - ) + let result = try acrossAllReaders(overrides.file, overrides.image) { $0.offset } #expect(result == MethodOverrideDescriptorBaseline.firstSubclassOverride.offset) } @@ -55,10 +48,9 @@ final class MethodOverrideDescriptorTests: MachOSwiftSectionFixtureTests, Fixtur /// ancestor depending on layout). Verify cross-reader presence. @Test func classDescriptor() async throws { let overrides = try loadFirstOverrides() - let presence = try acrossAllContexts( - file: { (try overrides.file.classDescriptor(in: fileContext)) != nil }, - image: { (try overrides.image.classDescriptor(in: imageContext)) != nil } - ) + let presence = try acrossAllContexts(overrides.file, overrides.image) { descriptor, context in + (try descriptor.classDescriptor(in: context)) != nil + } #expect(presence == true) } @@ -66,10 +58,9 @@ final class MethodOverrideDescriptorTests: MachOSwiftSectionFixtureTests, Fixtur /// Exercise the ReadingContext overload across both readers. @Test func methodDescriptor() async throws { let overrides = try loadFirstOverrides() - let presence = try acrossAllContexts( - file: { (try overrides.file.methodDescriptor(in: fileContext)) != nil }, - image: { (try overrides.image.methodDescriptor(in: imageContext)) != nil } - ) + let presence = try acrossAllContexts(overrides.file, overrides.image) { descriptor, context in + (try descriptor.methodDescriptor(in: context)) != nil + } #expect(presence == true) } @@ -78,10 +69,7 @@ final class MethodOverrideDescriptorTests: MachOSwiftSectionFixtureTests, Fixtur /// and identical across readers. @Test func implementationOffset() async throws { let overrides = try loadFirstOverrides() - let result = try acrossAllReaders( - file: { overrides.file.implementationOffset }, - image: { overrides.image.implementationOffset } - ) + let result = try acrossAllReaders(overrides.file, overrides.image) { $0.implementationOffset } #expect(result != nil) #expect(result == MethodOverrideDescriptorBaseline.firstSubclassOverride.implementationOffset) } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/OverrideTableHeaderTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/OverrideTableHeaderTests.swift index 303e3a1a7..d8a2892f5 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/OverrideTableHeaderTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/OverrideTableHeaderTests.swift @@ -10,12 +10,8 @@ import SwiftSectionFixtureSupport /// The Suite picks the override-table header from `Classes.SubclassTest` /// and asserts cross-reader equality on `offset` and `numEntries`. @Suite -final class OverrideTableHeaderTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "OverrideTableHeader" - static var registeredTestMethodNames: Set { - OverrideTableHeaderBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class OverrideTableHeaderTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadSubclassOverrideHeaders() throws -> (file: OverrideTableHeader, image: OverrideTableHeader) { let fileDescriptor = try BaselineFixturePicker.class_SubclassTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.class_SubclassTest(in: machOImage) @@ -28,19 +24,13 @@ final class OverrideTableHeaderTests: MachOSwiftSectionFixtureTests, FixtureSuit @Test func offset() async throws { let headers = try loadSubclassOverrideHeaders() - let result = try acrossAllReaders( - file: { headers.file.offset }, - image: { headers.image.offset } - ) + let result = try acrossAllReaders(headers.file, headers.image) { $0.offset } #expect(result == OverrideTableHeaderBaseline.subclassTest.offset) } @Test func layout() async throws { let headers = try loadSubclassOverrideHeaders() - let numEntries = try acrossAllReaders( - file: { headers.file.layout.numEntries }, - image: { headers.image.layout.numEntries } - ) + let numEntries = try acrossAllReaders(headers.file, headers.image) { $0.layout.numEntries } #expect(numEntries == OverrideTableHeaderBaseline.subclassTest.layoutNumEntries) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/VTableDescriptorHeaderTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/VTableDescriptorHeaderTests.swift index caea69608..64e2f6161 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/VTableDescriptorHeaderTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/VTableDescriptorHeaderTests.swift @@ -10,12 +10,8 @@ import SwiftSectionFixtureSupport /// The Suite picks the vtable header from `Classes.ClassTest` and asserts /// cross-reader equality on `offset`, `vTableOffset`, and `vTableSize`. @Suite -final class VTableDescriptorHeaderTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "VTableDescriptorHeader" - static var registeredTestMethodNames: Set { - VTableDescriptorHeaderBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class VTableDescriptorHeaderTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadClassTestVTableHeaders() throws -> (file: VTableDescriptorHeader, image: VTableDescriptorHeader) { let fileDescriptor = try BaselineFixturePicker.class_ClassTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.class_ClassTest(in: machOImage) @@ -28,23 +24,14 @@ final class VTableDescriptorHeaderTests: MachOSwiftSectionFixtureTests, FixtureS @Test func offset() async throws { let headers = try loadClassTestVTableHeaders() - let result = try acrossAllReaders( - file: { headers.file.offset }, - image: { headers.image.offset } - ) + let result = try acrossAllReaders(headers.file, headers.image) { $0.offset } #expect(result == VTableDescriptorHeaderBaseline.classTest.offset) } @Test func layout() async throws { let headers = try loadClassTestVTableHeaders() - let vTableOffset = try acrossAllReaders( - file: { headers.file.layout.vTableOffset }, - image: { headers.image.layout.vTableOffset } - ) - let vTableSize = try acrossAllReaders( - file: { headers.file.layout.vTableSize }, - image: { headers.image.layout.vTableSize } - ) + let vTableOffset = try acrossAllReaders(headers.file, headers.image) { $0.layout.vTableOffset } + let vTableSize = try acrossAllReaders(headers.file, headers.image) { $0.layout.vTableSize } #expect(vTableOffset == VTableDescriptorHeaderBaseline.classTest.layoutVTableOffset) #expect(vTableSize == VTableDescriptorHeaderBaseline.classTest.layoutVTableSize) } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Resilient/ObjCResilientClassStubInfoTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Resilient/ObjCResilientClassStubInfoTests.swift index 1d14fcf87..6ed1578de 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Resilient/ObjCResilientClassStubInfoTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Resilient/ObjCResilientClassStubInfoTests.swift @@ -17,12 +17,8 @@ import SwiftSectionFixtureSupport /// `SymbolTestsHelper.Object`, cross-module) and asserts cross-reader /// agreement on the discovered scalars. @Suite -final class ObjCResilientClassStubInfoTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ObjCResilientClassStubInfo" - static var registeredTestMethodNames: Set { - ObjCResilientClassStubInfoBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ObjCResilientClassStubInfoTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Helper: load the `ObjCResilientClassStubInfo` record from /// `ObjCResilientStubFixtures.ResilientObjCStubChild`. private func loadResilientObjCStubChildStub( @@ -36,10 +32,7 @@ final class ObjCResilientClassStubInfoTests: MachOSwiftSectionFixtureTests, Fixt @Test func offset() async throws { let fileSubject = try loadResilientObjCStubChildStub(in: machOFile) let imageSubject = try loadResilientObjCStubChildStub(in: machOImage) - let result = try acrossAllReaders( - file: { fileSubject.offset }, - image: { imageSubject.offset } - ) + let result = try acrossAllReaders(fileSubject, imageSubject) { $0.offset } #expect(result == ObjCResilientClassStubInfoBaseline.resilientObjCStubChild.offset) } @@ -48,10 +41,7 @@ final class ObjCResilientClassStubInfoTests: MachOSwiftSectionFixtureTests, Fixt let imageSubject = try loadResilientObjCStubChildStub(in: machOImage) // The relative raw pointer's relativeOffset scalar must agree // across readers (it's a stable file/image-relative displacement). - let result = try acrossAllReaders( - file: { fileSubject.layout.stub.relativeOffset }, - image: { imageSubject.layout.stub.relativeOffset } - ) + let result = try acrossAllReaders(fileSubject, imageSubject) { $0.layout.stub.relativeOffset } #expect(result == ObjCResilientClassStubInfoBaseline.resilientObjCStubChild.layoutStubRelativeOffset) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Resilient/ResilientSuperclassTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Resilient/ResilientSuperclassTests.swift index edef621a1..1cbe56e1e 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Resilient/ResilientSuperclassTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Resilient/ResilientSuperclassTests.swift @@ -15,12 +15,8 @@ import SwiftSectionFixtureSupport /// child's class context descriptor carries the trailing record) and /// asserts cross-reader agreement on the discovered scalar offset. @Suite -final class ResilientSuperclassTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ResilientSuperclass" - static var registeredTestMethodNames: Set { - ResilientSuperclassBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ResilientSuperclassTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Helper: load the `ResilientSuperclass` record from /// `ResilientClassFixtures.ResilientChild` (whose parent /// `SymbolTestsHelper.ResilientBase` is cross-module — only that @@ -36,10 +32,7 @@ final class ResilientSuperclassTests: MachOSwiftSectionFixtureTests, FixtureSuit @Test func offset() async throws { let fileSubject = try loadResilientChildSuperclass(in: machOFile) let imageSubject = try loadResilientChildSuperclass(in: machOImage) - let result = try acrossAllReaders( - file: { fileSubject.offset }, - image: { imageSubject.offset } - ) + let result = try acrossAllReaders(fileSubject, imageSubject) { $0.offset } #expect(result == ResilientSuperclassBaseline.resilientChild.offset) } @@ -48,10 +41,7 @@ final class ResilientSuperclassTests: MachOSwiftSectionFixtureTests, FixtureSuit let imageSubject = try loadResilientChildSuperclass(in: machOImage) // The relative raw pointer's relativeOffset scalar must agree // across readers (it's a stable file/image-relative displacement). - let result = try acrossAllReaders( - file: { fileSubject.layout.superclass.relativeOffset }, - image: { imageSubject.layout.superclass.relativeOffset } - ) + let result = try acrossAllReaders(fileSubject, imageSubject) { $0.layout.superclass.relativeOffset } #expect(result == ResilientSuperclassBaseline.resilientChild.layoutSuperclassRelativeOffset) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/EnumDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/EnumDescriptorTests.swift index 6c32998cc..658c975f8 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/EnumDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/EnumDescriptorTests.swift @@ -22,12 +22,8 @@ import SwiftSectionFixtureSupport /// - `Enums.MultiPayloadEnumTests` — the canonical `isMultiPayload` path /// (3 payload cases + 1 empty) @Suite -final class EnumDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "EnumDescriptor" - static var registeredTestMethodNames: Set { - EnumDescriptorBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class EnumDescriptorTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadNoPayloadDescriptors() throws -> (file: EnumDescriptor, image: EnumDescriptor) { let file = try BaselineFixturePicker.enum_NoPayloadEnumTest(in: machOFile) let image = try BaselineFixturePicker.enum_NoPayloadEnumTest(in: machOImage) @@ -50,27 +46,17 @@ final class EnumDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @u @Test func offset() async throws { let (fileSubject, imageSubject) = try loadNoPayloadDescriptors() - let result = try acrossAllReaders( - file: { fileSubject.offset }, - image: { imageSubject.offset } - ) + let result = try acrossAllReaders(fileSubject, imageSubject) { $0.offset } #expect(result == EnumDescriptorBaseline.noPayloadEnumTest.offset) } @Test func layout() async throws { let (fileSubject, imageSubject) = try loadNoPayloadDescriptors() - let numPayloadCasesAndPayloadSizeOffset = try acrossAllReaders( - file: { fileSubject.layout.numPayloadCasesAndPayloadSizeOffset }, - image: { imageSubject.layout.numPayloadCasesAndPayloadSizeOffset } - ) - let numEmptyCases = try acrossAllReaders( - file: { fileSubject.layout.numEmptyCases }, - image: { imageSubject.layout.numEmptyCases } - ) - let flagsRaw = try acrossAllReaders( - file: { fileSubject.layout.flags.rawValue }, - image: { imageSubject.layout.flags.rawValue } - ) + let numPayloadCasesAndPayloadSizeOffset = try acrossAllReaders(fileSubject, imageSubject) { descriptor in + descriptor.layout.numPayloadCasesAndPayloadSizeOffset + } + let numEmptyCases = try acrossAllReaders(fileSubject, imageSubject) { $0.layout.numEmptyCases } + let flagsRaw = try acrossAllReaders(fileSubject, imageSubject) { $0.layout.flags.rawValue } #expect(numPayloadCasesAndPayloadSizeOffset == EnumDescriptorBaseline.noPayloadEnumTest.layoutNumPayloadCasesAndPayloadSizeOffset) #expect(numEmptyCases == EnumDescriptorBaseline.noPayloadEnumTest.layoutNumEmptyCases) #expect(flagsRaw == EnumDescriptorBaseline.noPayloadEnumTest.layoutFlagsRawValue) @@ -80,28 +66,19 @@ final class EnumDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @u @Test func numberOfCases() async throws { let (fileSubject, imageSubject) = try loadNoPayloadDescriptors() - let result = try acrossAllReaders( - file: { fileSubject.numberOfCases }, - image: { imageSubject.numberOfCases } - ) + let result = try acrossAllReaders(fileSubject, imageSubject) { $0.numberOfCases } #expect(result == EnumDescriptorBaseline.noPayloadEnumTest.numberOfCases) } @Test func numberOfEmptyCases() async throws { let (fileSubject, imageSubject) = try loadNoPayloadDescriptors() - let result = try acrossAllReaders( - file: { fileSubject.numberOfEmptyCases }, - image: { imageSubject.numberOfEmptyCases } - ) + let result = try acrossAllReaders(fileSubject, imageSubject) { $0.numberOfEmptyCases } #expect(result == EnumDescriptorBaseline.noPayloadEnumTest.numberOfEmptyCases) } @Test func numberOfPayloadCases() async throws { let (fileSubject, imageSubject) = try loadNoPayloadDescriptors() - let result = try acrossAllReaders( - file: { fileSubject.numberOfPayloadCases }, - image: { imageSubject.numberOfPayloadCases } - ) + let result = try acrossAllReaders(fileSubject, imageSubject) { $0.numberOfPayloadCases } #expect(result == EnumDescriptorBaseline.noPayloadEnumTest.numberOfPayloadCases) } @@ -109,19 +86,13 @@ final class EnumDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @u @Test func hasPayloadSizeOffset() async throws { let (fileSubject, imageSubject) = try loadNoPayloadDescriptors() - let result = try acrossAllReaders( - file: { fileSubject.hasPayloadSizeOffset }, - image: { imageSubject.hasPayloadSizeOffset } - ) + let result = try acrossAllReaders(fileSubject, imageSubject) { $0.hasPayloadSizeOffset } #expect(result == EnumDescriptorBaseline.noPayloadEnumTest.hasPayloadSizeOffset) } @Test func payloadSizeOffset() async throws { let (fileSubject, imageSubject) = try loadNoPayloadDescriptors() - let result = try acrossAllReaders( - file: { fileSubject.payloadSizeOffset }, - image: { imageSubject.payloadSizeOffset } - ) + let result = try acrossAllReaders(fileSubject, imageSubject) { $0.payloadSizeOffset } #expect(result == EnumDescriptorBaseline.noPayloadEnumTest.payloadSizeOffset) } @@ -130,50 +101,35 @@ final class EnumDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @u /// Witnessed by `NoPayloadEnumTest`: false (4 cases, not 1). @Test func isSingleEmptyCaseOnly() async throws { let (fileSubject, imageSubject) = try loadNoPayloadDescriptors() - let result = try acrossAllReaders( - file: { fileSubject.isSingleEmptyCaseOnly }, - image: { imageSubject.isSingleEmptyCaseOnly } - ) + let result = try acrossAllReaders(fileSubject, imageSubject) { $0.isSingleEmptyCaseOnly } #expect(result == EnumDescriptorBaseline.noPayloadEnumTest.isSingleEmptyCaseOnly) } /// Witnessed by `NoPayloadEnumTest`: false (no payload case). @Test func isSinglePayloadCaseOnly() async throws { let (fileSubject, imageSubject) = try loadNoPayloadDescriptors() - let result = try acrossAllReaders( - file: { fileSubject.isSinglePayloadCaseOnly }, - image: { imageSubject.isSinglePayloadCaseOnly } - ) + let result = try acrossAllReaders(fileSubject, imageSubject) { $0.isSinglePayloadCaseOnly } #expect(result == EnumDescriptorBaseline.noPayloadEnumTest.isSinglePayloadCaseOnly) } /// Witnessed by `SinglePayloadEnumTest`: 1 payload + 2 empty = `true`. @Test func isSinglePayload() async throws { let (fileSubject, imageSubject) = try loadSinglePayloadDescriptors() - let result = try acrossAllReaders( - file: { fileSubject.isSinglePayload }, - image: { imageSubject.isSinglePayload } - ) + let result = try acrossAllReaders(fileSubject, imageSubject) { $0.isSinglePayload } #expect(result == EnumDescriptorBaseline.singlePayloadEnumTest.isSinglePayload) } /// Witnessed by `MultiPayloadEnumTests`: 3 payloads + 1 empty = `true`. @Test func isMultiPayload() async throws { let (fileSubject, imageSubject) = try loadMultiPayloadDescriptors() - let result = try acrossAllReaders( - file: { fileSubject.isMultiPayload }, - image: { imageSubject.isMultiPayload } - ) + let result = try acrossAllReaders(fileSubject, imageSubject) { $0.isMultiPayload } #expect(result == EnumDescriptorBaseline.multiPayloadEnumTest.isMultiPayload) } /// Witnessed by `SinglePayloadEnumTest`: at least one payload case. @Test func hasPayloadCases() async throws { let (fileSubject, imageSubject) = try loadSinglePayloadDescriptors() - let result = try acrossAllReaders( - file: { fileSubject.hasPayloadCases }, - image: { imageSubject.hasPayloadCases } - ) + let result = try acrossAllReaders(fileSubject, imageSubject) { $0.hasPayloadCases } #expect(result == EnumDescriptorBaseline.singlePayloadEnumTest.hasPayloadCases) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/EnumFunctionsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/EnumFunctionsTests.swift index aaa09591e..3f85335df 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/EnumFunctionsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/EnumFunctionsTests.swift @@ -16,12 +16,8 @@ import SwiftSectionFixtureSupport /// against deterministic inputs and compare against the literal baseline /// — there is no MachO dependency here. @Suite -final class EnumFunctionsTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "EnumTagCounts" - static var registeredTestMethodNames: Set { - EnumFunctionsBaseline.registeredTestMethodNames - } - +@FixtureSuite(testedTypeName: "EnumTagCounts") +final class EnumFunctionsTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test func numTags() async throws { for entry in EnumFunctionsBaseline.cases { let result = getEnumTagCounts( diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/EnumTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/EnumTests.swift index f54e2da15..d67fab41b 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/EnumTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/EnumTests.swift @@ -17,12 +17,8 @@ import SwiftSectionFixtureSupport /// `init(descriptor:in:)` is exercised by dedicated tests over the file /// and image contexts and over the in-process context. @Suite -final class EnumTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "Enum" - static var registeredTestMethodNames: Set { - EnumBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class EnumTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Helper: instantiate the `Enum` wrapper for `Enums.NoPayloadEnumTest` /// against both readers through their reading contexts. private func loadNoPayloadEnums() throws -> (file: Enum, image: Enum) { @@ -59,82 +55,55 @@ final class EnumTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked S @Test func descriptor() async throws { let enums = try loadNoPayloadEnums() - let descriptorOffsets = try acrossAllReaders( - file: { enums.file.descriptor.offset }, - image: { enums.image.descriptor.offset } - ) + let descriptorOffsets = try acrossAllReaders(enums.file, enums.image) { $0.descriptor.offset } #expect(descriptorOffsets == EnumBaseline.noPayloadEnumTest.descriptorOffset) } @Test func genericContext() async throws { let enums = try loadNoPayloadEnums() - let presence = try acrossAllReaders( - file: { enums.file.genericContext != nil }, - image: { enums.image.genericContext != nil } - ) + let presence = try acrossAllReaders(enums.file, enums.image) { $0.genericContext != nil } #expect(presence == EnumBaseline.noPayloadEnumTest.hasGenericContext) } @Test func foreignMetadataInitialization() async throws { let enums = try loadNoPayloadEnums() - let presence = try acrossAllReaders( - file: { enums.file.foreignMetadataInitialization != nil }, - image: { enums.image.foreignMetadataInitialization != nil } - ) + let presence = try acrossAllReaders(enums.file, enums.image) { $0.foreignMetadataInitialization != nil } #expect(presence == EnumBaseline.noPayloadEnumTest.hasForeignMetadataInitialization) } @Test func singletonMetadataInitialization() async throws { let enums = try loadNoPayloadEnums() - let presence = try acrossAllReaders( - file: { enums.file.singletonMetadataInitialization != nil }, - image: { enums.image.singletonMetadataInitialization != nil } - ) + let presence = try acrossAllReaders(enums.file, enums.image) { $0.singletonMetadataInitialization != nil } #expect(presence == EnumBaseline.noPayloadEnumTest.hasSingletonMetadataInitialization) } @Test func canonicalSpecializedMetadatas() async throws { let enums = try loadNoPayloadEnums() - let count = try acrossAllReaders( - file: { enums.file.canonicalSpecializedMetadatas.count }, - image: { enums.image.canonicalSpecializedMetadatas.count } - ) + let count = try acrossAllReaders(enums.file, enums.image) { $0.canonicalSpecializedMetadatas.count } #expect(count == EnumBaseline.noPayloadEnumTest.canonicalSpecializedMetadatasCount) } @Test func canonicalSpecializedMetadatasListCount() async throws { let enums = try loadNoPayloadEnums() - let presence = try acrossAllReaders( - file: { enums.file.canonicalSpecializedMetadatasListCount != nil }, - image: { enums.image.canonicalSpecializedMetadatasListCount != nil } - ) + let presence = try acrossAllReaders(enums.file, enums.image) { $0.canonicalSpecializedMetadatasListCount != nil } #expect(presence == EnumBaseline.noPayloadEnumTest.hasCanonicalSpecializedMetadatasListCount) } @Test func canonicalSpecializedMetadatasCachingOnceToken() async throws { let enums = try loadNoPayloadEnums() - let presence = try acrossAllReaders( - file: { enums.file.canonicalSpecializedMetadatasCachingOnceToken != nil }, - image: { enums.image.canonicalSpecializedMetadatasCachingOnceToken != nil } - ) + let presence = try acrossAllReaders(enums.file, enums.image) { $0.canonicalSpecializedMetadatasCachingOnceToken != nil } #expect(presence == EnumBaseline.noPayloadEnumTest.hasCanonicalSpecializedMetadatasCachingOnceToken) } @Test func invertibleProtocolSet() async throws { let enums = try loadNoPayloadEnums() - let presence = try acrossAllReaders( - file: { enums.file.invertibleProtocolSet != nil }, - image: { enums.image.invertibleProtocolSet != nil } - ) + let presence = try acrossAllReaders(enums.file, enums.image) { $0.invertibleProtocolSet != nil } #expect(presence == EnumBaseline.noPayloadEnumTest.hasInvertibleProtocolSet) } @Test func singletonMetadataPointer() async throws { let enums = try loadNoPayloadEnums() - let presence = try acrossAllReaders( - file: { enums.file.singletonMetadataPointer != nil }, - image: { enums.image.singletonMetadataPointer != nil } - ) + let presence = try acrossAllReaders(enums.file, enums.image) { $0.singletonMetadataPointer != nil } #expect(presence == EnumBaseline.noPayloadEnumTest.hasSingletonMetadataPointer) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/Metadata/EnumMetadataProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/Metadata/EnumMetadataProtocolTests.swift index 9bf7c6948..2c309b313 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/Metadata/EnumMetadataProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/Metadata/EnumMetadataProtocolTests.swift @@ -21,12 +21,8 @@ import SwiftSectionFixtureSupport /// baseline records this invariant. (No fixture in `SymbolTestsCore` /// currently surfaces a non-nil `payloadSize`.) @Suite -final class EnumMetadataProtocolTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "EnumMetadataProtocol" - static var registeredTestMethodNames: Set { - EnumMetadataProtocolBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class EnumMetadataProtocolTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadNoPayloadEnumMetadata() throws -> EnumMetadata { let descriptor = try BaselineFixturePicker.enum_NoPayloadEnumTest(in: machOImage) let accessor = try required(try descriptor.metadataAccessorFunction(in: imageContext)) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/Metadata/EnumMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/Metadata/EnumMetadataTests.swift index a1cae5a81..7de7c1026 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/Metadata/EnumMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/Metadata/EnumMetadataTests.swift @@ -4,6 +4,7 @@ import MachOFoundation @testable import MachOSwiftSection @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import MachOKit /// Fixture-based Suite for `EnumMetadata`. /// @@ -16,12 +17,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class EnumMetadataTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "EnumMetadata" - static var registeredTestMethodNames: Set { - EnumMetadataBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class EnumMetadataTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Materialize an `EnumMetadata` for `Enums.NoPayloadEnumTest` by /// calling the MachOImage metadata accessor and resolving the /// response's value-type wrapper. diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/MultiPayloadEnumDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/MultiPayloadEnumDescriptorTests.swift index d2ac005f0..746ff1d9d 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/MultiPayloadEnumDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/MultiPayloadEnumDescriptorTests.swift @@ -22,12 +22,8 @@ import SwiftSectionFixtureSupport /// All assertions use the multi-payload picker /// (`Enums.MultiPayloadEnumTests`). @Suite -final class MultiPayloadEnumDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "MultiPayloadEnumDescriptor" - static var registeredTestMethodNames: Set { - MultiPayloadEnumDescriptorBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class MultiPayloadEnumDescriptorTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadDescriptors() throws -> (file: MultiPayloadEnumDescriptor, image: MultiPayloadEnumDescriptor) { let file = try BaselineFixturePicker.multiPayloadEnumDescriptor_MultiPayloadEnumTest(in: machOFile) let image = try BaselineFixturePicker.multiPayloadEnumDescriptor_MultiPayloadEnumTest(in: machOImage) @@ -38,19 +34,13 @@ final class MultiPayloadEnumDescriptorTests: MachOSwiftSectionFixtureTests, Fixt @Test func offset() async throws { let (fileSubject, imageSubject) = try loadDescriptors() - let result = try acrossAllReaders( - file: { fileSubject.offset }, - image: { imageSubject.offset } - ) + let result = try acrossAllReaders(fileSubject, imageSubject) { $0.offset } #expect(result == MultiPayloadEnumDescriptorBaseline.multiPayloadEnumTest.offset) } @Test func layout() async throws { let (fileSubject, imageSubject) = try loadDescriptors() - let sizeFlags = try acrossAllReaders( - file: { fileSubject.layout.sizeFlags }, - image: { imageSubject.layout.sizeFlags } - ) + let sizeFlags = try acrossAllReaders(fileSubject, imageSubject) { $0.layout.sizeFlags } #expect(sizeFlags == MultiPayloadEnumDescriptorBaseline.multiPayloadEnumTest.layoutSizeFlags) } @@ -58,46 +48,41 @@ final class MultiPayloadEnumDescriptorTests: MachOSwiftSectionFixtureTests, Fixt @Test func mangledTypeName() async throws { let (fileSubject, imageSubject) = try loadDescriptors() - let rawString = try acrossAllContexts( - file: { try fileSubject.mangledTypeName(in: fileContext).rawString }, - image: { try imageSubject.mangledTypeName(in: imageContext).rawString } - ) + let rawString = try acrossAllContexts(fileSubject, imageSubject) { descriptor, context in + try descriptor.mangledTypeName(in: context).rawString + } #expect(rawString == MultiPayloadEnumDescriptorBaseline.multiPayloadEnumTest.mangledTypeNameRawString) } @Test func contents() async throws { let (fileSubject, imageSubject) = try loadDescriptors() - let count = try acrossAllContexts( - file: { try fileSubject.contents(in: fileContext).count }, - image: { try imageSubject.contents(in: imageContext).count } - ) + let count = try acrossAllContexts(fileSubject, imageSubject) { descriptor, context in + try descriptor.contents(in: context).count + } #expect(count == MultiPayloadEnumDescriptorBaseline.multiPayloadEnumTest.contentsCount) } @Test func payloadSpareBits() async throws { let (fileSubject, imageSubject) = try loadDescriptors() - let count = try acrossAllContexts( - file: { try fileSubject.payloadSpareBits(in: fileContext).count }, - image: { try imageSubject.payloadSpareBits(in: imageContext).count } - ) + let count = try acrossAllContexts(fileSubject, imageSubject) { descriptor, context in + try descriptor.payloadSpareBits(in: context).count + } #expect(count == MultiPayloadEnumDescriptorBaseline.multiPayloadEnumTest.payloadSpareBitsCount) } @Test func payloadSpareBitMaskByteOffset() async throws { let (fileSubject, imageSubject) = try loadDescriptors() - let result = try acrossAllContexts( - file: { try fileSubject.payloadSpareBitMaskByteOffset(in: fileContext) }, - image: { try imageSubject.payloadSpareBitMaskByteOffset(in: imageContext) } - ) + let result = try acrossAllContexts(fileSubject, imageSubject) { descriptor, context in + try descriptor.payloadSpareBitMaskByteOffset(in: context) + } #expect(result == MultiPayloadEnumDescriptorBaseline.multiPayloadEnumTest.payloadSpareBitMaskByteOffset) } @Test func payloadSpareBitMaskByteCount() async throws { let (fileSubject, imageSubject) = try loadDescriptors() - let result = try acrossAllContexts( - file: { try fileSubject.payloadSpareBitMaskByteCount(in: fileContext) }, - image: { try imageSubject.payloadSpareBitMaskByteCount(in: imageContext) } - ) + let result = try acrossAllContexts(fileSubject, imageSubject) { descriptor, context in + try descriptor.payloadSpareBitMaskByteCount(in: context) + } #expect(result == MultiPayloadEnumDescriptorBaseline.multiPayloadEnumTest.payloadSpareBitMaskByteCount) } @@ -105,64 +90,43 @@ final class MultiPayloadEnumDescriptorTests: MachOSwiftSectionFixtureTests, Fixt @Test func contentsSizeInWord() async throws { let (fileSubject, imageSubject) = try loadDescriptors() - let result = try acrossAllReaders( - file: { fileSubject.contentsSizeInWord }, - image: { imageSubject.contentsSizeInWord } - ) + let result = try acrossAllReaders(fileSubject, imageSubject) { $0.contentsSizeInWord } #expect(result == MultiPayloadEnumDescriptorBaseline.multiPayloadEnumTest.contentsSizeInWord) } @Test func flags() async throws { let (fileSubject, imageSubject) = try loadDescriptors() - let result = try acrossAllReaders( - file: { fileSubject.flags }, - image: { imageSubject.flags } - ) + let result = try acrossAllReaders(fileSubject, imageSubject) { $0.flags } #expect(result == MultiPayloadEnumDescriptorBaseline.multiPayloadEnumTest.flags) } @Test func usesPayloadSpareBits() async throws { let (fileSubject, imageSubject) = try loadDescriptors() - let result = try acrossAllReaders( - file: { fileSubject.usesPayloadSpareBits }, - image: { imageSubject.usesPayloadSpareBits } - ) + let result = try acrossAllReaders(fileSubject, imageSubject) { $0.usesPayloadSpareBits } #expect(result == MultiPayloadEnumDescriptorBaseline.multiPayloadEnumTest.usesPayloadSpareBits) } @Test func sizeFlagsIndex() async throws { let (fileSubject, imageSubject) = try loadDescriptors() - let result = try acrossAllReaders( - file: { fileSubject.sizeFlagsIndex }, - image: { imageSubject.sizeFlagsIndex } - ) + let result = try acrossAllReaders(fileSubject, imageSubject) { $0.sizeFlagsIndex } #expect(result == MultiPayloadEnumDescriptorBaseline.multiPayloadEnumTest.sizeFlagsIndex) } @Test func payloadSpareBitMaskByteCountIndex() async throws { let (fileSubject, imageSubject) = try loadDescriptors() - let result = try acrossAllReaders( - file: { fileSubject.payloadSpareBitMaskByteCountIndex }, - image: { imageSubject.payloadSpareBitMaskByteCountIndex } - ) + let result = try acrossAllReaders(fileSubject, imageSubject) { $0.payloadSpareBitMaskByteCountIndex } #expect(result == MultiPayloadEnumDescriptorBaseline.multiPayloadEnumTest.payloadSpareBitMaskByteCountIndex) } @Test func payloadSpareBitsIndex() async throws { let (fileSubject, imageSubject) = try loadDescriptors() - let result = try acrossAllReaders( - file: { fileSubject.payloadSpareBitsIndex }, - image: { imageSubject.payloadSpareBitsIndex } - ) + let result = try acrossAllReaders(fileSubject, imageSubject) { $0.payloadSpareBitsIndex } #expect(result == MultiPayloadEnumDescriptorBaseline.multiPayloadEnumTest.payloadSpareBitsIndex) } @Test func actualSize() async throws { let (fileSubject, imageSubject) = try loadDescriptors() - let result = try acrossAllReaders( - file: { fileSubject.actualSize }, - image: { imageSubject.actualSize } - ) + let result = try acrossAllReaders(fileSubject, imageSubject) { $0.actualSize } #expect(result == MultiPayloadEnumDescriptorBaseline.multiPayloadEnumTest.actualSize) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructDescriptorTests.swift index 6bdb14b62..b3d83585b 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructDescriptorTests.swift @@ -14,12 +14,8 @@ import SwiftSectionFixtureSupport /// `TypeContextDescriptorProtocol` and are exercised in Task 9 under /// `TypeContextDescriptorProtocolTests`. @Suite -final class StructDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "StructDescriptor" - static var registeredTestMethodNames: Set { - StructDescriptorBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class StructDescriptorTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// `StructDescriptor.offset` is the file/image position of the descriptor /// record. Cross-reader equality holds: both `MachOFile` and `MachOImage` /// resolve the same offset (in-process pointer arithmetic relative to the @@ -28,10 +24,7 @@ final class StructDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, let fileSubject = try BaselineFixturePicker.struct_StructTest(in: machOFile) let imageSubject = try BaselineFixturePicker.struct_StructTest(in: machOImage) - let result = try acrossAllReaders( - file: { fileSubject.offset }, - image: { imageSubject.offset } - ) + let result = try acrossAllReaders(fileSubject, imageSubject) { $0.offset } #expect(result == StructDescriptorBaseline.structTest.offset) } @@ -46,18 +39,9 @@ final class StructDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, let imageSubject = try BaselineFixturePicker.struct_StructTest(in: machOImage) // Cross-reader equality on the metadata-relevant scalar fields. - let numFields = try acrossAllReaders( - file: { fileSubject.layout.numFields }, - image: { imageSubject.layout.numFields } - ) - let fieldOffsetVector = try acrossAllReaders( - file: { fileSubject.layout.fieldOffsetVector }, - image: { imageSubject.layout.fieldOffsetVector } - ) - let flagsRaw = try acrossAllReaders( - file: { fileSubject.layout.flags.rawValue }, - image: { imageSubject.layout.flags.rawValue } - ) + let numFields = try acrossAllReaders(fileSubject, imageSubject) { $0.layout.numFields } + let fieldOffsetVector = try acrossAllReaders(fileSubject, imageSubject) { $0.layout.fieldOffsetVector } + let flagsRaw = try acrossAllReaders(fileSubject, imageSubject) { $0.layout.flags.rawValue } // Baseline literal equality. #expect(Int(numFields) == StructDescriptorBaseline.structTest.layoutNumFields) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructMetadataProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructMetadataProtocolTests.swift index 4811c684a..0cd8c659c 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructMetadataProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructMetadataProtocolTests.swift @@ -13,12 +13,8 @@ import SwiftSectionFixtureSupport /// asymmetric (the metadata originates from MachOImage but its methods /// accept the file/image/inProcess context families). @Suite -final class StructMetadataProtocolTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "StructMetadataProtocol" - static var registeredTestMethodNames: Set { - StructMetadataProtocolBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class StructMetadataProtocolTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadStructTestMetadata() throws -> StructMetadata { let descriptor = try BaselineFixturePicker.struct_StructTest(in: machOImage) let accessor = try required(try descriptor.metadataAccessorFunction(in: imageContext)) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructMetadataTests.swift index 93d5440a4..1856514be 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructMetadataTests.swift @@ -4,6 +4,7 @@ import MachOFoundation @testable import MachOSwiftSection @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import MachOKit /// Fixture-based Suite for `StructMetadata`. /// @@ -16,12 +17,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class StructMetadataTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "StructMetadata" - static var registeredTestMethodNames: Set { - StructMetadataBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class StructMetadataTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Materialize a `StructMetadata` for `Structs.StructTest` by calling the /// MachOImage metadata accessor and resolving the response. Returns `nil` /// only if the accessor isn't reachable for the descriptor (which we diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructTests.swift index d7ae16c26..fb38a9579 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructTests.swift @@ -21,12 +21,8 @@ import SwiftSectionFixtureSupport /// `Struct`; we surface explicit `@Test func init...` entries for coverage /// purposes. @Suite -final class StructTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "Struct" - static var registeredTestMethodNames: Set { - StructBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class StructTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Helper: instantiate the `Struct` wrapper for `Structs.StructTest` against /// both the file and image readers through their reading contexts. /// Used by every ivar test — the file/image-context and in-process @@ -73,20 +69,14 @@ final class StructTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked @Test func descriptor() async throws { let structs = try loadStructTestStructs() - let descriptorOffsets = try acrossAllReaders( - file: { structs.file.descriptor.offset }, - image: { structs.image.descriptor.offset } - ) + let descriptorOffsets = try acrossAllReaders(structs.file, structs.image) { $0.descriptor.offset } #expect(descriptorOffsets == StructBaseline.structTest.descriptorOffset) } @Test func genericContext() async throws { // Concrete struct (`StructTest`): no generic context. let structs = try loadStructTestStructs() - let structTestPresence = try acrossAllReaders( - file: { structs.file.genericContext != nil }, - image: { structs.image.genericContext != nil } - ) + let structTestPresence = try acrossAllReaders(structs.file, structs.image) { $0.genericContext != nil } #expect(structTestPresence == StructBaseline.structTest.hasGenericContext) // Generic struct (`GenericStructNonRequirement`): has a generic context. @@ -98,73 +88,51 @@ final class StructTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked descriptor: try BaselineFixturePicker.struct_GenericStructNonRequirement(in: machOImage), in: imageContext ) - let genericPresence = try acrossAllReaders( - file: { genericFile.genericContext != nil }, - image: { genericImage.genericContext != nil } - ) + let genericPresence = try acrossAllReaders(genericFile, genericImage) { $0.genericContext != nil } #expect(genericPresence == StructBaseline.genericStructNonRequirement.hasGenericContext) } @Test func foreignMetadataInitialization() async throws { let structs = try loadStructTestStructs() - let presence = try acrossAllReaders( - file: { structs.file.foreignMetadataInitialization != nil }, - image: { structs.image.foreignMetadataInitialization != nil } - ) + let presence = try acrossAllReaders(structs.file, structs.image) { $0.foreignMetadataInitialization != nil } #expect(presence == StructBaseline.structTest.hasForeignMetadataInitialization) } @Test func singletonMetadataInitialization() async throws { let structs = try loadStructTestStructs() - let presence = try acrossAllReaders( - file: { structs.file.singletonMetadataInitialization != nil }, - image: { structs.image.singletonMetadataInitialization != nil } - ) + let presence = try acrossAllReaders(structs.file, structs.image) { $0.singletonMetadataInitialization != nil } #expect(presence == StructBaseline.structTest.hasSingletonMetadataInitialization) } @Test func canonicalSpecializedMetadatas() async throws { let structs = try loadStructTestStructs() - let count = try acrossAllReaders( - file: { structs.file.canonicalSpecializedMetadatas.count }, - image: { structs.image.canonicalSpecializedMetadatas.count } - ) + let count = try acrossAllReaders(structs.file, structs.image) { $0.canonicalSpecializedMetadatas.count } #expect(count == StructBaseline.structTest.canonicalSpecializedMetadatasCount) } @Test func canonicalSpecializedMetadatasListCount() async throws { let structs = try loadStructTestStructs() - let presence = try acrossAllReaders( - file: { structs.file.canonicalSpecializedMetadatasListCount != nil }, - image: { structs.image.canonicalSpecializedMetadatasListCount != nil } - ) + let presence = try acrossAllReaders(structs.file, structs.image) { $0.canonicalSpecializedMetadatasListCount != nil } #expect(presence == StructBaseline.structTest.hasCanonicalSpecializedMetadatasListCount) } @Test func canonicalSpecializedMetadatasCachingOnceToken() async throws { let structs = try loadStructTestStructs() - let presence = try acrossAllReaders( - file: { structs.file.canonicalSpecializedMetadatasCachingOnceToken != nil }, - image: { structs.image.canonicalSpecializedMetadatasCachingOnceToken != nil } - ) + let presence = try acrossAllReaders(structs.file, structs.image) { swiftStruct in + swiftStruct.canonicalSpecializedMetadatasCachingOnceToken != nil + } #expect(presence == StructBaseline.structTest.hasCanonicalSpecializedMetadatasCachingOnceToken) } @Test func invertibleProtocolSet() async throws { let structs = try loadStructTestStructs() - let presence = try acrossAllReaders( - file: { structs.file.invertibleProtocolSet != nil }, - image: { structs.image.invertibleProtocolSet != nil } - ) + let presence = try acrossAllReaders(structs.file, structs.image) { $0.invertibleProtocolSet != nil } #expect(presence == StructBaseline.structTest.hasInvertibleProtocolSet) } @Test func singletonMetadataPointer() async throws { let structs = try loadStructTestStructs() - let presence = try acrossAllReaders( - file: { structs.file.singletonMetadataPointer != nil }, - image: { structs.image.singletonMetadataPointer != nil } - ) + let presence = try acrossAllReaders(structs.file, structs.image) { $0.singletonMetadataPointer != nil } #expect(presence == StructBaseline.structTest.hasSingletonMetadataPointer) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextDescriptorFlagsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextDescriptorFlagsTests.swift index 6318fdcb6..1914aae01 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextDescriptorFlagsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextDescriptorFlagsTests.swift @@ -15,12 +15,8 @@ import SwiftSectionFixtureSupport /// - `Classes.ClassTest` for the class-specific accessors (so /// `classHasVTable` and friends have a real-world value to assert). @Suite -final class TypeContextDescriptorFlagsTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "TypeContextDescriptorFlags" - static var registeredTestMethodNames: Set { - TypeContextDescriptorFlagsBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class TypeContextDescriptorFlagsTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadStructTestFlags() throws -> (file: TypeContextDescriptorFlags, image: TypeContextDescriptorFlags) { let fileDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOImage) @@ -39,10 +35,7 @@ final class TypeContextDescriptorFlagsTests: MachOSwiftSectionFixtureTests, Fixt @Test func rawValue() async throws { let flags = try loadStructTestFlags() - let result = try acrossAllReaders( - file: { flags.file.rawValue }, - image: { flags.image.rawValue } - ) + let result = try acrossAllReaders(flags.file, flags.image) { $0.rawValue } #expect(result == TypeContextDescriptorFlagsBaseline.structTest.rawValue) } @@ -63,28 +56,19 @@ final class TypeContextDescriptorFlagsTests: MachOSwiftSectionFixtureTests, Fixt @Test func noMetadataInitialization() async throws { let flags = try loadStructTestFlags() - let result = try acrossAllReaders( - file: { flags.file.noMetadataInitialization }, - image: { flags.image.noMetadataInitialization } - ) + let result = try acrossAllReaders(flags.file, flags.image) { $0.noMetadataInitialization } #expect(result == TypeContextDescriptorFlagsBaseline.structTest.noMetadataInitialization) } @Test func hasSingletonMetadataInitialization() async throws { let flags = try loadStructTestFlags() - let result = try acrossAllReaders( - file: { flags.file.hasSingletonMetadataInitialization }, - image: { flags.image.hasSingletonMetadataInitialization } - ) + let result = try acrossAllReaders(flags.file, flags.image) { $0.hasSingletonMetadataInitialization } #expect(result == TypeContextDescriptorFlagsBaseline.structTest.hasSingletonMetadataInitialization) } @Test func hasForeignMetadataInitialization() async throws { let flags = try loadStructTestFlags() - let result = try acrossAllReaders( - file: { flags.file.hasForeignMetadataInitialization }, - image: { flags.image.hasForeignMetadataInitialization } - ) + let result = try acrossAllReaders(flags.file, flags.image) { $0.hasForeignMetadataInitialization } #expect(result == TypeContextDescriptorFlagsBaseline.structTest.hasForeignMetadataInitialization) } @@ -92,28 +76,21 @@ final class TypeContextDescriptorFlagsTests: MachOSwiftSectionFixtureTests, Fixt @Test func hasImportInfo() async throws { let flags = try loadStructTestFlags() - let result = try acrossAllReaders( - file: { flags.file.hasImportInfo }, - image: { flags.image.hasImportInfo } - ) + let result = try acrossAllReaders(flags.file, flags.image) { $0.hasImportInfo } #expect(result == TypeContextDescriptorFlagsBaseline.structTest.hasImportInfo) } @Test func hasCanonicalMetadataPrespecializationsOrSingletonMetadataPointer() async throws { let flags = try loadStructTestFlags() - let result = try acrossAllReaders( - file: { flags.file.hasCanonicalMetadataPrespecializationsOrSingletonMetadataPointer }, - image: { flags.image.hasCanonicalMetadataPrespecializationsOrSingletonMetadataPointer } - ) + let result = try acrossAllReaders(flags.file, flags.image) { descriptorFlags in + descriptorFlags.hasCanonicalMetadataPrespecializationsOrSingletonMetadataPointer + } #expect(result == TypeContextDescriptorFlagsBaseline.structTest.hasCanonicalMetadataPrespecializationsOrSingletonMetadataPointer) } @Test func hasLayoutString() async throws { let flags = try loadStructTestFlags() - let result = try acrossAllReaders( - file: { flags.file.hasLayoutString }, - image: { flags.image.hasLayoutString } - ) + let result = try acrossAllReaders(flags.file, flags.image) { $0.hasLayoutString } #expect(result == TypeContextDescriptorFlagsBaseline.structTest.hasLayoutString) } @@ -121,64 +98,43 @@ final class TypeContextDescriptorFlagsTests: MachOSwiftSectionFixtureTests, Fixt @Test func classHasDefaultOverrideTable() async throws { let flags = try loadClassTestFlags() - let result = try acrossAllReaders( - file: { flags.file.classHasDefaultOverrideTable }, - image: { flags.image.classHasDefaultOverrideTable } - ) + let result = try acrossAllReaders(flags.file, flags.image) { $0.classHasDefaultOverrideTable } #expect(result == TypeContextDescriptorFlagsBaseline.classTest.classHasDefaultOverrideTable) } @Test func classIsActor() async throws { let flags = try loadClassTestFlags() - let result = try acrossAllReaders( - file: { flags.file.classIsActor }, - image: { flags.image.classIsActor } - ) + let result = try acrossAllReaders(flags.file, flags.image) { $0.classIsActor } #expect(result == TypeContextDescriptorFlagsBaseline.classTest.classIsActor) } @Test func classIsDefaultActor() async throws { let flags = try loadClassTestFlags() - let result = try acrossAllReaders( - file: { flags.file.classIsDefaultActor }, - image: { flags.image.classIsDefaultActor } - ) + let result = try acrossAllReaders(flags.file, flags.image) { $0.classIsDefaultActor } #expect(result == TypeContextDescriptorFlagsBaseline.classTest.classIsDefaultActor) } @Test func classResilientSuperclassReferenceKind() async throws { let flags = try loadClassTestFlags() - let result = try acrossAllReaders( - file: { flags.file.classResilientSuperclassReferenceKind?.rawValue }, - image: { flags.image.classResilientSuperclassReferenceKind?.rawValue } - ) + let result = try acrossAllReaders(flags.file, flags.image) { $0.classResilientSuperclassReferenceKind?.rawValue } #expect(result == TypeContextDescriptorFlagsBaseline.classTest.classResilientSuperclassReferenceKindRawValue) } @Test func classAreImmdiateMembersNegative() async throws { let flags = try loadClassTestFlags() - let result = try acrossAllReaders( - file: { flags.file.classAreImmdiateMembersNegative }, - image: { flags.image.classAreImmdiateMembersNegative } - ) + let result = try acrossAllReaders(flags.file, flags.image) { $0.classAreImmdiateMembersNegative } #expect(result == TypeContextDescriptorFlagsBaseline.classTest.classAreImmdiateMembersNegative) } @Test func classHasResilientSuperclass() async throws { let flags = try loadClassTestFlags() - let result = try acrossAllReaders( - file: { flags.file.classHasResilientSuperclass }, - image: { flags.image.classHasResilientSuperclass } - ) + let result = try acrossAllReaders(flags.file, flags.image) { $0.classHasResilientSuperclass } #expect(result == TypeContextDescriptorFlagsBaseline.classTest.classHasResilientSuperclass) } @Test func classHasOverrideTable() async throws { let flags = try loadClassTestFlags() - let result = try acrossAllReaders( - file: { flags.file.classHasOverrideTable }, - image: { flags.image.classHasOverrideTable } - ) + let result = try acrossAllReaders(flags.file, flags.image) { $0.classHasOverrideTable } #expect(result == TypeContextDescriptorFlagsBaseline.classTest.classHasOverrideTable) } @@ -186,10 +142,7 @@ final class TypeContextDescriptorFlagsTests: MachOSwiftSectionFixtureTests, Fixt /// specific flags carry the high bit (`classHasVTable: true`). @Test func classHasVTable() async throws { let flags = try loadClassTestFlags() - let result = try acrossAllReaders( - file: { flags.file.classHasVTable }, - image: { flags.image.classHasVTable } - ) + let result = try acrossAllReaders(flags.file, flags.image) { $0.classHasVTable } #expect(result == TypeContextDescriptorFlagsBaseline.classTest.classHasVTable) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextDescriptorProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextDescriptorProtocolTests.swift index ee739b3c3..91590d606 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextDescriptorProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextDescriptorProtocolTests.swift @@ -20,12 +20,8 @@ import SwiftSectionFixtureSupport /// /// Picker: `Structs.StructTest`'s descriptor. @Suite -final class TypeContextDescriptorProtocolTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "TypeContextDescriptorProtocol" - static var registeredTestMethodNames: Set { - TypeContextDescriptorProtocolBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class TypeContextDescriptorProtocolTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadStructTestDescriptors() throws -> (file: StructDescriptor, image: StructDescriptor) { let file = try BaselineFixturePicker.struct_StructTest(in: machOFile) let image = try BaselineFixturePicker.struct_StructTest(in: machOImage) @@ -34,28 +30,25 @@ final class TypeContextDescriptorProtocolTests: MachOSwiftSectionFixtureTests, F @Test func fieldDescriptor() async throws { let (fileSubject, imageSubject) = try loadStructTestDescriptors() - let presence = try acrossAllContexts( - file: { (try? fileSubject.fieldDescriptor(in: fileContext)) != nil }, - image: { (try? imageSubject.fieldDescriptor(in: imageContext)) != nil } - ) + let presence = try acrossAllContexts(fileSubject, imageSubject) { descriptor, context in + (try? descriptor.fieldDescriptor(in: context)) != nil + } #expect(presence == TypeContextDescriptorProtocolBaseline.structTest.hasFieldDescriptor) } @Test func genericContext() async throws { let (fileSubject, imageSubject) = try loadStructTestDescriptors() - let presence = try acrossAllContexts( - file: { (try fileSubject.genericContext(in: fileContext)) != nil }, - image: { (try imageSubject.genericContext(in: imageContext)) != nil } - ) + let presence = try acrossAllContexts(fileSubject, imageSubject) { descriptor, context in + (try descriptor.genericContext(in: context)) != nil + } #expect(presence == TypeContextDescriptorProtocolBaseline.structTest.hasGenericContext) } @Test func typeGenericContext() async throws { let (fileSubject, imageSubject) = try loadStructTestDescriptors() - let presence = try acrossAllContexts( - file: { (try fileSubject.typeGenericContext(in: fileContext)) != nil }, - image: { (try imageSubject.typeGenericContext(in: imageContext)) != nil } - ) + let presence = try acrossAllContexts(fileSubject, imageSubject) { descriptor, context in + (try descriptor.typeGenericContext(in: context)) != nil + } #expect(presence == TypeContextDescriptorProtocolBaseline.structTest.hasTypeGenericContext) } @@ -74,28 +67,19 @@ final class TypeContextDescriptorProtocolTests: MachOSwiftSectionFixtureTests, F @Test func hasSingletonMetadataInitialization() async throws { let (fileSubject, imageSubject) = try loadStructTestDescriptors() - let result = try acrossAllReaders( - file: { fileSubject.hasSingletonMetadataInitialization }, - image: { imageSubject.hasSingletonMetadataInitialization } - ) + let result = try acrossAllReaders(fileSubject, imageSubject) { $0.hasSingletonMetadataInitialization } #expect(result == TypeContextDescriptorProtocolBaseline.structTest.hasSingletonMetadataInitialization) } @Test func hasForeignMetadataInitialization() async throws { let (fileSubject, imageSubject) = try loadStructTestDescriptors() - let result = try acrossAllReaders( - file: { fileSubject.hasForeignMetadataInitialization }, - image: { imageSubject.hasForeignMetadataInitialization } - ) + let result = try acrossAllReaders(fileSubject, imageSubject) { $0.hasForeignMetadataInitialization } #expect(result == TypeContextDescriptorProtocolBaseline.structTest.hasForeignMetadataInitialization) } @Test func hasImportInfo() async throws { let (fileSubject, imageSubject) = try loadStructTestDescriptors() - let result = try acrossAllReaders( - file: { fileSubject.hasImportInfo }, - image: { imageSubject.hasImportInfo } - ) + let result = try acrossAllReaders(fileSubject, imageSubject) { $0.hasImportInfo } #expect(result == TypeContextDescriptorProtocolBaseline.structTest.hasImportInfo) } @@ -104,19 +88,17 @@ final class TypeContextDescriptorProtocolTests: MachOSwiftSectionFixtureTests, F /// C-typedef namespace, identically through every reader. @Test func typeImportInfo() async throws { let (fileSubject, imageSubject) = try loadStructTestDescriptors() - let swiftResult = try acrossAllContexts( - file: { try fileSubject.typeImportInfo(in: fileContext) }, - image: { try imageSubject.typeImportInfo(in: imageContext) } - ) + let swiftResult = try acrossAllContexts(fileSubject, imageSubject) { descriptor, context in + try descriptor.typeImportInfo(in: context) + } #expect(swiftResult == nil) #expect(TypeContextDescriptorProtocolBaseline.structTest.typeImportInfoABIName == nil) let foreignFile = try BaselineFixturePicker.struct_ForeignDecimal(in: machOFile) let foreignImage = try BaselineFixturePicker.struct_ForeignDecimal(in: machOImage) - let foreignResult = try acrossAllContexts( - file: { try foreignFile.typeImportInfo(in: fileContext) }, - image: { try foreignImage.typeImportInfo(in: imageContext) } - ) + let foreignResult = try acrossAllContexts(foreignFile, foreignImage) { descriptor, context in + try descriptor.typeImportInfo(in: context) + } let expected = TypeContextDescriptorProtocolBaseline.foreignDecimal #expect(foreignResult?.abiName == expected.typeImportInfoABIName) #expect(foreignResult?.symbolNamespace == expected.typeImportInfoSymbolNamespace) @@ -127,37 +109,27 @@ final class TypeContextDescriptorProtocolTests: MachOSwiftSectionFixtureTests, F @Test func hasCanonicalMetadataPrespecializationsOrSingletonMetadataPointer() async throws { let (fileSubject, imageSubject) = try loadStructTestDescriptors() - let result = try acrossAllReaders( - file: { fileSubject.hasCanonicalMetadataPrespecializationsOrSingletonMetadataPointer }, - image: { imageSubject.hasCanonicalMetadataPrespecializationsOrSingletonMetadataPointer } - ) + let result = try acrossAllReaders(fileSubject, imageSubject) { descriptor in + descriptor.hasCanonicalMetadataPrespecializationsOrSingletonMetadataPointer + } #expect(result == TypeContextDescriptorProtocolBaseline.structTest.hasCanonicalMetadataPrespecializationsOrSingletonMetadataPointer) } @Test func hasLayoutString() async throws { let (fileSubject, imageSubject) = try loadStructTestDescriptors() - let result = try acrossAllReaders( - file: { fileSubject.hasLayoutString }, - image: { imageSubject.hasLayoutString } - ) + let result = try acrossAllReaders(fileSubject, imageSubject) { $0.hasLayoutString } #expect(result == TypeContextDescriptorProtocolBaseline.structTest.hasLayoutString) } @Test func hasCanonicalMetadataPrespecializations() async throws { let (fileSubject, imageSubject) = try loadStructTestDescriptors() - let result = try acrossAllReaders( - file: { fileSubject.hasCanonicalMetadataPrespecializations }, - image: { imageSubject.hasCanonicalMetadataPrespecializations } - ) + let result = try acrossAllReaders(fileSubject, imageSubject) { $0.hasCanonicalMetadataPrespecializations } #expect(result == TypeContextDescriptorProtocolBaseline.structTest.hasCanonicalMetadataPrespecializations) } @Test func hasSingletonMetadataPointer() async throws { let (fileSubject, imageSubject) = try loadStructTestDescriptors() - let result = try acrossAllReaders( - file: { fileSubject.hasSingletonMetadataPointer }, - image: { imageSubject.hasSingletonMetadataPointer } - ) + let result = try acrossAllReaders(fileSubject, imageSubject) { $0.hasSingletonMetadataPointer } #expect(result == TypeContextDescriptorProtocolBaseline.structTest.hasSingletonMetadataPointer) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextDescriptorTests.swift index b0e3c1da2..04dac4b41 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextDescriptorTests.swift @@ -22,12 +22,8 @@ import SwiftSectionFixtureSupport /// header at its offset gives us `structDescriptor()` non-nil and the /// other two kind-projections nil. @Suite -final class TypeContextDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "TypeContextDescriptor" - static var registeredTestMethodNames: Set { - TypeContextDescriptorBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class TypeContextDescriptorTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Helper: read the bare `TypeContextDescriptor` header at the /// `Structs.StructTest` offset against both readers. private func loadStructTestDescriptors() throws -> (file: TypeContextDescriptor, image: TypeContextDescriptor) { @@ -40,10 +36,7 @@ final class TypeContextDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSu @Test func offset() async throws { let descriptors = try loadStructTestDescriptors() - let result = try acrossAllReaders( - file: { descriptors.file.offset }, - image: { descriptors.image.offset } - ) + let result = try acrossAllReaders(descriptors.file, descriptors.image) { $0.offset } #expect(result == TypeContextDescriptorBaseline.structTest.offset) } @@ -52,10 +45,7 @@ final class TypeContextDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSu // Cross-reader equality on the only stable scalar field // (`flags.rawValue`); other layout fields are relative pointers // whose value varies by reader. - let flagsRaw = try acrossAllReaders( - file: { descriptors.file.layout.flags.rawValue }, - image: { descriptors.image.layout.flags.rawValue } - ) + let flagsRaw = try acrossAllReaders(descriptors.file, descriptors.image) { $0.layout.flags.rawValue } #expect(flagsRaw == TypeContextDescriptorBaseline.structTest.layoutFlagsRawValue) } @@ -64,10 +54,9 @@ final class TypeContextDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSu /// is exercised end-to-end via the Type/Enum Suites. @Test func enumDescriptor() async throws { let descriptors = try loadStructTestDescriptors() - let presence = try acrossAllContexts( - file: { (try descriptors.file.enumDescriptor(in: fileContext)) != nil }, - image: { (try descriptors.image.enumDescriptor(in: imageContext)) != nil } - ) + let presence = try acrossAllContexts(descriptors.file, descriptors.image) { descriptor, context in + (try descriptor.enumDescriptor(in: context)) != nil + } #expect(presence == TypeContextDescriptorBaseline.structTest.hasEnumDescriptor) } @@ -75,10 +64,9 @@ final class TypeContextDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSu /// for our struct fixture. Witnesses the true branch. @Test func structDescriptor() async throws { let descriptors = try loadStructTestDescriptors() - let presence = try acrossAllContexts( - file: { (try descriptors.file.structDescriptor(in: fileContext)) != nil }, - image: { (try descriptors.image.structDescriptor(in: imageContext)) != nil } - ) + let presence = try acrossAllContexts(descriptors.file, descriptors.image) { descriptor, context in + (try descriptor.structDescriptor(in: context)) != nil + } #expect(presence == TypeContextDescriptorBaseline.structTest.hasStructDescriptor) } @@ -87,10 +75,9 @@ final class TypeContextDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSu /// is exercised end-to-end via the Type/Class Suites. @Test func classDescriptor() async throws { let descriptors = try loadStructTestDescriptors() - let presence = try acrossAllContexts( - file: { (try descriptors.file.classDescriptor(in: fileContext)) != nil }, - image: { (try descriptors.image.classDescriptor(in: imageContext)) != nil } - ) + let presence = try acrossAllContexts(descriptors.file, descriptors.image) { descriptor, context in + (try descriptor.classDescriptor(in: context)) != nil + } #expect(presence == TypeContextDescriptorBaseline.structTest.hasClassDescriptor) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextDescriptorWrapperTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextDescriptorWrapperTests.swift index 61f2edce2..aa32d3ddc 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextDescriptorWrapperTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextDescriptorWrapperTests.swift @@ -19,12 +19,8 @@ import SwiftSectionFixtureSupport /// /// Picker: `Structs.StructTest`'s descriptor wrapped in `.struct(...)`. @Suite -final class TypeContextDescriptorWrapperTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "TypeContextDescriptorWrapper" - static var registeredTestMethodNames: Set { - TypeContextDescriptorWrapperBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class TypeContextDescriptorWrapperTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadStructTestWrappers() throws -> (file: TypeContextDescriptorWrapper, image: TypeContextDescriptorWrapper) { let file = try BaselineFixturePicker.struct_StructTest(in: machOFile) let image = try BaselineFixturePicker.struct_StructTest(in: machOImage) @@ -35,28 +31,19 @@ final class TypeContextDescriptorWrapperTests: MachOSwiftSectionFixtureTests, Fi @Test func contextDescriptor() async throws { let wrappers = try loadStructTestWrappers() - let result = try acrossAllReaders( - file: { wrappers.file.contextDescriptor.offset }, - image: { wrappers.image.contextDescriptor.offset } - ) + let result = try acrossAllReaders(wrappers.file, wrappers.image) { $0.contextDescriptor.offset } #expect(result == TypeContextDescriptorWrapperBaseline.structTest.descriptorOffset) } @Test func namedContextDescriptor() async throws { let wrappers = try loadStructTestWrappers() - let result = try acrossAllReaders( - file: { wrappers.file.namedContextDescriptor.offset }, - image: { wrappers.image.namedContextDescriptor.offset } - ) + let result = try acrossAllReaders(wrappers.file, wrappers.image) { $0.namedContextDescriptor.offset } #expect(result == TypeContextDescriptorWrapperBaseline.structTest.descriptorOffset) } @Test func typeContextDescriptor() async throws { let wrappers = try loadStructTestWrappers() - let result = try acrossAllReaders( - file: { wrappers.file.typeContextDescriptor.offset }, - image: { wrappers.image.typeContextDescriptor.offset } - ) + let result = try acrossAllReaders(wrappers.file, wrappers.image) { $0.typeContextDescriptor.offset } #expect(result == TypeContextDescriptorWrapperBaseline.structTest.descriptorOffset) } @@ -64,10 +51,9 @@ final class TypeContextDescriptorWrapperTests: MachOSwiftSectionFixtureTests, Fi let wrappers = try loadStructTestWrappers() // `asContextDescriptorWrapper` lifts to the broader sum type // `ContextDescriptorWrapper`. Verify the descriptor offset round-trips. - let result = try acrossAllReaders( - file: { wrappers.file.asContextDescriptorWrapper.contextDescriptor.offset }, - image: { wrappers.image.asContextDescriptorWrapper.contextDescriptor.offset } - ) + let result = try acrossAllReaders(wrappers.file, wrappers.image) { wrapper in + wrapper.asContextDescriptorWrapper.contextDescriptor.offset + } #expect(result == TypeContextDescriptorWrapperBaseline.structTest.descriptorOffset) } @@ -83,28 +69,25 @@ final class TypeContextDescriptorWrapperTests: MachOSwiftSectionFixtureTests, Fi @Test func parent() async throws { let wrappers = try loadStructTestWrappers() - let presence = try acrossAllContexts( - file: { (try wrappers.file.parent(in: fileContext)) != nil }, - image: { (try wrappers.image.parent(in: imageContext)) != nil } - ) + let presence = try acrossAllContexts(wrappers.file, wrappers.image) { wrapper, context in + (try wrapper.parent(in: context)) != nil + } #expect(presence == TypeContextDescriptorWrapperBaseline.structTest.hasParent) } @Test func genericContext() async throws { let wrappers = try loadStructTestWrappers() - let presence = try acrossAllContexts( - file: { (try wrappers.file.genericContext(in: fileContext)) != nil }, - image: { (try wrappers.image.genericContext(in: imageContext)) != nil } - ) + let presence = try acrossAllContexts(wrappers.file, wrappers.image) { wrapper, context in + (try wrapper.genericContext(in: context)) != nil + } #expect(presence == TypeContextDescriptorWrapperBaseline.structTest.hasGenericContext) } @Test func typeGenericContext() async throws { let wrappers = try loadStructTestWrappers() - let presence = try acrossAllContexts( - file: { (try wrappers.file.typeGenericContext(in: fileContext)) != nil }, - image: { (try wrappers.image.typeGenericContext(in: imageContext)) != nil } - ) + let presence = try acrossAllContexts(wrappers.file, wrappers.image) { wrapper, context in + (try wrapper.typeGenericContext(in: context)) != nil + } #expect(presence == TypeContextDescriptorWrapperBaseline.structTest.hasTypeGenericContext) } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextWrapperTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextWrapperTests.swift index 4016556c1..f6e0f517d 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextWrapperTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextWrapperTests.swift @@ -16,12 +16,8 @@ import SwiftSectionFixtureSupport /// `TypeContextWrapper.forTypeContextDescriptorWrapper` to materialize a /// `.struct(...)` wrapper. @Suite -final class TypeContextWrapperTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "TypeContextWrapper" - static var registeredTestMethodNames: Set { - TypeContextWrapperBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class TypeContextWrapperTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadStructTestWrappers() throws -> (file: TypeContextWrapper, image: TypeContextWrapper) { let fileDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOImage) @@ -34,19 +30,15 @@ final class TypeContextWrapperTests: MachOSwiftSectionFixtureTests, FixtureSuite @Test func contextDescriptorWrapper() async throws { let wrappers = try loadStructTestWrappers() - let result = try acrossAllReaders( - file: { wrappers.file.contextDescriptorWrapper.contextDescriptor.offset }, - image: { wrappers.image.contextDescriptorWrapper.contextDescriptor.offset } - ) + let result = try acrossAllReaders(wrappers.file, wrappers.image) { $0.contextDescriptorWrapper.contextDescriptor.offset } #expect(result == TypeContextWrapperBaseline.structTest.descriptorOffset) } @Test func typeContextDescriptorWrapper() async throws { let wrappers = try loadStructTestWrappers() - let result = try acrossAllReaders( - file: { wrappers.file.typeContextDescriptorWrapper.contextDescriptor.offset }, - image: { wrappers.image.typeContextDescriptorWrapper.contextDescriptor.offset } - ) + let result = try acrossAllReaders(wrappers.file, wrappers.image) { wrapper in + wrapper.typeContextDescriptorWrapper.contextDescriptor.offset + } #expect(result == TypeContextWrapperBaseline.structTest.descriptorOffset) } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeMetadataRecordTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeMetadataRecordTests.swift index 4181e37b2..c888bb2bc 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeMetadataRecordTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeMetadataRecordTests.swift @@ -13,12 +13,8 @@ import SwiftSectionFixtureSupport /// We materialize a representative record by walking the section and /// finding the entry that resolves to `Structs.StructTest`. @Suite -final class TypeMetadataRecordTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "TypeMetadataRecord" - static var registeredTestMethodNames: Set { - TypeMetadataRecordBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class TypeMetadataRecordTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Walks `__swift5_types`/`__swift5_types2` and returns the /// `TypeMetadataRecord` whose resolved descriptor lives at /// `targetOffset`. Two specializations follow because the `section(for:)` @@ -94,10 +90,7 @@ final class TypeMetadataRecordTests: MachOSwiftSectionFixtureTests, FixtureSuite @Test func offset() async throws { let (fileRecord, imageRecord) = try loadStructTestRecords() - let result = try acrossAllReaders( - file: { fileRecord.offset }, - image: { imageRecord.offset } - ) + let result = try acrossAllReaders(fileRecord, imageRecord) { $0.offset } #expect(result == TypeMetadataRecordBaseline.structTestRecord.offset) } @@ -105,19 +98,13 @@ final class TypeMetadataRecordTests: MachOSwiftSectionFixtureTests, FixtureSuite let (fileRecord, imageRecord) = try loadStructTestRecords() // The `relativeOffset` field is stable across readers (it's a raw // value stored in the record). - let result = try acrossAllReaders( - file: { fileRecord.layout.nominalTypeDescriptor.relativeOffset }, - image: { imageRecord.layout.nominalTypeDescriptor.relativeOffset } - ) + let result = try acrossAllReaders(fileRecord, imageRecord) { $0.layout.nominalTypeDescriptor.relativeOffset } #expect(result == TypeMetadataRecordBaseline.structTestRecord.layoutRelativeOffset) } @Test func typeKind() async throws { let (fileRecord, imageRecord) = try loadStructTestRecords() - let result = try acrossAllReaders( - file: { fileRecord.typeKind.rawValue }, - image: { imageRecord.typeKind.rawValue } - ) + let result = try acrossAllReaders(fileRecord, imageRecord) { $0.typeKind.rawValue } #expect(result == TypeMetadataRecordBaseline.structTestRecord.typeKindRawValue) } @@ -125,10 +112,9 @@ final class TypeMetadataRecordTests: MachOSwiftSectionFixtureTests, FixtureSuite let (fileRecord, imageRecord) = try loadStructTestRecords() // `contextDescriptor(in:)` resolves to the wrapped descriptor; cross- // reader equality on the resolved descriptor's offset. - let result = try acrossAllContexts( - file: { try required(fileRecord.contextDescriptor(in: fileContext)).contextDescriptor.offset }, - image: { try required(imageRecord.contextDescriptor(in: imageContext)).contextDescriptor.offset } - ) + let result = try acrossAllContexts(fileRecord, imageRecord) { record, context in + try required(record.contextDescriptor(in: context)).contextDescriptor.offset + } #expect(result == TypeMetadataRecordBaseline.structTestRecord.contextDescriptorOffset) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeReferenceTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeReferenceTests.swift index 58bc1bf49..ae9886f90 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeReferenceTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeReferenceTests.swift @@ -21,12 +21,8 @@ import SwiftSectionFixtureSupport /// `typeKind` byte to materialize a `TypeReference.directTypeDescriptor(...)` /// via `forKind(.directTypeDescriptor, at: …)`. @Suite -final class TypeReferenceTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "TypeReference" - static var registeredTestMethodNames: Set { - TypeReferenceBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class TypeReferenceTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Find the `TypeMetadataRecord` for `Structs.StructTest` and project /// its (record-field-offset, relative-offset, kind) tuple — the /// inputs to `TypeReference.forKind(_:at:)`. Two specializations diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/ValueMetadataProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/ValueMetadataProtocolTests.swift index 45cd392db..52e9be93e 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/ValueMetadataProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/ValueMetadataProtocolTests.swift @@ -15,12 +15,8 @@ import SwiftSectionFixtureSupport /// `ValueMetadata` instances are only obtainable via a loaded MachOImage's /// metadata accessor, so the cross-reader assertions here are asymmetric. @Suite -final class ValueMetadataProtocolTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ValueMetadataProtocol" - static var registeredTestMethodNames: Set { - ValueMetadataProtocolBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ValueMetadataProtocolTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Materialize a concrete `ValueMetadataProtocol`-conforming instance /// (a `StructMetadata` for `Structs.StructTest`). private func loadStructTestStructMetadata() throws -> StructMetadata { diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/ValueMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/ValueMetadataTests.swift index dc867af19..f15c93b6c 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/ValueMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/ValueMetadataTests.swift @@ -15,12 +15,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class ValueMetadataTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ValueMetadata" - static var registeredTestMethodNames: Set { - ValueMetadataBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ValueMetadataTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Materialize a `ValueMetadata` by reading the kind-erased layout at /// the offset of the metadata for `Structs.StructTest`. The struct's /// metadata is a `StructMetadata` whose layout shares the diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/ValueTypeDescriptorWrapperTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/ValueTypeDescriptorWrapperTests.swift index 332e98e16..0cb0ef603 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/ValueTypeDescriptorWrapperTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/ValueTypeDescriptorWrapperTests.swift @@ -15,12 +15,8 @@ import SwiftSectionFixtureSupport /// /// Picker: `Structs.StructTest`'s descriptor wrapped in `.struct(...)`. @Suite -final class ValueTypeDescriptorWrapperTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ValueTypeDescriptorWrapper" - static var registeredTestMethodNames: Set { - ValueTypeDescriptorWrapperBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ValueTypeDescriptorWrapperTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadStructTestWrappers() throws -> (file: ValueTypeDescriptorWrapper, image: ValueTypeDescriptorWrapper) { let file = try BaselineFixturePicker.struct_StructTest(in: machOFile) let image = try BaselineFixturePicker.struct_StructTest(in: machOImage) @@ -31,47 +27,34 @@ final class ValueTypeDescriptorWrapperTests: MachOSwiftSectionFixtureTests, Fixt @Test func contextDescriptor() async throws { let wrappers = try loadStructTestWrappers() - let result = try acrossAllReaders( - file: { wrappers.file.contextDescriptor.offset }, - image: { wrappers.image.contextDescriptor.offset } - ) + let result = try acrossAllReaders(wrappers.file, wrappers.image) { $0.contextDescriptor.offset } #expect(result == ValueTypeDescriptorWrapperBaseline.structTest.descriptorOffset) } @Test func namedContextDescriptor() async throws { let wrappers = try loadStructTestWrappers() - let result = try acrossAllReaders( - file: { wrappers.file.namedContextDescriptor.offset }, - image: { wrappers.image.namedContextDescriptor.offset } - ) + let result = try acrossAllReaders(wrappers.file, wrappers.image) { $0.namedContextDescriptor.offset } #expect(result == ValueTypeDescriptorWrapperBaseline.structTest.descriptorOffset) } @Test func typeContextDescriptor() async throws { let wrappers = try loadStructTestWrappers() - let result = try acrossAllReaders( - file: { wrappers.file.typeContextDescriptor.offset }, - image: { wrappers.image.typeContextDescriptor.offset } - ) + let result = try acrossAllReaders(wrappers.file, wrappers.image) { $0.typeContextDescriptor.offset } #expect(result == ValueTypeDescriptorWrapperBaseline.structTest.descriptorOffset) } @Test func asTypeContextDescriptorWrapper() async throws { let wrappers = try loadStructTestWrappers() // Lifting to `TypeContextDescriptorWrapper` should preserve kind. - let result = try acrossAllReaders( - file: { wrappers.file.asTypeContextDescriptorWrapper.isStruct }, - image: { wrappers.image.asTypeContextDescriptorWrapper.isStruct } - ) + let result = try acrossAllReaders(wrappers.file, wrappers.image) { $0.asTypeContextDescriptorWrapper.isStruct } #expect(result == true) } @Test func asContextDescriptorWrapper() async throws { let wrappers = try loadStructTestWrappers() - let result = try acrossAllReaders( - file: { wrappers.file.asContextDescriptorWrapper.contextDescriptor.offset }, - image: { wrappers.image.asContextDescriptorWrapper.contextDescriptor.offset } - ) + let result = try acrossAllReaders(wrappers.file, wrappers.image) { wrapper in + wrapper.asContextDescriptorWrapper.contextDescriptor.offset + } #expect(result == ValueTypeDescriptorWrapperBaseline.structTest.descriptorOffset) } @@ -79,19 +62,17 @@ final class ValueTypeDescriptorWrapperTests: MachOSwiftSectionFixtureTests, Fixt @Test func parent() async throws { let wrappers = try loadStructTestWrappers() - let presence = try acrossAllContexts( - file: { (try wrappers.file.parent(in: fileContext)) != nil }, - image: { (try wrappers.image.parent(in: imageContext)) != nil } - ) + let presence = try acrossAllContexts(wrappers.file, wrappers.image) { wrapper, context in + (try wrapper.parent(in: context)) != nil + } #expect(presence == ValueTypeDescriptorWrapperBaseline.structTest.hasParent) } @Test func genericContext() async throws { let wrappers = try loadStructTestWrappers() - let presence = try acrossAllContexts( - file: { (try wrappers.file.genericContext(in: fileContext)) != nil }, - image: { (try wrappers.image.genericContext(in: imageContext)) != nil } - ) + let presence = try acrossAllContexts(wrappers.file, wrappers.image) { wrapper, context in + (try wrapper.genericContext(in: context)) != nil + } #expect(presence == ValueTypeDescriptorWrapperBaseline.structTest.hasGenericContext) } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ValueWitnessTable/TypeLayoutTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ValueWitnessTable/TypeLayoutTests.swift index d2eb236ae..db5393391 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ValueWitnessTable/TypeLayoutTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ValueWitnessTable/TypeLayoutTests.swift @@ -11,12 +11,8 @@ import SwiftSectionFixtureSupport /// quadruple projected from a `ValueWitnessTable`. Pure value-type — /// the Suite re-evaluates each accessor against a synthetic instance. @Suite -final class TypeLayoutTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "TypeLayout" - static var registeredTestMethodNames: Set { - TypeLayoutBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class TypeLayoutTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { /// Construct a synthetic `TypeLayout` representing a non-POD, /// inline, bitwise-takable, copyable type with alignment 8 (mask 7), /// size 16, stride 16, no extra inhabitants. diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ValueWitnessTable/ValueWitnessFlagsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ValueWitnessTable/ValueWitnessFlagsTests.swift index 47617227d..34cdda65c 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ValueWitnessTable/ValueWitnessFlagsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ValueWitnessTable/ValueWitnessFlagsTests.swift @@ -14,12 +14,8 @@ import SwiftSectionFixtureSupport /// static-constant smoke checks verify the raw-value constants haven't /// drifted. @Suite -final class ValueWitnessFlagsTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ValueWitnessFlags" - static var registeredTestMethodNames: Set { - ValueWitnessFlagsBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ValueWitnessFlagsTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { @Test("init(rawValue:)") func initializer() async throws { for entry in ValueWitnessFlagsBaseline.cases { let flags = ValueWitnessFlags(rawValue: entry.rawValue) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ValueWitnessTable/ValueWitnessTableTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ValueWitnessTable/ValueWitnessTableTests.swift index ca1a5aa16..a5236026b 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ValueWitnessTable/ValueWitnessTableTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ValueWitnessTable/ValueWitnessTableTests.swift @@ -19,12 +19,8 @@ import SwiftSectionFixtureSupport /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite -final class ValueWitnessTableTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { - static let testedTypeName = "ValueWitnessTable" - static var registeredTestMethodNames: Set { - ValueWitnessTableBaseline.registeredTestMethodNames - } - +@FixtureSuite +final class ValueWitnessTableTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func loadStructTestValueWitnesses() throws -> ValueWitnessTable { let descriptor = try BaselineFixturePicker.struct_StructTest(in: machOImage) let accessor = try required(try descriptor.metadataAccessorFunction(in: imageContext)) diff --git a/Tests/MachOSwiftSectionTests/MachOSwiftSectionCUmbrellaHeaderTests.swift b/Tests/MachOSwiftSectionTests/MachOSwiftSectionCUmbrellaHeaderTests.swift new file mode 100644 index 000000000..60d75a952 --- /dev/null +++ b/Tests/MachOSwiftSectionTests/MachOSwiftSectionCUmbrellaHeaderTests.swift @@ -0,0 +1,29 @@ +import Foundation +import Testing + +/// `MachOSwiftSectionC`'s umbrella header has to include every header of the +/// module. One it leaves out stays out of the module, and no build says so: +/// Xcode reuses the module it built before the header existed, without the +/// warning a fresh build of the module would give. +@Suite +struct MachOSwiftSectionCUmbrellaHeaderTests { + @Test func umbrellaHeaderIncludesEveryHeader() throws { + let includeDirectory = URL(fileURLWithPath: #filePath) + .deletingLastPathComponent() + .deletingLastPathComponent() + .deletingLastPathComponent() + .appendingPathComponent("Sources/ABI/MachOSwiftSectionC/include") + let umbrellaHeaderName = "MachOSwiftSectionC.h" + let umbrellaHeader = try String( + contentsOf: includeDirectory.appendingPathComponent(umbrellaHeaderName), + encoding: .utf8 + ) + let headerNames = try FileManager.default.contentsOfDirectory(atPath: includeDirectory.path) + .filter { $0.hasSuffix(".h") && $0 != umbrellaHeaderName } + .sorted() + #expect(!headerNames.isEmpty) + for headerName in headerNames { + #expect(umbrellaHeader.contains("\n#include \"\(headerName)\"\n"), "\(umbrellaHeaderName) does not include \(headerName)") + } + } +} diff --git a/Tests/MachOSwiftSectionTests/ReadingContextRelocationTests.swift b/Tests/MachOSwiftSectionTests/ReadingContextRelocationTests.swift index d55aa2533..eec7704df 100644 --- a/Tests/MachOSwiftSectionTests/ReadingContextRelocationTests.swift +++ b/Tests/MachOSwiftSectionTests/ReadingContextRelocationTests.swift @@ -65,7 +65,7 @@ final class ReadingContextRelocationTests: MachOSwiftSectionFixtureTests, @unche /// files, so a cross-image reference is a bind rather than a rebase. enum StandaloneSimulatorRuntimeLibraries { static let synchronizationPath: String = { - let swiftUIPath = MachOFileName.iOS_26_5_Simulator_SwiftUI.rawValue + let swiftUIPath = MachOFileName.iOS_26_5_Simulator_SwiftUI.path let runtimeRoot = swiftUIPath.dropLast("/System/Library/Frameworks/SwiftUI.framework/SwiftUI".count) return runtimeRoot + "/usr/lib/swift/libswiftSynchronization.dylib" }() diff --git a/Tests/MachOSwiftSectionTests/StandaloneFileReadingTests.swift b/Tests/MachOSwiftSectionTests/StandaloneFileReadingTests.swift index a30ce9301..ca39d96e1 100644 --- a/Tests/MachOSwiftSectionTests/StandaloneFileReadingTests.swift +++ b/Tests/MachOSwiftSectionTests/StandaloneFileReadingTests.swift @@ -19,7 +19,7 @@ import SwiftSectionFixtureSupport @Suite struct StandaloneFileReadingTests { private static var isHostDyldCacheAvailable: Bool { - FileManager.default.fileExists(atPath: DyldSharedCachePath.current.rawValue) + FileManager.default.fileExists(atPath: DyldSharedCachePath.current.path) } @Test(.enabled(if: isHostDyldCacheAvailable)) @@ -55,7 +55,7 @@ struct StandaloneFileReadingTests { /// The first bytes of the host's dyld cache: enough for MachOKit to accept /// a file as a cache. private static func hostCacheHeaderBytes() throws -> Data { - let fileHandle = try FileHandle(forReadingFrom: URL(fileURLWithPath: DyldSharedCachePath.current.rawValue)) + let fileHandle = try FileHandle(forReadingFrom: URL(fileURLWithPath: DyldSharedCachePath.current.path)) defer { try? fileHandle.close() } return try #require(try fileHandle.read(upToCount: 0x10000)) } diff --git a/Tests/SwiftDeclarationRenderingTests/FieldLayoutRendererReaderSpecializationTests.swift b/Tests/SwiftDeclarationRenderingTests/FieldLayoutRendererReaderSpecializationTests.swift index 641029059..a25f8fc95 100644 --- a/Tests/SwiftDeclarationRenderingTests/FieldLayoutRendererReaderSpecializationTests.swift +++ b/Tests/SwiftDeclarationRenderingTests/FieldLayoutRendererReaderSpecializationTests.swift @@ -9,6 +9,7 @@ import SwiftDeclarationRendering import Demangling @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import Semantic /// Verifies the reader-specialized `FieldLayoutRenderer`: /// diff --git a/Tests/SwiftDeclarationRenderingTests/MultilineTypeFormattingPreservationTests.swift b/Tests/SwiftDeclarationRenderingTests/MultilineTypeFormattingPreservationTests.swift new file mode 100644 index 000000000..a36527617 --- /dev/null +++ b/Tests/SwiftDeclarationRenderingTests/MultilineTypeFormattingPreservationTests.swift @@ -0,0 +1,159 @@ +import Foundation +import Testing +import Semantic +@testable import SwiftDeclarationRendering + +/// What formatting promises to keep: it adds line breaks and indentation and +/// drops the space of a broken `, `, and nothing else changes — not the +/// text, not a component's semantic type or identifier, not the regions a +/// host reads back out of the identifiers. +@Suite +struct MultilineTypeFormattingPreservationTests { + private static let swiftUIBody = """ + extension SettingsApp.SettingsNavigationSplitView: SwiftUI.View { + typealias Body = SwiftUI.ModifiedContent, SwiftUI.NavigationSplitView, SettingsApp.SettingsSecondaryColumn>>>, SwiftUI._EnvironmentKeyWritingModifier>, SwiftUI.OnTestViewModifier> + func update(model: Swift.Result, content: Pair])>) -> Swift.Bool + var handler: (Pair) -> Swift.Void + } + """ + + private static let sources: [String] = [ + swiftUIBody, + "var value: Box>", + " var pair: (Swift.Int, Swift.String, Pair)", + "func make() -> Pair", + ] + + private static let widths = [10, 30, 60, 100] + + /// `source` with every component carrying an identifier of its own, the + /// way a printer stamps type references and regions. + private static func identified(_ source: SemanticString) -> SemanticString { + SemanticString(components: source.components.enumerated().map { componentIndex, component in + AtomicComponent(string: component.string, type: component.type, identifier: "component\(componentIndex)") + }) + } + + /// Every character of `string` that is not whitespace, with the semantic + /// type and identifier of the component it lies in. + private static func visibleCharacters(of string: SemanticString) -> [(character: Character, type: SemanticType, identifier: String?)] { + string.components.flatMap { component in + component.string.filter { !$0.isWhitespace }.map { (character: $0, type: component.type, identifier: component.identifier) } + } + } + + @Test(arguments: sources, widths) + func formattingKeepsSemanticTypesAndIdentifiers(source: String, maximumLineWidth: Int) { + let identifiedSource = Self.identified(PrinterShapedSource.make(source)) + let formatted = MultilineTypeFormatting(maximumLineWidth: maximumLineWidth).format(identifiedSource) + let sourceCharacters = Self.visibleCharacters(of: identifiedSource) + let formattedCharacters = Self.visibleCharacters(of: formatted) + #expect(sourceCharacters.count == formattedCharacters.count) + for (sourceCharacter, formattedCharacter) in zip(sourceCharacters, formattedCharacters) { + #expect(sourceCharacter.character == formattedCharacter.character) + #expect(sourceCharacter.type == formattedCharacter.type) + #expect(sourceCharacter.identifier == formattedCharacter.identifier) + } + } + + @Test func insertedLineBreaksCarryTheIdentifierOfTheirBracketOrComma() { + let source = SemanticString(components: [ + AtomicComponent(string: "Pair", type: .type(.struct, .name), identifier: "pair"), + AtomicComponent(string: "<", type: .standard, identifier: "opening"), + AtomicComponent(string: "A", type: .type(.other, .name)), + AtomicComponent(string: ", ", type: .standard, identifier: "separator"), + AtomicComponent(string: "B", type: .type(.other, .name)), + AtomicComponent(string: ">", type: .standard, identifier: "closing"), + ]) + let formatted = MultilineTypeFormatting(maximumLineWidth: 5).format(source) + #expect(formatted.components == [ + AtomicComponent(string: "Pair", type: .type(.struct, .name), identifier: "pair"), + AtomicComponent(string: "<", type: .standard, identifier: "opening"), + AtomicComponent(string: "\n", type: .standard, identifier: "opening"), + AtomicComponent(string: " ", type: .standard, identifier: "opening"), + AtomicComponent(string: "A", type: .type(.other, .name)), + AtomicComponent(string: ",", type: .standard, identifier: "separator"), + AtomicComponent(string: "\n", type: .standard, identifier: "separator"), + AtomicComponent(string: " ", type: .standard, identifier: "separator"), + AtomicComponent(string: "B", type: .type(.other, .name)), + AtomicComponent(string: "\n", type: .standard, identifier: "closing"), + AtomicComponent(string: ">", type: .standard, identifier: "closing"), + ]) + } + + @Test func unchangedLinesAroundAChangedLineKeepTheirComponents() { + let comment = AtomicComponent(string: "// first\n// second\n", type: .comment, identifier: "comment") + var source = SemanticString(components: [comment]) + source.append(PrinterShapedSource.make("var value: Pair\n")) + source.append(AtomicComponent(string: "// third", type: .comment, identifier: "trailing")) + let formatted = MultilineTypeFormatting(maximumLineWidth: 10).format(source) + #expect(formatted.components.first == comment) + #expect(formatted.components.last == AtomicComponent(string: "// third", type: .comment, identifier: "trailing")) + #expect(formatted.string == """ + // first + // second + var value: Pair< + A, + B + > + // third + """) + } + + @Test(arguments: sources, widths) + func removingInsertedBreaksRestoresTheOriginalText(source: String, maximumLineWidth: Int) throws { + let formatted = MultilineTypeFormatting(maximumLineWidth: maximumLineWidth).format(PrinterShapedSource.make(source)).string + var restored = formatted + for (pattern, template) in [(#"([<(\[])\n +"#, "$1"), (#",\n +"#, ", "), (#"\n +([>)\]])"#, "$1"), (#"\n([>)\]])"#, "$1")] { + let expression = try NSRegularExpression(pattern: pattern) + restored = expression.stringByReplacingMatches(in: restored, range: NSRange(restored.startIndex..., in: restored), withTemplate: template) + } + #expect(restored == source) + } + + @Test(arguments: sources, widths) + func formattingIsIdempotent(source: String, maximumLineWidth: Int) { + let formatting = MultilineTypeFormatting(maximumLineWidth: maximumLineWidth) + let formattedOnce = formatting.format(PrinterShapedSource.make(source)) + let formattedTwice = formatting.format(formattedOnce) + #expect(formattedTwice.components == formattedOnce.components) + } + + /// Indenting every non-empty line by four spaces. + private static func indented(_ text: String) -> String { + text.split(separator: "\n", omittingEmptySubsequences: false) + .map { $0.isEmpty ? String($0) : " " + $0 } + .joined(separator: "\n") + } + + @Test(arguments: sources, widths) + func formattingCommutesWithIndentation(source: String, maximumLineWidth: Int) { + let formatting = MultilineTypeFormatting(maximumLineWidth: maximumLineWidth) + let formattedThenIndented = Self.indented(formatting.format(PrinterShapedSource.make(source)).string) + let indentedThenFormatted = formatting.format(PrinterShapedSource.make(Self.indented(source))).string + #expect(indentedThenFormatted == formattedThenIndented) + } + + @Test func annotationAndVisibilityRegionsReadBackUnchanged() throws { + let typeAlias = " typealias Body = Pair, Pair>" + var source = PrinterShapedSource.make("struct Holder {\n") + source.append(VisibilityRegion(.enabled("printsTypeAliases"), content: SemanticString(AnnotationRegion(AnnotationRegion.Kind("note"), content: PrinterShapedSource.make(typeAlias))))) + source.append(PrinterShapedSource.make("\n}")) + let formatting = MultilineTypeFormatting(maximumLineWidth: 30) + let formattedTypeAlias = formatting.format(PrinterShapedSource.make(typeAlias)).string + + let formatted = formatting.format(source).frozen() + let visibility = formatted.separatingVisibilityRegions() + #expect(visibility.regions.regions.count == 1) + let hidden = visibility.regions.projection(of: visibility.text, where: { _ in false }).text.string + #expect(hidden == "struct Holder {\n\n}") + let shown = visibility.regions.projection(of: visibility.text, where: { _ in true }).text + #expect(shown.string == "struct Holder {\n" + formattedTypeAlias + "\n}") + + let annotations = shown.separatingAnnotationRegions() + let region = try #require(annotations.annotations.regions.only) + #expect(region.kind == AnnotationRegion.Kind("note")) + let regionBytes = Array(annotations.text.string.utf8)[Int(region.utf8Offset) ..< Int(region.utf8Offset + region.utf8Length)] + #expect(String(decoding: regionBytes, as: UTF8.self) == formattedTypeAlias.trimmingCharacters(in: .whitespaces)) + } +} diff --git a/Tests/SwiftDeclarationRenderingTests/MultilineTypeFormattingTests.swift b/Tests/SwiftDeclarationRenderingTests/MultilineTypeFormattingTests.swift new file mode 100644 index 000000000..4e400e0d2 --- /dev/null +++ b/Tests/SwiftDeclarationRenderingTests/MultilineTypeFormattingTests.swift @@ -0,0 +1,498 @@ +import Foundation +import Testing +import Semantic +@testable import SwiftDeclarationRendering + +/// Builds a `SemanticString` split into components the way both printers split +/// a declaration: each bracket, each `", "`, each run of spaces and each +/// `" -> "` its own `.standard` component, and each word one component of its +/// own — `.keyword` for a keyword, `.type(.other, .name)` for anything else. +/// A test then reads as the text it prints. +enum PrinterShapedSource { + static let keywords: Set = [ + "any", "case", "class", "enum", "extension", "func", "init", "inout", + "let", "some", "static", "struct", "typealias", "var", "where", + ] + + static func make(_ text: String) -> SemanticString { + var components: [AtomicComponent] = [] + var remainingText = Substring(text) + while let firstCharacter = remainingText.first { + if remainingText.hasPrefix(", ") { + components.append(AtomicComponent(string: ", ", type: .standard)) + remainingText = remainingText.dropFirst(2) + } else if remainingText.hasPrefix(" -> ") { + components.append(AtomicComponent(string: " -> ", type: .standard)) + remainingText = remainingText.dropFirst(4) + } else if firstCharacter == " " { + let spaces = remainingText.prefix(while: { $0 == " " }) + components.append(AtomicComponent(string: String(spaces), type: .standard)) + remainingText = remainingText.dropFirst(spaces.count) + } else if isWordCharacter(firstCharacter) { + let word = String(remainingText.prefix(while: isWordCharacter)) + components.append(AtomicComponent(string: word, type: keywords.contains(word) ? .keyword : .type(.other, .name))) + remainingText = remainingText.dropFirst(word.count) + } else { + components.append(AtomicComponent(string: String(firstCharacter), type: .standard)) + remainingText = remainingText.dropFirst() + } + } + return SemanticString(components: components) + } + + private static func isWordCharacter(_ character: Character) -> Bool { + character.isLetter || character.isNumber || character == "_" || character == "." || character == "$" + } +} + +@Suite +struct MultilineTypeFormattingTests { + // MARK: - Lines and the width gate + + @Test func emptySourceIsUnchanged() { + let formatted = MultilineTypeFormatting(maximumLineWidth: 10).format(SemanticString()) + #expect(formatted.components.isEmpty) + } + + @Test func linesWithinWidthAreUnchangedComponentForComponent() { + let source = PrinterShapedSource.make(""" + struct Holder { + var result: Swift.Result + typealias Body = SwiftUI.ModifiedContent + } + """) + let formatted = MultilineTypeFormatting(maximumLineWidth: 120).format(source) + #expect(formatted.components == source.components) + } + + @Test func contentWidthIgnoresLeadingIndentation() throws { + let lines = MultilineTypeFormatting.SourceLine.lines(in: PrinterShapedSource.make(" var count: Int").components) + let line = try #require(lines.only) + #expect(line.leadingIndentation == 8) + #expect(line.contentWidth == "var count: Int".count) + } + + @Test func linesSplitAtLineBreaksInsideAComponent() { + let components = [ + AtomicComponent(string: "first\n second", type: .comment, identifier: "identity"), + AtomicComponent(string: " tail", type: .standard), + ] + let lines = MultilineTypeFormatting.SourceLine.lines(in: components) + #expect(lines.count == 2) + #expect(lines[0].fragments.map(\.text) == ["first"]) + #expect(lines[0].terminator?.componentIndex == 0) + #expect(lines[1].fragments.map(\.text) == [" second", " tail"]) + #expect(lines[1].fragments.map(\.componentIndex) == [0, 1]) + #expect(lines[1].leadingIndentation == 4) + #expect(lines[1].contentWidth == "second tail".count) + } + + @Test func unchangedLinesSplitInsideAComponentComeBackAsThatComponent() { + let source = SemanticString(components: [ + AtomicComponent(string: "// first\n // second", type: .comment, identifier: "identity"), + AtomicComponent(string: "\n", type: .standard), + ]) + let formatted = MultilineTypeFormatting(maximumLineWidth: 4).format(source) + #expect(formatted.components == source.components) + } + + @Test func nonPositiveWidthIsAPreconditionFailure() async { + await #expect(processExitsWith: .failure) { + _ = MultilineTypeFormatting(maximumLineWidth: 0) + } + } + + // MARK: - The bracket tree + + /// The bracket tree of the single line `source` holds, written back as + /// text: each list with its elements separated by `|` instead of their + /// commas, a declaration's generic parameters in `‹›`. `nil` when the + /// line does not parse. + private func bracketStructure(of source: SemanticString) throws -> String? { + let components = source.components + let line = try #require(MultilineTypeFormatting.SourceLine.lines(in: components).only) + return MultilineTypeFormatting.BracketTree.parse(line, sourceComponents: components).map(describe) + } + + private func describe(_ nodes: [MultilineTypeFormatting.BracketTreeNode]) -> String { + nodes.map { node in + switch node { + case .text(let fragment): + return String(fragment.text) + case .list(let list): + let brackets: (opening: String, closing: String) = switch list.kind { + case .genericArguments: ("<", ">") + case .genericParameters: ("‹", "›") + case .parentheses: ("(", ")") + case .squareBrackets: ("[", "]") + } + return brackets.opening + list.elements.map(describe).joined(separator: "|") + brackets.closing + } + }.joined() + } + + @Test func genericArgumentListsNestInsideParenthesesAndBrackets() throws { + let structure = try bracketStructure(of: PrinterShapedSource.make("var value: ([Pair], C) -> Box")) + #expect(structure == "var value: ([Pair]| C) -> Box") + } + + @Test func angleBracketAfterDeclarationNameIsGenericParameterClause() throws { + let function = SemanticString(components: [ + AtomicComponent(string: "func", type: .keyword), + AtomicComponent(string: " ", type: .standard), + AtomicComponent(string: "make", type: .function(.declaration)), + AtomicComponent(string: "<", type: .standard), + AtomicComponent(string: "A", type: .type(.other, .name)), + AtomicComponent(string: ", ", type: .standard), + AtomicComponent(string: "B", type: .type(.other, .name)), + AtomicComponent(string: ">", type: .standard), + AtomicComponent(string: "(", type: .standard), + AtomicComponent(string: ")", type: .standard), + ]) + #expect(try bracketStructure(of: function) == "func make‹A| B›()") + + let structure = SemanticString(components: [ + AtomicComponent(string: "struct", type: .keyword), + AtomicComponent(string: " ", type: .standard), + AtomicComponent(string: "Holder", type: .type(.struct, .declaration)), + AtomicComponent(string: "<", type: .standard), + AtomicComponent(string: "Element", type: .type(.other, .name)), + AtomicComponent(string: ">", type: .standard), + ]) + #expect(try bracketStructure(of: structure) == "struct Holder‹Element›") + } + + @Test func arrowIsNotAClosingBracket() throws { + #expect(try bracketStructure(of: PrinterShapedSource.make("Box<(A) -> B>")) == "Box<(A) -> B>") + + let arrowAcrossComponents = SemanticString(components: [ + AtomicComponent(string: "Box", type: .type(.other, .name)), + AtomicComponent(string: "<", type: .standard), + AtomicComponent(string: "(", type: .standard), + AtomicComponent(string: ")", type: .standard), + AtomicComponent(string: " -", type: .standard), + AtomicComponent(string: "> ", type: .standard), + AtomicComponent(string: "B", type: .type(.other, .name)), + AtomicComponent(string: ">", type: .standard), + ]) + #expect(try bracketStructure(of: arrowAcrossComponents) == "Box<() -> B>") + } + + @Test func bracketsInsideStringLiteralsAreText() throws { + let attribute = SemanticString(components: [ + AtomicComponent(string: "@available", type: .keyword), + AtomicComponent(string: "(*, deprecated, message: \"use Box or \\\"(\\\"\")", type: .standard), + ]) + #expect(try bracketStructure(of: attribute) == "@available(*| deprecated| message: \"use Box or \\\"(\\\"\")") + } + + @Test func bracketsInsideBackticksAreText() throws { + let name = SemanticString(components: [ + AtomicComponent(string: "Box<`<(`, B>", type: .standard), + ]) + #expect(try bracketStructure(of: name) == "Box<`<(`| B>") + } + + @Test func bracketsAfterLineCommentAreText() throws { + let line = SemanticString(components: [ + AtomicComponent(string: "var value: Box // Box // Box` + /// — and a function's as ``: requirements, not + /// arguments, whatever name they follow. + @Test func angleBracketsHoldingRequirementsAreAGenericSignature() throws { + let extensionContext = "(extension in SwiftUI):SwiftUI._ConditionalContent< where A: SwiftUI.TableColumnContent, B: SwiftUI.TableColumnContent>.(Provider in _ABC)" + #expect(try bracketStructure(of: PrinterShapedSource.make(extensionContext)) == "(extension in SwiftUI):SwiftUI._ConditionalContent‹ where A: SwiftUI.TableColumnContent| B: SwiftUI.TableColumnContent›.(Provider in _ABC)") + #expect(try bracketStructure(of: PrinterShapedSource.make("Holder.make()")) == "Holder.make‹A| B where A == B.Element›()") + } + + @Test func moduleSelectorsAndExtensionContextsLeaveAnArgumentList() throws { + #expect(try bracketStructure(of: PrinterShapedSource.make("var value: Swift::Dictionary")) == "var value: Swift::Dictionary") + #expect(try bracketStructure(of: PrinterShapedSource.make("var value: Pair<(extension in SwiftUI):SwiftUI.Box, Swift.Int>")) == "var value: Pair<(extension in SwiftUI):SwiftUI.Box| Swift.Int>") + } + + @Test func commaOutsideBracketsIsText() throws { + #expect(try bracketStructure(of: PrinterShapedSource.make("case first, second")) == "case first, second") + } + + @Test func unbalancedLineIsLeftUnparsed() throws { + #expect(try bracketStructure(of: PrinterShapedSource.make("Box")) == nil) + #expect(try bracketStructure(of: PrinterShapedSource.make("Box ", type: .standard), + AtomicComponent(string: "Swift.Bool", type: .type(.struct, .name)), + ]) + #expect(try bracketStructure(of: line) == nil) + } + + @Test func closingColumnCountsFromTheEndOfIndentation() throws { + let components = PrinterShapedSource.make(" Box>").components + let line = try #require(MultilineTypeFormatting.SourceLine.lines(in: components).only) + let nodes = try #require(MultilineTypeFormatting.BracketTree.parse(line, sourceComponents: components)) + guard case .list(let outerList) = try #require(nodes.last) else { + Issue.record("the line should end in a list") + return + } + #expect(outerList.closingColumn == "Box>".count) + guard case .list(let innerList) = try #require(outerList.elements.only?.last) else { + Issue.record("the outer list should hold a list") + return + } + #expect(innerList.closingColumn == "Box".count) + } + + // MARK: - Layout + + private func formatted(_ text: String, maximumLineWidth: Int) -> String { + MultilineTypeFormatting(maximumLineWidth: maximumLineWidth).format(PrinterShapedSource.make(text)).string + } + + private func isLeftUnchanged(_ source: SemanticString, maximumLineWidth: Int) -> Bool { + MultilineTypeFormatting(maximumLineWidth: maximumLineWidth).format(source).components == source.components + } + + @Test func multiArgumentGenericBreaksOneArgumentPerLine() { + #expect(formatted("typealias Body = Pair", maximumLineWidth: 40) == """ + typealias Body = Pair< + Swift.Int, + Swift.String + > + """) + } + + @Test func singleArgumentGenericStaysInlineUnlessItsArgumentBreaks() { + #expect(formatted("var value: Box>", maximumLineWidth: 40) == """ + var value: Box< + Pair< + Swift.Int, + Swift.String + > + > + """) + #expect(isLeftUnchanged(PrinterShapedSource.make("var value: Box>>"), maximumLineWidth: 10)) + } + + @Test func tupleBreaksOnlyWhenAnElementBreaks() { + #expect(formatted("var pair: (Swift.Int, Swift.String, Pair)", maximumLineWidth: 40) == """ + var pair: ( + Swift.Int, + Swift.String, + Pair< + A, + B + > + ) + """) + #expect(isLeftUnchanged(PrinterShapedSource.make("var tuple: (Swift.Int, Swift.String, Swift.Double, Swift.Float)"), maximumLineWidth: 20)) + } + + @Test func functionTypeParametersBreakOnlyWhenAParameterBreaks() { + #expect(formatted("var handler: (Pair) -> Swift.Void", maximumLineWidth: 40) == """ + var handler: ( + Pair< + Swift.Int, + Swift.String + > + ) -> Swift.Void + """) + } + + @Test func collectionSugarBreaksOnlyWhenAnElementBreaks() { + #expect(formatted("var table: [Swift.String : Pair]", maximumLineWidth: 40) == """ + var table: [ + Swift.String : Pair< + Swift.Int, + Swift.String + > + ] + """) + } + + @Test func typeThatFitsStaysOnOneLineInAnOverlongLine() { + let line = "func update(model: Swift.Result, content: Pair) -> Swift.Bool" + #expect(formatted(line, maximumLineWidth: 60) == """ + func update( + model: Swift.Result, + content: Pair< + Swift.Int, + Swift.String + > + ) -> Swift.Bool + """) + } + + @Test func overlongLineWithoutLongTypeIsUnchanged() { + let parameters = "func update(first: Swift.Int, second: Swift.Int, third: Swift.Int) // and a trailing comment" + #expect(isLeftUnchanged(PrinterShapedSource.make(parameters), maximumLineWidth: 30)) + let comment = "var value: Pair // a trailing comment long enough to run past the width" + #expect(isLeftUnchanged(PrinterShapedSource.make(comment), maximumLineWidth: 30)) + } + + @Test func genericParameterClauseDoesNotBreakForHavingTwoParameters() { + let function = SemanticString(components: [ + AtomicComponent(string: "func", type: .keyword), + AtomicComponent(string: " ", type: .standard), + AtomicComponent(string: "make", type: .function(.declaration)), + AtomicComponent(string: "<", type: .standard), + AtomicComponent(string: "A", type: .type(.other, .name)), + AtomicComponent(string: ", ", type: .standard), + AtomicComponent(string: "B", type: .type(.other, .name)), + AtomicComponent(string: ">", type: .standard), + AtomicComponent(string: "(", type: .standard), + AtomicComponent(string: "value", type: .argument), + AtomicComponent(string: ": ", type: .standard), + AtomicComponent(string: "Pair", type: .type(.struct, .name)), + AtomicComponent(string: "<", type: .standard), + AtomicComponent(string: "Swift.Int", type: .type(.struct, .name)), + AtomicComponent(string: ", ", type: .standard), + AtomicComponent(string: "Swift.String", type: .type(.struct, .name)), + AtomicComponent(string: ">", type: .standard), + AtomicComponent(string: ")", type: .standard), + ]) + #expect(MultilineTypeFormatting(maximumLineWidth: 12).format(function).string == """ + func make( + value: Pair< + Swift.Int, + Swift.String + > + ) + """) + } + + @Test func genericSignatureIsNotBrokenForItsRequirements() { + let line = "(extension in SwiftUI):SwiftUI._ConditionalContent< where A: SwiftUI.TableColumnContent, B: SwiftUI.TableColumnContent>.(Provider in _ABC).init() -> SwiftUI._ConditionalContent< where A: SwiftUI.TableColumnContent, B: SwiftUI.TableColumnContent>.(Provider in _ABC)" + #expect(formatted(line, maximumLineWidth: 100) == """ + (extension in SwiftUI):SwiftUI._ConditionalContent< where A: SwiftUI.TableColumnContent, B: SwiftUI.TableColumnContent>.(Provider in _ABC).init() -> SwiftUI._ConditionalContent< + A, + B + >< where A: SwiftUI.TableColumnContent, B: SwiftUI.TableColumnContent>.(Provider in _ABC) + """) + } + + @Test func moduleSelectorsStillBreakAsArguments() { + #expect(formatted("var value: Swift::Dictionary", maximumLineWidth: 20) == """ + var value: Swift::Dictionary< + Swift::String, + Swift::Int + > + """) + } + + @Test func emptyParenthesesNeverBreak() { + #expect(formatted("func make() -> Pair", maximumLineWidth: 10) == """ + func make() -> Pair< + A, + B + > + """) + } + + @Test func continuationLinesIndentFromTheLineIndentation() { + #expect(formatted(" var value: Pair", maximumLineWidth: 10) == """ + var value: Pair< + A, + B + > + """) + } + + @Test func separatorLosesItsSpaceWhenBroken() { + let formattedSource = MultilineTypeFormatting(maximumLineWidth: 10).format(PrinterShapedSource.make("var value: Pair")) + #expect(formattedSource.components.contains(AtomicComponent(string: ",", type: .standard))) + #expect(!formattedSource.components.contains { $0.string.hasSuffix(" ") && $0.string.contains(",") }) + } + + @Test func operatorDeclarationFromDumpIsLeftUnchanged() { + let line = SemanticString(components: [ + AtomicComponent(string: "static func", type: .keyword), + AtomicComponent(string: " ", type: .standard), + AtomicComponent(string: "< infix", type: .standard), + AtomicComponent(string: "(", type: .standard), + AtomicComponent(string: "Pair", type: .type(.struct, .name)), + AtomicComponent(string: "<", type: .standard), + AtomicComponent(string: "Swift.Int", type: .type(.struct, .name)), + AtomicComponent(string: ", ", type: .standard), + AtomicComponent(string: "Swift.Int", type: .type(.struct, .name)), + AtomicComponent(string: ">", type: .standard), + AtomicComponent(string: ")", type: .standard), + AtomicComponent(string: " -> ", type: .standard), + AtomicComponent(string: "Swift.Bool", type: .type(.struct, .name)), + ]) + #expect(isLeftUnchanged(line, maximumLineWidth: 10)) + } + + @Test func swiftUIBodyIsLaidOutByStructure() { + let source = """ + extension SettingsApp.SettingsNavigationSplitView: SwiftUI.View { + typealias Body = SwiftUI.ModifiedContent, SwiftUI.NavigationSplitView, SettingsApp.SettingsSecondaryColumn>>>, SwiftUI._EnvironmentKeyWritingModifier>, SwiftUI.OnTestViewModifier> + } + """ + #expect(formatted(source, maximumLineWidth: 100) == """ + extension SettingsApp.SettingsNavigationSplitView: SwiftUI.View { + typealias Body = SwiftUI.ModifiedContent< + SwiftUI.ModifiedContent< + SwiftUI.SceneBridgeReader< + SwiftUI.SubscriptionView< + Combine.PassthroughSubject< + Any, + Swift.Never + >, + SwiftUI.NavigationSplitView< + SwiftUI.ModifiedContent< + SettingsApp.SettingsSidebarList, + SwiftUI.ToolbarRemovingModifier + >, + SettingsApp.SettingsSecondaryColumn + > + > + >, + SwiftUI._EnvironmentKeyWritingModifier + >, + SwiftUI.OnTestViewModifier + > + } + """) + } +} + +extension Collection { + /// The collection's single element; `nil` when it has none or several. + var only: Element? { + count == 1 ? first : nil + } +} diff --git a/Tests/SwiftDeclarationRenderingTests/NestedFieldOffsetMemoizationTests.swift b/Tests/SwiftDeclarationRenderingTests/NestedFieldOffsetMemoizationTests.swift index d9ee4f55c..9086832d9 100644 --- a/Tests/SwiftDeclarationRenderingTests/NestedFieldOffsetMemoizationTests.swift +++ b/Tests/SwiftDeclarationRenderingTests/NestedFieldOffsetMemoizationTests.swift @@ -8,6 +8,7 @@ import MachOFoundation import Demangling @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import Semantic /// The in-process nested field-offset expansion reads byte for byte the same /// with its per-metatype memo as without it (evolution proposal @@ -28,9 +29,15 @@ final class NestedFieldOffsetMemoizationTests: MachOSwiftSectionFixtureTests, @u /// Every stored field of every non-generic struct and class in the /// fixture, rendered in process with field offsets, expanded field - /// offsets and type layouts on. - private func renderEveryStoredField() async throws -> [(label: String, rendered: String)] { + /// offsets and type layouts on. With `rowSpellingResolver`, each row + /// spells its type through it from the node the level keeps, the way the + /// interface printer has the rows spelled (evolution proposal + /// `consistent-c-imported-type-spelling`). + private func renderEveryStoredField(rowSpellingResolver: DemangleResolver? = nil) async throws -> [(label: String, rendered: String)] { var configuration = DeclarationRenderConfiguration.demangleOptions(.default) + if let rowSpellingResolver { + configuration = DeclarationRenderConfiguration(demangleResolver: rowSpellingResolver).spellingFieldLayoutTypeNamesThroughResolver(true) + } configuration.printFieldOffset = true configuration.printExpandedFieldOffsets = true configuration.printTypeLayout = true @@ -86,6 +93,24 @@ final class NestedFieldOffsetMemoizationTests: MachOSwiftSectionFixtureTests, @u #expect(mismatches.isEmpty, "\(mismatches.prefix(3).joined(separator: "\n\n"))") } + /// Rows spelled from the node a level keeps read the same from a cold + /// memo, from a warm one and without the memo — and do take the + /// resolver's spelling, not the `.default` one stored beside the node. + @Test func memoizedExpansionSpelledThroughAResolverReadsAsTheUnmemoizedOne() async throws { + let rowSpellingResolver = DemangleResolver.options(.interface) + RuntimeFieldLayoutMemo.removeAll() + let unmemoized = try await NestedFieldOffsetLevelMemo.$isBypassed.withValue(true) { + try await renderEveryStoredField(rowSpellingResolver: rowSpellingResolver) + } + let firstMemoized = try await renderEveryStoredField(rowSpellingResolver: rowSpellingResolver) + let secondMemoized = try await renderEveryStoredField(rowSpellingResolver: rowSpellingResolver) + let mismatches = Self.mismatches(between: unmemoized, and: firstMemoized) + Self.mismatches(between: unmemoized, and: secondMemoized) + #expect(mismatches.isEmpty, "\(mismatches.prefix(3).joined(separator: "\n\n"))") + + let defaultSpelled = try await renderEveryStoredField() + #expect(!Self.mismatches(between: defaultSpelled, and: firstMemoized).isEmpty, "the resolver's spelling should differ from `.default` on some row") + } + /// The row before an unresolved last payload keeps the branch it drew /// without the memo, read from a cold memo and from a warm one alike. @Test func aRowBeforeAnUnresolvedLastPayloadKeepsItsOpenBranch() async throws { diff --git a/Tests/SwiftDeclarationRenderingTests/OpaqueTypeArgumentDepthTests.swift b/Tests/SwiftDeclarationRenderingTests/OpaqueTypeArgumentDepthTests.swift index c97ba0bfe..d57aacd8b 100644 --- a/Tests/SwiftDeclarationRenderingTests/OpaqueTypeArgumentDepthTests.swift +++ b/Tests/SwiftDeclarationRenderingTests/OpaqueTypeArgumentDepthTests.swift @@ -7,6 +7,7 @@ import MachOFoundation import Demangling @_spi(Internals) import SwiftInspection @_spi(Internals) import SwiftSymbols +import SwiftSectionFixtureSupport /// An opaque type reference spells its generic arguments as one list per /// declaration around the opaque result, outermost first, and the mangler @@ -29,22 +30,6 @@ import Demangling /// carries the argument lists the mangler writes for these declarations. @Suite struct OpaqueTypeArgumentDepthTests { - private enum FixtureWorkingDirectoryCleanup { - nonisolated(unsafe) static var directories: [URL] = [] - static let registration: Void = { - atexit { - for directory in FixtureWorkingDirectoryCleanup.directories { - try? FileManager.default.removeItem(at: directory) - } - } - }() - } - - private struct FixtureCompilationError: Swift.Error, CustomStringConvertible { - let diagnostics: String - var description: String { "opaque-type-argument-depth fixture compilation failed:\n\(diagnostics)" } - } - private static let moduleName = "OpaqueTypeArgumentDepthFixture" /// `FixtureAnchor` is ballast: a fixture dylib with no class has no @@ -88,47 +73,14 @@ struct OpaqueTypeArgumentDepthTests { } """ - private static let fixtureCompilationResult: Result = { - Result { - let workingDirectory = FileManager.default.temporaryDirectory - .appendingPathComponent("\(moduleName)-\(UUID().uuidString)") - try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) - _ = FixtureWorkingDirectoryCleanup.registration - FixtureWorkingDirectoryCleanup.directories.append(workingDirectory) - - let sourceURL = workingDirectory.appendingPathComponent("\(moduleName).swift") - let libraryURL = workingDirectory.appendingPathComponent("lib\(moduleName).dylib") - try fixtureSource.write(to: sourceURL, atomically: true, encoding: .utf8) - - let process = Process() - process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") - process.arguments = [ - "swiftc", "-swift-version", "5", "-emit-library", "-module-name", moduleName, - "-target", "arm64-apple-macosx15.0", - sourceURL.path, "-o", libraryURL.path, - ] - let standardErrorPipe = Pipe() - process.standardError = standardErrorPipe - try process.run() - // Drain before waiting, or a long diagnostic deadlocks both sides. - let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() - process.waitUntilExit() - guard process.terminationStatus == 0 else { - throw FixtureCompilationError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) - } - return libraryURL - } - }() - private func loadFixtureMachOFile() throws -> MachOFile { - let libraryURL = try Self.fixtureCompilationResult.get() - switch try MachOKit.loadFromFile(url: libraryURL) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } + let libraryURL = try FixtureCompiler.shared.dynamicLibrary( + named: Self.moduleName, + language: .swift, + source: Self.fixtureSource, + arguments: ["-swift-version", "5", "-target", "arm64-apple-macosx15.0"] + ) + return try HostSlice.machOFile(at: libraryURL) } /// The offset of the opaque type descriptor of the declaration named diff --git a/Tests/SwiftDeclarationRenderingTests/OpaqueTypeOrdinalTests.swift b/Tests/SwiftDeclarationRenderingTests/OpaqueTypeOrdinalTests.swift index 3a43c19b5..ffabf0ce3 100644 --- a/Tests/SwiftDeclarationRenderingTests/OpaqueTypeOrdinalTests.swift +++ b/Tests/SwiftDeclarationRenderingTests/OpaqueTypeOrdinalTests.swift @@ -7,6 +7,7 @@ import MachOFoundation import Demangling @_spi(Internals) import SwiftInspection @_spi(Internals) import SwiftSymbols +import SwiftSectionFixtureSupport /// A declaration may produce more than one opaque type — `-> Pair` /// is two — and the demangled `opaqueType` node says which one it is in its @@ -23,17 +24,6 @@ import Demangling /// survived a full dump of both. @Suite struct OpaqueTypeOrdinalTests { - private enum FixtureWorkingDirectoryCleanup { - nonisolated(unsafe) static var directories: [URL] = [] - static let registration: Void = { - atexit { - for directory in FixtureWorkingDirectoryCleanup.directories { - try? FileManager.default.removeItem(at: directory) - } - } - }() - } - /// `Anchor` keeps a `__DATA` segment in the dylib (see AGENTS.md, /// "On-the-fly-compiled fixture dylibs need a class"). /// @@ -77,52 +67,14 @@ struct OpaqueTypeOrdinalTests { } """ - private static let fixtureCompilationResult: Result = { - Result { - let workingDirectory = FileManager.default.temporaryDirectory - .appendingPathComponent("OpaqueTypeOrdinalFixture-\(UUID().uuidString)") - try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) - _ = FixtureWorkingDirectoryCleanup.registration - FixtureWorkingDirectoryCleanup.directories.append(workingDirectory) - - let sourceURL = workingDirectory.appendingPathComponent("OpaqueTypeOrdinalFixture.swift") - let libraryURL = workingDirectory.appendingPathComponent("libOpaqueTypeOrdinalFixture.dylib") - try fixtureSource.write(to: sourceURL, atomically: true, encoding: .utf8) - - let process = Process() - process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") - process.arguments = [ - "swiftc", "-emit-library", "-module-name", "OpaqueTypeOrdinalFixture", - "-target", "arm64-apple-macosx15.0", - sourceURL.path, "-o", libraryURL.path, - ] - let standardErrorPipe = Pipe() - process.standardError = standardErrorPipe - try process.run() - // Drain BEFORE waitUntilExit — see LegacyDyldInfoBindTests. - let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() - process.waitUntilExit() - guard process.terminationStatus == 0 else { - throw FixtureCompilationError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) - } - return libraryURL - } - }() - - private struct FixtureCompilationError: Swift.Error, CustomStringConvertible { - let diagnostics: String - var description: String { "opaque-type-ordinal fixture compilation failed:\n\(diagnostics)" } - } - private func loadFixtureMachOFile() throws -> MachOFile { - let libraryURL = try Self.fixtureCompilationResult.get() - switch try MachOKit.loadFromFile(url: libraryURL) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } + let libraryURL = try FixtureCompiler.shared.dynamicLibrary( + named: "OpaqueTypeOrdinalFixture", + language: .swift, + source: Self.fixtureSource, + arguments: ["-target", "arm64-apple-macosx15.0"] + ) + return try HostSlice.machOFile(at: libraryURL) } /// `…QOMQ` is the opaque type descriptor's own symbol; `makeOpaquePair`'s diff --git a/Tests/SwiftDeclarationRenderingTests/RecursiveNestedFieldOffsetExpansionTests.swift b/Tests/SwiftDeclarationRenderingTests/RecursiveNestedFieldOffsetExpansionTests.swift index 99ba55f16..4c74bb7e1 100644 --- a/Tests/SwiftDeclarationRenderingTests/RecursiveNestedFieldOffsetExpansionTests.swift +++ b/Tests/SwiftDeclarationRenderingTests/RecursiveNestedFieldOffsetExpansionTests.swift @@ -8,6 +8,7 @@ import MachOFoundation import Demangling @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import Semantic /// Regression coverage for the nested expanded-field-offset walk on a **cyclic** /// field graph. diff --git a/Tests/SwiftDeclarationRenderingTests/RuntimeEnumLayoutRenderingTests.swift b/Tests/SwiftDeclarationRenderingTests/RuntimeEnumLayoutRenderingTests.swift index 731a345a8..25f889d5b 100644 --- a/Tests/SwiftDeclarationRenderingTests/RuntimeEnumLayoutRenderingTests.swift +++ b/Tests/SwiftDeclarationRenderingTests/RuntimeEnumLayoutRenderingTests.swift @@ -8,6 +8,7 @@ import MachOFoundation import Demangling @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import Semantic /// Verifies the **MachOImage** (runtime) enum-layout path end-to-end on the /// fixture: single-payload empty cases render their *exact* extra-inhabitant diff --git a/Tests/SwiftDumpTests/CustomObjCClassNameDumpTests.swift b/Tests/SwiftDumpTests/CustomObjCClassNameDumpTests.swift index 8a8cfedee..dcee45f1e 100644 --- a/Tests/SwiftDumpTests/CustomObjCClassNameDumpTests.swift +++ b/Tests/SwiftDumpTests/CustomObjCClassNameDumpTests.swift @@ -8,6 +8,8 @@ import SwiftDeclarationRendering import SwiftInspection import SwiftObjCInterop @testable import SwiftSectionTestingSupport +import Semantic +import SwiftSectionFixtureSupport /// The dump path's rendering of a class the source renamed for the /// Objective-C runtime (evolution proposal `objc-custom-class-name`): the diff --git a/Tests/SwiftDumpTests/ExistentialAnyDumpTests.swift b/Tests/SwiftDumpTests/ExistentialAnyDumpTests.swift index d2318ae48..b0523127f 100644 --- a/Tests/SwiftDumpTests/ExistentialAnyDumpTests.swift +++ b/Tests/SwiftDumpTests/ExistentialAnyDumpTests.swift @@ -5,6 +5,9 @@ import MachOFoundation import MachOSwiftSection import SwiftDump @testable import SwiftSectionTestingSupport +import Demangling +import SwiftDeclarationRendering +import Semantic /// `dump` with `DemangleOptions.useExistentialAny` (evolution proposal /// `existential-any`): the field types swift-demangling prints spell diff --git a/Tests/SwiftDumpTests/ExportStatusDumpAnnotationTests.swift b/Tests/SwiftDumpTests/ExportStatusDumpAnnotationTests.swift index b4371ed4a..e95958225 100644 --- a/Tests/SwiftDumpTests/ExportStatusDumpAnnotationTests.swift +++ b/Tests/SwiftDumpTests/ExportStatusDumpAnnotationTests.swift @@ -8,6 +8,7 @@ import SwiftDeclarationRendering @_spi(Internals) @testable import SwiftSymbols @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import Semantic /// Dump-path coverage for the `// not exported` annotation (evolution /// proposal 0008), pinning the two false-positive classes the member-symbol diff --git a/Tests/SwiftDumpTests/GenericParameterDepthDumpTests.swift b/Tests/SwiftDumpTests/GenericParameterDepthDumpTests.swift index ca505c8b0..368bb4388 100644 --- a/Tests/SwiftDumpTests/GenericParameterDepthDumpTests.swift +++ b/Tests/SwiftDumpTests/GenericParameterDepthDumpTests.swift @@ -5,6 +5,9 @@ import MachOFoundation @testable import MachOSwiftSection @testable import SwiftDump import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport +import SwiftDeclarationRendering +import Semantic /// The dump path's half of `GenericParameterDepthNamingTests`: the dumpers /// render a generic declaration's parameter clause through the same diff --git a/Tests/SwiftDumpTests/InitAccessorDumpTests.swift b/Tests/SwiftDumpTests/InitAccessorDumpTests.swift index 84c78e398..f07a9d257 100644 --- a/Tests/SwiftDumpTests/InitAccessorDumpTests.swift +++ b/Tests/SwiftDumpTests/InitAccessorDumpTests.swift @@ -5,6 +5,9 @@ import MachOFoundation import MachOSwiftSection import SwiftDump @testable import SwiftSectionTestingSupport +import SwiftDeclarationRendering +import Semantic +import Demangling /// `dump` lists a property's SE-0400 init accessor among its type's variable /// symbols, with the address and export status every member symbol gets diff --git a/Tests/SwiftDumpTests/LocalTypeDumpTests.swift b/Tests/SwiftDumpTests/LocalTypeDumpTests.swift index 7b8bbdcc2..d73d4b1cf 100644 --- a/Tests/SwiftDumpTests/LocalTypeDumpTests.swift +++ b/Tests/SwiftDumpTests/LocalTypeDumpTests.swift @@ -5,6 +5,9 @@ import MachOFoundation @testable import MachOSwiftSection @testable import SwiftDump @testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport +import Semantic +import SwiftDeclarationRendering /// The dump declares a local type under the compiler's full name and lists /// the members its symbols attribute to it (evolution proposal diff --git a/Tests/SwiftDumpTests/ModuleSelectorDumpTests.swift b/Tests/SwiftDumpTests/ModuleSelectorDumpTests.swift index 9e28b40aa..475eb96c6 100644 --- a/Tests/SwiftDumpTests/ModuleSelectorDumpTests.swift +++ b/Tests/SwiftDumpTests/ModuleSelectorDumpTests.swift @@ -5,6 +5,9 @@ import MachOFoundation import MachOSwiftSection import SwiftDump @testable import SwiftSectionTestingSupport +import Demangling +import Semantic +import SwiftDeclarationRendering /// `dump` with `DemangleOptions.useModuleSelectors` (evolution proposal /// `module-selectors`): the names swift-demangling prints follow the option, diff --git a/Tests/SwiftDumpTests/ObjCImplementationClassDumpTests.swift b/Tests/SwiftDumpTests/ObjCImplementationClassDumpTests.swift index 52589d0e2..3e8ac3efd 100644 --- a/Tests/SwiftDumpTests/ObjCImplementationClassDumpTests.swift +++ b/Tests/SwiftDumpTests/ObjCImplementationClassDumpTests.swift @@ -5,6 +5,8 @@ import MachOFoundation import SwiftDump import SwiftDeclarationRendering @testable import SwiftSectionTestingSupport +import Semantic +import SwiftSectionFixtureSupport /// The dump path's rendering of an `@objc @implementation` class (evolution /// proposal `objc-implementation-class-recognition`): everything the binary @@ -66,7 +68,12 @@ struct ObjCImplementationClassDumpTests { let output = try await dump(.strippedEverything) #expect(output.hasPrefix("@objc @implementation /* inferred from ObjC class data: 4 ivars carry Swift-style type encodings */ extension Widget {")) #expect(output.contains("// Evidence: inferred from ObjC class data: 4 ivars carry Swift-style type encodings")) - #expect(output.contains("title // offset 0x8, size 16, alignment 8, encoding \"?\", Swift type not recoverable")) + // The Objective-C side still gives the `@objc` ivars' types, and the + // comment says which part did (evolution proposal + // `objc-ivar-type-recovery`). + #expect(output.contains("var title: Swift.String! // offset 0x8, size 16, alignment 8, encoding \"?\", Swift type from the ObjC property"), "\(output)") + #expect(output.contains("var count: Swift.Int // offset 0x18, size 8, alignment 8, encoding \"q\", Swift type from the ObjC type encoding"), "\(output)") + #expect(output.contains("swiftOnlyCache // offset 0x20, size 8, alignment 8, encoding \"\", Swift type not recoverable, not exposed to ObjC"), "\(output)") // IMPs with no symbol print as addresses only. #expect(output.contains("-[Widget refresh] // types \"v16@0:8\", imp 0x")) #expect(!output.contains("To\n")) diff --git a/Tests/SwiftDumpTests/ObjCMemberDumpTests.swift b/Tests/SwiftDumpTests/ObjCMemberDumpTests.swift index 5fd06e5d8..be6286007 100644 --- a/Tests/SwiftDumpTests/ObjCMemberDumpTests.swift +++ b/Tests/SwiftDumpTests/ObjCMemberDumpTests.swift @@ -9,6 +9,8 @@ import SwiftInspection import SwiftObjCInterop import SwiftThunkAnalysis @testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport +import Semantic /// The dump path's rendering of the ObjC member facts (evolution proposals /// `objc-ancestor-override-recovery` and `objc-member-selector-recovery`): diff --git a/Tests/SwiftDumpTests/ObservableMacroDumpTests.swift b/Tests/SwiftDumpTests/ObservableMacroDumpTests.swift index 77417b07d..ed62d930d 100644 --- a/Tests/SwiftDumpTests/ObservableMacroDumpTests.swift +++ b/Tests/SwiftDumpTests/ObservableMacroDumpTests.swift @@ -5,6 +5,9 @@ import MachOFoundation import MachOSwiftSection import SwiftDump @testable import SwiftSectionTestingSupport +import Semantic +import SwiftDeclarationRendering +import Demangling /// `dump` names the macro that generated an `@Observable` class's members on /// its header line and keeps every member as the records have them diff --git a/Tests/SwiftDumpTests/OpaqueWitnessDumpAnnotationTests.swift b/Tests/SwiftDumpTests/OpaqueWitnessDumpAnnotationTests.swift index bceca48a5..4d057756b 100644 --- a/Tests/SwiftDumpTests/OpaqueWitnessDumpAnnotationTests.swift +++ b/Tests/SwiftDumpTests/OpaqueWitnessDumpAnnotationTests.swift @@ -5,8 +5,11 @@ import MachOFoundation import MachOSwiftSection import SwiftDeclarationRendering import SwiftDump +import SwiftSectionFixtureSupport @_spi(Internals) import SwiftInspection import SwiftThunkAnalysis +import Demangling +import Semantic /// What the dump adds on top of the interface's spelling for an /// associated-type witness built from another module's opaque archetype @@ -28,7 +31,7 @@ struct OpaqueWitnessDumpAnnotationTests { }() } - private struct FixtureCompilationError: Error, CustomStringConvertible { + private struct FixtureCompilationError: Swift.Error, CustomStringConvertible { let diagnostics: String var description: String { "opaque witness dump fixture compilation failed:\n\(diagnostics)" } } @@ -38,7 +41,7 @@ struct OpaqueWitnessDumpAnnotationTests { let clientLibraryURL: URL } - private static let fixtureCompilationResult: Result = { + private static let fixtureCompilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("OpaqueWitnessDumpFixture-\(UUID().uuidString)") @@ -127,12 +130,7 @@ struct OpaqueWitnessDumpAnnotationTests { private func loadClient() throws -> (client: MachOFile, corePath: String) { let fixture = try Self.fixtureCompilationResult.get() - switch try File.loadFromFile(url: fixture.clientLibraryURL) { - case .machO(let machOFile): - return (machOFile, fixture.coreLibraryURL.path) - case .fat(let fatFile): - return (try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }), fixture.coreLibraryURL.path) - } + return (try HostSlice.machOFile(at: fixture.clientLibraryURL), fixture.coreLibraryURL.path) } /// The dump of every conformance in the client, keyed by diff --git a/Tests/SwiftDumpTests/PrivateTypeMemberAttributionTests.swift b/Tests/SwiftDumpTests/PrivateTypeMemberAttributionTests.swift index e805785e5..e47df99b7 100644 --- a/Tests/SwiftDumpTests/PrivateTypeMemberAttributionTests.swift +++ b/Tests/SwiftDumpTests/PrivateTypeMemberAttributionTests.swift @@ -6,6 +6,8 @@ import MachOFoundation @testable import SwiftDump @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import SwiftDeclarationRendering +import Semantic /// Issue #115: two top-level `private struct PrivateDoppelganger` declarations /// (one per fixture file) share their interface-printed name — the private diff --git a/Tests/SwiftDumpTests/ProtocolRequirementRightHandSideDumpTests.swift b/Tests/SwiftDumpTests/ProtocolRequirementRightHandSideDumpTests.swift index b77ab749e..fb57f022c 100644 --- a/Tests/SwiftDumpTests/ProtocolRequirementRightHandSideDumpTests.swift +++ b/Tests/SwiftDumpTests/ProtocolRequirementRightHandSideDumpTests.swift @@ -5,6 +5,9 @@ import MachOFoundation import MachOSwiftSection import SwiftDump @testable import SwiftSectionTestingSupport +import SwiftDeclarationRendering +import Semantic +import Demangling /// A protocol's same-type or superclass requirement whose right-hand side is /// a composite type prints that type (evolution proposal diff --git a/Tests/SwiftDumpTests/Swift64DeclarationShapeDumpTests.swift b/Tests/SwiftDumpTests/Swift64DeclarationShapeDumpTests.swift index 5fbc568b8..4d5c553b2 100644 --- a/Tests/SwiftDumpTests/Swift64DeclarationShapeDumpTests.swift +++ b/Tests/SwiftDumpTests/Swift64DeclarationShapeDumpTests.swift @@ -5,6 +5,9 @@ import MachOFoundation import MachOSwiftSection import SwiftDump @testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport +import SwiftDeclarationRendering +import Semantic /// The dump of the declaration shapes Swift 6.4 introduced (evolution /// proposal `borrow-accessors-and-suppressed-associated-types`): a member diff --git a/Tests/SwiftDumpTests/SwiftDeclaredObjCProtocolDumpTests.swift b/Tests/SwiftDumpTests/SwiftDeclaredObjCProtocolDumpTests.swift index db949d9a0..ced8d14bc 100644 --- a/Tests/SwiftDumpTests/SwiftDeclaredObjCProtocolDumpTests.swift +++ b/Tests/SwiftDumpTests/SwiftDeclaredObjCProtocolDumpTests.swift @@ -8,6 +8,8 @@ import SwiftDeclarationRendering @_spi(Internals) import SwiftInspection @_spi(Internals) import SwiftObjCInterop @testable import SwiftSectionTestingSupport +import Semantic +import SwiftSectionFixtureSupport /// The dump of an `@objc` protocol declared in Swift (evolution proposal /// `swift-declared-objc-protocols`): each requirement as a Swift declaration diff --git a/Tests/SwiftDumpTests/ThunkOnlyObjCMemberDumpTests.swift b/Tests/SwiftDumpTests/ThunkOnlyObjCMemberDumpTests.swift index 244039042..7e7eadac4 100644 --- a/Tests/SwiftDumpTests/ThunkOnlyObjCMemberDumpTests.swift +++ b/Tests/SwiftDumpTests/ThunkOnlyObjCMemberDumpTests.swift @@ -6,6 +6,8 @@ import MachOFoundation @testable import SwiftDump import SwiftDeclarationRendering @testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport +import Semantic /// The dump path's listing of the members an image keeps only as their /// `@objc` thunk (evolution proposal `thunk-only-objc-members`): the diff --git a/Tests/SwiftDumpTests/VTableSlotAttributionTests.swift b/Tests/SwiftDumpTests/VTableSlotAttributionTests.swift index ef5d6df4d..5a0acd84c 100644 --- a/Tests/SwiftDumpTests/VTableSlotAttributionTests.swift +++ b/Tests/SwiftDumpTests/VTableSlotAttributionTests.swift @@ -7,6 +7,8 @@ import MachOFoundation import SwiftDeclarationRendering @_spi(Internals) @testable import SwiftSymbols @testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport +import Semantic /// Vtable slot attribution under identical code folding. /// @@ -25,17 +27,6 @@ import SwiftDeclarationRendering /// premise of every test here rather than a soft check. @Suite(.serialized) struct VTableSlotAttributionTests { - private enum FixtureWorkingDirectoryCleanup { - nonisolated(unsafe) static var directories: [URL] = [] - static let registration: Void = { - atexit { - for directory in FixtureWorkingDirectoryCleanup.directories { - try? FileManager.default.removeItem(at: directory) - } - } - }() - } - /// `alpha` / `beta` / `gamma` have byte-identical (empty) bodies and fold /// onto one address. `Nested.nestedNoop` folds onto the SAME address and is /// the cross-type trap: its demangled tree's first class node is `Host`, so @@ -58,54 +49,23 @@ struct VTableSlotAttributionTests { } """ - private static let fixtureCompilationResult: Result = { - Result { - let workingDirectory = FileManager.default.temporaryDirectory - .appendingPathComponent("VTableAttributionFixture-\(UUID().uuidString)") - try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) - _ = FixtureWorkingDirectoryCleanup.registration - FixtureWorkingDirectoryCleanup.directories.append(workingDirectory) - - let sourceURL = workingDirectory.appendingPathComponent("VTableAttributionFixture.swift") - let libraryURL = workingDirectory.appendingPathComponent("libVTableAttributionFixture.dylib") - try fixtureSource.write(to: sourceURL, atomically: true, encoding: .utf8) + private struct FixtureLookupError: Swift.Error, CustomStringConvertible { + let diagnostics: String + var description: String { "vtable-attribution fixture lookup failed:\n\(diagnostics)" } + } - let process = Process() - process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") - process.arguments = [ - "swiftc", "-emit-library", "-module-name", "VTableAttributionFixture", - sourceURL.path, "-o", libraryURL.path, + private func loadFixtureMachOFile() throws -> MachOFile { + let libraryURL = try FixtureCompiler.shared.dynamicLibrary( + named: "VTableAttributionFixture", + language: .swift, + source: Self.fixtureSource, + arguments: [ // ld64's identical-code-folding switch: without it the empty // bodies keep four distinct addresses and nothing is ambiguous. "-Xlinker", "-deduplicate", ] - let standardErrorPipe = Pipe() - process.standardError = standardErrorPipe - try process.run() - // Drain BEFORE waitUntilExit — see LegacyDyldInfoBindTests. - let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() - process.waitUntilExit() - guard process.terminationStatus == 0 else { - throw FixtureCompilationError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) - } - return libraryURL - } - }() - - private struct FixtureCompilationError: Swift.Error, CustomStringConvertible { - let diagnostics: String - var description: String { "vtable-attribution fixture compilation failed:\n\(diagnostics)" } - } - - private func loadFixtureMachOFile() throws -> MachOFile { - let libraryURL = try Self.fixtureCompilationResult.get() - switch try MachOKit.loadFromFile(url: libraryURL) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } + ) + return try HostSlice.machOFile(at: libraryURL) } private func classDescriptor(named name: String, in machOFile: MachOFile) throws -> ClassDescriptor { @@ -115,7 +75,7 @@ struct VTableSlotAttributionTests { return classDescriptor } Issue.record("fixture is missing the class \(name)") - throw FixtureCompilationError(diagnostics: "class \(name) not found") + throw FixtureLookupError(diagnostics: "class \(name) not found") } /// The vtable slot declarations of a dumped class, in slot order, as @@ -290,13 +250,7 @@ enum SimulatorRuntimeSwiftUICore { struct GraphHostVTableAttributionTests { private func graphHostDump() async throws -> String { let url = try #require(SimulatorRuntimeSwiftUICore.url) - let machOFile: MachOFile - switch try MachOKit.loadFromFile(url: url) { - case .machO(let file): - machOFile = file - case .fat(let fatFile): - machOFile = try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }) - } + let machOFile = try HostSlice.machOFile(at: url) for typeContextDescriptor in try machOFile.swift.typeContextDescriptors { guard case .class(let classDescriptor) = typeContextDescriptor, diff --git a/Tests/SwiftIndexingTests/CImportedExtensionKindTests.swift b/Tests/SwiftIndexingTests/CImportedExtensionKindTests.swift index 3fe8db3c2..5fdc5676e 100644 --- a/Tests/SwiftIndexingTests/CImportedExtensionKindTests.swift +++ b/Tests/SwiftIndexingTests/CImportedExtensionKindTests.swift @@ -4,6 +4,8 @@ import MachOKit @testable import MachOSwiftSection @_spi(Support) @testable import SwiftDeclaration @_spi(Support) @testable import SwiftIndexing +import OrderedCollections +import SwiftSectionFixtureSupport /// A type declared inside `extension { … }` is filed under a /// synthetic extension of that C type, keyed by an `ExtensionName` whose @@ -67,7 +69,7 @@ struct CImportedExtensionKindTests { } """ - private static let fixtureCompilationResult: Result = { + private static let fixtureCompilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("CImportedExtensionKindFixture-\(UUID().uuidString)") @@ -92,7 +94,7 @@ struct CImportedExtensionKindTests { let standardErrorPipe = Pipe() process.standardError = standardErrorPipe try process.run() - // Drain BEFORE waitUntilExit — see LegacyDyldInfoBindTests. + // Drain BEFORE waitUntilExit, or a long diagnostic deadlocks both sides. let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() process.waitUntilExit() guard process.terminationStatus == 0 else { @@ -108,14 +110,7 @@ struct CImportedExtensionKindTests { } private func loadFixtureMachOFile() throws -> MachOFile { - let libraryURL = try Self.fixtureCompilationResult.get() - switch try MachOKit.loadFromFile(url: libraryURL) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } + try HostSlice.machOFile(at: Self.fixtureCompilationResult.get()) } private func typeExtensionKind(of extendedTypeName: String) async throws -> ExtensionKind { diff --git a/Tests/SwiftIndexingTests/InitAccessorIndexingTests.swift b/Tests/SwiftIndexingTests/InitAccessorIndexingTests.swift index 2f6577905..d41176ebd 100644 --- a/Tests/SwiftIndexingTests/InitAccessorIndexingTests.swift +++ b/Tests/SwiftIndexingTests/InitAccessorIndexingTests.swift @@ -7,6 +7,8 @@ import MachOSwiftSection @_spi(Support) @testable import SwiftDeclaration @_spi(Support) @testable import SwiftIndexing @testable import SwiftSectionTestingSupport +import OrderedCollections +import SwiftSymbols /// A SE-0400 init accessor is one of its property's accessors (evolution /// proposal `init-accessor-recovery`): the index files its symbol with the diff --git a/Tests/SwiftIndexingTests/LocalTypeDisplayNameTests.swift b/Tests/SwiftIndexingTests/LocalTypeDisplayNameTests.swift index 085ffa43a..4efb778c4 100644 --- a/Tests/SwiftIndexingTests/LocalTypeDisplayNameTests.swift +++ b/Tests/SwiftIndexingTests/LocalTypeDisplayNameTests.swift @@ -6,6 +6,7 @@ import MachOSwiftSection import SwiftDeclaration @_spi(Support) import SwiftIndexing import SwiftInspection +import OrderedCollections /// The name a reader is shown of a type declared in a function or closure /// body, or of a type nested in one (evolution proposal diff --git a/Tests/SwiftIndexingTests/ObjCProtocolDefinitionIndexingTests.swift b/Tests/SwiftIndexingTests/ObjCProtocolDefinitionIndexingTests.swift index 5b3944be4..f650c4868 100644 --- a/Tests/SwiftIndexingTests/ObjCProtocolDefinitionIndexingTests.swift +++ b/Tests/SwiftIndexingTests/ObjCProtocolDefinitionIndexingTests.swift @@ -7,6 +7,7 @@ import MachOSwiftSection @_spi(Support) @testable import SwiftDeclaration @_spi(Support) @testable import SwiftIndexing @testable import SwiftSectionTestingSupport +import OrderedCollections /// The declaration model of the `@objc` protocols a Swift module declares /// (evolution proposal `swift-declared-objc-protocols`): one diff --git a/Tests/SwiftIndexingTests/ObjCWrittenCategoryConformanceTests.swift b/Tests/SwiftIndexingTests/ObjCWrittenCategoryConformanceTests.swift new file mode 100644 index 000000000..ae405acd5 --- /dev/null +++ b/Tests/SwiftIndexingTests/ObjCWrittenCategoryConformanceTests.swift @@ -0,0 +1,61 @@ +import Foundation +import Testing +import MachOKit +import MachOFoundation +import MachOSwiftSection +@_spi(Support) @testable import SwiftDeclaration +@_spi(Support) @testable import SwiftIndexing +@_spi(Internals) import SwiftObjCInterop +@testable import SwiftSectionTestingSupport + +/// An image no Swift code went into has no extension of Swift's, so none of +/// its categories gives a conformance extension — OS X 10.9's AppKit, all +/// Objective-C, printed four. An image Swift went into keeps its categories, +/// Objective-C code's among them: the linker merges the categories of one +/// class, so the Swift extensions' protocols and the Objective-C category's +/// arrive in one list. +/// +/// Holds `ExclusiveImageAccess` because the adoption index is per-image +/// state the indexer and the queries below share. +@Suite(.serialized, ExclusiveImageAccess(ObjCWrittenCategoriesFixture.moduleName)) +struct ObjCWrittenCategoryConformanceTests { + private static let moduleName = ObjCWrittenCategoriesFixture.moduleName + + private static func indexer(for machO: MachO) async throws -> SwiftDeclarationIndexer { + let indexer = SwiftDeclarationIndexer(configuration: SwiftDeclarationIndexConfiguration(), in: machO) + try await indexer.prepare() + return indexer + } + + private static func expectNoCategoryConformances(in machO: some MachOSwiftSectionRepresentableWithCache) async throws { + #expect(ObjCProtocolAdoptionIndex.shared.categoryAdoptions(in: machO).map(\.classRuntimeName) == []) + let indexer = try await Self.indexer(for: machO) + #expect(indexer.objcCategoryConformances.map(\.extendedTypeName.name) == []) + } + + @Test func objectiveCOnlyImageFromTheFile() async throws { + try await Self.expectNoCategoryConformances(in: ObjCWrittenCategoriesFixture.machOFile(.objectiveCOnly)) + } + + @Test func objectiveCOnlyImageFromTheLoadedImage() async throws { + try await Self.expectNoCategoryConformances(in: ObjCWrittenCategoriesFixture.loadedImage(.objectiveCOnly)) + } + + /// The two extensions of `DateFormatter` adopt one protocol each; both + /// reach the conformance extension of `NSDateFormatter`. + private static func expectSwiftProtocolsKept(in machO: some MachOSwiftSectionRepresentableWithCache) async throws { + let indexer = try await Self.indexer(for: machO) + let dateFormatterProtocolNames = indexer.objcCategoryConformances + .filter { $0.extendedTypeName.name == "__C.NSDateFormatter" } + .flatMap { $0.protocolNames.map(\.name) } + #expect(Set(dateFormatterProtocolNames).isSuperset(of: ["\(moduleName).SwiftDeclaredAdoption", "\(moduleName).SecondSwiftDeclaredAdoption"])) + } + + @Test func mixedImageFromTheFile() async throws { + try await Self.expectSwiftProtocolsKept(in: ObjCWrittenCategoriesFixture.machOFile(.mixed)) + } + + @Test func mixedImageFromTheLoadedImage() async throws { + try await Self.expectSwiftProtocolsKept(in: ObjCWrittenCategoriesFixture.loadedImage(.mixed)) + } +} diff --git a/Tests/SwiftIndexingTests/ObservableMacroExpansionRecoveryTests.swift b/Tests/SwiftIndexingTests/ObservableMacroExpansionRecoveryTests.swift index c5b49d6d0..d2d060097 100644 --- a/Tests/SwiftIndexingTests/ObservableMacroExpansionRecoveryTests.swift +++ b/Tests/SwiftIndexingTests/ObservableMacroExpansionRecoveryTests.swift @@ -8,6 +8,8 @@ import MachOSwiftSection @_spi(Support) @testable import SwiftIndexing import SwiftInspection @testable import SwiftSectionTestingSupport +import SwiftSymbols +import OrderedCollections /// `TypeDefinition.observableMacroExpansion` sorts an `@Observable` class's /// stored `var`s into the storage of the properties the macro tracks and the diff --git a/Tests/SwiftIndexingTests/ObservableMacroRecognitionTests.swift b/Tests/SwiftIndexingTests/ObservableMacroRecognitionTests.swift index 53302a6a5..199a7e336 100644 --- a/Tests/SwiftIndexingTests/ObservableMacroRecognitionTests.swift +++ b/Tests/SwiftIndexingTests/ObservableMacroRecognitionTests.swift @@ -8,6 +8,7 @@ import MachOSwiftSection @_spi(Support) @testable import SwiftIndexing @testable import SwiftInspection @testable import SwiftSectionTestingSupport +import OrderedCollections /// `TypeDefinition.attachedMacros` recognizes a class `@Observable` expanded /// from its field records when the definition is built, before anything is diff --git a/Tests/SwiftIndexingTests/PrivateDeclarationsWholeTreeTests.swift b/Tests/SwiftIndexingTests/PrivateDeclarationsWholeTreeTests.swift index 2d9133a19..4e03ab4df 100644 --- a/Tests/SwiftIndexingTests/PrivateDeclarationsWholeTreeTests.swift +++ b/Tests/SwiftIndexingTests/PrivateDeclarationsWholeTreeTests.swift @@ -7,6 +7,7 @@ import Demangling import SwiftDeclaration @_spi(Support) import SwiftIndexing import SwiftInspection +import OrderedCollections /// `privateDeclarations` reads a name's whole tree but for two parts: the /// signature of a function, closure, variable, subscript, initializer or @@ -106,13 +107,7 @@ struct PrivateDeclarationsWholeTreeTests { /// SymbolTestsCore declares private types (`PrivateDoppelgangers.swift`, /// `Structs.swift`), so here the names compared do read some. @Test func symbolTestsCore() async throws { - let machOFile: MachOFile - switch try loadFromFile(named: .SymbolTestsCore) { - case .machO(let thinMachOFile): - machOFile = thinMachOFile - case .fat(let fatFile): - machOFile = try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }) - } + let machOFile = try HostSlice.machOFile(in: loadFromFile(named: .SymbolTestsCore)) let indexer = SwiftDeclarationIndexer(configuration: .init(), eventHandlers: [], in: machOFile) try await indexer.prepare() diff --git a/Tests/SwiftIndexingTests/SymbolTestsCoreIntegrationTests.swift b/Tests/SwiftIndexingTests/SymbolTestsCoreIntegrationTests.swift index e458c4c52..ae07d60cc 100644 --- a/Tests/SwiftIndexingTests/SymbolTestsCoreIntegrationTests.swift +++ b/Tests/SwiftIndexingTests/SymbolTestsCoreIntegrationTests.swift @@ -6,6 +6,7 @@ import Foundation import Testing import MachOKit import Dependencies +import OrderedCollections @_spi(Internals) import SwiftSymbols @_spi(Internals) import MachOCaches @_spi(Support) @testable import SwiftInterface @@ -13,6 +14,7 @@ import Dependencies @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport @testable import SwiftDump +import Semantic // MARK: - Shared Setup @@ -539,7 +541,7 @@ extension STCoreTests { ) let printer = SwiftDeclarationPrinter(in: machOFile) - await #expect(throws: (any Error).self) { + await #expect(throws: (any Swift.Error).self) { _ = try await printer.printExtensionHeader(unreadableExtensionDefinition, level: 1) } } diff --git a/Tests/SwiftIndexingTests/WrappedPropertyRecoveryTests.swift b/Tests/SwiftIndexingTests/WrappedPropertyRecoveryTests.swift index 0ca9e8fba..c2cc595ba 100644 --- a/Tests/SwiftIndexingTests/WrappedPropertyRecoveryTests.swift +++ b/Tests/SwiftIndexingTests/WrappedPropertyRecoveryTests.swift @@ -6,6 +6,8 @@ import MachOFoundation import MachOSwiftSection @_spi(Support) @testable import SwiftDeclaration @_spi(Support) @testable import SwiftIndexing +import OrderedCollections +import SwiftSectionFixtureSupport /// Two modules compiled on the fly, each carrying a class (a struct-only /// fixture dylib has no `__DATA` segment and MachOKit before 0.52.103 mis-walked @@ -88,7 +90,7 @@ enum WrappedPropertyFixture { let clientURL: URL } - static let compilationResult: Result = { + static let compilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("WrappedPropertyFixture-\(UUID().uuidString)") @@ -138,12 +140,7 @@ enum WrappedPropertyFixture { } static func machOFile(at url: URL) throws -> MachOFile { - switch try File.loadFromFile(url: url) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - return try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }) - } + try HostSlice.machOFile(at: url) } /// Loads both dylibs into the test process (the kit first, so the diff --git a/Tests/SwiftInspectionTests/AnonymousContextPrivateDiscriminatorTests.swift b/Tests/SwiftInspectionTests/AnonymousContextPrivateDiscriminatorTests.swift index da7b37551..726d8c4f1 100644 --- a/Tests/SwiftInspectionTests/AnonymousContextPrivateDiscriminatorTests.swift +++ b/Tests/SwiftInspectionTests/AnonymousContextPrivateDiscriminatorTests.swift @@ -34,7 +34,7 @@ struct AnonymousContextPrivateDiscriminatorTests { @Test(.enabled(if: runsOnMacOS26OrLater, "the anchor class ships with macOS 26's AppKit")) func privateClassKeepsItsDiscriminatorInTheSystemCache() throws { - let cache = try DyldCache(path: .current) + let cache = try #require(FullDyldCache.cachedHost, "no host dyld shared cache").mainCache let machOFile = try #require(cache.machOFile(named: .AppKit), "the running system's cache has no AppKit") let classDescriptor = try #require(try Self.classDescriptor(named: Self.privateClassName, in: machOFile)) let expectedDiscriminator = try #require(try Self.discriminatorFromObjCRuntimeName(in: machOFile)) diff --git a/Tests/SwiftInspectionTests/Arm64eSignedVWTPointerTests.swift b/Tests/SwiftInspectionTests/Arm64eSignedVWTPointerTests.swift index 37680ea5a..f0404f159 100644 --- a/Tests/SwiftInspectionTests/Arm64eSignedVWTPointerTests.swift +++ b/Tests/SwiftInspectionTests/Arm64eSignedVWTPointerTests.swift @@ -1,5 +1,6 @@ import Foundation import Testing +import SwiftSectionFixtureSupport @testable import SwiftInspection // MARK: - Test Enum @@ -42,17 +43,12 @@ private enum Arm64eProbeHost { /// `nil` when the host can execute arm64e third-party processes; otherwise /// the reason the probe layer must skip. static let arm64eExecutionUnavailabilityReason: String? = { - let canarySourceURL = temporaryDirectoryURL.appendingPathComponent("canary.c") - let canaryBinaryURL = temporaryDirectoryURL.appendingPathComponent("canary") - do { - try "int main(void) { return 42; }\n".write(to: canarySourceURL, atomically: true, encoding: .utf8) - } catch { - return "cannot write canary source: \(error)" - } - guard let compileResult = try? spawn( - executablePath: "/usr/bin/xcrun", - arguments: ["clang", "-arch", "arm64e", "-o", canaryBinaryURL.path, canarySourceURL.path] - ), compileResult.exitCode == 0 else { + guard let canaryBinaryURL = try? FixtureCompiler.shared.executable( + named: "canary", + language: .c, + source: "int main(void) { return 42; }\n", + arguments: ["-arch", "arm64e"] + ) else { return "clang cannot produce an arm64e canary on this host" } guard let runResult = try? spawn(executablePath: canaryBinaryURL.path, arguments: []) else { diff --git a/Tests/SwiftInspectionTests/CImportedTypeIdentityTests.swift b/Tests/SwiftInspectionTests/CImportedTypeIdentityTests.swift index 1f2ccdf7a..4ae5534df 100644 --- a/Tests/SwiftInspectionTests/CImportedTypeIdentityTests.swift +++ b/Tests/SwiftInspectionTests/CImportedTypeIdentityTests.swift @@ -5,6 +5,7 @@ import MachOFoundation @_spi(Internals) import Demangling @testable import MachOSwiftSection @_spi(Internals) @testable import SwiftInspection +import SwiftSectionFixtureSupport // Evolution proposal `type-import-info-identity`: a descriptor-derived // demangling of a C-imported type must spell the type the way the compiler @@ -208,7 +209,7 @@ struct CImportedTypeIdentityFixtureTests { ("sdkRenamedTag", "So8_NSRangeV", "__C._NSRange"), ] - private static let fixtureCompilationResult: Result = { + private static let fixtureCompilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("CImportedTypeIdentityFixture-\(UUID().uuidString)") @@ -237,7 +238,7 @@ struct CImportedTypeIdentityFixtureTests { let standardErrorPipe = Pipe() process.standardError = standardErrorPipe try process.run() - // Drain BEFORE waitUntilExit — see LegacyDyldInfoBindTests. + // Drain BEFORE waitUntilExit, or a long diagnostic deadlocks both sides. let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() process.waitUntilExit() guard process.terminationStatus == 0 else { @@ -253,14 +254,7 @@ struct CImportedTypeIdentityFixtureTests { } private func loadFixtureMachOFile() throws -> MachOFile { - let libraryURL = try Self.fixtureCompilationResult.get() - switch try MachOKit.loadFromFile(url: libraryURL) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } + try HostSlice.machOFile(at: try Self.fixtureCompilationResult.get()) } private func holderFieldMangledTypeNames(in machOFile: MachOFile) throws -> [String: MangledName] { diff --git a/Tests/SwiftInspectionTests/DyldCacheTwinImageTests.swift b/Tests/SwiftInspectionTests/DyldCacheTwinImageTests.swift index b07d82346..3962eeef6 100644 --- a/Tests/SwiftInspectionTests/DyldCacheTwinImageTests.swift +++ b/Tests/SwiftInspectionTests/DyldCacheTwinImageTests.swift @@ -4,6 +4,7 @@ import MachOKit import MachOObjCSection @testable import SwiftInspection @testable import SwiftObjCInterop +import MachOKitExtensions private enum TwinSwiftUICaches { static let swiftUIPath = "/System/Library/Frameworks/SwiftUI.framework/Versions/A/SwiftUI" diff --git a/Tests/SwiftInspectionTests/EnumLayoutVerificationTests.swift b/Tests/SwiftInspectionTests/EnumLayoutVerificationTests.swift index 26aeb13f7..0f73a2c0e 100644 --- a/Tests/SwiftInspectionTests/EnumLayoutVerificationTests.swift +++ b/Tests/SwiftInspectionTests/EnumLayoutVerificationTests.swift @@ -5,6 +5,7 @@ import MachOKit @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport @testable @_spi(Internals) import SwiftInspection +import Demangling // MARK: - Test Enum Definitions diff --git a/Tests/SwiftInspectionTests/MalformedSymbolValueTests.swift b/Tests/SwiftInspectionTests/MalformedSymbolValueTests.swift index 1310c3049..8f34205a2 100644 --- a/Tests/SwiftInspectionTests/MalformedSymbolValueTests.swift +++ b/Tests/SwiftInspectionTests/MalformedSymbolValueTests.swift @@ -6,6 +6,9 @@ import Demangling @_spi(Internals) import SwiftSymbols @testable @_spi(Internals) import SwiftInspection @testable @_spi(Internals) import SwiftObjCInterop +import MachOKitExtensions +import MachOResolving +import SwiftSectionFixtureSupport /// A symbol's value is the binary's own claim about where something sits, and /// two indexes read the bytes there: `SymbolicManglingIndex` (the mangled name @@ -50,7 +53,7 @@ struct MalformedSymbolValueTests { var description: String { "malformed symbol value fixture compilation failed:\n\(diagnostics)" } } - private static let fixtureCompilationResult: Result = { + private static let fixtureCompilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("MalformedSymbolValueFixture-\(UUID().uuidString)") @@ -97,13 +100,7 @@ struct MalformedSymbolValueTests { } private static func fixtureFile() throws -> MachOFile { - let libraryURL = try fixtureCompilationResult.get() - switch try File.loadFromFile(url: libraryURL) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - return try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }) - } + try HostSlice.machOFile(at: fixtureCompilationResult.get()) } @Test("a symbolic-mangling symbol whose value is no offset is counted unpaired instead of read") diff --git a/Tests/SwiftInspectionTests/ParentChainCycleTests.swift b/Tests/SwiftInspectionTests/ParentChainCycleTests.swift new file mode 100644 index 000000000..3626ca428 --- /dev/null +++ b/Tests/SwiftInspectionTests/ParentChainCycleTests.swift @@ -0,0 +1,72 @@ +import Foundation +import Testing +import MachOKit +import MachOFoundation +@testable import MachOSwiftSection +@_spi(Internals) @testable import SwiftInspection +import SwiftSectionFixtureSupport + +/// A context descriptor whose parent pointer leads back to itself, which +/// only a malformed binary has. Every walk up the parents followed it for +/// ever: the generic context read each generic parent's own context, which +/// walked its parents in turn, until the stack ran out; the module lookup +/// and the depth layout spun (2026-11-29 codebase audit, finding 6). In a +/// child process, where they used to crash or hang. +@Suite +struct ParentChainCycleTests { + private static let moduleName = "ParentChainCycleFixture" + + /// `FixtureAnchor` is ballast: a fixture dylib with no class has no + /// `__DATA` segment, which older MachOKit releases mis-walked. + private static let source = """ + public final class FixtureAnchor {} + + public struct Box { + public var value: Value + } + + public struct Pair { + public var first: First + public var second: Second + } + """ + + private static func typeDescriptor(named name: String, in machOFile: MachOFile) throws -> TypeContextDescriptorWrapper { + try #require(try machOFile.swift.typeContextDescriptors.first { try $0.namedContextDescriptor.name(in: machOFile.context) == name }, "no \(name) in the fixture") + } + + @Test func aGenericTypeThatIsItsOwnParentReadsAsUnreadable() async { + await #expect(processExitsWith: .success) { + exit(Self.readTheTypeThatIsItsOwnParent()) + } + } + + private static func readTheTypeThatIsItsOwnParent() -> Int32 { + do { + let library = try FixtureCompiler.shared.dynamicLibrary( + named: moduleName, + language: .swift, + source: source, + arguments: ["-swift-version", "5", "-Onone", "-target", "arm64-apple-macosx15.0"] + ) + // A context descriptor's parent pointer sits at offset 4, after + // its flags; -4 leads back to the descriptor itself. + let patchedLibrary = try CompiledFixtureCopies.patchedCopy(of: library) { bytes, file in + let box = try typeDescriptor(named: "Box", in: file).typeContextDescriptor.offset + CompiledFixtureCopies.write(Int32(-4), at: box + 4, in: &bytes) + } + let patched = try HostSlice.machOFile(at: patchedLibrary) + let box = try typeDescriptor(named: "Box", in: patched).typeContextDescriptor + let genericContextIsUnreadable = (try? box.genericContext(in: patched.context)) == nil + let moduleIsUnreadable = (try? box.moduleContextDescriptor(in: patched.context)) == nil + // An intact generic context, laid out against the chain that + // leads back into itself. + let pair = try typeDescriptor(named: "Pair", in: patched).typeContextDescriptor + guard let pairContext = try pair.genericContext(in: patched.context) else { return EXIT_FAILURE } + _ = GenericParameterDepthLayout.make(for: pairContext, ownedBy: box, in: patched.context) + return genericContextIsUnreadable && moduleIsUnreadable ? EXIT_SUCCESS : 2 + } catch { + return EXIT_FAILURE + } + } +} diff --git a/Tests/SwiftInspectionTests/SymbolicDemanglerFixedShapeExtractionTests.swift b/Tests/SwiftInspectionTests/SymbolicDemanglerFixedShapeExtractionTests.swift index 4700e05a2..5d262944d 100644 --- a/Tests/SwiftInspectionTests/SymbolicDemanglerFixedShapeExtractionTests.swift +++ b/Tests/SwiftInspectionTests/SymbolicDemanglerFixedShapeExtractionTests.swift @@ -5,6 +5,7 @@ import MachOFoundation @_spi(Internals) import Demangling @testable import MachOSwiftSection @_spi(Internals) @testable import SwiftInspection +import SwiftSectionFixtureSupport /// `SymbolicDemangler`'s two fixed-shape node extractions (evolution proposal /// `metadata-reader-deterministic-node-extraction`). @@ -138,17 +139,6 @@ struct SymbolicDemanglerFixedShapeExtractionTests { // MARK: - Real `\x0C` references from an on-the-fly fixture - private enum FixtureWorkingDirectoryCleanup { - nonisolated(unsafe) static var directories: [URL] = [] - static let registration: Void = { - atexit { - for directory in FixtureWorkingDirectoryCleanup.directories { - try? FileManager.default.removeItem(at: directory) - } - } - }() - } - /// `Anchor` keeps a `__DATA` segment in the dylib (see AGENTS.md, /// "On-the-fly-compiled fixture dylibs need a class"). `Holder`'s two /// fields are what put ObjC protocols into mangled type names: a single @@ -170,54 +160,24 @@ struct SymbolicDemanglerFixedShapeExtractionTests { } """ - private static let fixtureCompilationResult: Result = { - Result { - let workingDirectory = FileManager.default.temporaryDirectory - .appendingPathComponent("ObjCProtocolReferenceFixture-\(UUID().uuidString)") - try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) - _ = FixtureWorkingDirectoryCleanup.registration - FixtureWorkingDirectoryCleanup.directories.append(workingDirectory) - - let sourceURL = workingDirectory.appendingPathComponent("ObjCProtocolReferenceFixture.swift") - let libraryURL = workingDirectory.appendingPathComponent("libObjCProtocolReferenceFixture.dylib") - try fixtureSource.write(to: sourceURL, atomically: true, encoding: .utf8) - - let process = Process() - process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") - process.arguments = [ - "swiftc", "-emit-library", "-module-name", "ObjCProtocolReferenceFixture", - // The deployment target that turns ObjC-protocol symbolic - // references on (feature availability 6.0 = macOS 15). - "-target", "arm64-apple-macosx15.0", - sourceURL.path, "-o", libraryURL.path, - ] - let standardErrorPipe = Pipe() - process.standardError = standardErrorPipe - try process.run() - // Drain BEFORE waitUntilExit — see LegacyDyldInfoBindTests. - let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() - process.waitUntilExit() - guard process.terminationStatus == 0 else { - throw FixtureCompilationError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) - } - return libraryURL - } - }() - private struct FixtureCompilationError: Swift.Error, CustomStringConvertible { let diagnostics: String var description: String { "ObjC-protocol-reference fixture compilation failed:\n\(diagnostics)" } } + /// Compiled once per process by the shared compiler. private func loadFixtureMachOFile() throws -> MachOFile { - let libraryURL = try Self.fixtureCompilationResult.get() - switch try MachOKit.loadFromFile(url: libraryURL) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } + let libraryURL = try FixtureCompiler.shared.dynamicLibrary( + named: "ObjCProtocolReferenceFixture", + language: .swift, + source: Self.fixtureSource, + arguments: [ + // The deployment target that turns ObjC-protocol symbolic + // references on (feature availability 6.0 = macOS 15). + "-target", "arm64-apple-macosx15.0", + ] + ) + return try HostSlice.machOFile(at: libraryURL) } private func holderFieldMangledTypeName(named fieldName: String, in machOFile: MachOFile) throws -> MangledName { @@ -281,7 +241,7 @@ struct SymbolicDemanglerFixedShapeExtractionTests { // The protocol Swift spells `NSObjectProtocol` is the ObjC protocol // `NSObject`; the reference record mangles the ObjC runtime name // (`So8NSObject_p`), and the Swift-side rename is APINotes' business - // (TypeIndexing), not the demangler's. + // (swift-type-indexing), not the demangler's. let printed = node.print(using: .default) #expect(printed == "__C.NSCopying & __C.NSObject") diff --git a/Tests/SwiftInspectionTests/SymbolicManglingIndexTests.swift b/Tests/SwiftInspectionTests/SymbolicManglingIndexTests.swift index cfdb98a88..055f21e61 100644 --- a/Tests/SwiftInspectionTests/SymbolicManglingIndexTests.swift +++ b/Tests/SwiftInspectionTests/SymbolicManglingIndexTests.swift @@ -57,7 +57,7 @@ struct SymbolicManglingIndexTests { /// proposal's memory note: what the paired references cost per image. @Test(.enabled(if: runsOnMacOS26OrLater, "the anchor symbols ship with macOS 26's AppKit")) func referenceCensusOfSystemCacheImages() throws { - let cache = try DyldCache(path: .current) + let cache = try #require(FullDyldCache.cachedHost, "no host dyld shared cache").mainCache var censusLines: [String] = [] for imageName in [MachOImageName.AppKit, .SwiftUICore] { let machOFile = try #require(cache.machOFile(named: imageName), "the running system's cache has no \(imageName)") @@ -224,7 +224,7 @@ struct SymbolicManglingIndexTests { } private static func appKitFileInSystemCache() throws -> MachOFile { - let cache = try DyldCache(path: .current) + let cache = try #require(FullDyldCache.cachedHost, "no host dyld shared cache").mainCache return try #require(cache.machOFile(named: .AppKit), "the running system's cache has no AppKit") } diff --git a/Tests/SwiftInterfaceTests/BoundedConcurrentMapTests.swift b/Tests/SwiftInterfaceTests/BoundedConcurrentMapTests.swift index 4f639e974..d920edf3b 100644 --- a/Tests/SwiftInterfaceTests/BoundedConcurrentMapTests.swift +++ b/Tests/SwiftInterfaceTests/BoundedConcurrentMapTests.swift @@ -1,6 +1,7 @@ import Foundation import Testing import MachOFoundation +import Utilities /// Pins `concurrentMap(maximumConcurrency:_:)` (evolution proposal /// `large-stack-executor-and-cross-version-parallelism`), the windowed diff --git a/Tests/SwiftInterfaceTests/CImportedTypeConformanceInterfaceTests.swift b/Tests/SwiftInterfaceTests/CImportedTypeConformanceInterfaceTests.swift index 79100581d..ca61edd2f 100644 --- a/Tests/SwiftInterfaceTests/CImportedTypeConformanceInterfaceTests.swift +++ b/Tests/SwiftInterfaceTests/CImportedTypeConformanceInterfaceTests.swift @@ -4,6 +4,8 @@ import MachOKit @testable import MachOSwiftSection @_spi(Support) @testable import SwiftPrinting @_spi(Support) @testable import SwiftInterface +import Semantic +import SwiftSectionTestingSupport /// Evolution proposal `type-import-info-identity`: the conformance extensions /// the importer synthesizes for C-imported types render as ONE block per @@ -70,7 +72,7 @@ struct CImportedTypeConformanceInterfaceTests { } """ - private static let fixtureCompilationResult: Result = { + private static let fixtureCompilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("CImportedTypeConformanceFixture-\(UUID().uuidString)") @@ -95,7 +97,7 @@ struct CImportedTypeConformanceInterfaceTests { let standardErrorPipe = Pipe() process.standardError = standardErrorPipe try process.run() - // Drain BEFORE waitUntilExit — see LegacyDyldInfoBindTests. + // Drain BEFORE waitUntilExit, or a long diagnostic deadlocks both sides. let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() process.waitUntilExit() guard process.terminationStatus == 0 else { @@ -111,14 +113,7 @@ struct CImportedTypeConformanceInterfaceTests { } private func loadFixtureMachOFile() throws -> MachOFile { - let libraryURL = try Self.fixtureCompilationResult.get() - switch try MachOKit.loadFromFile(url: libraryURL) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } + try HostSlice.machOFile(at: Self.fixtureCompilationResult.get()) } private func buildInterface() async throws -> String { @@ -159,11 +154,14 @@ struct CImportedTypeConformanceInterfaceTests { return bodies } + // Both types are imported under their own C names and this image carries + // their descriptors, so their extensions print the bare name the + // declarations print (evolution proposal `consistent-c-imported-type-spelling`). @Test(arguments: [ // A C tag enum: descriptor kind `enum`, mangled as a structure. - ("__C.ProbeMode", "typealias RawValue = Swift.Int"), + ("ProbeMode", "typealias RawValue = Swift.Int"), // A `swift_wrapper` typedef: mangled as a `typeAlias`. - ("__C.ProbeIdentifier", "typealias RawValue = Swift.String"), + ("ProbeIdentifier", "typealias RawValue = Swift.String"), ]) func rawRepresentableConformanceRendersWitnessAndMembersInOneBlock(typeName: String, witnessLine: String) async throws { let interface = try await buildInterface() diff --git a/Tests/SwiftInterfaceTests/CImportedTypeNameSpellingTests.swift b/Tests/SwiftInterfaceTests/CImportedTypeNameSpellingTests.swift new file mode 100644 index 000000000..4539d070b --- /dev/null +++ b/Tests/SwiftInterfaceTests/CImportedTypeNameSpellingTests.swift @@ -0,0 +1,618 @@ +import Foundation +import Testing +import MachOKit +@testable import MachOSwiftSection +@_spi(Support) @testable import SwiftPrinting +@_spi(Support) @testable import SwiftInterface +@testable import SwiftDeclarationRendering +import Demangling +import SwiftDeclaration +import SwiftIndexing +@_spi(Internals) import SwiftInspection +import Semantic +import SwiftSectionTestingSupport + +/// Evolution proposal `c-imported-type-name-spelling`: a C-imported type the +/// compiler knows by two names prints under one of them everywhere — +/// declaration, member types and extension headers. Evolution proposal +/// `consistent-c-imported-type-spelling` extends that to a type whose two +/// names are one, and to the field layout tree's comments. +/// +/// The fixture's bridging header reproduces the shapes AttributeGraph and the +/// SDK have: a struct renamed with `swift_name` (`AGWeakAttribute` → +/// `AnyWeakAttribute`) holding an anonymous struct, a `swift_wrapper` typedef +/// renamed the same way (`AGAttribute` → `AnyAttribute`), a typedef +/// imported as a member of another type (`NSAttributedStringKey` → +/// `NSAttributedString.Key`), whose descriptor keeps only the leaf, and two +/// types imported under their own C names: a plain struct, whose descriptor +/// carries no import info at all, and a `swift_wrapper` typedef, whose import +/// info carries the typedef namespace but no ABI name +/// (`AGDescriptionOption`). +@Suite +struct CImportedTypeNameSpellingTests { + // MARK: - Fixture + + private enum FixtureWorkingDirectoryCleanup { + nonisolated(unsafe) static var directories: [URL] = [] + static let registration: Void = { + atexit { + for directory in FixtureWorkingDirectoryCleanup.directories { + try? FileManager.default.removeItem(at: directory) + } + } + }() + } + + private static let fixtureHeader = """ + #import + #include + + typedef uint32_t AGFooIdentifier __attribute__((swift_wrapper(struct))) __attribute__((swift_name("AnyFooIdentifier"))); + + typedef struct __attribute__((swift_name("AnyFooThing"))) AGFooThing { + struct { + AGFooIdentifier identifier; + uint32_t seed; + } _details; + } AGFooThing; + + typedef struct ProbeOwner { + int value; + } ProbeOwner; + + typedef NSString *ProbeOwnerKey __attribute__((swift_wrapper(struct))) __attribute__((swift_name("ProbeOwner.Key"))); + + typedef struct ProbePlainValue { + int32_t value; + } ProbePlainValue; + + typedef NSString *ProbeOption __attribute__((swift_wrapper(struct))); + """ + + /// `Anchor` keeps a `__DATA` segment in the dylib (see AGENTS.md, + /// "On-the-fly-compiled fixture dylibs need a class"). The conformances + /// put the C-imported types' descriptors into this image: the Swift-side + /// `Equatable` of `AnyFooThing` and `ProbePlainValue`, and the importer's + /// synthesized `Hashable` of the three wrappers, reached through a generic + /// function. + private static let fixtureSource = """ + import Foundation + + public final class Anchor {} + + public struct PlainBox { + public var plain: ProbePlainValue + public var count: Int + + public init(plain: ProbePlainValue, count: Int) { + self.plain = plain + self.count = count + } + } + + public struct Holder { + public var thing: AnyFooThing + public var identifier: AnyFooIdentifier + public var key: ProbeOwner.Key + public var plain: ProbePlainValue + public var option: ProbeOption + public var box: PlainBox + + public init(thing: AnyFooThing, identifier: AnyFooIdentifier, key: ProbeOwner.Key, plain: ProbePlainValue, option: ProbeOption, box: PlainBox) { + self.thing = thing + self.identifier = identifier + self.key = key + self.plain = plain + self.option = option + self.box = box + } + } + + extension AnyFooThing: Equatable { + public static func == (left: AnyFooThing, right: AnyFooThing) -> Bool { + left._details.identifier == right._details.identifier && left._details.seed == right._details.seed + } + } + + extension ProbePlainValue: Equatable { + public static func == (left: ProbePlainValue, right: ProbePlainValue) -> Bool { + left.value == right.value + } + } + + @inline(never) public func hashValue(of value: Value) -> Int { value.hashValue } + @inline(never) public func isEqual(_ left: Value, _ right: Value) -> Bool { left == right } + + public func exercise(_ holder: Holder) -> (Int, Int, Bool, Bool, Int) { + (hashValue(of: holder.identifier), hashValue(of: holder.key), isEqual(holder.thing, holder.thing), isEqual(holder.plain, holder.plain), hashValue(of: holder.option)) + } + """ + + private static let fixtureCompilationResult: Result = { + Result { + let workingDirectory = FileManager.default.temporaryDirectory + .appendingPathComponent("CImportedTypeNameSpellingFixture-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) + _ = FixtureWorkingDirectoryCleanup.registration + FixtureWorkingDirectoryCleanup.directories.append(workingDirectory) + + let headerURL = workingDirectory.appendingPathComponent("CImportedTypeNameSpellingFixture.h") + let sourceURL = workingDirectory.appendingPathComponent("CImportedTypeNameSpellingFixture.swift") + let libraryURL = workingDirectory.appendingPathComponent("libCImportedTypeNameSpellingFixture.dylib") + try fixtureHeader.write(to: headerURL, atomically: true, encoding: .utf8) + try fixtureSource.write(to: sourceURL, atomically: true, encoding: .utf8) + + let process = Process() + process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") + process.arguments = [ + "swiftc", "-emit-library", "-module-name", "CImportedTypeNameSpellingFixture", + "-target", "arm64-apple-macosx15.0", + "-import-objc-header", headerURL.path, + sourceURL.path, "-o", libraryURL.path, + ] + let standardErrorPipe = Pipe() + process.standardError = standardErrorPipe + try process.run() + // Drain BEFORE waitUntilExit, or a long diagnostic deadlocks both sides. + let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() + process.waitUntilExit() + guard process.terminationStatus == 0 else { + throw FixtureCompilationError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) + } + return libraryURL + } + }() + + private struct FixtureCompilationError: Swift.Error, CustomStringConvertible { + let diagnostics: String + var description: String { "C-imported type name spelling fixture compilation failed:\n\(diagnostics)" } + } + + private func loadFixtureMachOFile() throws -> MachOFile { + try HostSlice.machOFile(at: Self.fixtureCompilationResult.get()) + } + + /// The fixture loaded into the test process, for the in-process layout + /// backend. + private func loadFixtureMachOImage() throws -> MachOImage { + let libraryURL = try Self.fixtureCompilationResult.get() + _ = libraryURL.path.withCString { dlopen($0, RTLD_NOW) } + let imageName = libraryURL.deletingPathExtension().lastPathComponent + return try #require(MachOImage(name: imageName), "the fixture dylib did not load in-process") + } + + /// Records every query, and answers the ones it was set up to answer. + private final class RecordingResolver: ModuleNameResolving, CImportedNameResolving, @unchecked Sendable { + private let lock = NSLock() + private var recordedQueryCount = 0 + private let moduleNamesByTypeName: [String: String] + private let swiftNamesByCName: [String: String] + + init(moduleNamesByTypeName: [String: String], swiftNamesByCName: [String: String] = [:]) { + self.moduleNamesByTypeName = moduleNamesByTypeName + self.swiftNamesByCName = swiftNamesByCName + } + + var queryCount: Int { + lock.withLock { recordedQueryCount } + } + + func moduleName(forTypeName typeName: String) async -> String? { + lock.withLock { recordedQueryCount += 1 } + return moduleNamesByTypeName[typeName] + } + + func swiftName(forCName cName: String, category: CImportedTypeNameCategory) async -> String? { + lock.withLock { recordedQueryCount += 1 } + return swiftNamesByCName[cName] + } + } + + private func makeBuilder(spelling: CImportedTypeNameSpelling = .swiftName, marksCImportedTypeNames: Bool = false, printsFieldLayout: Bool = false, usesModuleSelectors: Bool = false, resolver: RecordingResolver? = nil) async throws -> SwiftInterfaceBuilder { + try await makeBuilder(spelling: spelling, marksCImportedTypeNames: marksCImportedTypeNames, printsFieldLayout: printsFieldLayout, usesModuleSelectors: usesModuleSelectors, resolver: resolver, in: loadFixtureMachOFile()) + } + + /// `printsFieldLayout` turns on the field offsets and the expanded tree + /// of nested field offsets under them. + private func makeBuilder(spelling: CImportedTypeNameSpelling = .swiftName, marksCImportedTypeNames: Bool = false, printsFieldLayout: Bool = false, usesModuleSelectors: Bool = false, resolver: RecordingResolver? = nil, in machO: MachO) async throws -> SwiftInterfaceBuilder { + var printConfiguration = SwiftDeclarationPrintConfiguration() + printConfiguration.cImportedTypeNameSpelling = spelling + printConfiguration.marksCImportedTypeNames = marksCImportedTypeNames + printConfiguration.printFieldOffset = printsFieldLayout + printConfiguration.printExpandedFieldOffsets = printsFieldLayout + printConfiguration.usesModuleSelectors = usesModuleSelectors + var configuration = SwiftInterfaceBuilderConfiguration() + configuration.indexConfiguration = SwiftDeclarationIndexConfiguration(showCImportedTypes: true) + configuration.printConfiguration = printConfiguration + let builder = try SwiftInterfaceBuilder(configuration: configuration, eventHandlers: [], in: machO) + if let resolver { + builder.printer.addTypeNameResolver(resolver) + } + try await builder.prepare() + return builder + } + + private func buildInterface(spelling: CImportedTypeNameSpelling = .swiftName, printsFieldLayout: Bool = false, usesModuleSelectors: Bool = false, resolver: RecordingResolver? = nil) async throws -> String { + try await makeBuilder(spelling: spelling, printsFieldLayout: printsFieldLayout, usesModuleSelectors: usesModuleSelectors, resolver: resolver).printRoot().string + } + + private func lines(of interface: String, startingWith prefix: String) -> [String] { + interface.split(separator: "\n").map { $0.trimmingCharacters(in: .whitespaces) }.filter { $0.hasPrefix(prefix) } + } + + // MARK: - Trusting a descriptor's name + + @Test("A descriptor name is trusted when it is the type's whole Swift name", arguments: [ + ("AnyWeakAttribute", "AGWeakAttribute"), + ("AnyAttribute", "AGAttribute"), + ("CGColor", "CGColorRef"), + ("__UIPointerShape", "UIPointerShape"), + ]) + func trustsUserFacingNameWhenABINameDiffers(userFacingName: String, abiName: String) { + let importInfo = TypeImportInfo(abiName: abiName, symbolNamespace: nil, relatedEntityName: nil) + #expect(CImportedTypeSwiftNameTable.trustsUserFacingName(userFacingName, importInfo: importInfo)) + } + + /// A type imported as a member keeps only its leaf; a top-level rename of + /// the same shape is refused with it. + @Test("A leaf the C name ends with is not trusted", arguments: [ + ("Key", "NSAttributedStringKey"), + ("Name", "NSNotificationName"), + ("Decimal", "NSDecimal"), + ]) + func refusesLeafNameOfTypeImportedAsMember(userFacingName: String, abiName: String) { + let importInfo = TypeImportInfo(abiName: abiName, symbolNamespace: nil, relatedEntityName: nil) + #expect(!CImportedTypeSwiftNameTable.trustsUserFacingName(userFacingName, importInfo: importInfo)) + } + + @Test func refusesRelatedEntityName() { + let importInfo = TypeImportInfo(abiName: "CKErrorCode", symbolNamespace: nil, relatedEntityName: "e") + #expect(!CImportedTypeSwiftNameTable.trustsUserFacingName("CKError", importInfo: importInfo)) + } + + @Test func refusesNameWithoutABIName() { + let importInfo = TypeImportInfo(abiName: nil, symbolNamespace: TypeImportInfo.cTypedefSymbolNamespace, relatedEntityName: nil) + #expect(!CImportedTypeSwiftNameTable.trustsUserFacingName("CGRect", importInfo: importInfo)) + } + + @Test func nameTableReadsTheFixturesDescriptors() throws { + let machOFile = try loadFixtureMachOFile() + let descriptors = try machOFile.swift.typeContextDescriptors + let table = CImportedTypeSwiftNameTable(typeContextDescriptors: descriptors, in: machOFile.context) + var swiftNamesByDescriptorName: [String: String?] = [:] + for descriptorWrapper in descriptors where (try? descriptorWrapper.typeContextDescriptor.isCImportedContextDescriptor(in: machOFile.context)) == true { + let descriptorName = try descriptorWrapper.namedContextDescriptor.name(in: machOFile.context) + let identity = try SymbolicDemangler.demangleContext(for: descriptorWrapper.asContextDescriptorWrapper, in: machOFile.context) + swiftNamesByDescriptorName[descriptorName] = table.swiftName(forIdentity: identity) + } + #expect(swiftNamesByDescriptorName["AnyFooThing"] == .some("AnyFooThing")) + #expect(swiftNamesByDescriptorName["AnyFooIdentifier"] == .some("AnyFooIdentifier")) + // Imported as `ProbeOwner.Key`: the descriptor says `Key`, which is not trusted. + #expect(swiftNamesByDescriptorName["Key"] == .some(nil)) + // The anonymous struct keeps its own name and has no entry. + #expect(swiftNamesByDescriptorName["__Unnamed_struct__details"] == .some(nil)) + // No ABI name: the compiler writes one only when the two names differ. + #expect(swiftNamesByDescriptorName["ProbePlainValue"] == .some("ProbePlainValue")) + #expect(swiftNamesByDescriptorName["ProbeOption"] == .some("ProbeOption")) + } + + // MARK: - A descriptor's known Swift name + + @Test("A descriptor whose ABI name is absent or its own name is its own Swift name", arguments: [ + TypeImportInfo?.none, + TypeImportInfo(abiName: nil, symbolNamespace: TypeImportInfo.cTypedefSymbolNamespace, relatedEntityName: nil), + TypeImportInfo(abiName: "AGDescriptionOption", symbolNamespace: TypeImportInfo.cTypedefSymbolNamespace, relatedEntityName: nil), + ]) + func knowsDescriptorNameWithoutABIName(importInfo: TypeImportInfo?) { + #expect(CImportedTypeSwiftNameTable.knownSwiftName(ofDescriptorNamed: "AGDescriptionOption", importInfo: importInfo, isDirectlyInImportedModule: true) == "AGDescriptionOption") + } + + /// A type nested in a C type is printed through its parent, never looked + /// up by its own name. + @Test func doesNotKnowNestedDescriptorNameWithoutABIName() { + #expect(CImportedTypeSwiftNameTable.knownSwiftName(ofDescriptorNamed: "__Unnamed_struct__details", importInfo: nil, isDirectlyInImportedModule: false) == nil) + } + + @Test func knowsTrustedRenameAndNotUntrustedOne() { + let trusted = TypeImportInfo(abiName: "AGWeakAttribute", symbolNamespace: nil, relatedEntityName: nil) + #expect(CImportedTypeSwiftNameTable.knownSwiftName(ofDescriptorNamed: "AnyWeakAttribute", importInfo: trusted, isDirectlyInImportedModule: true) == "AnyWeakAttribute") + let untrusted = TypeImportInfo(abiName: "AGTreeValue", symbolNamespace: TypeImportInfo.cTypedefSymbolNamespace, relatedEntityName: nil) + #expect(CImportedTypeSwiftNameTable.knownSwiftName(ofDescriptorNamed: "TreeValue", importInfo: untrusted, isDirectlyInImportedModule: true) == nil) + } + + @Test func doesNotKnowRelatedEntityName() { + let withABIName = TypeImportInfo(abiName: "CKErrorCode", symbolNamespace: nil, relatedEntityName: "e") + #expect(CImportedTypeSwiftNameTable.knownSwiftName(ofDescriptorNamed: "CKError", importInfo: withABIName, isDirectlyInImportedModule: true) == nil) + let withoutABIName = TypeImportInfo(abiName: nil, symbolNamespace: nil, relatedEntityName: "e") + #expect(CImportedTypeSwiftNameTable.knownSwiftName(ofDescriptorNamed: "CKError", importInfo: withoutABIName, isDirectlyInImportedModule: true) == nil) + } + + // MARK: - Types imported under their own C names + + @Test func sameNameTypeReferencePrintsBareName() async throws { + let interface = try await buildInterface() + #expect(interface.contains("var plain: ProbePlainValue"), "\(interface)") + #expect(interface.contains("var option: ProbeOption"), "\(interface)") + #expect(!interface.contains("__C.ProbePlainValue"), "\(interface)") + #expect(!interface.contains("__C.ProbeOption"), "\(interface)") + } + + @Test func sameNameTypeExtensionHeaderPrintsBareName() async throws { + let interface = try await buildInterface() + let plainLines = lines(of: interface, startingWith: "extension ProbePlainValue: ") + #expect(plainLines.contains { $0.contains("Swift.Equatable") }, "\(interface)") + #expect(!lines(of: interface, startingWith: "extension ProbeOption: ").isEmpty, "\(interface)") + #expect(lines(of: interface, startingWith: "extension __C.ProbePlainValue").isEmpty, "\(interface)") + #expect(lines(of: interface, startingWith: "extension __C.ProbeOption").isEmpty, "\(interface)") + } + + @Test func sameNameTypeKeepsModuleThatResolverFinds() async throws { + let resolver = RecordingResolver(moduleNamesByTypeName: ["ProbePlainValue": "ProbeModule"]) + let interface = try await buildInterface(resolver: resolver) + #expect(interface.contains("var plain: ProbeModule.ProbePlainValue"), "\(interface)") + #expect(!lines(of: interface, startingWith: "extension ProbeModule.ProbePlainValue: ").isEmpty, "\(interface)") + // Nothing found for the wrapper: its own name, alone. + #expect(interface.contains("var option: ProbeOption"), "\(interface)") + } + + @Test func cSpellingKeepsMangledSameNameType() async throws { + let interface = try await buildInterface(spelling: .cName) + #expect(interface.contains("var plain: __C.ProbePlainValue"), "\(interface)") + #expect(interface.contains("var option: __C.ProbeOption"), "\(interface)") + #expect(!lines(of: interface, startingWith: "extension __C.ProbePlainValue: ").isEmpty, "\(interface)") + #expect(interface.contains("struct ProbePlainValue {"), "\(interface)") + } + + // MARK: - Field layout comments (offline) + + /// `Holder.thing` expands into the anonymous struct and the wrapper in + /// it: the rows name them the way the declarations do. + @Test func offlineLayoutCommentSpellsRenamedTypesAsDeclared() async throws { + let interface = try await buildInterface(printsFieldLayout: true) + #expect(interface.contains("_details (AnyFooThing.__Unnamed_struct__details): 0x0"), "\(interface)") + #expect(interface.contains("identifier (AnyFooIdentifier): 0x0"), "\(interface)") + #expect(!interface.contains("__C.AGFoo"), "\(interface)") + } + + /// `Holder.box` expands into `PlainBox`, whose field is the type + /// imported under its own C name. + @Test func offlineLayoutCommentSpellsSameNameTypeBare() async throws { + let interface = try await buildInterface(printsFieldLayout: true) + #expect(interface.contains("plain (ProbePlainValue): 0x"), "\(interface)") + #expect(!interface.contains("(__C.ProbePlainValue)"), "\(interface)") + } + + /// With module selectors on, so the printer's C spelling (`__C::`) is + /// told apart from the `.default` one the tree was built with (`__C.`). + @Test func offlineLayoutCommentSpellsCNamesWhenSpellingCNames() async throws { + let interface = try await buildInterface(spelling: .cName, printsFieldLayout: true, usesModuleSelectors: true) + #expect(interface.contains("identifier (__C::AGFooIdentifier): 0x0"), "\(interface)") + #expect(interface.contains("plain (__C::ProbePlainValue): 0x"), "\(interface)") + #expect(!interface.contains("AnyFooIdentifier"), "\(interface)") + } + + @Test func offlineLayoutCommentCarriesModuleSelectors() async throws { + let interface = try await buildInterface(printsFieldLayout: true, usesModuleSelectors: true) + #expect(interface.contains("rawValue (Swift::UInt32): 0x0"), "\(interface)") + #expect(!interface.contains("(Swift.UInt32)"), "\(interface)") + } + + /// The comments `Holder.` renders with through + /// `demangleResolver`, with or without asking for its spelling — offline + /// from a `MachOFile`, in process from a `MachOImage`. Drives the field + /// layout renderer directly, the way the printer does, without indexing + /// the image. + private func renderHolderFieldComments(named fieldName: String, in machO: MachO, demangleResolver: DemangleResolver, spellsThroughResolver: Bool) async throws -> String { + var configuration = DeclarationRenderConfiguration(demangleResolver: demangleResolver) + configuration.printFieldOffset = true + configuration.printExpandedFieldOffsets = true + configuration.staticFieldLayoutProvider = MachO.makeStaticFieldLayoutProvider(machO: machO, resolution: .default) + configuration = configuration.spellingFieldLayoutTypeNamesThroughResolver(spellsThroughResolver) + var holderType: TypeContextWrapper? + var holderDescriptor: StructDescriptor? + for type in try machO.swift.types { + guard case .struct(let structType) = type, try structType.descriptor.name(in: machO.context) == "Holder" else { continue } + holderType = type + holderDescriptor = structType.descriptor + } + let type = try #require(holderType) + let descriptor = try #require(holderDescriptor) + let renderer = FieldLayoutRenderer(type: type, metadata: nil, machO: machO, configuration: configuration) + let records = try descriptor.fieldDescriptor(in: machO.context).records(in: machO.context) + let fieldIndex = try #require(try records.firstIndex { try $0.fieldName(in: machO.context) == fieldName }) + return try await renderer.storedFieldComments(forFieldAtIndex: fieldIndex, mangledTypeName: records[fieldIndex].mangledTypeName(in: machO.context), fieldOffsets: renderer.fieldOffsets).string + } + + private func renderHolderThingComments(demangleResolver: DemangleResolver, spellsThroughResolver: Bool) async throws -> String { + try await renderHolderFieldComments(named: "thing", in: loadFixtureMachOFile(), demangleResolver: demangleResolver, spellsThroughResolver: spellsThroughResolver) + } + + /// The comments `Holder.` renders with through the interface + /// printer's own type spelling, with module selectors on. + private func renderHolderFieldCommentsAsInterface(named fieldName: String, in machO: MachO) async throws -> String { + var printConfiguration = SwiftDeclarationPrintConfiguration() + printConfiguration.usesModuleSelectors = true + let printer = SwiftDeclarationPrinter(configuration: printConfiguration, in: machO) + // The resolver holds the printer weakly and prints nothing once it is + // gone, which would leave every row on its `.default` spelling — on + // both sides of a comparison alike. + defer { withExtendedLifetime(printer) {} } + return try await renderHolderFieldComments(named: fieldName, in: machO, demangleResolver: printer.typeDemangleResolver, spellsThroughResolver: true) + } + + /// A resolver that spells every type alike, so a row it spelled is + /// unmistakable. + private static let markingResolver = DemangleResolver.builder { _ in + "SpelledByResolver" + } + + /// The dump never asks for the printer's spelling: whatever its resolver + /// is, its rows keep the `.default` one the tree was built with. + @Test func layoutCommentKeepsDefaultSpellingUnlessAsked() async throws { + let rendered = try await renderHolderThingComments(demangleResolver: Self.markingResolver, spellsThroughResolver: false) + #expect(rendered.contains("identifier (__C.AGFooIdentifier): 0x0"), "\(rendered)") + #expect(rendered.contains("rawValue (Swift.UInt32): 0x0"), "\(rendered)") + #expect(!rendered.contains("SpelledByResolver"), "\(rendered)") + } + + @Test func layoutCommentSpellsThroughResolverWhenAsked() async throws { + let rendered = try await renderHolderThingComments(demangleResolver: Self.markingResolver, spellsThroughResolver: true) + #expect(rendered.contains("identifier (SpelledByResolver): 0x0"), "\(rendered)") + #expect(!rendered.contains("__C.AGFooIdentifier"), "\(rendered)") + } + + @Test func freshRenderConfigurationDoesNotSpellThroughResolver() { + #expect(!DeclarationRenderConfiguration.demangleOptions(.default).spellsFieldLayoutTypeNamesThroughResolver) + } + + // MARK: - Field layout comments (in process) + + private func treeRows(of comments: String) -> [String] { + comments.split(separator: "\n").map(String.init).filter { $0.contains("── ") } + } + + /// `Holder.box` expands, in process, into `PlainBox`'s two fields. + @Test func inProcessLayoutCommentSpellsTypesAsDeclared() async throws { + let comments = try await renderHolderFieldCommentsAsInterface(named: "box", in: loadFixtureMachOImage()) + #expect(comments.contains("plain (ProbePlainValue): 0x"), "\(comments)") + #expect(comments.contains("count (Swift::Int): 0x"), "\(comments)") + #expect(!comments.contains("(__C.ProbePlainValue)"), "\(comments)") + #expect(!comments.contains("(Swift.Int)"), "\(comments)") + } + + /// The in-process walk prints the offline walk's rows, row for row. These + /// fields are non-generic, so neither walk has a reason to stop before + /// the other (it does under a generic standard-library struct, see + /// `OfflineSpecializationParityTests`). + @Test(arguments: ["thing", "identifier", "plain", "box"]) + func inProcessLayoutCommentRowsMatchOfflineOnes(fieldName: String) async throws { + let offline = try await renderHolderFieldCommentsAsInterface(named: fieldName, in: loadFixtureMachOFile()) + let inProcess = try await renderHolderFieldCommentsAsInterface(named: fieldName, in: loadFixtureMachOImage()) + let inProcessRows = treeRows(of: inProcess) + #expect(!inProcessRows.isEmpty, "\(inProcess)") + // Only the printer writes module selectors: rows on the `.default` + // spelling would match each other too, and prove nothing. + #expect(inProcessRows.contains { $0.contains("::") }, "\(inProcess)") + #expect(inProcessRows == treeRows(of: offline), "--- in process ---\n\(inProcess)\n--- offline ---\n\(offline)") + } + + /// The headline case, in process: the renamed C type in `Holder.thing`'s + /// anonymous struct. + @Test func inProcessLayoutCommentSpellsRenamedTypeAsDeclared() async throws { + let comments = try await renderHolderFieldCommentsAsInterface(named: "thing", in: loadFixtureMachOImage()) + #expect(comments.contains("identifier (AnyFooIdentifier): 0x0"), "\(comments)") + #expect(!comments.contains("__C"), "\(comments)") + } + + // MARK: - Spelling Swift names + + @Test func swiftSpellingPrintsBareSwiftNameWhenModuleIsUnknown() async throws { + let interface = try await buildInterface() + #expect(interface.contains("struct AnyFooThing {"), "\(interface)") + #expect(interface.contains("var _details: AnyFooThing.__Unnamed_struct__details"), "\(interface)") + #expect(interface.contains("var identifier: AnyFooIdentifier"), "\(interface)") + #expect(interface.contains("var thing: AnyFooThing"), "\(interface)") + let equatableLines = lines(of: interface, startingWith: "extension AnyFooThing: ") + #expect(equatableLines.contains { $0.contains("Swift.Equatable") }, "\(interface)") + #expect(!interface.contains("AGFooThing"), "\(interface)") + #expect(!interface.contains("AGFooIdentifier"), "\(interface)") + } + + @Test func untrustedDeclaredNamePrintsCName() async throws { + let interface = try await buildInterface() + #expect(interface.contains("struct ProbeOwnerKey {"), "\(interface)") + #expect(!interface.contains("struct Key {"), "\(interface)") + #expect(interface.contains("var key: __C.ProbeOwnerKey"), "\(interface)") + #expect(!lines(of: interface, startingWith: "extension __C.ProbeOwnerKey: ").isEmpty, "\(interface)") + } + + @Test func swiftSpellingKeepsModuleThatResolverFinds() async throws { + let resolver = RecordingResolver( + moduleNamesByTypeName: ["AGFooThing": "ProbeModule", "ProbeOwnerKey": "ProbeModule"], + swiftNamesByCName: ["ProbeOwnerKey": "ProbeOwner.Key"] + ) + let interface = try await buildInterface(resolver: resolver) + // The resolver finds the module but has no Swift name: the descriptor's. + #expect(interface.contains("var thing: ProbeModule.AnyFooThing"), "\(interface)") + #expect(!lines(of: interface, startingWith: "extension ProbeModule.AnyFooThing: ").isEmpty, "\(interface)") + #expect(interface.contains("struct AnyFooThing {"), "\(interface)") + // The resolver spells the member import whole. + #expect(interface.contains("var key: ProbeModule.ProbeOwner.Key"), "\(interface)") + #expect(!lines(of: interface, startingWith: "extension ProbeModule.ProbeOwner.Key: ").isEmpty, "\(interface)") + #expect(interface.contains("struct ProbeOwner.Key {"), "\(interface)") + // Nothing found for the wrapper: the descriptor's name, alone. + #expect(interface.contains("var identifier: AnyFooIdentifier"), "\(interface)") + } + + @Test func extensionHeaderSpellsLikeMemberTypes() async throws { + let interface = try await buildInterface() + let extensionLines = lines(of: interface, startingWith: "extension ") + #expect(!extensionLines.isEmpty, "\(interface)") + for line in extensionLines { + #expect(!line.hasPrefix("extension __C.AGFoo"), "\(line)") + } + } + + // MARK: - Spelling C names + + @Test func cSpellingPrintsMangledNamesAndAsksNoResolver() async throws { + let resolver = RecordingResolver(moduleNamesByTypeName: ["AGFooThing": "ProbeModule", "ProbeOwnerKey": "ProbeModule"]) + let interface = try await buildInterface(spelling: .cName, resolver: resolver) + #expect(interface.contains("struct AGFooThing {"), "\(interface)") + #expect(interface.contains("var _details: __C.AGFooThing.__Unnamed_struct__details"), "\(interface)") + #expect(interface.contains("var identifier: __C.AGFooIdentifier"), "\(interface)") + #expect(interface.contains("var thing: __C.AGFooThing"), "\(interface)") + #expect(!lines(of: interface, startingWith: "extension __C.AGFooThing: ").isEmpty, "\(interface)") + #expect(interface.contains("struct ProbeOwnerKey {"), "\(interface)") + #expect(!interface.contains("AnyFooThing"), "\(interface)") + #expect(!interface.contains("ProbeModule"), "\(interface)") + #expect(resolver.queryCount == 0) + } + + // MARK: - Marking declared names + + @Test func markedDeclaredNameCarriesBothSpellings() async throws { + let unmarked = try await makeBuilder().printRoot().frozen() + let marked = try await makeBuilder(marksCImportedTypeNames: true).printRoot().frozen() + let separated = marked.separatingAnnotationRegions() + #expect(separated.text == unmarked) + #expect(unmarked.separatingAnnotationRegions().annotations.isEmpty) + + let printedBytes = Array(separated.text.string.utf8) + var markedNames: [CImportedTypeNames: String] = [:] + for region in separated.annotations.regions { + guard let names = region.kind.cImportedTypeNames else { continue } + let regionStart = Int(region.utf8Offset) + markedNames[names] = String(decoding: printedBytes[regionStart ..< regionStart + Int(region.utf8Length)], as: UTF8.self) + } + #expect(markedNames == [ + CImportedTypeNames(swiftName: "AnyFooThing", cName: "AGFooThing"): "AnyFooThing", + CImportedTypeNames(swiftName: "AnyFooIdentifier", cName: "AGFooIdentifier"): "AnyFooIdentifier", + ]) + } + + @Test func markedCSpellingCarriesTheSameNames() async throws { + let marked = try await makeBuilder(spelling: .cName, marksCImportedTypeNames: true).printRoot().frozen() + let separated = marked.separatingAnnotationRegions() + let printedBytes = Array(separated.text.string.utf8) + let region = try #require(separated.annotations.regions(ofKind: .cImportedTypeName(CImportedTypeNames(swiftName: "AnyFooThing", cName: "AGFooThing"))).first) + let regionStart = Int(region.utf8Offset) + #expect(String(decoding: printedBytes[regionStart ..< regionStart + Int(region.utf8Length)], as: UTF8.self) == "AGFooThing") + } + + @Test func sameSpellingsAreNotMarked() async throws { + let marked = try await makeBuilder(marksCImportedTypeNames: true).printRoot().frozen() + let names = marked.separatingAnnotationRegions().annotations.regions.compactMap(\.kind.cImportedTypeNames) + // `ProbeOwnerKey` has no known Swift name without a resolver, and + // the anonymous struct and the two types imported under their own C + // names have one name only. + #expect(!names.contains { ["ProbeOwnerKey", "__Unnamed_struct__details", "ProbePlainValue", "ProbeOption"].contains($0.cName) }) + } + + @Test func regionKindRoundTripsDottedSwiftName() { + let names = CImportedTypeNames(swiftName: "NSAttributedString.Key", cName: "NSAttributedStringKey") + #expect(AnnotationRegion.Kind.cImportedTypeName(names).cImportedTypeNames == names) + #expect(AnnotationRegion.Kind.note.cImportedTypeNames == nil) + #expect(AnnotationRegion.Kind("cImportedTypeName").cImportedTypeNames == nil) + } +} diff --git a/Tests/SwiftInterfaceTests/ClassesWithoutClassObjectsInterfaceTests.swift b/Tests/SwiftInterfaceTests/ClassesWithoutClassObjectsInterfaceTests.swift index b1065e79a..b790b2581 100644 --- a/Tests/SwiftInterfaceTests/ClassesWithoutClassObjectsInterfaceTests.swift +++ b/Tests/SwiftInterfaceTests/ClassesWithoutClassObjectsInterfaceTests.swift @@ -9,6 +9,9 @@ import SwiftInterface import SwiftThunkAnalysis @_spi(Internals) import SwiftInspection @testable import SwiftSectionTestingSupport +import Semantic +import SwiftIndexing +import SwiftObjCInterop /// Swift classes without a class object on the interface path (evolution /// proposal `objc-classes-without-class-objects`): a generic class, or one diff --git a/Tests/SwiftInterfaceTests/CommentStructureContractTests.swift b/Tests/SwiftInterfaceTests/CommentStructureContractTests.swift index 2f3ec831a..ef60a77a0 100644 --- a/Tests/SwiftInterfaceTests/CommentStructureContractTests.swift +++ b/Tests/SwiftInterfaceTests/CommentStructureContractTests.swift @@ -13,6 +13,7 @@ import MachOKit @testable import MachOSwiftSection @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import OrderedCollections /// With `SwiftDeclarationPrintConfiguration.marksCommentStructure`, every /// definition of the SymbolTestsCore fixture separates to exactly its print diff --git a/Tests/SwiftInterfaceTests/CommentStructureShapeTests.swift b/Tests/SwiftInterfaceTests/CommentStructureShapeTests.swift index f1aa7af6b..31441986f 100644 --- a/Tests/SwiftInterfaceTests/CommentStructureShapeTests.swift +++ b/Tests/SwiftInterfaceTests/CommentStructureShapeTests.swift @@ -10,6 +10,7 @@ import MachOKit @testable import MachOSwiftSection @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import OrderedCollections /// The shapes RuntimeViewer draws its comment tags and folds from (evolution /// proposal `comment-structure`), read from the table a marked print of the diff --git a/Tests/SwiftInterfaceTests/ConditionalWitnessCommentStructureTests.swift b/Tests/SwiftInterfaceTests/ConditionalWitnessCommentStructureTests.swift index 67bdce374..c021da687 100644 --- a/Tests/SwiftInterfaceTests/ConditionalWitnessCommentStructureTests.swift +++ b/Tests/SwiftInterfaceTests/ConditionalWitnessCommentStructureTests.swift @@ -22,22 +22,6 @@ import SwiftSectionTestingSupport /// written into the witness record, so the fixture here is built for it. @Suite struct ConditionalWitnessCommentStructureTests { - private enum FixtureWorkingDirectoryCleanup { - nonisolated(unsafe) static var directories: [URL] = [] - static let registration: Void = { - atexit { - for directory in FixtureWorkingDirectoryCleanup.directories { - try? FileManager.default.removeItem(at: directory) - } - } - }() - } - - private struct FixtureCompilationError: Swift.Error, CustomStringConvertible { - let diagnostics: String - var description: String { "conditional-witness fixture compilation failed:\n\(diagnostics)" } - } - private static let moduleName = "CommentStructureConditionalWitnessFixture" /// `FixtureAnchor` is ballast: a fixture dylib with no class has no @@ -68,48 +52,14 @@ struct ConditionalWitnessCommentStructureTests { } """ - private static let fixtureCompilationResult: Result = { - Result { - let workingDirectory = FileManager.default.temporaryDirectory - .appendingPathComponent("\(moduleName)-\(UUID().uuidString)") - try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) - _ = FixtureWorkingDirectoryCleanup.registration - FixtureWorkingDirectoryCleanup.directories.append(workingDirectory) - - let sourceURL = workingDirectory.appendingPathComponent("\(moduleName).swift") - let libraryURL = workingDirectory.appendingPathComponent("lib\(moduleName).dylib") - try fixtureSource.write(to: sourceURL, atomically: true, encoding: .utf8) - - let process = Process() - process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") - process.arguments = [ - "swiftc", "-swift-version", "5", "-O", "-emit-library", - "-module-name", moduleName, - "-target", "arm64-apple-macosx15.0", - sourceURL.path, "-o", libraryURL.path, - ] - let standardErrorPipe = Pipe() - process.standardError = standardErrorPipe - try process.run() - // Drain before waiting, or a long diagnostic deadlocks both sides. - let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() - process.waitUntilExit() - guard process.terminationStatus == 0 else { - throw FixtureCompilationError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) - } - return libraryURL - } - }() - private func printInterface(marksCommentStructure: Bool) async throws -> FrozenSemanticString { - let libraryURL = try Self.fixtureCompilationResult.get() - let machOFile: MachOFile - switch try MachOKit.loadFromFile(url: libraryURL) { - case .machO(let file): - machOFile = file - case .fat(let fatFile): - machOFile = try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }) - } + let libraryURL = try FixtureCompiler.shared.dynamicLibrary( + named: Self.moduleName, + language: .swift, + source: Self.fixtureSource, + arguments: ["-swift-version", "5", "-O", "-target", "arm64-apple-macosx15.0"] + ) + let machOFile = try HostSlice.machOFile(at: libraryURL) var configuration = SwiftInterfaceBuilderConfiguration() configuration.printConfiguration.marksCommentStructure = marksCommentStructure let builder = try SwiftInterfaceBuilder(configuration: configuration, eventHandlers: [], in: machOFile) diff --git a/Tests/SwiftInterfaceTests/ConformanceProtocolNameSemanticsTests.swift b/Tests/SwiftInterfaceTests/ConformanceProtocolNameSemanticsTests.swift index c1ae60d22..ffb493dea 100644 --- a/Tests/SwiftInterfaceTests/ConformanceProtocolNameSemanticsTests.swift +++ b/Tests/SwiftInterfaceTests/ConformanceProtocolNameSemanticsTests.swift @@ -9,6 +9,7 @@ import Semantic @_spi(Support) @testable import SwiftInterface @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import OrderedCollections /// The protocol a conformance extension names is a type reference like any /// other, so its name must carry the semantic type the rest of the interface diff --git a/Tests/SwiftInterfaceTests/CrossImageOpaqueReferenceTests.swift b/Tests/SwiftInterfaceTests/CrossImageOpaqueReferenceTests.swift index fc519210c..b489c02e9 100644 --- a/Tests/SwiftInterfaceTests/CrossImageOpaqueReferenceTests.swift +++ b/Tests/SwiftInterfaceTests/CrossImageOpaqueReferenceTests.swift @@ -7,6 +7,8 @@ import Demangling @_spi(Internals) import SwiftInspection import SwiftDeclarationRendering @_spi(Support) @testable import SwiftInterface +import Semantic +import SwiftSectionTestingSupport /// An associated-type witness built from a `some` result that lives in /// ANOTHER image — the shape SwiftUI's `SidebarListBody.CollectionViewBody.Body` @@ -38,7 +40,7 @@ struct CrossImageOpaqueReferenceTests { }() } - private struct FixtureCompilationError: Error, CustomStringConvertible { + private struct FixtureCompilationError: Swift.Error, CustomStringConvertible { let diagnostics: String var description: String { "cross-image opaque fixture compilation failed:\n\(diagnostics)" } } @@ -48,7 +50,7 @@ struct CrossImageOpaqueReferenceTests { let clientLibraryURL: URL } - private static let fixtureCompilationResult: Result = { + private static let fixtureCompilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("CrossImageOpaqueFixture-\(UUID().uuidString)") @@ -134,12 +136,7 @@ struct CrossImageOpaqueReferenceTests { private func loadClient() throws -> (client: MachOFile, corePath: String) { let fixture = try Self.fixtureCompilationResult.get() - switch try File.loadFromFile(url: fixture.clientLibraryURL) { - case .machO(let machOFile): - return (machOFile, fixture.coreLibraryURL.path) - case .fat(let fatFile): - return (try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }), fixture.coreLibraryURL.path) - } + return (try HostSlice.machOFile(at: fixture.clientLibraryURL), fixture.coreLibraryURL.path) } /// How the two unexpandable witnesses must be spelled: the attribute the diff --git a/Tests/SwiftInterfaceTests/CustomObjCClassNameInterfaceTests.swift b/Tests/SwiftInterfaceTests/CustomObjCClassNameInterfaceTests.swift index a6c17d13d..0b92aef09 100644 --- a/Tests/SwiftInterfaceTests/CustomObjCClassNameInterfaceTests.swift +++ b/Tests/SwiftInterfaceTests/CustomObjCClassNameInterfaceTests.swift @@ -10,6 +10,10 @@ import SwiftThunkAnalysis @_spi(Internals) import SwiftInspection @_spi(Internals) import SwiftObjCInterop @testable import SwiftSectionTestingSupport +import SwiftIndexing +import Semantic +import SwiftPrinting +import SwiftSectionFixtureSupport /// Classes a source renamed for the Objective-C runtime on the interface /// path (evolution proposal `objc-custom-class-name`): the attribute the @@ -178,7 +182,7 @@ struct SystemFrameworkCustomObjCClassNameTests { } private static func appKitFileInSystemCache() throws -> MachOFile { - let cache = try DyldCache(path: .current) + let cache = try #require(FullDyldCache.cachedHost, "no host dyld shared cache").mainCache return try #require(cache.machOFile(named: .AppKit), "the running system's cache has no AppKit") } diff --git a/Tests/SwiftInterfaceTests/DescriptorOnlyVTableMemberTests.swift b/Tests/SwiftInterfaceTests/DescriptorOnlyVTableMemberTests.swift index 80124f918..ba535ff03 100644 --- a/Tests/SwiftInterfaceTests/DescriptorOnlyVTableMemberTests.swift +++ b/Tests/SwiftInterfaceTests/DescriptorOnlyVTableMemberTests.swift @@ -6,6 +6,8 @@ import MachOSwiftSection import SwiftDeclarationRendering import SwiftInterface @testable import SwiftSectionTestingSupport +import Semantic +import SwiftPrinting /// An on-the-fly fixture for class members whose only symbol is their method /// descriptor, compiled twice over: `.full` keeps every symbol, and @@ -81,7 +83,7 @@ enum DescriptorOnlyMemberFixture { } /// Compiled once per process. - private static let compilationResult: Result<[Variant: URL], Swift.Error> = { + private static let compilationResult: Result<[Variant: URL], any Swift.Error> = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("\(moduleName)-\(UUID().uuidString)") @@ -134,13 +136,7 @@ enum DescriptorOnlyMemberFixture { } static func machOFile(_ variant: Variant) throws -> MachOFile { - switch try MachOKit.loadFromFile(url: try libraryURL(variant)) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } + try HostSlice.machOFile(at: libraryURL(variant)) } /// The `.strippedLocals` copy loaded into the test process — only that diff --git a/Tests/SwiftInterfaceTests/DiffFormatTests.swift b/Tests/SwiftInterfaceTests/DiffFormatTests.swift index 4d2c26c9a..f110ad791 100644 --- a/Tests/SwiftInterfaceTests/DiffFormatTests.swift +++ b/Tests/SwiftInterfaceTests/DiffFormatTests.swift @@ -1,6 +1,7 @@ import Testing import Semantic @testable import SwiftInterface +import Foundation /// Builds a one-line ``DiffLine`` for the synthetic block fixtures below. private func line(_ marker: DiffMarker, _ content: SemanticString, indent: Int = 0) -> DiffLine { diff --git a/Tests/SwiftInterfaceTests/DiffMemberIndentationTests.swift b/Tests/SwiftInterfaceTests/DiffMemberIndentationTests.swift index ddab5b872..01ba30df8 100644 --- a/Tests/SwiftInterfaceTests/DiffMemberIndentationTests.swift +++ b/Tests/SwiftInterfaceTests/DiffMemberIndentationTests.swift @@ -4,6 +4,7 @@ import MachOKit import Semantic @testable import MachOSwiftSection @_spi(Support) @testable import SwiftInterface +import SwiftSectionTestingSupport /// The diff path's member-indentation contract, unified with the evolution /// path: members render at printer level 0 — the accessor block's interior @@ -67,7 +68,7 @@ struct DiffMemberIndentationTests { // `Swift.Error` spelled out: the `Semantic` import brings its own `Error` // type into scope, which would otherwise win the lookup. - private static let fixtureCompilationResult: Result<[URL], Swift.Error> = { + private static let fixtureCompilationResult: Result<[URL], any Swift.Error> = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("DiffIndentFixture-\(UUID().uuidString)") @@ -90,7 +91,7 @@ struct DiffMemberIndentationTests { let standardErrorPipe = Pipe() process.standardError = standardErrorPipe try process.run() - // Drain BEFORE waitUntilExit — see LegacyDyldInfoBindTests. + // Drain BEFORE waitUntilExit, or a long diagnostic deadlocks both sides. let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() process.waitUntilExit() guard process.terminationStatus == 0 else { @@ -110,14 +111,7 @@ struct DiffMemberIndentationTests { private func loadFixtureMachOFiles() throws -> [MachOFile] { try Self.fixtureCompilationResult.get().map { libraryURL in - let file = try MachOKit.loadFromFile(url: libraryURL) - switch file { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } + try HostSlice.machOFile(at: libraryURL) } } diff --git a/Tests/SwiftInterfaceTests/DiffRendererHeaderFailureTests.swift b/Tests/SwiftInterfaceTests/DiffRendererHeaderFailureTests.swift index 9bd4e2627..aece51397 100644 --- a/Tests/SwiftInterfaceTests/DiffRendererHeaderFailureTests.swift +++ b/Tests/SwiftInterfaceTests/DiffRendererHeaderFailureTests.swift @@ -10,6 +10,8 @@ import Dependencies @testable import MachOSwiftSection @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import Semantic +import OrderedCollections /// The diff renderer's header contract: a declaration whose HEADER cannot be /// rendered must be dropped whole, never rendered as a body under a blank @@ -32,7 +34,7 @@ final class DiffRendererHeaderFailureTests: MachOFileTests, @unchecked Sendable override class var fileName: MachOFileName { .SymbolTestsCore } private func preparedBuilder( - eventHandlers: [SwiftIndexEvents.Handler] = [] + eventHandlers: [any SwiftIndexEvents.Handler] = [] ) async throws -> SwiftDiffableInterfaceBuilder { let unsafeMachOFile = machOFile let builder = SwiftDiffableInterfaceBuilder(eventHandlers: eventHandlers, in: unsafeMachOFile) @@ -221,7 +223,7 @@ final class DiffRendererHeaderFailureTests: MachOFileTests, @unchecked Sendable ) } - private enum UnrenderableDefinitionError: Error { + private enum UnrenderableDefinitionError: Swift.Error { case donorIsNotAStruct } } diff --git a/Tests/SwiftInterfaceTests/ExecutableImageSymbolOffsetTests.swift b/Tests/SwiftInterfaceTests/ExecutableImageSymbolOffsetTests.swift index f9d764739..392e6bbb9 100644 --- a/Tests/SwiftInterfaceTests/ExecutableImageSymbolOffsetTests.swift +++ b/Tests/SwiftInterfaceTests/ExecutableImageSymbolOffsetTests.swift @@ -11,6 +11,8 @@ import SwiftInterface @_spi(Internals) @testable import SwiftSymbols @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import SwiftPrinting +import Semantic /// An on-the-fly fixture compiled twice from one class: as a main executable, /// whose `__TEXT` sits at 0x100000000, and as a dylib, whose `__TEXT` sits at @@ -53,79 +55,30 @@ enum ExecutableImageFixture { print(host.alpha() + host.beta(), OffsetHost.sharedNames.count) """ - struct CompilationError: Swift.Error, CustomStringConvertible { - let step: String - let diagnostics: String - var description: String { "\(ExecutableImageFixture.moduleName) fixture \(step) failed:\n\(diagnostics)" } - } - - private enum WorkingDirectoryCleanup { - nonisolated(unsafe) static var directories: [URL] = [] - static let registration: Void = { - atexit { - for directory in WorkingDirectoryCleanup.directories { - try? FileManager.default.removeItem(at: directory) - } - } - }() - } - - /// Compiled once per process. - private static let compilationResult: Result<[Variant: URL], Swift.Error> = { - Result { - let workingDirectory = FileManager.default.temporaryDirectory - .appendingPathComponent("\(moduleName)-\(UUID().uuidString)") - try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) - _ = WorkingDirectoryCleanup.registration - WorkingDirectoryCleanup.directories.append(workingDirectory) - - let librarySourceURL = workingDirectory.appendingPathComponent("OffsetHost.swift") - let mainSourceURL = workingDirectory.appendingPathComponent("main.swift") - try librarySource.write(to: librarySourceURL, atomically: true, encoding: .utf8) - try mainSource.write(to: mainSourceURL, atomically: true, encoding: .utf8) - let executableURL = workingDirectory.appendingPathComponent(moduleName) - let libraryURL = workingDirectory.appendingPathComponent("lib\(moduleName).dylib") - // The language mode pinned so CI's toolchain and a newer local one - // compile the same source the same way; `-g` leaves the debug map - // in the symbol table. - let commonArguments = ["swiftc", "-swift-version", "5", "-Onone", "-g", "-module-name", moduleName] - try run(step: "swiftc (executable)", commonArguments + [librarySourceURL.path, mainSourceURL.path, "-o", executableURL.path]) - try run(step: "swiftc (library)", commonArguments + ["-emit-library", librarySourceURL.path, "-o", libraryURL.path]) - return [.executable: executableURL, .library: libraryURL] - } - }() - - private static func run(step: String, _ arguments: [String]) throws { - let process = Process() - process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") - process.arguments = arguments - let standardErrorPipe = Pipe() - process.standardError = standardErrorPipe - try process.run() - // Drain BEFORE waitUntilExit, or a long diagnostic deadlocks both sides. - let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() - process.waitUntilExit() - guard process.terminationStatus == 0 else { - throw CompilationError(step: step, diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) - } - } - + /// The executable links `OffsetHost.swift` and `main.swift`; the library + /// is `OffsetHost.swift` alone. The shared compiler builds each once per + /// process. static func url(_ variant: Variant) throws -> URL { - let products = try compilationResult.get() - guard let url = products[variant] else { - throw CompilationError(step: "lookup", diagnostics: "no product for variant \(variant.rawValue)") + let librarySourceFile = FixtureSourceFile(name: "OffsetHost.swift", contents: librarySource) + // The language mode pinned so CI's toolchain and a newer local one + // compile the same source the same way; `-g` leaves the debug map + // in the symbol table. + let arguments = ["-swift-version", "5", "-Onone", "-g"] + switch variant { + case .executable: + return try FixtureCompiler.shared.executable( + named: moduleName, + language: .swift, + sourceFiles: [librarySourceFile, FixtureSourceFile(name: "main.swift", contents: mainSource)], + arguments: arguments + ) + case .library: + return try FixtureCompiler.shared.dynamicLibrary(named: moduleName, language: .swift, sourceFiles: [librarySourceFile], arguments: arguments) } - return url } static func machOFile(_ variant: Variant) throws -> MachOFile { - switch try MachOKit.loadFromFile(url: try url(variant)) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } + try HostSlice.machOFile(at: url(variant)) } /// The library loaded into the test process. The executable cannot be: diff --git a/Tests/SwiftInterfaceTests/ExistentialAnyInterfaceTests.swift b/Tests/SwiftInterfaceTests/ExistentialAnyInterfaceTests.swift index 6c1f7fe20..eea612557 100644 --- a/Tests/SwiftInterfaceTests/ExistentialAnyInterfaceTests.swift +++ b/Tests/SwiftInterfaceTests/ExistentialAnyInterfaceTests.swift @@ -4,6 +4,7 @@ import MachOKit @_spi(Support) @testable import SwiftPrinting @_spi(Support) @testable import SwiftInterface @testable import SwiftSectionTestingSupport +import Semantic /// `SwiftDeclarationPrintConfiguration.usesExistentialAny`, on by default, /// spells existential types with the `any` keyword by the rules the compiler diff --git a/Tests/SwiftInterfaceTests/ExportStatusAnnotationTests.swift b/Tests/SwiftInterfaceTests/ExportStatusAnnotationTests.swift index 593983c40..072c559be 100644 --- a/Tests/SwiftInterfaceTests/ExportStatusAnnotationTests.swift +++ b/Tests/SwiftInterfaceTests/ExportStatusAnnotationTests.swift @@ -7,6 +7,8 @@ import MachOKit @_spi(Support) @testable import SwiftInterface @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import Semantic +import SwiftIndexing /// End-to-end coverage for the `// not exported` annotation (evolution /// proposal 0008) on the `SymbolTestsCore` fixture — a library-evolution diff --git a/Tests/SwiftInterfaceTests/ExportStatusTests.swift b/Tests/SwiftInterfaceTests/ExportStatusTests.swift index 0234731f5..88a514d94 100644 --- a/Tests/SwiftInterfaceTests/ExportStatusTests.swift +++ b/Tests/SwiftInterfaceTests/ExportStatusTests.swift @@ -7,6 +7,10 @@ import MachOKit @_spi(Support) @testable import SwiftIndexing @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import MachOKitExtensions +import OrderedCollections +import MachOResolving +import MachOSwiftSection /// `TypeDefinition.exportStatus` / `ProtocolDefinition.exportStatus` — the /// export fact carried on the declaration model (evolution proposal diff --git a/Tests/SwiftInterfaceTests/ExportedOnlyInterfaceTests.swift b/Tests/SwiftInterfaceTests/ExportedOnlyInterfaceTests.swift index 0e89c38d4..4a2c343c2 100644 --- a/Tests/SwiftInterfaceTests/ExportedOnlyInterfaceTests.swift +++ b/Tests/SwiftInterfaceTests/ExportedOnlyInterfaceTests.swift @@ -7,6 +7,8 @@ import MachOKit @_spi(Support) @testable import SwiftInterface @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import Semantic +import SwiftIndexing /// End-to-end coverage for the exported-only filter (evolution proposal /// `exported-only-interface`) on the `SymbolTestsCore` fixture — a diff --git a/Tests/SwiftInterfaceTests/ExportedOnlyLibraryEvolutionFixtureTests.swift b/Tests/SwiftInterfaceTests/ExportedOnlyLibraryEvolutionFixtureTests.swift index 71beeff6f..93b7f17c4 100644 --- a/Tests/SwiftInterfaceTests/ExportedOnlyLibraryEvolutionFixtureTests.swift +++ b/Tests/SwiftInterfaceTests/ExportedOnlyLibraryEvolutionFixtureTests.swift @@ -9,6 +9,7 @@ import SwiftDeclaration @_spi(Support) @testable import SwiftPrinting @_spi(Support) @testable import SwiftInterface import SwiftSectionTestingSupport +import OrderedCollections /// The exported-only filter (evolution proposal /// `exported-only-interface`) over `internal` declarations, on the diff --git a/Tests/SwiftInterfaceTests/ExtensionContainerUnificationTests.swift b/Tests/SwiftInterfaceTests/ExtensionContainerUnificationTests.swift index be52598a4..7b739fbee 100644 --- a/Tests/SwiftInterfaceTests/ExtensionContainerUnificationTests.swift +++ b/Tests/SwiftInterfaceTests/ExtensionContainerUnificationTests.swift @@ -4,10 +4,13 @@ import Foundation import Testing import MachOKit +import OrderedCollections @_spi(Support) @testable import SwiftInterface @testable import MachOSwiftSection @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import Demangling +import Semantic /// Coverage for the extension-container unification (evolution proposal 0007): /// same-identity bucket merging, protocol attachment (a protocol's extension diff --git a/Tests/SwiftInterfaceTests/ExtensionContextExportStatusTests.swift b/Tests/SwiftInterfaceTests/ExtensionContextExportStatusTests.swift index 009cfaf01..1931b6173 100644 --- a/Tests/SwiftInterfaceTests/ExtensionContextExportStatusTests.swift +++ b/Tests/SwiftInterfaceTests/ExtensionContextExportStatusTests.swift @@ -7,6 +7,12 @@ import MachOKit @_spi(Support) @testable import SwiftIndexing import SwiftInterface @testable import SwiftSectionTestingSupport +import MachOResolving +import SwiftPrinting +import MachOKitExtensions +import Semantic +import MachOSwiftSection +import OrderedCollections /// The export verdict of declarations in extensions of another module's /// types, in images that keep no symbol at a non-exported descriptor diff --git a/Tests/SwiftInterfaceTests/ExtensionContextTypeNameTests.swift b/Tests/SwiftInterfaceTests/ExtensionContextTypeNameTests.swift index 97ea327d6..55704144d 100644 --- a/Tests/SwiftInterfaceTests/ExtensionContextTypeNameTests.swift +++ b/Tests/SwiftInterfaceTests/ExtensionContextTypeNameTests.swift @@ -4,6 +4,8 @@ import MachOKit import MachOFoundation import MachOSwiftSection @_spi(Support) @testable import SwiftInterface +import Semantic +import SwiftSectionTestingSupport /// A type declared in an extension of another module's type is parented on an /// extension context descriptor, so every name for it — the offline one from @@ -18,56 +20,6 @@ import MachOSwiftSection /// interface cannot spell. @Suite(.serialized) struct ExtensionContextTypeNameTests { - private enum FixtureWorkingDirectoryCleanup { - nonisolated(unsafe) static var directories: [URL] = [] - static let registration: Void = { - atexit { - for directory in FixtureWorkingDirectoryCleanup.directories { - try? FileManager.default.removeItem(at: directory) - } - } - }() - } - - private struct FixtureCompilationError: Error, CustomStringConvertible { - let diagnostics: String - var description: String { "extension-context fixture compilation failed:\n\(diagnostics)" } - } - - private static let fixtureCompilationResult: Result = { - Result { - let workingDirectory = FileManager.default.temporaryDirectory - .appendingPathComponent("ExtensionContextFixture-\(UUID().uuidString)") - _ = FixtureWorkingDirectoryCleanup.registration - FixtureWorkingDirectoryCleanup.directories.append(workingDirectory) - try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) - let sourceURL = workingDirectory.appendingPathComponent("ExtensionContexts.swift") - try source.write(to: sourceURL, atomically: true, encoding: .utf8) - let libraryURL = workingDirectory.appendingPathComponent("libProbeExtensionContext.dylib") - try run(swiftcArguments: [ - "-O", "-emit-library", "-module-name", "ProbeExtensionContext", - "-target", "arm64-apple-macosx15.0", - sourceURL.path, "-o", libraryURL.path, - ]) - return libraryURL - } - }() - - private static func run(swiftcArguments: [String]) throws { - let process = Process() - process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") - process.arguments = ["swiftc"] + swiftcArguments - let standardErrorPipe = Pipe() - process.standardError = standardErrorPipe - try process.run() - // Drain before waiting, or a long diagnostic deadlocks both sides. - let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() - process.waitUntilExit() - guard process.terminationStatus == 0 else { - throw FixtureCompilationError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) - } - } - /// `FixtureAnchor` is ballast: a struct-only fixture dylib has no `__DATA` /// segment and MachOKit before 0.52.103 mis-walked its chained-fixup pages. /// `Holder` is what references the nested types, so their names are printed @@ -103,14 +55,13 @@ struct ExtensionContextTypeNameTests { """ private func renderInterface() async throws -> String { - let libraryURL = try Self.fixtureCompilationResult.get() - let machOFile: MachOFile - switch try File.loadFromFile(url: libraryURL) { - case .machO(let file): - machOFile = file - case .fat(let fatFile): - machOFile = try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }) - } + let libraryURL = try FixtureCompiler.shared.dynamicLibrary( + named: "ProbeExtensionContext", + language: .swift, + sourceFiles: [FixtureSourceFile(name: "ExtensionContexts.swift", contents: Self.source)], + arguments: ["-O", "-target", "arm64-apple-macosx15.0"] + ) + let machOFile = try HostSlice.machOFile(at: libraryURL) let builder = try SwiftInterfaceBuilder(configuration: .init(), eventHandlers: [], in: machOFile) try await builder.prepare() return try await builder.printRoot().string diff --git a/Tests/SwiftInterfaceTests/FinalKeywordICFRegressionTests.swift b/Tests/SwiftInterfaceTests/FinalKeywordICFRegressionTests.swift index a2b817fb7..5b69b7d46 100644 --- a/Tests/SwiftInterfaceTests/FinalKeywordICFRegressionTests.swift +++ b/Tests/SwiftInterfaceTests/FinalKeywordICFRegressionTests.swift @@ -8,6 +8,7 @@ import MachOKit @testable import MachOSwiftSection @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import Semantic /// Regression coverage for the identical-code-folding false positive in the /// `final` recovery (evolution proposal 0006), pinned against Xcode's real @@ -21,7 +22,7 @@ import SwiftSectionFixtureSupport /// evidence gate is what this suite pins. /// /// Environment-gated: skipped on machines without Xcode's SourceEditor. -@Suite(.serialized, .enabled(if: FileManager.default.fileExists(atPath: MachOFileName.SourceEditorFromXcode.rawValue))) +@Suite(.serialized, .enabled(if: FileManager.default.fileExists(atPath: MachOFileName.SourceEditorFromXcode.path))) final class FinalKeywordICFRegressionTests: MachOFileTests, @unchecked Sendable { override class var fileName: MachOFileName { .SourceEditorFromXcode } diff --git a/Tests/SwiftInterfaceTests/FinalMemberRecoveryTests.swift b/Tests/SwiftInterfaceTests/FinalMemberRecoveryTests.swift index 05b3888ee..87859426d 100644 --- a/Tests/SwiftInterfaceTests/FinalMemberRecoveryTests.swift +++ b/Tests/SwiftInterfaceTests/FinalMemberRecoveryTests.swift @@ -8,6 +8,9 @@ import MachOKit @testable import MachOSwiftSection @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import OrderedCollections +import Semantic +import Demangling /// End-to-end coverage for the `final` keyword recovery and the lazy-var /// accessor-type correction (evolution proposal 0006), pinned against the diff --git a/Tests/SwiftInterfaceTests/GenericParameterDepthNamingTests.swift b/Tests/SwiftInterfaceTests/GenericParameterDepthNamingTests.swift index 1b51a2917..a06685e33 100644 --- a/Tests/SwiftInterfaceTests/GenericParameterDepthNamingTests.swift +++ b/Tests/SwiftInterfaceTests/GenericParameterDepthNamingTests.swift @@ -5,6 +5,7 @@ import MachOFoundation import MachOSwiftSection @_spi(Support) @testable import SwiftInterface import SwiftSectionTestingSupport +import Semantic /// A generic parameter's printed name encodes its depth (`A1` is depth 1, /// index 0), and a depth counts only the contexts that declare parameters. diff --git a/Tests/SwiftInterfaceTests/ImageGroupEvolutionTests.swift b/Tests/SwiftInterfaceTests/ImageGroupEvolutionTests.swift index 89ba8ae51..0ae17453b 100644 --- a/Tests/SwiftInterfaceTests/ImageGroupEvolutionTests.swift +++ b/Tests/SwiftInterfaceTests/ImageGroupEvolutionTests.swift @@ -4,6 +4,7 @@ import MachOKit import SwiftDiffing import SwiftInterface @testable import SwiftSectionTestingSupport +import Semantic /// An evolution whose versions are groups of images (evolution proposal /// `image-group-evolution`), over `ImageGroupFixture`: one module split from diff --git a/Tests/SwiftInterfaceTests/InitAccessorInterfaceTests.swift b/Tests/SwiftInterfaceTests/InitAccessorInterfaceTests.swift index c98dfa33b..612056de3 100644 --- a/Tests/SwiftInterfaceTests/InitAccessorInterfaceTests.swift +++ b/Tests/SwiftInterfaceTests/InitAccessorInterfaceTests.swift @@ -9,6 +9,7 @@ import SwiftDeclarationRendering @_spi(Support) @testable import SwiftIndexing @_spi(Support) @testable import SwiftPrinting @testable import SwiftSectionTestingSupport +import OrderedCollections /// The interface opens a property's accessor block with its SE-0400 `init` /// (evolution proposal `init-accessor-recovery`): `@storageRestrictions(initializes: _x) init` diff --git a/Tests/SwiftInterfaceTests/InterfaceHeaderTests.swift b/Tests/SwiftInterfaceTests/InterfaceHeaderTests.swift index cc726eb2a..450075732 100644 --- a/Tests/SwiftInterfaceTests/InterfaceHeaderTests.swift +++ b/Tests/SwiftInterfaceTests/InterfaceHeaderTests.swift @@ -6,6 +6,7 @@ import Semantic @_spi(Support) @testable import SwiftInterface @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import SwiftIndexing /// Coverage for the interface header block (evolution proposal 0008): /// pure-value rendering (line composition, per-field omission, the diff --git a/Tests/SwiftInterfaceTests/LegacyDyldInfoBindTests.swift b/Tests/SwiftInterfaceTests/LegacyDyldInfoBindTests.swift index 09aade776..63ae3b217 100644 --- a/Tests/SwiftInterfaceTests/LegacyDyldInfoBindTests.swift +++ b/Tests/SwiftInterfaceTests/LegacyDyldInfoBindTests.swift @@ -4,6 +4,8 @@ import MachOKit import MachOKitExtensions @testable import MachOSwiftSection @_spi(Support) @testable import SwiftInterface +import Semantic +import SwiftSectionTestingSupport /// Regression tests for binaries carrying the legacy `LC_DYLD_INFO(_ONLY)` /// opcode-based fixups (deployment target < macOS 12 / iOS 16, e.g. every @@ -22,64 +24,6 @@ import MachOKitExtensions /// format as the iOS 15.5 simulator frameworks that surfaced the bug. @Suite(.serialized) struct LegacyDyldInfoBindTests { - /// The fixture's working directory must outlive every test in the - /// (serialized) suite, so it is removed at process exit rather than per - /// test. A crashed run still leaks one directory; the unique name keeps - /// that harmless and non-colliding across parallel test processes. - private enum FixtureWorkingDirectoryCleanup { - nonisolated(unsafe) static var directories: [URL] = [] - static let registration: Void = { - atexit { - for directory in FixtureWorkingDirectoryCleanup.directories { - try? FileManager.default.removeItem(at: directory) - } - } - }() - } - - private static let fixtureCompilationResult: Result = { - Result { - let workingDirectory = FileManager.default.temporaryDirectory - .appendingPathComponent("LegacyDyldInfoBindFixture-\(UUID().uuidString)") - try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) - _ = FixtureWorkingDirectoryCleanup.registration - FixtureWorkingDirectoryCleanup.directories.append(workingDirectory) - - let sourceURL = workingDirectory.appendingPathComponent("LegacyFixture.swift") - let libraryURL = workingDirectory.appendingPathComponent("libLegacyFixture.dylib") - try Self.fixtureSource.write(to: sourceURL, atomically: true, encoding: .utf8) - - let process = Process() - process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") - // macOS 11 predates chained fixups, forcing LC_DYLD_INFO_ONLY output. - process.arguments = [ - "swiftc", "-emit-library", "-module-name", "LegacyFixture", - "-target", "arm64-apple-macosx11.0", - sourceURL.path, "-o", libraryURL.path, - ] - let standardErrorPipe = Pipe() - process.standardError = standardErrorPipe - try process.run() - // Drain BEFORE waitUntilExit: diagnostics beyond the ~64 KB pipe - // buffer would otherwise deadlock compiler and parent (the child - // blocked writing, the parent parked waiting) — and because this - // is a static let under a serialized suite, that deadlock would - // hang the whole test run instead of reporting a failure. - let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() - process.waitUntilExit() - guard process.terminationStatus == 0 else { - let diagnostics = String(decoding: diagnosticsData, as: UTF8.self) - throw LegacyFixtureCompilationError(diagnostics: diagnostics) - } - return libraryURL - } - }() - - private struct LegacyFixtureCompilationError: Error, CustomStringConvertible { - let diagnostics: String - var description: String { "Legacy fixture compilation failed:\n\(diagnostics)" } - } - private static let fixtureSource = """ import Foundation @@ -107,15 +51,14 @@ struct LegacyDyldInfoBindTests { """ private func loadFixtureMachOFile() throws -> MachOFile { - let libraryURL = try Self.fixtureCompilationResult.get() - let file = try MachOKit.loadFromFile(url: libraryURL) - switch file { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } + let libraryURL = try FixtureCompiler.shared.dynamicLibrary( + named: "LegacyFixture", + language: .swift, + source: Self.fixtureSource, + // macOS 11 predates chained fixups, forcing LC_DYLD_INFO_ONLY output. + arguments: ["-target", "arm64-apple-macosx11.0"] + ) + return try HostSlice.machOFile(at: libraryURL) } private func buildInterfaceOutput(of machOFile: MachOFile) async throws -> String { diff --git a/Tests/SwiftInterfaceTests/LocalTypeInterfaceTests.swift b/Tests/SwiftInterfaceTests/LocalTypeInterfaceTests.swift index ff2b490b5..55c8fb824 100644 --- a/Tests/SwiftInterfaceTests/LocalTypeInterfaceTests.swift +++ b/Tests/SwiftInterfaceTests/LocalTypeInterfaceTests.swift @@ -9,6 +9,7 @@ import SwiftPrinting @_spi(Support) import SwiftInterface import Semantic @testable import SwiftSectionTestingSupport +import OrderedCollections /// Local types on the indexing and interface paths (evolution proposal /// `local-type-context-names`). Named after their method, two methods' diff --git a/Tests/SwiftInterfaceTests/MembersOfAnotherImagesTypeTests.swift b/Tests/SwiftInterfaceTests/MembersOfAnotherImagesTypeTests.swift index 8b2c743f8..206832d4c 100644 --- a/Tests/SwiftInterfaceTests/MembersOfAnotherImagesTypeTests.swift +++ b/Tests/SwiftInterfaceTests/MembersOfAnotherImagesTypeTests.swift @@ -7,6 +7,7 @@ import SwiftDiffing import SwiftInterface @_spi(Internals) import SwiftSymbols @testable import SwiftSectionTestingSupport +import Semantic /// A member an image declares on a type another image defines, with no /// extension context in its mangling (evolution proposal diff --git a/Tests/SwiftInterfaceTests/ModuleSelectorInterfaceTests.swift b/Tests/SwiftInterfaceTests/ModuleSelectorInterfaceTests.swift index f3e5dda28..741acf3b9 100644 --- a/Tests/SwiftInterfaceTests/ModuleSelectorInterfaceTests.swift +++ b/Tests/SwiftInterfaceTests/ModuleSelectorInterfaceTests.swift @@ -4,6 +4,7 @@ import MachOKit @_spi(Support) @testable import SwiftPrinting @_spi(Support) @testable import SwiftInterface @testable import SwiftSectionTestingSupport +import Semantic /// `SwiftDeclarationPrintConfiguration.usesModuleSelectors` qualifies the /// interface's names with SE-0491 module selectors, by the rules the Swift diff --git a/Tests/SwiftInterfaceTests/MovedTypeModuleTests.swift b/Tests/SwiftInterfaceTests/MovedTypeModuleTests.swift new file mode 100644 index 000000000..d6ebcea5d --- /dev/null +++ b/Tests/SwiftInterfaceTests/MovedTypeModuleTests.swift @@ -0,0 +1,175 @@ +import Foundation +import Testing +import MachOKit +import MachOSwiftSection +@_spi(Support) @testable import SwiftPrinting +@_spi(Support) @testable import SwiftInterface +import Semantic +import SwiftSectionFixtureSupport + +/// Evolution proposal `moved-swift-type-modules`: a Swift type the SDK moved +/// between modules (`@_originallyDefinedIn`) mangles under the module it was +/// originally defined in, and prints under the module a +/// `MovedTypeModuleResolving` resolver names — nested types with it. +/// +/// The resolver here is a table, so no SDK is involved: `CGFloat` moves from +/// CoreGraphics to CoreFoundation as the SDK says, and the fixture's own +/// `Outer` and `Drawable` move to a module named `NewHome`. +@Suite +struct MovedTypeModuleTests { + private static let fixtureModuleName = "MovedTypeModuleFixture" + + /// The class is ballast: a struct-only fixture dylib has no `__DATA` + /// segment and MachOKit before 0.52.103 mis-walked its chained-fixup pages. + private static let source = """ + import Foundation + + public final class FixtureAnchor {} + + public struct Outer { + public struct Inner { + public init() {} + } + public init() {} + } + + public protocol Drawable {} + + extension Drawable { + public func draw() {} + } + + public struct Holder { + public var width: CGFloat + public var inner: Outer.Inner + public var drawable: any Drawable + public var name: NSString + public init(width: CGFloat, inner: Outer.Inner, drawable: any Drawable, name: NSString) { + self.width = width + self.inner = inner + self.drawable = drawable + self.name = name + } + } + + extension CGFloat { + public var doubled: CGFloat { self * 2 } + } + """ + + private static func libraryURL() throws -> URL { + try FixtureCompiler.shared.dynamicLibrary( + named: fixtureModuleName, + language: .swift, + sourceFiles: [FixtureSourceFile(name: "MovedTypeModuleFixture.swift", contents: source)], + arguments: ["-swift-version", "5", "-O", "-target", "arm64-apple-macosx15.0"] + ) + } + + /// Answers from a table and records every question. + private final class RecordingMovedTypeResolver: MovedTypeModuleResolving, @unchecked Sendable { + struct Question: Hashable { + let typeName: String + let originalModuleName: String + } + + private let lock = NSLock() + private var recordedQuestions: Set = [] + private let declaringModuleNames: [Question: String] + + init(declaringModuleNames: [Question: String]) { + self.declaringModuleNames = declaringModuleNames + } + + var questions: Set { + lock.withLock { recordedQuestions } + } + + func declaringModuleName(ofMovedTypeNamed typeName: String, originallyDefinedIn originalModuleName: String) async -> String? { + let question = Question(typeName: typeName, originalModuleName: originalModuleName) + lock.withLock { _ = recordedQuestions.insert(question) } + return declaringModuleNames[question] + } + } + + private static func makeResolver() -> RecordingMovedTypeResolver { + RecordingMovedTypeResolver(declaringModuleNames: [ + .init(typeName: "CGFloat", originalModuleName: "CoreGraphics"): "CoreFoundation", + .init(typeName: "Outer", originalModuleName: fixtureModuleName): "NewHome", + .init(typeName: "Drawable", originalModuleName: fixtureModuleName): "NewHome", + ]) + } + + private func buildInterface(usesModuleSelectors: Bool = false, resolver: RecordingMovedTypeResolver?) async throws -> String { + var printConfiguration = SwiftDeclarationPrintConfiguration() + printConfiguration.usesModuleSelectors = usesModuleSelectors + var configuration = SwiftInterfaceBuilderConfiguration() + configuration.printConfiguration = printConfiguration + let builder = try SwiftInterfaceBuilder(configuration: configuration, eventHandlers: [], in: HostSlice.machOFile(at: Self.libraryURL())) + if let resolver { + builder.printer.addTypeNameResolver(resolver) + } + try await builder.prepare() + return try await builder.printRoot().string + } + + private func lines(of interface: String, startingWith prefix: String) -> [String] { + interface.split(separator: "\n").map { $0.trimmingCharacters(in: .whitespaces) }.filter { $0.hasPrefix(prefix) } + } + + @Test + func movedTopLevelTypePrintsUnderItsDeclaringModule() async throws { + let interface = try await buildInterface(resolver: Self.makeResolver()) + #expect(lines(of: interface, startingWith: "var width:") == ["var width: CoreFoundation.CGFloat"]) + #expect(!interface.contains("CoreGraphics.CGFloat"), "\(interface)") + } + + @Test + func nestedTypeFollowsItsOutermostType() async throws { + let interface = try await buildInterface(resolver: Self.makeResolver()) + #expect(lines(of: interface, startingWith: "var inner:") == ["var inner: NewHome.Outer.Inner"]) + } + + /// With module selectors a nested type writes its own, which is the + /// outermost type's declaring module too. + @Test + func moduleSelectorsSpellTheDeclaringModuleOnNestedTypes() async throws { + let interface = try await buildInterface(usesModuleSelectors: true, resolver: Self.makeResolver()) + #expect(lines(of: interface, startingWith: "var inner:") == ["var inner: NewHome::Outer.NewHome::Inner"]) + #expect(lines(of: interface, startingWith: "var width:") == ["var width: CoreFoundation::CGFloat"]) + } + + @Test + func extensionHeaderOfAMovedProtocolUsesTheDeclaringModule() async throws { + let interface = try await buildInterface(resolver: Self.makeResolver()) + #expect(lines(of: interface, startingWith: "extension NewHome.Drawable").count == 1, "\(interface)") + #expect(lines(of: interface, startingWith: "extension CoreFoundation.CGFloat").count == 1, "\(interface)") + #expect(lines(of: interface, startingWith: "var drawable:") == ["var drawable: any NewHome.Drawable"]) + } + + @Test + func cImportedModulesAreNeverAskedAboutMoves() async throws { + let resolver = Self.makeResolver() + _ = try await buildInterface(resolver: resolver) + let askedModules = Set(resolver.questions.map(\.originalModuleName)) + #expect(!askedModules.contains("__C")) + #expect(!askedModules.contains("__ObjC")) + #expect(askedModules.contains("CoreGraphics")) + } + + @Test + func withoutAResolverTheManglingModuleIsKept() async throws { + let interface = try await buildInterface(resolver: nil) + #expect(lines(of: interface, startingWith: "var width:") == ["var width: CoreGraphics.CGFloat"]) + #expect(lines(of: interface, startingWith: "var inner:") == ["var inner: \(Self.fixtureModuleName).Outer.Inner"]) + } + + /// The original module re-exports the one declaring the type now, so the + /// imports the binary's symbols name still compile the rewritten names. + @Test + func importLinesKeepTheManglingModules() async throws { + let rewrittenInterface = try await buildInterface(resolver: Self.makeResolver()) + let unresolvedInterface = try await buildInterface(resolver: nil) + #expect(lines(of: rewrittenInterface, startingWith: "import ") == lines(of: unresolvedInterface, startingWith: "import ")) + } +} diff --git a/Tests/SwiftInterfaceTests/NestedDefinitionRegionContractTests.swift b/Tests/SwiftInterfaceTests/NestedDefinitionRegionContractTests.swift index 7b6e9c774..153040e1a 100644 --- a/Tests/SwiftInterfaceTests/NestedDefinitionRegionContractTests.swift +++ b/Tests/SwiftInterfaceTests/NestedDefinitionRegionContractTests.swift @@ -14,6 +14,7 @@ import MachOKit @testable import MachOSwiftSection @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import OrderedCollections /// With `SwiftDeclarationPrintConfiguration.marksNestedDefinitions`, every /// nested type and protocol taken out of its parent's print — @@ -52,6 +53,13 @@ final class NestedDefinitionRegionContractTests: MachOSwiftSectionFixtureTests, /// proposal `comment-structure`): the marks of a nested definition's /// comments must not depend on where it prints. case everyOptionMarkingCommentStructure + /// The marked print with every option, its long types laid out over + /// several lines (evolution proposal `multiline-type-formatting`) — + /// the parent's print and the definition's own each formatted. The + /// width is narrow so that the fixture's long generic types break; it + /// does not count indentation, so a definition must break the same + /// way at every depth. + case everyOptionFormattedAsMultilineTypes var description: String { switch self { @@ -60,9 +68,20 @@ final class NestedDefinitionRegionContractTests: MachOSwiftSectionFixtureTests, case .everyOptionWithTransformers: "every option with transformers" case .privateDeclarationSourceFiles: "private declaration source files" case .everyOptionMarkingCommentStructure: "every option marking comment structure" + case .everyOptionFormattedAsMultilineTypes: "every option formatted as multiline types" } } + /// How a print of this variant is formatted before it is compared; + /// `nil` leaves it as printed. + var multilineTypeFormatting: MultilineTypeFormatting? { + self == .everyOptionFormattedAsMultilineTypes ? MultilineTypeFormatting(maximumLineWidth: 30) : nil + } + + func finished(_ printed: SemanticString) -> SemanticString { + multilineTypeFormatting?.format(printed) ?? printed + } + var configuration: SwiftDeclarationPrintConfiguration { var configuration = SwiftDeclarationPrintConfiguration() configuration.marksNestedDefinitions = true @@ -87,7 +106,8 @@ final class NestedDefinitionRegionContractTests: MachOSwiftSectionFixtureTests, transformers.swiftTypeLayout.isEnabled = true transformers.swiftEnumLayout.isEnabled = true configuration.applyTransformers(transformers) - case .everyOptionMarkingCommentStructure: + case .everyOptionMarkingCommentStructure, + .everyOptionFormattedAsMultilineTypes: configuration.printFieldOffset = true configuration.printExpandedFieldOffsets = true configuration.printMemberAddress = true @@ -251,7 +271,7 @@ final class NestedDefinitionRegionContractTests: MachOSwiftSectionFixtureTests, var exceptionRegionCount = 0 var mismatches: [String] = [] for parent in parents { - let printed = try await parent.print(printer).frozen() + let printed = try await variant.finished(parent.print(printer)).frozen() let regions = printed.separatingDefinitionRegions().definitions.regions if regions.count != parent.nestedDefinitionCount { mismatches.append("\(parent.label): \(regions.count) regions for \(parent.nestedDefinitionCount) nested definitions") @@ -263,7 +283,7 @@ final class NestedDefinitionRegionContractTests: MachOSwiftSectionFixtureTests, mismatches.append("\(label): no definition has this identity") continue } - let ownPrint = try await ownPrinting(printer).frozen() + let ownPrint = try await variant.finished(ownPrinting(printer)).frozen() let regionContent = printed.content(ofDefinitionRegion: region) guard let takenOut = regionContent.removingIndentation(levels: region.depth + 1) else { mismatches.append("\(label): the indentation could not be removed\n\(regionContent.string)") @@ -304,6 +324,24 @@ final class NestedDefinitionRegionContractTests: MachOSwiftSectionFixtureTests, #expect(result.mismatches.isEmpty, "\(result.mismatches.joined(separator: "\n\n"))") } + /// The formatted variant proves something only if the fixture's prints + /// actually break at its width. The fixture has few long generic types — + /// most of them fields of `GenericFieldLayout`'s nested types — and at 30 + /// columns they insert about a hundred lines. + @Test func formattedVariantBreaksTheFixtureTypes() async throws { + let indexer = SwiftDeclarationIndexer(in: machOFile) + try await indexer.prepare() + let variant = Variant.everyOptionFormattedAsMultilineTypes + let printer = SwiftDeclarationPrinter(configuration: variant.configuration, in: machOFile) + var insertedLineCount = 0 + for typeDefinition in indexer.rootTypeDefinitions.values { + let printed = try await printer.printTypeDefinition(typeDefinition) + let formatted = variant.finished(printed) + insertedLineCount += formatted.string.count { $0 == "\n" } - printed.string.count { $0 == "\n" } + } + #expect(insertedLineCount > 50) + } + /// The exception on `ExportedOnlyFixture`, whose `UnexportedParent` the /// link leaves unexported while its nested `ExportedNested` stays /// exported — the shape of Foundation's diff --git a/Tests/SwiftInterfaceTests/ObjCImplementationClassRecognitionTests.swift b/Tests/SwiftInterfaceTests/ObjCImplementationClassRecognitionTests.swift index 55290c789..61b43373a 100644 --- a/Tests/SwiftInterfaceTests/ObjCImplementationClassRecognitionTests.swift +++ b/Tests/SwiftInterfaceTests/ObjCImplementationClassRecognitionTests.swift @@ -9,6 +9,10 @@ import SwiftObjCInterop import Semantic @_spi(Internals) import SwiftSymbols @testable import SwiftSectionTestingSupport +import SwiftPrinting +import SwiftSectionFixtureSupport +import OutputTransformer +import ObjCOutputTransformer /// `@objc @implementation` recognition on the interface path (evolution /// proposal `objc-implementation-class-recognition`), over the on-the-fly @@ -17,15 +21,16 @@ import Semantic /// adds to, and a plain Swift class with ObjC ancestry. @Suite(.serialized, ExclusiveImageAccess(ObjCImplementationFixture.moduleName)) struct ObjCImplementationClassRecognitionTests { - private func interface(of variant: ObjCImplementationFixture.Variant, printFieldOffset: Bool = false) async throws -> String { - try await printInterface(of: variant, printFieldOffset: printFieldOffset, marksCommentStructure: false).string + private func interface(of variant: ObjCImplementationFixture.Variant, printFieldOffset: Bool = false, configure: (inout SwiftDeclarationPrintConfiguration) -> Void = { _ in }) async throws -> String { + try await printInterface(of: variant, printFieldOffset: printFieldOffset, marksCommentStructure: false, configure: configure).string } - private func printInterface(of variant: ObjCImplementationFixture.Variant, printFieldOffset: Bool, marksCommentStructure: Bool) async throws -> SemanticString { + private func printInterface(of variant: ObjCImplementationFixture.Variant, printFieldOffset: Bool, marksCommentStructure: Bool, configure: (inout SwiftDeclarationPrintConfiguration) -> Void = { _ in }) async throws -> SemanticString { let machOFile = try ObjCImplementationFixture.machOFile(variant) var configuration = SwiftInterfaceBuilderConfiguration() configuration.printConfiguration.printFieldOffset = printFieldOffset configuration.printConfiguration.marksCommentStructure = marksCommentStructure + configure(&configuration.printConfiguration) let builder = try SwiftInterfaceBuilder(configuration: configuration, eventHandlers: [], in: machOFile) try await builder.prepare() return try await builder.printRoot() @@ -109,15 +114,158 @@ struct ObjCImplementationClassRecognitionTests { let interface = try await interface(of: .strippedLocals) let widget = try #require(block(named: "@objc @implementation extension __C.Widget {", in: interface)) #expect(!widget.contains("inferred from ObjC class data")) - // No field-offset symbol survived, so the ivars render as honest - // comments — ObjC facts, no fabricated Swift type. - #expect(widget.contains("// stored property title: Swift type not recoverable (ObjC ivar, offset 0x8, size 16, encoding \"?\")")) - #expect(widget.contains("// stored property count: Swift type not recoverable (ObjC ivar, offset 0x18, size 8, encoding \"q\")")) + // No field-offset symbol survived. The Objective-C side still gives + // the types of the `@objc` ones (evolution proposal + // `objc-ivar-type-recovery`): a complete encoding is the type itself, + // a `?` one the bridged form of its Objective-C property. The others + // render as honest comments — ObjC facts, no fabricated Swift type. + #expect(widget.contains(" var title: Swift.String!\n")) + #expect(!widget.contains("stored property title")) + #expect(widget.contains(" var count: Swift.Int\n")) + #expect(!widget.contains("stored property count")) #expect(widget.contains("// stored property swiftOnlyCache: Swift type not recoverable (ObjC ivar, offset 0x20, size 8, encoding \"\")")) #expect(widget.contains("// stored property hiddenTally: Swift type not recoverable (ObjC ivar, offset 0x28, size 8, encoding \"\")")) #expect(widget.contains("// stored property $__lazy_storage_$_summary: Swift type not recoverable (ObjC ivar, offset 0x30, size 16, encoding \"\")")) } + // MARK: - Stored property types the Objective-C side gives + + // Evolution proposal `objc-ivar-type-recovery`: `AdaptiveTransitionWidget`'s + // members are internal, so `strip -x` leaves only its ivar list and + // Objective-C properties. + + private func adaptiveTransitionWidget(of variant: ObjCImplementationFixture.Variant, configure: (inout SwiftDeclarationPrintConfiguration) -> Void = { _ in }) async throws -> String { + let interface = try await interface(of: variant, configure: configure) + // The fully stripped variant's header carries the inferred evidence + // between `@implementation` and `extension`. + #expect(variant == .strippedEverything || interface.contains("@objc @implementation extension __C.AdaptiveTransitionWidget {")) + return try #require(block(named: "extension __C.AdaptiveTransitionWidget {", in: interface)) + } + + /// What follows `var : ` or `let : ` on its line in `block`. + private func declaredType(of propertyName: String, in block: String) -> String? { + for line in block.split(separator: "\n") { + for introducer in ["var ", "let "] { + guard let range = line.range(of: "\(introducer)\(propertyName): ") else { continue } + return String(line[range.upperBound...]) + } + } + return nil + } + + @Test func strippedClassTypedIvarsRecoverTheClassImplicitlyUnwrapped() async throws { + let widget = try await adaptiveTransitionWidget(of: .strippedLocals) + #expect(widget.contains(" var containerView: __C.NSObject!\n"), "\(widget)") + // `NSMutableString` is no class Swift bridges. + #expect(widget.contains(" var buffer: __C.NSMutableString!\n"), "\(widget)") + #expect(!widget.contains("stored property containerView")) + } + + @Test func strippedProtocolTypedIvarRecoversTheExistentialImplicitlyUnwrapped() async throws { + let widget = try await adaptiveTransitionWidget(of: .strippedLocals) + #expect(widget.contains(" var previousLayout: (any __C.AdaptiveLayout)!\n"), "\(widget)") + } + + @Test func strippedScalarIvarsRecoverTheTypesTheirEncodingsName() async throws { + let widget = try await adaptiveTransitionWidget(of: .strippedLocals) + #expect(widget.contains(" var isAnimated: Swift.Bool\n"), "\(widget)") + // `CGFloat` and `Double` encode alike; with no C type replacement the + // encoding's own type prints. + #expect(widget.contains(" var interactiveProgress: Swift.Double\n"), "\(widget)") + #expect(widget.contains(" var stepCount: Swift.Int\n"), "\(widget)") + // A structure prints as the field-offset symbol spells it. + let full = try await adaptiveTransitionWidget(of: .full) + let structureType = try #require(declaredType(of: "selectedRange", in: full)) + #expect(declaredType(of: "selectedRange", in: widget) == structureType, "\(widget)") + } + + @Test func readOnlyObjCPropertyRecoversAsALet() async throws { + let widget = try await adaptiveTransitionWidget(of: .strippedLocals) + #expect(widget.contains(" let revision: Swift.Int\n"), "\(widget)") + } + + @Test func bridgedIvarsRecoverTheImportedTypeOfTheirObjCProperty() async throws { + let widget = try await adaptiveTransitionWidget(of: .strippedLocals) + // `readonly` over stored storage: a `let`. + #expect(widget.contains(" let identifier: Swift.String!\n"), "\(widget)") + // The `T` attribute names no element type. + #expect(widget.contains(" var names: [Any]!\n"), "\(widget)") + #expect(widget.contains(" var payload: Any!\n"), "\(widget)") + #expect(!widget.contains("stored property identifier")) + } + + @Test func weakObjCPropertyRecoversAsAWeakOptionalOfItsClass() async throws { + let widget = try await adaptiveTransitionWidget(of: .strippedLocals) + // An `unowned(unsafe)` property reads the same on the Objective-C + // side, and the comment says so. + #expect(widget.contains(" weak var observer: __C.NSObject? /* or unowned(unsafe) var observer: NSObject: the Objective-C property reads the same for both */\n"), "\(widget)") + } + + /// The header's `unsafe_unretained` imports as `unowned(unsafe)`, whose + /// storage the compiler marks `?` and whose property `W`, as for `weak` + /// — or, read-only, `R` alone, as for a bridged `let`. Read off the + /// Objective-C side alone, it printed as `weak var …: NSObject?` and as + /// `let …: String!`, stated as facts (2026-11-29 codebase audit, + /// finding 2): the common reading still prints, and says what else it + /// may be. + @Test func unownedUnsafeObjCPropertiesSayWhatElseTheyMayBe() async throws { + let widget = try await adaptiveTransitionWidget(of: .strippedLocals) + #expect(widget.contains(" weak var unretainedObserver: __C.NSObject? /* or unowned(unsafe) var unretainedObserver: NSObject: the Objective-C property reads the same for both */\n"), "\(widget)") + #expect(widget.contains(" let unretainedOwner: Swift.String! /* or unowned(unsafe) let unretainedOwner: NSString: the Objective-C property reads the same for both */\n"), "\(widget)") + // A `String` takes two words where `unowned(unsafe)` storage takes + // one, and a settable bridged property carries `C`: nothing is left + // open for either. + #expect(widget.contains(" let identifier: Swift.String!\n"), "\(widget)") + #expect(widget.contains(" var payload: Any!\n"), "\(widget)") + } + + /// With its symbols, the property's type settles it: `weak` holds only + /// an `Optional`. + @Test func unownedUnsafePropertyWithItsTypeIsDeclaredUnownedUnsafe() async throws { + let widget = try await adaptiveTransitionWidget(of: .full) + #expect(widget.contains("unowned(unsafe) var unretainedObserver: __C.NSObject\n"), "\(widget)") + #expect(!widget.contains("weak var unretainedObserver"), "\(widget)") + #expect(widget.contains("weak var observer: __C.NSObject?\n"), "\(widget)") + } + + @Test func cTypeReplacementsSpellARecoveredPrimitiveType() async throws { + let widget = try await adaptiveTransitionWidget(of: .strippedLocals) { configuration in + configuration.cTypeReplacements = [.double: "CGFloat", .longLong: "NSInteger", .ulongLong: "NSUInteger"] + } + #expect(widget.contains(" var interactiveProgress: CGFloat\n"), "\(widget)") + #expect(widget.contains(" var stepCount: NSInteger\n"), "\(widget)") + // Only the type itself is replaced: `NSRange`'s `QQ` fields are not. + let unreplaced = try await adaptiveTransitionWidget(of: .strippedLocals) + #expect(declaredType(of: "selectedRange", in: widget) == declaredType(of: "selectedRange", in: unreplaced), "\(widget)") + #expect(widget.contains(" var isAnimated: Swift.Bool\n"), "\(widget)") + } + + @Test func objcTransformersInstallTheirCTypeReplacementsOnlyWhenEnabled() async throws { + let enabled = try await adaptiveTransitionWidget(of: .strippedLocals) { configuration in + configuration.applyTransformers(Transformer.ObjCConfiguration(cType: .init(isEnabled: true, replacements: [.double: "CGFloat", .longLong: ""]))) + } + #expect(enabled.contains(" var interactiveProgress: CGFloat\n"), "\(enabled)") + // An empty spelling replaces nothing. + #expect(enabled.contains(" var stepCount: Swift.Int\n"), "\(enabled)") + let disabled = try await adaptiveTransitionWidget(of: .strippedLocals) { configuration in + configuration.cTypeReplacements = [.double: "Float64"] + configuration.applyTransformers(Transformer.ObjCConfiguration(cType: .init(isEnabled: false, replacements: [.double: "CGFloat"]))) + } + #expect(disabled.contains(" var interactiveProgress: Swift.Double\n"), "\(disabled)") + } + + @Test func ivarWithNoEncodingStaysAComment() async throws { + let widget = try await adaptiveTransitionWidget(of: .strippedLocals) + #expect(widget.contains("// stored property transitionAnimations: Swift type not recoverable (ObjC ivar, offset 0x"), "\(widget)") + #expect(!widget.contains("var transitionAnimations")) + } + + @Test func recoveredTypesHoldWithEveryObjCImplementationSymbolGone() async throws { + let widget = try await adaptiveTransitionWidget(of: .strippedEverything) + #expect(widget.contains(" var containerView: __C.NSObject!\n"), "\(widget)") + #expect(widget.contains(" var isAnimated: Swift.Bool\n"), "\(widget)") + } + // MARK: - Inferred tier: no Swift symbol at all @Test func fullyStrippedImageIsRecognizedFromIvarEncodingsAndSaysSo() async throws { @@ -125,7 +273,7 @@ struct ObjCImplementationClassRecognitionTests { // The class has no member symbol left, so the extension is synthesized // from the ObjC side alone — and labelled as an inference. let widget = try #require(block(named: "@objc @implementation /* inferred from ObjC class data: 4 ivars carry Swift-style type encodings */ extension __C.Widget {", in: interface)) - #expect(widget.contains("// stored property title: Swift type not recoverable")) + #expect(widget.contains(" var title: Swift.String!\n")) #expect(widget.contains("// stored property swiftOnlyCache: Swift type not recoverable")) // The clang class has complete encodings and no Swift symbols: silent // (it still appears as the SUPERCLASS of the fixture's Swift subclasses). @@ -180,10 +328,11 @@ struct ObjCImplementationClassRecognitionTests { #expect(facts.properties.map(\.name).sorted() == ["count", "title"]) #expect(ObjCImplementationClasses.facts(forClassNamed: "ClangWidget", in: machOFile) == nil) - // Three `@implementation` bodies: `Widget`, the override-recovery - // fixture's `DerivedImplementationWidget` and the imported - // declarations' `ScenePresentationWidget`. - #expect(Set(ObjCImplementationClasses.all(in: machOFile).map(\.className)) == ["Widget", "DerivedImplementationWidget", "ScenePresentationWidget"]) + // Four `@implementation` bodies: `Widget`, the override-recovery + // fixture's `DerivedImplementationWidget`, the imported + // declarations' `ScenePresentationWidget` and the ivar type + // recovery's `AdaptiveTransitionWidget`. + #expect(Set(ObjCImplementationClasses.all(in: machOFile).map(\.className)) == ["Widget", "DerivedImplementationWidget", "ScenePresentationWidget", "AdaptiveTransitionWidget"]) } /// An imported ObjC class has `PublicNonUnique` linkage, so any module @@ -220,7 +369,7 @@ struct ObjCImplementationClassRecognitionTests { guard case .objcImplementationClassRecognized(let context) = event else { return nil } return context } - #expect(Set(recognized.map(\.className)) == ["Widget", "DerivedImplementationWidget", "ScenePresentationWidget"]) + #expect(Set(recognized.map(\.className)) == ["Widget", "DerivedImplementationWidget", "ScenePresentationWidget", "AdaptiveTransitionWidget"]) let widget = try #require(recognized.first { $0.className == "Widget" }) #expect(widget.isInferred == false) #expect(widget.instanceVariableCount == 5) @@ -240,7 +389,7 @@ struct AppKitObjCImplementationClassTests { } @Test(.enabled(if: runsOnMacOS26OrLater, "NSGlassEffectView ships with macOS 26")) func appKitGlassEffectViewIsDefinitive() throws { - let cache = try DyldCache(path: .current) + let cache = try #require(FullDyldCache.cachedHost, "no host dyld shared cache").mainCache let machOFile = try #require(cache.machOFile(named: .AppKit), "the running system's cache has no AppKit") let facts = try #require(ObjCImplementationClasses.facts(forClassNamed: "NSGlassEffectView", in: machOFile)) guard case .definitive(let reasons) = facts.evidence else { diff --git a/Tests/SwiftInterfaceTests/ObjCImplementationInstanceVariableFactsTests.swift b/Tests/SwiftInterfaceTests/ObjCImplementationInstanceVariableFactsTests.swift new file mode 100644 index 000000000..e59d2e407 --- /dev/null +++ b/Tests/SwiftInterfaceTests/ObjCImplementationInstanceVariableFactsTests.swift @@ -0,0 +1,60 @@ +import Foundation +import Testing +import MachOKit +import MachOFoundation +import SwiftInspection +import SwiftObjCInterop +@testable import SwiftSectionTestingSupport +import SwiftSectionFixtureSupport + +/// The premise the stored property type recovery stands on (evolution +/// proposal `objc-ivar-type-recovery`): with every field-offset symbol of the +/// fixture's `AdaptiveTransitionWidget` stripped, its ivars still carry their +/// names and the encodings the compiler writes — complete for a type +/// Objective-C represents as it is, `?` for a bridged one, empty for a +/// Swift-only property — and each `@objc` one still finds the Objective-C +/// property synthesized on it, `readonly` and `weak` included. Should the +/// compiler ever write them differently, this fails before the printing tests +/// do, and says so. +@Suite(.serialized, ExclusiveImageAccess(ObjCImplementationFixture.moduleName)) +struct ObjCImplementationInstanceVariableFactsTests { + @Test(arguments: [ObjCImplementationFixture.Variant.strippedLocals, .strippedEverything, .optimizedStripped]) + func strippedInstanceVariablesKeepTheirNamesEncodingsAndObjCProperties(variant: ObjCImplementationFixture.Variant) throws { + let machOFile = try ObjCImplementationFixture.machOFile(variant) + let facts = try #require(ObjCImplementationClasses.facts(forClassNamed: "AdaptiveTransitionWidget", in: machOFile)) + #expect(facts.evidence.isInferred == (variant == .strippedEverything)) + #expect(facts.instanceVariables.allSatisfy { $0.swiftFieldOffsetSymbolName == nil }) + let encodingsByName = Dictionary(facts.instanceVariables.map { ($0.name, $0.typeEncoding) }, uniquingKeysWith: { first, _ in first }) + #expect(encodingsByName == [ + "containerView": "@\"NSObject\"", + "buffer": "@\"NSMutableString\"", + "previousLayout": "@\"\"", + "identifier": "?", + // A `weak` property's storage is no type Objective-C represents + // as it is, so its ivar says `?` even for a class. + "observer": "?", + "isAnimated": "B", + "interactiveProgress": "d", + "stepCount": "q", + "revision": "q", + "selectedRange": "{_NSRange=QQ}", + "names": "?", + "payload": "?", + "transitionAnimations": "", + // `unowned(unsafe)` storage, like `weak`, says `?`. + "unretainedObserver": "?", + "unretainedOwner": "?", + ]) + for instanceVariable in facts.instanceVariables where instanceVariable.isObjCVisible { + #expect(facts.objcProperty(storedIn: instanceVariable, swiftPropertyName: instanceVariable.name) != nil, "\(instanceVariable.name) finds no Objective-C property") + } + let identifier = try #require(facts.instanceVariables.first { $0.name == "identifier" }) + #expect(facts.objcProperty(storedIn: identifier, swiftPropertyName: identifier.name)?.isReadOnly == true) + let revision = try #require(facts.instanceVariables.first { $0.name == "revision" }) + #expect(facts.objcProperty(storedIn: revision, swiftPropertyName: revision.name)?.isReadOnly == true) + let observer = try #require(facts.instanceVariables.first { $0.name == "observer" }) + #expect(facts.objcProperty(storedIn: observer, swiftPropertyName: observer.name)?.isWeak == true) + let containerView = try #require(facts.instanceVariables.first { $0.name == "containerView" }) + #expect(facts.objcProperty(storedIn: containerView, swiftPropertyName: containerView.name)?.isReadOnly == false) + } +} diff --git a/Tests/SwiftInterfaceTests/ObjCImportedDefinitionTests.swift b/Tests/SwiftInterfaceTests/ObjCImportedDefinitionTests.swift index 031b78009..f39a5b8c9 100644 --- a/Tests/SwiftInterfaceTests/ObjCImportedDefinitionTests.swift +++ b/Tests/SwiftInterfaceTests/ObjCImportedDefinitionTests.swift @@ -254,13 +254,7 @@ struct ObjCImportedDefinitionTests { /// separately shipped dylib: a category on a class of another image /// stays a category. @Test func aCategoryOnAClassOfAnotherImage() async throws { - let categoriesLibrary: MachOFile - switch try MachOKit.loadFromFile(url: ObjCImplementationFixture.categoriesLibraryURL()) { - case .machO(let machOFile): - categoriesLibrary = machOFile - case .fat(let fatFile): - categoriesLibrary = try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }) - } + let categoriesLibrary = try HostSlice.machOFile(at: ObjCImplementationFixture.categoriesLibraryURL()) let builder = try await builder(of: categoriesLibrary) #expect(builder.indexer.objcImportedCategoryUniqueNames == ["NSObject(SeparatelyShipped)"]) let definition = try #require(builder.indexer.objcImportedCategoryDefinition(uniqueName: "NSObject(SeparatelyShipped)")) diff --git a/Tests/SwiftInterfaceTests/ObjCMemberRecoveryTests.swift b/Tests/SwiftInterfaceTests/ObjCMemberRecoveryTests.swift index 9d743b289..58a1e46d2 100644 --- a/Tests/SwiftInterfaceTests/ObjCMemberRecoveryTests.swift +++ b/Tests/SwiftInterfaceTests/ObjCMemberRecoveryTests.swift @@ -13,6 +13,11 @@ import SwiftInspection import SwiftObjCInterop import SwiftThunkAnalysis @testable import SwiftSectionTestingSupport +import MachOObjCSection +import SwiftPrinting +import Semantic +import OrderedCollections +import SwiftSectionFixtureSupport /// The ObjC member recovery over the shared `@objc @implementation` fixture /// (evolution proposals `objc-ancestor-override-recovery` and @@ -920,7 +925,7 @@ struct AppKitObjCMemberTests { } @Test(.enabled(if: runsOnMacOS26OrLater, "NSGlassEffectView ships with macOS 26")) func glassEffectViewOverridesResolveAgainstNSView() throws { - let cache = try DyldCache(path: .current) + let cache = try #require(FullDyldCache.cachedHost, "no host dyld shared cache").mainCache let machOFile = try #require(cache.machOFile(named: .AppKit), "the running system's cache has no AppKit") let table = try #require(ObjCMembers.table(forObjCClassNamed: "NSGlassEffectView", in: machOFile)) // The chain crosses into libobjc inside the cache and reaches the root. @@ -972,7 +977,7 @@ struct AppKitObjCMemberTests { /// `@objc(drawInRect:angle:)` — an explicit selector, provable because /// the chain and the protocols resolve inside the cache. @Test(.enabled(if: runsOnMacOS26OrLater, "NSGradient's Swift implementation ships with macOS 26")) func gradientHeaderSelectorsAreExplicit() throws { - let cache = try DyldCache(path: .current) + let cache = try #require(FullDyldCache.cachedHost, "no host dyld shared cache").mainCache let machOFile = try #require(cache.machOFile(named: .AppKit), "the running system's cache has no AppKit") let table = try #require(ObjCMembers.table(forObjCClassNamed: "NSGradient", in: machOFile)) #expect(table.hierarchy.isAncestorChainComplete) diff --git a/Tests/SwiftInterfaceTests/ObservableMacroInterfaceTests.swift b/Tests/SwiftInterfaceTests/ObservableMacroInterfaceTests.swift index a51020320..9d80b3be1 100644 --- a/Tests/SwiftInterfaceTests/ObservableMacroInterfaceTests.swift +++ b/Tests/SwiftInterfaceTests/ObservableMacroInterfaceTests.swift @@ -10,6 +10,7 @@ import SwiftDeclarationRendering @_spi(Support) @testable import SwiftPrinting @_spi(Support) @testable import SwiftInterface @testable import SwiftSectionTestingSupport +import OrderedCollections /// The interface folds what `@Observable` generated (evolution proposal /// `observable-macro-folding`): by default a class the macro expanded reads diff --git a/Tests/SwiftInterfaceTests/OpaqueAttributionImageE2ETests.swift b/Tests/SwiftInterfaceTests/OpaqueAttributionImageE2ETests.swift index 06d14a140..ec6003c70 100644 --- a/Tests/SwiftInterfaceTests/OpaqueAttributionImageE2ETests.swift +++ b/Tests/SwiftInterfaceTests/OpaqueAttributionImageE2ETests.swift @@ -4,6 +4,9 @@ import MachOKit @testable import SwiftSectionTestingSupport @_spi(Support) @testable import SwiftInterface @testable import MachOSwiftSection +import Semantic +import SwiftIndexing +import SwiftPrinting /// MachOImage-side counterpart of the opaque-attribution tests: the /// in-process reader resolves cross-image protocol descriptors (the third diff --git a/Tests/SwiftInterfaceTests/OpaqueConstraintRenderingTests.swift b/Tests/SwiftInterfaceTests/OpaqueConstraintRenderingTests.swift index 79f757396..36d75cfc2 100644 --- a/Tests/SwiftInterfaceTests/OpaqueConstraintRenderingTests.swift +++ b/Tests/SwiftInterfaceTests/OpaqueConstraintRenderingTests.swift @@ -4,6 +4,8 @@ import MachOKit import MachOFoundation import MachOSwiftSection @_spi(Support) @testable import SwiftInterface +import Semantic +import SwiftSectionTestingSupport /// The spelling of an opaque result type's constraints beyond the plain /// `some Protocol` shape the fixture covers. @@ -26,56 +28,6 @@ import MachOSwiftSection /// its `` and `Set` printed as `Swift.Set`. @Suite(.serialized) struct OpaqueConstraintRenderingTests { - private enum FixtureWorkingDirectoryCleanup { - nonisolated(unsafe) static var directories: [URL] = [] - static let registration: Void = { - atexit { - for directory in FixtureWorkingDirectoryCleanup.directories { - try? FileManager.default.removeItem(at: directory) - } - } - }() - } - - private struct FixtureCompilationError: Error, CustomStringConvertible { - let diagnostics: String - var description: String { "opaque-constraint fixture compilation failed:\n\(diagnostics)" } - } - - private static let fixtureCompilationResult: Result = { - Result { - let workingDirectory = FileManager.default.temporaryDirectory - .appendingPathComponent("OpaqueConstraintFixture-\(UUID().uuidString)") - _ = FixtureWorkingDirectoryCleanup.registration - FixtureWorkingDirectoryCleanup.directories.append(workingDirectory) - try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) - let sourceURL = workingDirectory.appendingPathComponent("OpaqueConstraints.swift") - try source.write(to: sourceURL, atomically: true, encoding: .utf8) - let libraryURL = workingDirectory.appendingPathComponent("libProbeOpaqueConstraint.dylib") - try run(swiftcArguments: [ - "-O", "-emit-library", "-module-name", "ProbeOpaqueConstraint", - "-target", "arm64-apple-macosx15.0", - sourceURL.path, "-o", libraryURL.path, - ]) - return libraryURL - } - }() - - private static func run(swiftcArguments: [String]) throws { - let process = Process() - process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") - process.arguments = ["swiftc"] + swiftcArguments - let standardErrorPipe = Pipe() - process.standardError = standardErrorPipe - try process.run() - // Drain before waiting, or a long diagnostic deadlocks both sides. - let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() - process.waitUntilExit() - guard process.terminationStatus == 0 else { - throw FixtureCompilationError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) - } - } - /// The classes double as ballast: a struct-only fixture dylib has no /// `__DATA` segment and MachOKit before 0.52.103 mis-walked its chained-fixup /// pages. @@ -103,14 +55,13 @@ struct OpaqueConstraintRenderingTests { """ private func renderInterface() async throws -> String { - let libraryURL = try Self.fixtureCompilationResult.get() - let machOFile: MachOFile - switch try File.loadFromFile(url: libraryURL) { - case .machO(let file): - machOFile = file - case .fat(let fatFile): - machOFile = try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }) - } + let libraryURL = try FixtureCompiler.shared.dynamicLibrary( + named: "ProbeOpaqueConstraint", + language: .swift, + sourceFiles: [FixtureSourceFile(name: "OpaqueConstraints.swift", contents: Self.source)], + arguments: ["-O", "-target", "arm64-apple-macosx15.0"] + ) + let machOFile = try HostSlice.machOFile(at: libraryURL) let builder = try SwiftInterfaceBuilder(configuration: .init(), eventHandlers: [], in: machOFile) builder.addExtraDataProvider(SwiftInterfaceBuilderOpaqueTypeProvider(machO: machOFile)) try await builder.prepare() diff --git a/Tests/SwiftInterfaceTests/OpaqueParameterDepthTests.swift b/Tests/SwiftInterfaceTests/OpaqueParameterDepthTests.swift index 17e1d6fd2..627e96858 100644 --- a/Tests/SwiftInterfaceTests/OpaqueParameterDepthTests.swift +++ b/Tests/SwiftInterfaceTests/OpaqueParameterDepthTests.swift @@ -6,6 +6,8 @@ import MachOSwiftSection @_spi(Internals) import SwiftInspection import SwiftDeclarationRendering @_spi(Support) @testable import SwiftInterface +import Semantic +import SwiftSectionTestingSupport /// The depth of an opaque result's parameters: the innermost depth of the /// descriptor's own layout, counted over every context above it that adds @@ -56,12 +58,12 @@ struct OpaqueParameterDepthTests { }() } - private struct FixtureCompilationError: Error, CustomStringConvertible { + private struct FixtureCompilationError: Swift.Error, CustomStringConvertible { let diagnostics: String var description: String { "opaque-parameter depth fixture compilation failed:\n\(diagnostics)" } } - private struct UnexpectedInterface: Error, CustomStringConvertible { + private struct UnexpectedInterface: Swift.Error, CustomStringConvertible { let interface: String var description: String { "the opaque results did not print their own constraints:\n\(interface)" } } @@ -150,7 +152,7 @@ struct OpaqueParameterDepthTests { /// core image exports. private static let inProcessReaderExpectedInterfaceLine = "var foreignValues: some Swift.Sequence {" - private static let fixtureCompilationResult: Result = { + private static let fixtureCompilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("OpaqueParameterDepthFixture-\(UUID().uuidString)") @@ -197,13 +199,7 @@ struct OpaqueParameterDepthTests { } private static func machOFile() throws -> MachOFile { - let libraryURL = try fixtureCompilationResult.get() - switch try File.loadFromFile(url: libraryURL) { - case .machO(let file): - return file - case .fat(let fatFile): - return try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }) - } + try HostSlice.machOFile(at: fixtureCompilationResult.get()) } /// The fixture loaded into the process, read the way RuntimeViewer reads diff --git a/Tests/SwiftInterfaceTests/OpaqueParameterInMultiDepthExtensionTests.swift b/Tests/SwiftInterfaceTests/OpaqueParameterInMultiDepthExtensionTests.swift index a495e47cb..919f869de 100644 --- a/Tests/SwiftInterfaceTests/OpaqueParameterInMultiDepthExtensionTests.swift +++ b/Tests/SwiftInterfaceTests/OpaqueParameterInMultiDepthExtensionTests.swift @@ -4,6 +4,8 @@ import MachOKit import MachOFoundation import MachOSwiftSection @_spi(Support) @testable import SwiftInterface +import Semantic +import SwiftSectionFixtureSupport /// `SwiftInterfaceBuilderOpaqueTypeProvider` finds an opaque result's /// constraint at the depth of the opaque parameters, which it counts from the @@ -19,23 +21,7 @@ import MachOSwiftSection /// An exit test, because the defect traps. @Suite(.serialized) struct OpaqueParameterInMultiDepthExtensionTests { - private enum FixtureWorkingDirectoryCleanup { - nonisolated(unsafe) static var directories: [URL] = [] - static let registration: Void = { - atexit { - for directory in FixtureWorkingDirectoryCleanup.directories { - try? FileManager.default.removeItem(at: directory) - } - } - }() - } - - private struct FixtureCompilationError: Error, CustomStringConvertible { - let diagnostics: String - var description: String { "opaque-parameter extension-depth fixture compilation failed:\n\(diagnostics)" } - } - - private struct MissingConstraint: Error, CustomStringConvertible { + private struct MissingConstraint: Swift.Error, CustomStringConvertible { let interface: String var description: String { "the opaque result did not print its constraint:\n\(interface)" } } @@ -60,48 +46,20 @@ struct OpaqueParameterInMultiDepthExtensionTests { } """ - private static let fixtureCompilationResult: Result = { - Result { - let workingDirectory = FileManager.default.temporaryDirectory - .appendingPathComponent("OpaqueParameterExtensionDepthFixture-\(UUID().uuidString)") - _ = FixtureWorkingDirectoryCleanup.registration - FixtureWorkingDirectoryCleanup.directories.append(workingDirectory) - try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) - let sourceURL = workingDirectory.appendingPathComponent("OpaqueParameterExtensionDepth.swift") - try source.write(to: sourceURL, atomically: true, encoding: .utf8) - let libraryURL = workingDirectory.appendingPathComponent("libProbeOpaqueExtensionDepth.dylib") - let process = Process() - process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") - process.arguments = [ - "swiftc", "-swift-version", "5", "-O", "-emit-library", "-module-name", "ProbeOpaqueExtensionDepth", - "-target", "arm64-apple-macosx15.0", - sourceURL.path, "-o", libraryURL.path, - ] - let standardErrorPipe = Pipe() - process.standardError = standardErrorPipe - try process.run() - // Drain before waiting, or a long diagnostic deadlocks both sides. - let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() - process.waitUntilExit() - guard process.terminationStatus == 0 else { - throw FixtureCompilationError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) - } - return libraryURL - } - }() + private static func libraryURL() throws -> URL { + try FixtureCompiler.shared.dynamicLibrary( + named: "ProbeOpaqueExtensionDepth", + language: .swift, + sourceFiles: [FixtureSourceFile(name: "OpaqueParameterExtensionDepth.swift", contents: source)], + arguments: ["-swift-version", "5", "-O", "-target", "arm64-apple-macosx15.0"] + ) + } /// The fixture's interface with the opaque type provider attached, as /// `interface --parse-opaque-return-type` and RuntimeViewer print it; it /// throws unless the opaque result names its constraint. static func printInterfaceNamingTheOpaqueConstraint() async throws { - let libraryURL = try fixtureCompilationResult.get() - let machOFile: MachOFile - switch try File.loadFromFile(url: libraryURL) { - case .machO(let file): - machOFile = file - case .fat(let fatFile): - machOFile = try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }) - } + let machOFile = try HostSlice.machOFile(at: libraryURL()) let builder = try SwiftInterfaceBuilder(configuration: .init(), eventHandlers: [], in: machOFile) builder.addExtraDataProvider(SwiftInterfaceBuilderOpaqueTypeProvider(machO: machOFile)) try await builder.prepare() diff --git a/Tests/SwiftInterfaceTests/OpaqueParameterWithoutProtocolRequirementTests.swift b/Tests/SwiftInterfaceTests/OpaqueParameterWithoutProtocolRequirementTests.swift index 35f86001b..0e223ab93 100644 --- a/Tests/SwiftInterfaceTests/OpaqueParameterWithoutProtocolRequirementTests.swift +++ b/Tests/SwiftInterfaceTests/OpaqueParameterWithoutProtocolRequirementTests.swift @@ -4,6 +4,8 @@ import MachOKit import MachOFoundation import MachOSwiftSection @_spi(Support) @testable import SwiftInterface +import Semantic +import SwiftSectionFixtureSupport /// An opaque parameter that carries no runtime-visible protocol requirement. /// @@ -27,56 +29,6 @@ import MachOSwiftSection /// plus one for a generic member's own parameters. @Suite(.serialized) struct OpaqueParameterWithoutProtocolRequirementTests { - private enum FixtureWorkingDirectoryCleanup { - nonisolated(unsafe) static var directories: [URL] = [] - static let registration: Void = { - atexit { - for directory in FixtureWorkingDirectoryCleanup.directories { - try? FileManager.default.removeItem(at: directory) - } - } - }() - } - - private struct FixtureCompilationError: Error, CustomStringConvertible { - let diagnostics: String - var description: String { "opaque-parameter fixture compilation failed:\n\(diagnostics)" } - } - - private static let fixtureCompilationResult: Result = { - Result { - let workingDirectory = FileManager.default.temporaryDirectory - .appendingPathComponent("OpaqueParameterFixture-\(UUID().uuidString)") - _ = FixtureWorkingDirectoryCleanup.registration - FixtureWorkingDirectoryCleanup.directories.append(workingDirectory) - try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) - let sourceURL = workingDirectory.appendingPathComponent("OpaqueParameters.swift") - try source.write(to: sourceURL, atomically: true, encoding: .utf8) - let libraryURL = workingDirectory.appendingPathComponent("libProbeOpaqueParameter.dylib") - try run(swiftcArguments: [ - "-O", "-emit-library", "-module-name", "ProbeOpaqueParameter", - "-target", "arm64-apple-macosx15.0", - sourceURL.path, "-o", libraryURL.path, - ]) - return libraryURL - } - }() - - private static func run(swiftcArguments: [String]) throws { - let process = Process() - process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") - process.arguments = ["swiftc"] + swiftcArguments - let standardErrorPipe = Pipe() - process.standardError = standardErrorPipe - try process.run() - // Drain before waiting, or a long diagnostic deadlocks both sides. - let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() - process.waitUntilExit() - guard process.terminationStatus == 0 else { - throw FixtureCompilationError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) - } - } - /// The class is ballast: a struct-only fixture dylib has no `__DATA` /// segment and MachOKit before 0.52.103 mis-walked its chained-fixup pages. private static let source = """ @@ -101,15 +53,17 @@ struct OpaqueParameterWithoutProtocolRequirementTests { } """ + private static func libraryURL() throws -> URL { + try FixtureCompiler.shared.dynamicLibrary( + named: "ProbeOpaqueParameter", + language: .swift, + sourceFiles: [FixtureSourceFile(name: "OpaqueParameters.swift", contents: source)], + arguments: ["-O", "-target", "arm64-apple-macosx15.0"] + ) + } + private func renderInterface() async throws -> String { - let libraryURL = try Self.fixtureCompilationResult.get() - let machOFile: MachOFile - switch try File.loadFromFile(url: libraryURL) { - case .machO(let file): - machOFile = file - case .fat(let fatFile): - machOFile = try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }) - } + let machOFile = try HostSlice.machOFile(at: Self.libraryURL()) let builder = try SwiftInterfaceBuilder(configuration: .init(), eventHandlers: [], in: machOFile) builder.addExtraDataProvider(SwiftInterfaceBuilderOpaqueTypeProvider(machO: machOFile)) try await builder.prepare() diff --git a/Tests/SwiftInterfaceTests/PrintFailureEventTests.swift b/Tests/SwiftInterfaceTests/PrintFailureEventTests.swift index d8603bd60..3aa09d112 100644 --- a/Tests/SwiftInterfaceTests/PrintFailureEventTests.swift +++ b/Tests/SwiftInterfaceTests/PrintFailureEventTests.swift @@ -9,6 +9,8 @@ import Dependencies @testable import MachOSwiftSection @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import OrderedCollections +import Semantic /// A definition that cannot be printed must be **reported**, not printed away. /// @@ -88,7 +90,7 @@ final class PrintFailureEventTests: MachOFileTests, @unchecked Sendable { ) } - private enum PrintFailureEventTestError: Error { + private enum PrintFailureEventTestError: Swift.Error { case fixtureTypeIsNotAStruct } @@ -327,7 +329,7 @@ final class PrintFailureEventTests: MachOFileTests, @unchecked Sendable { /// write; on the diff path, where no sink existed at all, `case foo(Payload)` /// became `case foo` in silence. @Test func catchWithoutDefinitionIdentityReportsDegradation() async throws { - struct UnrenderableNodeError: Error {} + struct UnrenderableNodeError: Swift.Error {} let collector = SwiftIndexEventCollector() let eventDispatcher = SwiftIndexEvents.Dispatcher() @@ -355,7 +357,7 @@ final class PrintFailureEventTests: MachOFileTests, @unchecked Sendable { /// Assert the partition directly; the os_log write itself is not observable /// in-process. @Test func everyFailureEventIsRecognizedByTheFloor() async throws { - struct SomeError: Error {} + struct SomeError: Swift.Error {} let context = SwiftIndexEvents.PrintingContext(name: "Foo", kind: .type) #expect(SwiftIndexEvents.Payload.definitionPrintFailed(context: context, error: SomeError()).unhandledFailureDescription != nil) diff --git a/Tests/SwiftInterfaceTests/ProjectedOpaqueMemberWitnessTests.swift b/Tests/SwiftInterfaceTests/ProjectedOpaqueMemberWitnessTests.swift index 1be05d8c5..77ebf26db 100644 --- a/Tests/SwiftInterfaceTests/ProjectedOpaqueMemberWitnessTests.swift +++ b/Tests/SwiftInterfaceTests/ProjectedOpaqueMemberWitnessTests.swift @@ -7,6 +7,8 @@ import Demangling @_spi(Internals) import SwiftInspection import SwiftDeclarationRendering @_spi(Support) @testable import SwiftInterface +import Semantic +import SwiftSectionFixtureSupport /// An associated-type witness that is a *member* of another module's opaque /// archetype — `(↻τ.Element)` in the generics book's notation, spelled @@ -38,7 +40,7 @@ struct ProjectedOpaqueMemberWitnessTests { }() } - private struct FixtureCompilationError: Error, CustomStringConvertible { + private struct FixtureCompilationError: Swift.Error, CustomStringConvertible { let diagnostics: String var description: String { "projected opaque member fixture compilation failed:\n\(diagnostics)" } } @@ -49,7 +51,7 @@ struct ProjectedOpaqueMemberWitnessTests { let clientInterfaceText: String } - private static let fixtureCompilationResult: Result = { + private static let fixtureCompilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("ProjectedOpaqueMemberFixture-\(UUID().uuidString)") @@ -133,12 +135,7 @@ struct ProjectedOpaqueMemberWitnessTests { private func loadClient() throws -> (client: MachOFile, corePath: String) { let fixture = try Self.fixtureCompilationResult.get() - switch try File.loadFromFile(url: fixture.clientLibraryURL) { - case .machO(let machOFile): - return (machOFile, fixture.coreLibraryURL.path) - case .fat(let fatFile): - return (try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }), fixture.coreLibraryURL.path) - } + return (try HostSlice.machOFile(at: fixture.clientLibraryURL), fixture.coreLibraryURL.path) } /// `typealias = …` as the compiler's own interface spells it, keyed diff --git a/Tests/SwiftInterfaceTests/PropertyWrapperSynthesizedMemberTests.swift b/Tests/SwiftInterfaceTests/PropertyWrapperSynthesizedMemberTests.swift index 28eaa5bdc..3057ada77 100644 --- a/Tests/SwiftInterfaceTests/PropertyWrapperSynthesizedMemberTests.swift +++ b/Tests/SwiftInterfaceTests/PropertyWrapperSynthesizedMemberTests.swift @@ -4,6 +4,8 @@ import MachOKit import MachOFoundation import MachOSwiftSection @_spi(Support) @testable import SwiftInterface +import Semantic +import SwiftSectionFixtureSupport /// `@Wrapper var x: Int` makes the compiler synthesize a stored `_x` of the /// wrapper type and, when the wrapper projects, a computed `$x`. The source @@ -16,56 +18,6 @@ import MachOSwiftSection /// chained-fixup pages). @Suite(.serialized) struct PropertyWrapperSynthesizedMemberTests { - private enum FixtureWorkingDirectoryCleanup { - nonisolated(unsafe) static var directories: [URL] = [] - static let registration: Void = { - atexit { - for directory in FixtureWorkingDirectoryCleanup.directories { - try? FileManager.default.removeItem(at: directory) - } - } - }() - } - - private struct FixtureCompilationError: Error, CustomStringConvertible { - let diagnostics: String - var description: String { "property-wrapper fixture compilation failed:\n\(diagnostics)" } - } - - private static let fixtureCompilationResult: Result = { - Result { - let workingDirectory = FileManager.default.temporaryDirectory - .appendingPathComponent("PropertyWrapperFixture-\(UUID().uuidString)") - _ = FixtureWorkingDirectoryCleanup.registration - FixtureWorkingDirectoryCleanup.directories.append(workingDirectory) - try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) - let sourceURL = workingDirectory.appendingPathComponent("Wrappers.swift") - try source.write(to: sourceURL, atomically: true, encoding: .utf8) - let libraryURL = workingDirectory.appendingPathComponent("libProbeWrappers.dylib") - try run(swiftcArguments: [ - "-O", "-emit-library", "-module-name", "ProbeWrappers", - "-target", "arm64-apple-macosx15.0", - sourceURL.path, "-o", libraryURL.path, - ]) - return libraryURL - } - }() - - private static func run(swiftcArguments: [String]) throws { - let process = Process() - process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") - process.arguments = ["swiftc"] + swiftcArguments - let standardErrorPipe = Pipe() - process.standardError = standardErrorPipe - try process.run() - // Drain before waiting, or a long diagnostic deadlocks both sides. - let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() - process.waitUntilExit() - guard process.terminationStatus == 0 else { - throw FixtureCompilationError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) - } - } - private static let source = """ public final class ProbeAnchor {} @@ -99,14 +51,17 @@ struct PropertyWrapperSynthesizedMemberTests { } """ + private static func libraryURL() throws -> URL { + try FixtureCompiler.shared.dynamicLibrary( + named: "ProbeWrappers", + language: .swift, + sourceFiles: [FixtureSourceFile(name: "Wrappers.swift", contents: source)], + arguments: ["-O", "-target", "arm64-apple-macosx15.0"] + ) + } + private func loadFixture() throws -> MachOFile { - let libraryURL = try Self.fixtureCompilationResult.get() - switch try File.loadFromFile(url: libraryURL) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - return try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }) - } + try HostSlice.machOFile(at: Self.libraryURL()) } @Test func theInterfaceShowsTheDeclaredPropertyNotItsSynthesizedMembers() async throws { @@ -156,7 +111,7 @@ struct PropertyWrapperSynthesizedMemberTests { /// that drives `SwiftDeclarationPrinter` directly, as RuntimeViewer /// does, gets the hiding and the attribute without any wiring. @Test func theInProcessReaderRendersTheSameWrapperAttribute() async throws { - let libraryURL = try Self.fixtureCompilationResult.get() + let libraryURL = try Self.libraryURL() _ = libraryURL.path.withCString { dlopen($0, RTLD_LAZY) } // `MachOImage(name:)` matches the loaded image by its bare file name. let machOImage = try #require(MachOImage(name: "libProbeWrappers"), "the fixture dylib did not load in-process") diff --git a/Tests/SwiftInterfaceTests/ProtocolInExtensionDefaultWitnessTests.swift b/Tests/SwiftInterfaceTests/ProtocolInExtensionDefaultWitnessTests.swift index 771e1d855..260959f0e 100644 --- a/Tests/SwiftInterfaceTests/ProtocolInExtensionDefaultWitnessTests.swift +++ b/Tests/SwiftInterfaceTests/ProtocolInExtensionDefaultWitnessTests.swift @@ -4,6 +4,8 @@ import MachOKit import MachOFoundation import MachOSwiftSection @_spi(Support) @testable import SwiftInterface +import Semantic +import SwiftSectionFixtureSupport /// A protocol declared in an extension of another module's type prints its /// default-implementation extensions in the interface's top-level block for @@ -22,22 +24,6 @@ import MachOSwiftSection /// its extensions, and not in the top-level block, which ran first. @Suite(.serialized) struct ProtocolInExtensionDefaultWitnessTests { - private enum FixtureWorkingDirectoryCleanup { - nonisolated(unsafe) static var directories: [URL] = [] - static let registration: Void = { - atexit { - for directory in FixtureWorkingDirectoryCleanup.directories { - try? FileManager.default.removeItem(at: directory) - } - } - }() - } - - private struct FixtureCompilationError: Swift.Error, CustomStringConvertible { - let diagnostics: String - var description: String { "protocol-in-extension default-witness fixture compilation failed:\n\(diagnostics)" } - } - /// `FixtureAnchor` is ballast: a fixture dylib with no class has no /// `__DATA` segment, which older MachOKit releases mis-walked. private static let source = """ @@ -56,52 +42,19 @@ struct ProtocolInExtensionDefaultWitnessTests { } """ - private static let fixtureCompilationResult: Result = { - Result { - let workingDirectory = FileManager.default.temporaryDirectory - .appendingPathComponent("ProtocolInExtensionDefaultWitnessFixture-\(UUID().uuidString)") - _ = FixtureWorkingDirectoryCleanup.registration - FixtureWorkingDirectoryCleanup.directories.append(workingDirectory) - try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) - let sourceURL = workingDirectory.appendingPathComponent("ProtocolInExtensionDefaultWitness.swift") - try source.write(to: sourceURL, atomically: true, encoding: .utf8) - let libraryURL = workingDirectory.appendingPathComponent("libProbeDefaultWitness.dylib") + private static func libraryURL() throws -> URL { + try FixtureCompiler.shared.dynamicLibrary( + named: "ProbeDefaultWitness", + language: .swift, + sourceFiles: [FixtureSourceFile(name: "ProtocolInExtensionDefaultWitness.swift", contents: source)], // Library evolution makes `Labeled` resilient, which is what // gives its requirement a default witness of its own. - try run(swiftcArguments: [ - "-swift-version", "5", "-O", "-emit-library", "-enable-library-evolution", - "-module-name", "ProbeDefaultWitness", - "-target", "arm64-apple-macosx15.0", - sourceURL.path, "-o", libraryURL.path, - ]) - return libraryURL - } - }() - - private static func run(swiftcArguments: [String]) throws { - let process = Process() - process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") - process.arguments = ["swiftc"] + swiftcArguments - let standardErrorPipe = Pipe() - process.standardError = standardErrorPipe - try process.run() - // Drain before waiting, or a long diagnostic deadlocks both sides. - let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() - process.waitUntilExit() - guard process.terminationStatus == 0 else { - throw FixtureCompilationError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) - } + arguments: ["-swift-version", "5", "-O", "-enable-library-evolution", "-target", "arm64-apple-macosx15.0"] + ) } private func makeBuilder() async throws -> SwiftInterfaceBuilder { - let libraryURL = try Self.fixtureCompilationResult.get() - let machOFile: MachOFile - switch try File.loadFromFile(url: libraryURL) { - case .machO(let file): - machOFile = file - case .fat(let fatFile): - machOFile = try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }) - } + let machOFile = try HostSlice.machOFile(at: Self.libraryURL()) let builder = try SwiftInterfaceBuilder(configuration: .init(), eventHandlers: [], in: machOFile) try await builder.prepare() return builder diff --git a/Tests/SwiftInterfaceTests/ProtocolInExtensionTests.swift b/Tests/SwiftInterfaceTests/ProtocolInExtensionTests.swift index 117413a07..a19aa9d50 100644 --- a/Tests/SwiftInterfaceTests/ProtocolInExtensionTests.swift +++ b/Tests/SwiftInterfaceTests/ProtocolInExtensionTests.swift @@ -4,11 +4,13 @@ import MachOKit import MachOFoundation import MachOSwiftSection import Semantic +import SwiftSectionFixtureSupport import Demangling @_spi(Support) @testable import SwiftDeclaration @_spi(Support) @testable import SwiftIndexing @_spi(Support) @testable import SwiftPrinting @_spi(Support) @testable import SwiftInterface +import OrderedCollections /// A protocol declared inside an extension (SE-0404) — `extension Host { /// protocol Delegate {…} }` — has no parent type definition, only an @@ -23,56 +25,6 @@ import Demangling /// extensions block, like the extensions of a protocol nested in a type. @Suite(.serialized) struct ProtocolInExtensionTests { - private enum FixtureWorkingDirectoryCleanup { - nonisolated(unsafe) static var directories: [URL] = [] - static let registration: Void = { - atexit { - for directory in FixtureWorkingDirectoryCleanup.directories { - try? FileManager.default.removeItem(at: directory) - } - } - }() - } - - private struct FixtureCompilationError: Swift.Error, CustomStringConvertible { - let diagnostics: String - var description: String { "protocol-in-extension fixture compilation failed:\n\(diagnostics)" } - } - - private static let fixtureCompilationResult: Result = { - Result { - let workingDirectory = FileManager.default.temporaryDirectory - .appendingPathComponent("ProtocolInExtensionFixture-\(UUID().uuidString)") - _ = FixtureWorkingDirectoryCleanup.registration - FixtureWorkingDirectoryCleanup.directories.append(workingDirectory) - try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) - let sourceURL = workingDirectory.appendingPathComponent("ProtocolsInExtensions.swift") - try source.write(to: sourceURL, atomically: true, encoding: .utf8) - let libraryURL = workingDirectory.appendingPathComponent("libProbeProtocolInExtension.dylib") - try run(swiftcArguments: [ - "-swift-version", "5", "-O", "-emit-library", "-module-name", "ProbeProtocolInExtension", - "-target", "arm64-apple-macosx15.0", - sourceURL.path, "-o", libraryURL.path, - ]) - return libraryURL - } - }() - - private static func run(swiftcArguments: [String]) throws { - let process = Process() - process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") - process.arguments = ["swiftc"] + swiftcArguments - let standardErrorPipe = Pipe() - process.standardError = standardErrorPipe - try process.run() - // Drain before waiting, or a long diagnostic deadlocks both sides. - let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() - process.waitUntilExit() - guard process.terminationStatus == 0 else { - throw FixtureCompilationError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) - } - } - /// `FixtureAnchor` is ballast: a fixture dylib with no class has no /// `__DATA` segment, which older MachOKit releases mis-walked. /// @@ -122,14 +74,17 @@ struct ProtocolInExtensionTests { } """ + private static func libraryURL() throws -> URL { + try FixtureCompiler.shared.dynamicLibrary( + named: "ProbeProtocolInExtension", + language: .swift, + sourceFiles: [FixtureSourceFile(name: "ProtocolsInExtensions.swift", contents: source)], + arguments: ["-swift-version", "5", "-O", "-target", "arm64-apple-macosx15.0"] + ) + } + private func loadFixture() throws -> MachOFile { - let libraryURL = try Self.fixtureCompilationResult.get() - switch try File.loadFromFile(url: libraryURL) { - case .machO(let file): - return file - case .fat(let fatFile): - return try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }) - } + try HostSlice.machOFile(at: Self.libraryURL()) } /// The lines starting an `extension` while inside another declaration's diff --git a/Tests/SwiftInterfaceTests/ProtocolRequirementPlacementInterfaceTests.swift b/Tests/SwiftInterfaceTests/ProtocolRequirementPlacementInterfaceTests.swift index 938a37c4e..cae16e1a5 100644 --- a/Tests/SwiftInterfaceTests/ProtocolRequirementPlacementInterfaceTests.swift +++ b/Tests/SwiftInterfaceTests/ProtocolRequirementPlacementInterfaceTests.swift @@ -7,6 +7,10 @@ import SwiftDeclarationRendering @_spi(Support) @testable import SwiftPrinting @_spi(Support) @testable import SwiftInterface @testable import SwiftSectionTestingSupport +import OrderedCollections +import Demangling +import SwiftDeclaration +import Semantic /// How the interface prints a protocol's requirement signature (evolution /// proposal `protocol-requirement-placement`): every requirement in the diff --git a/Tests/SwiftInterfaceTests/RawLayoutAttributeRenderingTests.swift b/Tests/SwiftInterfaceTests/RawLayoutAttributeRenderingTests.swift index 60f719965..dd9206dfa 100644 --- a/Tests/SwiftInterfaceTests/RawLayoutAttributeRenderingTests.swift +++ b/Tests/SwiftInterfaceTests/RawLayoutAttributeRenderingTests.swift @@ -4,6 +4,7 @@ import MachOKit import MachOFoundation import MachOSwiftSection import SwiftInterface +import Semantic /// Where the archived-cache-gated suite below finds its cache (see the /// SwiftLayout suite of the same shape for why this is a separate type). diff --git a/Tests/SwiftInterfaceTests/RawLayoutBuiltinDescriptorRenderingTests.swift b/Tests/SwiftInterfaceTests/RawLayoutBuiltinDescriptorRenderingTests.swift index 08a316304..63e00f4a3 100644 --- a/Tests/SwiftInterfaceTests/RawLayoutBuiltinDescriptorRenderingTests.swift +++ b/Tests/SwiftInterfaceTests/RawLayoutBuiltinDescriptorRenderingTests.swift @@ -8,6 +8,7 @@ import SwiftInterface import struct Semantic.SemanticString import struct Semantic.FrozenSemanticString import SwiftSectionTestingSupport +import SwiftPrinting /// `@_rawLayout` is an experimental feature any module can enable, not a /// standard-library privilege, and only its `like:` spelling leaves a field @@ -26,58 +27,6 @@ import SwiftSectionTestingSupport /// record does not — the assertions hold; see the last test. @Suite(.serialized) struct RawLayoutBuiltinDescriptorRenderingTests { - private enum FixtureWorkingDirectoryCleanup { - nonisolated(unsafe) static var directories: [URL] = [] - static let registration: Void = { - atexit { - for directory in FixtureWorkingDirectoryCleanup.directories { - try? FileManager.default.removeItem(at: directory) - } - } - }() - } - - private struct FixtureCompilationError: Error, CustomStringConvertible { - let diagnostics: String - var description: String { "raw-layout fixture compilation failed:\n\(diagnostics)" } - } - - private static let fixtureCompilationResult: Result = { - Result { - let workingDirectory = FileManager.default.temporaryDirectory - .appendingPathComponent("RawLayoutRenderingFixture-\(UUID().uuidString)") - _ = FixtureWorkingDirectoryCleanup.registration - FixtureWorkingDirectoryCleanup.directories.append(workingDirectory) - try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) - let sourceURL = workingDirectory.appendingPathComponent("RawLayouts.swift") - try source.write(to: sourceURL, atomically: true, encoding: .utf8) - let libraryURL = workingDirectory.appendingPathComponent("libProbeRawLayout.dylib") - try run(swiftcArguments: [ - "-O", "-emit-library", "-module-name", "ProbeRawLayout", - "-enable-experimental-feature", "RawLayout", - // Value generics (`let count: Int`) need macOS 26. - "-target", "arm64-apple-macosx26.0", - sourceURL.path, "-o", libraryURL.path, - ]) - return libraryURL - } - }() - - private static func run(swiftcArguments: [String]) throws { - let process = Process() - process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") - process.arguments = ["swiftc"] + swiftcArguments - let standardErrorPipe = Pipe() - process.standardError = standardErrorPipe - try process.run() - // Drain before waiting, or a long diagnostic deadlocks both sides. - let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() - process.waitUntilExit() - guard process.terminationStatus == 0 else { - throw FixtureCompilationError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) - } - } - private static let source = """ public final class ProbeAnchor {} @@ -112,19 +61,26 @@ struct RawLayoutBuiltinDescriptorRenderingTests { } """ + private static func libraryURL() throws -> URL { + try FixtureCompiler.shared.dynamicLibrary( + named: "ProbeRawLayout", + language: .swift, + sourceFiles: [FixtureSourceFile(name: "RawLayouts.swift", contents: source)], + arguments: [ + "-O", + "-enable-experimental-feature", "RawLayout", + // Value generics (`let count: Int`) need macOS 26. + "-target", "arm64-apple-macosx26.0", + ] + ) + } + private func renderInterface() async throws -> String { try await printInterface(marksCommentStructure: false).string } private func printInterface(marksCommentStructure: Bool) async throws -> SemanticString { - let libraryURL = try Self.fixtureCompilationResult.get() - let machOFile: MachOFile - switch try File.loadFromFile(url: libraryURL) { - case .machO(let file): - machOFile = file - case .fat(let fatFile): - machOFile = try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }) - } + let machOFile = try HostSlice.machOFile(at: Self.libraryURL()) var configuration = SwiftInterfaceBuilderConfiguration() configuration.printConfiguration.marksCommentStructure = marksCommentStructure let builder = try SwiftInterfaceBuilder(configuration: configuration, eventHandlers: [], in: machOFile) diff --git a/Tests/SwiftInterfaceTests/Snapshots/__Snapshots__/SymbolTestsCoreInterfaceSnapshotTests/interfaceSnapshot.1.txt b/Tests/SwiftInterfaceTests/Snapshots/__Snapshots__/SymbolTestsCoreInterfaceSnapshotTests/interfaceSnapshot.1.txt index 30b5ea8d0..2e68f1a88 100644 --- a/Tests/SwiftInterfaceTests/Snapshots/__Snapshots__/SymbolTestsCoreInterfaceSnapshotTests/interfaceSnapshot.1.txt +++ b/Tests/SwiftInterfaceTests/Snapshots/__Snapshots__/SymbolTestsCoreInterfaceSnapshotTests/interfaceSnapshot.1.txt @@ -1167,12 +1167,12 @@ enum FieldDescriptorVariants { struct ForeignPackedTimeContainer { // Field offset: 0x0 // Type Layout: (size: 24, stride: 24, alignment: 4, extraInhabitantCount: 0) - var startTime: __C.CMTime + var startTime: CMTime // Field offset: 0x18 // Type Layout: (size: 8, stride: 8, alignment: 8, extraInhabitantCount: 0) var elapsedSeconds: Swift.Double - init(startTime: __C.CMTime, elapsedSeconds: Swift.Double) + init(startTime: CMTime, elapsedSeconds: Swift.Double) } enum ForeignTypeFixtures { static func foreignClassReference() -> __C.CFStringRef diff --git a/Tests/SwiftInterfaceTests/StrippedWrappedPropertyRenderingTests.swift b/Tests/SwiftInterfaceTests/StrippedWrappedPropertyRenderingTests.swift index 258e70fcb..2e44056ec 100644 --- a/Tests/SwiftInterfaceTests/StrippedWrappedPropertyRenderingTests.swift +++ b/Tests/SwiftInterfaceTests/StrippedWrappedPropertyRenderingTests.swift @@ -9,6 +9,7 @@ import SwiftPrinting import struct Semantic.SemanticString import struct Semantic.FrozenSemanticString import SwiftSectionTestingSupport +import SwiftIndexing /// The interface side of wrapped-property recovery for the two cases the /// same-image suite (`PropertyWrapperSynthesizedMemberTests`) cannot show: @@ -72,7 +73,7 @@ struct StrippedWrappedPropertyRenderingTests { } """ - private static let compilationResult: Result = { + private static let compilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("StrippedWrappedPropertyFixture-\(UUID().uuidString)") @@ -123,13 +124,7 @@ struct StrippedWrappedPropertyRenderingTests { private func printOfflineInterface(marksCommentStructure: Bool) async throws -> SemanticString { let products = try Self.compilationResult.get() - let machOFile: MachOFile - switch try File.loadFromFile(url: products.clientURL) { - case .machO(let file): - machOFile = file - case .fat(let fatFile): - machOFile = try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }) - } + let machOFile = try HostSlice.machOFile(at: products.clientURL) var printConfiguration = SwiftDeclarationPrintConfiguration() printConfiguration.marksCommentStructure = marksCommentStructure let configuration = SwiftInterfaceBuilderConfiguration( diff --git a/Tests/SwiftInterfaceTests/SwiftDeclaredObjCProtocolInterfaceTests.swift b/Tests/SwiftInterfaceTests/SwiftDeclaredObjCProtocolInterfaceTests.swift index b9b5423bb..03d852877 100644 --- a/Tests/SwiftInterfaceTests/SwiftDeclaredObjCProtocolInterfaceTests.swift +++ b/Tests/SwiftInterfaceTests/SwiftDeclaredObjCProtocolInterfaceTests.swift @@ -8,6 +8,8 @@ import SwiftDeclarationRendering import SwiftInterface import Semantic @testable import SwiftSectionTestingSupport +import SwiftIndexing +import SwiftPrinting /// The `@objc` protocols a Swift module declares, on the interface path /// (evolution proposal `swift-declared-objc-protocols`): they have no diff --git a/Tests/SwiftInterfaceTests/SwiftEvolutionInterfaceBuilderTests.swift b/Tests/SwiftInterfaceTests/SwiftEvolutionInterfaceBuilderTests.swift index 725dabe4d..9c33405e6 100644 --- a/Tests/SwiftInterfaceTests/SwiftEvolutionInterfaceBuilderTests.swift +++ b/Tests/SwiftInterfaceTests/SwiftEvolutionInterfaceBuilderTests.swift @@ -6,10 +6,11 @@ import SwiftDiffing import SwiftDeclaration @testable import MachOSwiftSection @_spi(Support) @testable import SwiftInterface +import SwiftSectionFixtureSupport /// End-to-end tests for the annotated evolution interface over three -/// on-the-fly-compiled versions of one fixture module (the -/// `LegacyDyldInfoBindTests` compilation approach, minus the legacy target): +/// on-the-fly-compiled versions of one fixture module (each built with +/// `swiftc` at test time): /// /// - v1 → v2: `Alpha.bar(id:)` added, `Legacy` (whole class) removed. /// - v2 → v3: `Alpha.bar()` and the computed `Alpha.summary` removed, @@ -80,7 +81,7 @@ struct SwiftEvolutionInterfaceBuilderTests { // `Swift.Error` spelled out: the `Semantic` import brings its own `Error` // type into scope, which would otherwise win the lookup. - private static let fixtureCompilationResult: Result<[URL], Swift.Error> = { + private static let fixtureCompilationResult: Result<[URL], any Swift.Error> = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("EvolutionInterfaceFixture-\(UUID().uuidString)") @@ -105,7 +106,7 @@ struct SwiftEvolutionInterfaceBuilderTests { let standardErrorPipe = Pipe() process.standardError = standardErrorPipe try process.run() - // Drain BEFORE waitUntilExit — see LegacyDyldInfoBindTests. + // Drain BEFORE waitUntilExit, or a long diagnostic deadlocks both sides. let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() process.waitUntilExit() guard process.terminationStatus == 0 else { @@ -125,14 +126,7 @@ struct SwiftEvolutionInterfaceBuilderTests { private func loadFixtureMachOFiles() throws -> [MachOFile] { try Self.fixtureCompilationResult.get().map { libraryURL in - let file = try MachOKit.loadFromFile(url: libraryURL) - switch file { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } + try HostSlice.machOFile(at: libraryURL) } } diff --git a/Tests/SwiftInterfaceTests/SymbolTableRetentionTests.swift b/Tests/SwiftInterfaceTests/SymbolTableRetentionTests.swift index cdc194bc9..d76dedaa3 100644 --- a/Tests/SwiftInterfaceTests/SymbolTableRetentionTests.swift +++ b/Tests/SwiftInterfaceTests/SymbolTableRetentionTests.swift @@ -10,6 +10,8 @@ import MachOKit @testable import MachOSwiftSection @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import Demangling +import OrderedCollections /// A `DemangledSymbol` stored in the declaration model must not keep the /// shared per-image symbol table alive. diff --git a/Tests/SwiftInterfaceTests/SymbolTestsCoreE2ETests.swift b/Tests/SwiftInterfaceTests/SymbolTestsCoreE2ETests.swift index beb9314b1..9a0e94572 100644 --- a/Tests/SwiftInterfaceTests/SymbolTestsCoreE2ETests.swift +++ b/Tests/SwiftInterfaceTests/SymbolTestsCoreE2ETests.swift @@ -12,6 +12,7 @@ import Dependencies @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport @testable import SwiftDump +import Semantic @Suite(.serialized) final class STCoreE2ETests: MachOFileTests, @unchecked Sendable { diff --git a/Tests/SwiftInterfaceTests/ThunkOnlyObjCMemberTests.swift b/Tests/SwiftInterfaceTests/ThunkOnlyObjCMemberTests.swift index e247f83c2..e07b35329 100644 --- a/Tests/SwiftInterfaceTests/ThunkOnlyObjCMemberTests.swift +++ b/Tests/SwiftInterfaceTests/ThunkOnlyObjCMemberTests.swift @@ -8,6 +8,8 @@ import SwiftDeclarationRendering import SwiftInterface @_spi(Internals) import SwiftSymbols @testable import SwiftSectionTestingSupport +import Semantic +import SwiftPrinting /// Members whose implementation symbol the optimizer deleted while another of /// their entry points survived (evolution proposal `thunk-only-objc-members`): diff --git a/Tests/SwiftInterfaceTests/UnobservablePresenceTests.swift b/Tests/SwiftInterfaceTests/UnobservablePresenceTests.swift index 30c7a4e3f..d7d24af3b 100644 --- a/Tests/SwiftInterfaceTests/UnobservablePresenceTests.swift +++ b/Tests/SwiftInterfaceTests/UnobservablePresenceTests.swift @@ -4,6 +4,7 @@ import MachOKit import SwiftDiffing import SwiftInterface @testable import SwiftSectionTestingSupport +import Semantic /// Telling a declaration a version cannot show from one that is gone /// (evolution proposal `evolution-unobservable-presence`), over diff --git a/Tests/SwiftInterfaceTests/VisibilityRegionProjectionTests.swift b/Tests/SwiftInterfaceTests/VisibilityRegionProjectionTests.swift index 6436c5301..583c9baca 100644 --- a/Tests/SwiftInterfaceTests/VisibilityRegionProjectionTests.swift +++ b/Tests/SwiftInterfaceTests/VisibilityRegionProjectionTests.swift @@ -10,6 +10,7 @@ import MachOKit @testable import MachOSwiftSection @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import OrderedCollections /// A marked print (`SwiftDeclarationPrintConfiguration.marksOptionalContent`), /// projected to a configuration, reads byte for byte as printing with that diff --git a/Tests/SwiftInterfaceTests/WrappedReaderInterfaceTests.swift b/Tests/SwiftInterfaceTests/WrappedReaderInterfaceTests.swift index 06ad5da95..04a460d66 100644 --- a/Tests/SwiftInterfaceTests/WrappedReaderInterfaceTests.swift +++ b/Tests/SwiftInterfaceTests/WrappedReaderInterfaceTests.swift @@ -7,6 +7,7 @@ import SwiftPrinting import SwiftInterface import SwiftDeclarationRendering @testable import SwiftSectionTestingSupport +import Semantic /// The fixture's interface printed through a host's wrapper — a type that /// forwards every read to a `MachOFile` or an in-process `MachOImage`, as diff --git a/Tests/SwiftLayoutTests/BasicLayoutTests.swift b/Tests/SwiftLayoutTests/BasicLayoutTests.swift index 42d22d0cb..2a95a25fe 100644 --- a/Tests/SwiftLayoutTests/BasicLayoutTests.swift +++ b/Tests/SwiftLayoutTests/BasicLayoutTests.swift @@ -9,51 +9,51 @@ struct BasicLayoutTests { private let int16 = StaticTypeLayout.fixedWidthScalar(byteCount: 2) private let int8 = StaticTypeLayout.fixedWidthScalar(byteCount: 1) - @Test func threeWordFieldsArePackedAtEightByteStride() { - let result = BasicLayout.compute(startOffset: 0, startAlignmentMask: 0, fieldLayouts: [int, int, int]) + @Test func threeWordFieldsArePackedAtEightByteStride() throws { + let result = try BasicLayout.compute(startOffset: 0, startAlignmentMask: 0, fieldLayouts: [int, int, int]) #expect(result.fieldOffsets == [0, 8, 16]) #expect(result.size == 24) #expect(result.stride == 24) #expect(result.alignmentMask == 7) } - @Test func mixedAlignmentRoundsEachFieldUp() { + @Test func mixedAlignmentRoundsEachFieldUp() throws { // Int8 at 0, then Int needs 8-byte alignment -> jumps to offset 8. - let result = BasicLayout.compute(startOffset: 0, startAlignmentMask: 0, fieldLayouts: [int8, int]) + let result = try BasicLayout.compute(startOffset: 0, startAlignmentMask: 0, fieldLayouts: [int8, int]) #expect(result.fieldOffsets == [0, 8]) #expect(result.size == 16) #expect(result.stride == 16) #expect(result.alignmentMask == 7) } - @Test func smallFieldsPackTightlyByAlignment() { + @Test func smallFieldsPackTightlyByAlignment() throws { // Int8 at 0, Int16 aligned to 2 -> offset 2, Int32 aligned to 4 -> offset 4. - let result = BasicLayout.compute(startOffset: 0, startAlignmentMask: 0, fieldLayouts: [int8, int16, int32]) + let result = try BasicLayout.compute(startOffset: 0, startAlignmentMask: 0, fieldLayouts: [int8, int16, int32]) #expect(result.fieldOffsets == [0, 2, 4]) #expect(result.size == 8) #expect(result.stride == 8) #expect(result.alignmentMask == 3) } - @Test func trailingPaddingLandsOnlyInStride() { + @Test func trailingPaddingLandsOnlyInStride() throws { // Int at 0, Int8 at 8 -> size 9, but stride rounds up to 16. - let result = BasicLayout.compute(startOffset: 0, startAlignmentMask: 0, fieldLayouts: [int, int8]) + let result = try BasicLayout.compute(startOffset: 0, startAlignmentMask: 0, fieldLayouts: [int, int8]) #expect(result.fieldOffsets == [0, 8]) #expect(result.size == 9) #expect(result.stride == 16) #expect(result.alignmentMask == 7) } - @Test func emptyAggregateHasZeroSizeAndUnitStride() { - let result = BasicLayout.compute(startOffset: 0, startAlignmentMask: 0, fieldLayouts: []) + @Test func emptyAggregateHasZeroSizeAndUnitStride() throws { + let result = try BasicLayout.compute(startOffset: 0, startAlignmentMask: 0, fieldLayouts: []) #expect(result.fieldOffsets == []) #expect(result.size == 0) #expect(result.stride == 1) } - @Test func classStartsAtSuperclassInstanceSize() { + @Test func classStartsAtSuperclassInstanceSize() throws { // A root class instance starts at sizeof(HeapObject) == 16, 8-byte aligned. - let result = BasicLayout.compute(startOffset: 16, startAlignmentMask: 7, fieldLayouts: [int, int8]) + let result = try BasicLayout.compute(startOffset: 16, startAlignmentMask: 7, fieldLayouts: [int, int8]) #expect(result.fieldOffsets == [16, 24]) #expect(result.size == 25) #expect(result.stride == 32) diff --git a/Tests/SwiftLayoutTests/CacheRootDependencyLayoutTests.swift b/Tests/SwiftLayoutTests/CacheRootDependencyLayoutTests.swift index e9a0ccf37..e2a296ae2 100644 --- a/Tests/SwiftLayoutTests/CacheRootDependencyLayoutTests.swift +++ b/Tests/SwiftLayoutTests/CacheRootDependencyLayoutTests.swift @@ -12,7 +12,7 @@ import SwiftSectionFixtureSupport /// of the suite it decorates is a circular macro reference. enum ArchivedMacOS15LayoutFixtures { static let cachePath = DyldSharedCachePath.macOS_15_5 - static var hasCache: Bool { FileManager.default.fileExists(atPath: cachePath.rawValue) } + static var hasCache: Bool { FileManager.default.fileExists(atPath: cachePath.path) } static func swiftUICore() throws -> MachOFile { let cache = try FullDyldCache(path: cachePath) diff --git a/Tests/SwiftLayoutTests/DependencyClosureTests.swift b/Tests/SwiftLayoutTests/DependencyClosureTests.swift index 56fd12202..04e538619 100644 --- a/Tests/SwiftLayoutTests/DependencyClosureTests.swift +++ b/Tests/SwiftLayoutTests/DependencyClosureTests.swift @@ -165,7 +165,7 @@ final class DependencyClosureTests: MachOSwiftSectionFixtureTests, @unchecked Se @MainActor @Test func sameImageReachedUnderTwoLoadNamesIsCollectedOnce() throws { let root = machOFile - let helperFile = try #require(File.loadFromFile(url: URL(fileURLWithPath: Self.symbolTestsHelperOnDiskPath)).machOFiles.first) + let helperFile = try HostSlice.machOFile(at: URL(fileURLWithPath: Self.symbolTestsHelperOnDiskPath)) // Two of the root's direct load names, both answered by the same file. let locator = RecordingLocator(imagesByBareImageName: ["SymbolTestsHelper": helperFile, "libswiftCore": helperFile]) @@ -180,7 +180,7 @@ final class DependencyClosureTests: MachOSwiftSectionFixtureTests, @unchecked Se @MainActor @Test func customLocatorReceivesRawLoadNamesAndSuppliesTheImages() throws { let root = machOFile - let helperFile = try #require(File.loadFromFile(url: URL(fileURLWithPath: Self.symbolTestsHelperOnDiskPath)).machOFiles.first) + let helperFile = try HostSlice.machOFile(at: URL(fileURLWithPath: Self.symbolTestsHelperOnDiskPath)) let locator = RecordingLocator(imagesByBareImageName: ["SymbolTestsHelper": helperFile]) let closure = DependencyClosure(root: root, traversal: .direct, locator: locator) diff --git a/Tests/SwiftLayoutTests/MalformedBinaryLayoutTests.swift b/Tests/SwiftLayoutTests/MalformedBinaryLayoutTests.swift new file mode 100644 index 000000000..8e2474da5 --- /dev/null +++ b/Tests/SwiftLayoutTests/MalformedBinaryLayoutTests.swift @@ -0,0 +1,214 @@ +import Foundation +import Testing +import MachOKit +import MachOFoundation +import Demangling +@testable import MachOSwiftSection +@_spi(Internals) import SwiftInspection +@testable import SwiftLayout +import SwiftSectionFixtureSupport + +/// Inputs only a malformed binary carries, which made the static layout +/// engine trap, recurse until the stack ran out, or build without bound — +/// taking a host that reads untrusted binaries with it (2026-11-29 codebase +/// audit, findings 7–9). The binaries are a compiled library with a few bytes +/// rewritten; the ones that used to crash run in a child process. +@Suite +struct MalformedBinaryLayoutTests { + private static let moduleName = "MalformedBinaryLayoutFixture" + + /// `FixtureAnchor` is ballast: a fixture dylib with no class has no + /// `__DATA` segment, which older MachOKit releases mis-walked. + private static let source = """ + public final class FixtureAnchor {} + + public class Base { + public var base: Int = 0 + } + + public final class Derived: Base { + public var derived: Int8 = 0 + } + + public enum Choice { + case first(Int) + case second(String) + case third + case fourth + } + + public protocol Shape { + associatedtype Element + } + + public struct Circle: Shape { + public typealias Element = Int + } + + public struct Holder { + public var element: Item.Element + } + + // Room for a mangled name the test writes into the image. + public let witnessFiller = "\(String(repeating: "W", count: 160))" + """ + + private static func compiledLibrary() throws -> URL { + try FixtureCompiler.shared.dynamicLibrary( + named: moduleName, + language: .swift, + source: source, + arguments: ["-swift-version", "5", "-Onone", "-target", "arm64-apple-macosx15.0"] + ) + } + + private static func typeDescriptor(named name: String, in machOFile: MachOFile) throws -> TypeContextDescriptorWrapper { + try #require(try machOFile.swift.typeContextDescriptors.first { try $0.namedContextDescriptor.name(in: machOFile.context) == name }, "no \(name) in the fixture") + } + + private static func int32(at fileOffset: Int, in bytes: Data) -> Int32 { + bytes[fileOffset ..< fileOffset + 4].withUnsafeBytes { Int32(littleEndian: $0.loadUnaligned(as: Int32.self)) } + } + + // MARK: - Cases (finding 7) + + /// `Choice`'s empty-case count, raised past any enum a compiler emits. + /// A multi-payload enum's count sits at offset 24 of its descriptor + /// (flags, parent, name, accessor, fields, payload cases). + @Test func anEnumClaimingMoreCasesThanAnyCompilerEmitsIsNotProjected() throws { + let library = try Self.compiledLibrary() + let original = try HostSlice.machOFile(at: library) + let originalChoice = try Self.typeDescriptor(named: "Choice", in: original) + let originalCalculator = StaticLayoutCalculator(imageUniverse: try ImageUniverse.singleImage(original)) + try #require(originalCalculator.enumCaseLayoutResult(forDescriptor: originalChoice) != nil, "the unpatched enum projects no layout") + + let claimedEmptyCaseCount: UInt32 = 1 << 17 + let patched = try HostSlice.machOFile(at: try CompiledFixtureCopies.patchedCopy(of: library) { bytes, file in + let choice = try Self.typeDescriptor(named: "Choice", in: file) + CompiledFixtureCopies.write(claimedEmptyCaseCount, at: choice.typeContextDescriptor.offset + 24, in: &bytes) + }) + let choice = try Self.typeDescriptor(named: "Choice", in: patched) + try #require(choice.enum?.numberOfEmptyCases == Int(claimedEmptyCaseCount), "the patch missed the empty-case count") + let calculator = StaticLayoutCalculator(imageUniverse: try ImageUniverse.singleImage(patched)) + #expect(calculator.enumCaseLayoutResult(forDescriptor: choice) == nil) + } + + /// `getEnumTagCounts` does `unsigned` arithmetic, as the runtime's does, + /// and wraps where the Swift port trapped. + @Test func tagCountsOfAnEnumClaimingEveryEmptyCaseDoNotTrap() async { + await #expect(processExitsWith: .success) { + let counts = getEnumTagCounts(payloadSize: 1, emptyCases: .max, payloadCases: 1) + exit(counts.numTagBytes >= 0 ? EXIT_SUCCESS : 2) + } + } + + // MARK: - Sizes (finding 8) + + /// `(InlineArray<9223372036854775807, Int8>, Int8)`: the array's bytes + /// fit an `Int`, the next element's offset does not. + private static let overflowingTupleMangling = "s11InlineArrayVy$9223372036854775806_s4Int8VG_s4Int8Vt" + + @Test func aTupleWhoseElementOffsetOverflowsReadsAsUnknown() async { + await #expect(processExitsWith: .success) { + exit(Self.layOutTheOverflowingTuple()) + } + } + + private static func layOutTheOverflowingTuple() -> Int32 { + guard let libswiftCore = MachOImage(name: "libswiftCore"), + let universe = try? ImageUniverse.singleImage(libswiftCore), + let typeNode = try? demangleAsNode(overflowingTupleMangling, isType: true) + else { return EXIT_FAILURE } + let resolver = StaticTypeLayoutResolver(imageUniverse: universe) + do { + _ = try resolver.layout(forTypeNode: typeNode, in: universe.rootImage) + // A layout no value can have. + return 2 + } catch { + return EXIT_SUCCESS + } + } + + @Test func foldingAFieldPastIntMaxDoesNotTrap() async { + await #expect(processExitsWith: .success) { + let huge = StaticTypeLayout(size: .max, stride: .max, alignmentMask: 0, extraInhabitantCount: 0, isBitwiseTakable: true) + let byte = StaticTypeLayout(size: 1, stride: 1, alignmentMask: 0, extraInhabitantCount: 0, isBitwiseTakable: true) + let folded = try? BasicLayout.compute(startOffset: 0, startAlignmentMask: 0, fieldLayouts: [huge, byte]) + exit(folded == nil ? EXIT_SUCCESS : 2) + } + } + + // MARK: - Superclasses (finding 9) + + /// `Derived`'s superclass name pointed at the name its own field + /// descriptor starts with — itself. A class descriptor's superclass + /// pointer sits at offset 20 (flags, parent, name, accessor, fields), its + /// field-descriptor pointer at 16; a field descriptor starts with the + /// pointer to its type's name. + @Test func aClassThatIsItsOwnSuperclassReadsAsCyclic() async { + await #expect(processExitsWith: .success) { + exit(Self.layOutTheClassThatIsItsOwnSuperclass()) + } + } + + private static func layOutTheClassThatIsItsOwnSuperclass() -> Int32 { + do { + let patchedLibrary = try CompiledFixtureCopies.patchedCopy(of: try compiledLibrary()) { bytes, file in + let derived = try typeDescriptor(named: "Derived", in: file).typeContextDescriptor.offset + let fieldDescriptor = derived + 16 + Int(int32(at: derived + 16, in: bytes)) + let ownName = fieldDescriptor + Int(int32(at: fieldDescriptor, in: bytes)) + CompiledFixtureCopies.write(Int32(ownName - (derived + 20)), at: derived + 20, in: &bytes) + } + let patched = try HostSlice.machOFile(at: patchedLibrary) + guard case .class(let derived) = try typeDescriptor(named: "Derived", in: patched) else { return EXIT_FAILURE } + let calculator = StaticLayoutCalculator(imageUniverse: try ImageUniverse.singleImage(patched)) + // The superclass start is unknown, and every field with it. + let layout = try calculator.fieldLayout(of: .class(derived)) + let isCyclic = !layout.fields.isEmpty && layout.fields.allSatisfy { $0.resolution == .unknown(reason: .cyclicLayout) } + return isCyclic ? EXIT_SUCCESS : 2 + } catch { + return EXIT_FAILURE + } + } + + // MARK: - Associated types (finding 10) + + /// `Circle.Element`, spelled with `Circle` and `Shape` by name: an + /// associated type relative to a base type (`Qx`), `AA` the module. + private static let selfReferentialWitnessMangling = "\(moduleName.count)\(moduleName)6CircleV7ElementAA5ShapePQx" + + /// `Circle`'s witness for `Shape.Element` names `Circle.Element` — itself + /// — instead of `Int`. The image's one associated-type descriptor (two + /// names, a count, a record size) is followed by its record (a name, the + /// witness); the witness name is written over the filler string. + @Test func anAssociatedTypeWitnessNamingItselfReadsAsCyclic() async { + await #expect(processExitsWith: .success) { + exit(Self.layOutTheHolderOfTheSelfReferentialWitness()) + } + } + + private static func layOutTheHolderOfTheSelfReferentialWitness() -> Int32 { + do { + let witnessBytes = Data(selfReferentialWitnessMangling.utf8) + [0] + let patchedLibrary = try CompiledFixtureCopies.patchedCopy(of: try compiledLibrary()) { bytes, file in + guard let associatedTypes = file.sections64.first(where: { $0.sectionName == "__swift5_assocty" }), + let filler = bytes.range(of: Data(String(repeating: "W", count: 160).utf8)) + else { throw CompiledFixtureCopies.Failure(description: "no associated-type section or filler") } + bytes.replaceSubrange(filler.lowerBound ..< filler.lowerBound + witnessBytes.count, with: witnessBytes) + let witnessPointer = Int(associatedTypes.offset) + 16 + 4 + CompiledFixtureCopies.write(Int32(filler.lowerBound - witnessPointer), at: witnessPointer, in: &bytes) + } + let patched = try HostSlice.machOFile(at: patchedLibrary) + guard let witnessNode = try? demangleAsNode(selfReferentialWitnessMangling, isType: true), + witnessNode.first(of: .dependentMemberType) != nil, + let circle = try? demangleAsNode("\(moduleName.count)\(moduleName)6CircleV", isType: true) + else { return 4 } + let calculator = StaticLayoutCalculator(imageUniverse: try ImageUniverse.singleImage(patched)) + let layout = try fieldLayout(ofGenericQualifiedTypeName: "\(moduleName).Holder", genericArguments: [circle], with: calculator, in: patched) + guard let element = layout.fields.first(where: { $0.fieldName == "element" }) else { return 5 } + return element.resolution == .unknown(reason: .cyclicLayout) ? EXIT_SUCCESS : 2 + } catch { + return EXIT_FAILURE + } + } +} diff --git a/Tests/SwiftLayoutTests/NestedFieldExtentTests.swift b/Tests/SwiftLayoutTests/NestedFieldExtentTests.swift index 4c981e940..adf4e54f7 100644 --- a/Tests/SwiftLayoutTests/NestedFieldExtentTests.swift +++ b/Tests/SwiftLayoutTests/NestedFieldExtentTests.swift @@ -3,6 +3,7 @@ import MachOKit import MachOSwiftSection import SwiftLayout import Testing +import MachODependencies /// Real compiler-emitted records, independent of the shared SymbolTestsCore /// binary. The source layouts below are the expected values, not a snapshot of diff --git a/Tests/SwiftLayoutTests/NestedFieldOffsetOpaqueWitnessTests.swift b/Tests/SwiftLayoutTests/NestedFieldOffsetOpaqueWitnessTests.swift index 3fe47be72..2fb4ad9af 100644 --- a/Tests/SwiftLayoutTests/NestedFieldOffsetOpaqueWitnessTests.swift +++ b/Tests/SwiftLayoutTests/NestedFieldOffsetOpaqueWitnessTests.swift @@ -6,6 +6,7 @@ import MachOFoundation @_spi(Internals) import SwiftInspection @testable import SwiftLayout import Demangling +import SwiftSectionFixtureSupport /// The static expanded field-offset tree names a member of a concrete type by /// the type its conformance's witness record names (evolution proposal @@ -21,22 +22,6 @@ import Demangling /// member, `DynamicConcrete.Body`. @Suite struct NestedFieldOffsetOpaqueWitnessTests { - private enum FixtureWorkingDirectoryCleanup { - nonisolated(unsafe) static var directories: [URL] = [] - static let registration: Void = { - atexit { - for directory in FixtureWorkingDirectoryCleanup.directories { - try? FileManager.default.removeItem(at: directory) - } - } - }() - } - - private struct FixtureCompilationError: Swift.Error, CustomStringConvertible { - let diagnostics: String - var description: String { "nested-field-offset opaque-witness fixture compilation failed:\n\(diagnostics)" } - } - private static let moduleName = "NestedFieldOffsetOpaqueWitnessFixture" /// `FixtureAnchor` is ballast: a fixture dylib with no class has no @@ -78,48 +63,15 @@ struct NestedFieldOffsetOpaqueWitnessTests { } """ - private static let fixtureCompilationResult: Result = { - Result { - let workingDirectory = FileManager.default.temporaryDirectory - .appendingPathComponent("\(moduleName)-\(UUID().uuidString)") - try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) - _ = FixtureWorkingDirectoryCleanup.registration - FixtureWorkingDirectoryCleanup.directories.append(workingDirectory) - - let sourceURL = workingDirectory.appendingPathComponent("\(moduleName).swift") - let libraryURL = workingDirectory.appendingPathComponent("lib\(moduleName).dylib") - try fixtureSource.write(to: sourceURL, atomically: true, encoding: .utf8) - - let process = Process() - process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") - process.arguments = [ - "swiftc", "-swift-version", "5", "-O", "-emit-library", - "-module-name", moduleName, - "-target", "arm64-apple-macosx15.0", - sourceURL.path, "-o", libraryURL.path, - ] - let standardErrorPipe = Pipe() - process.standardError = standardErrorPipe - try process.run() - // Drain before waiting, or a long diagnostic deadlocks both sides. - let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() - process.waitUntilExit() - guard process.terminationStatus == 0 else { - throw FixtureCompilationError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) - } - return libraryURL - } - }() - + /// Compiled once per process by the shared compiler. private func loadFixtureMachOFile() throws -> MachOFile { - let libraryURL = try Self.fixtureCompilationResult.get() - switch try MachOKit.loadFromFile(url: libraryURL) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } + let libraryURL = try FixtureCompiler.shared.dynamicLibrary( + named: Self.moduleName, + language: .swift, + source: Self.fixtureSource, + arguments: ["-swift-version", "5", "-O", "-target", "arm64-apple-macosx15.0"] + ) + return try HostSlice.machOFile(at: libraryURL) } @Test("a member whose witness is an opaque type is not named by a placeholder", arguments: ["DynamicHolder", "ConditionalHolder"]) diff --git a/Tests/SwiftLayoutTests/RawLayoutBuiltinDescriptorLayoutTests.swift b/Tests/SwiftLayoutTests/RawLayoutBuiltinDescriptorLayoutTests.swift index 92e3c043f..90c4e7aaf 100644 --- a/Tests/SwiftLayoutTests/RawLayoutBuiltinDescriptorLayoutTests.swift +++ b/Tests/SwiftLayoutTests/RawLayoutBuiltinDescriptorLayoutTests.swift @@ -6,6 +6,7 @@ import Demangling @testable import MachOSwiftSection @testable import SwiftLayout @_spi(Internals) import SwiftInspection +import SwiftSectionFixtureSupport /// The fixture the two suites below share: a module with `@_rawLayout` /// enabled, compiled on the fly (it carries a class: a struct-only fixture @@ -22,22 +23,6 @@ import Demangling /// under Swift 6.4 or newer; the whole-type suite reads nothing but the /// struct declarations and runs everywhere. enum RawLayoutBuiltinDescriptorFixture { - private enum WorkingDirectoryCleanup { - nonisolated(unsafe) static var directories: [URL] = [] - static let registration: Void = { - atexit { - for directory in WorkingDirectoryCleanup.directories { - try? FileManager.default.removeItem(at: directory) - } - } - }() - } - - private struct CompilationError: Error, CustomStringConvertible { - let diagnostics: String - var description: String { "raw-layout layout fixture compilation failed:\n\(diagnostics)" } - } - static let moduleName = "ProbeRawLayoutLayout" private static let source = """ @@ -62,29 +47,8 @@ enum RawLayoutBuiltinDescriptorFixture { } """ - static let compilationResult: Result = { - Result { - let workingDirectory = FileManager.default.temporaryDirectory - .appendingPathComponent("RawLayoutLayoutFixture-\(UUID().uuidString)") - _ = WorkingDirectoryCleanup.registration - WorkingDirectoryCleanup.directories.append(workingDirectory) - try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) - let sourceURL = workingDirectory.appendingPathComponent("RawLayouts.swift") - try source.write(to: sourceURL, atomically: true, encoding: .utf8) - let libraryURL = workingDirectory.appendingPathComponent("lib\(moduleName).dylib") - let output = try run(swiftcArguments: [ - "-O", "-emit-library", "-module-name", moduleName, - "-enable-experimental-feature", "RawLayout", - "-target", "arm64-apple-macos27.0", - sourceURL.path, "-o", libraryURL.path, - ]) - guard output.terminationStatus == 0 else { throw CompilationError(diagnostics: output.standardError) } - return libraryURL - } - }() - /// `xcrun swiftc -version` reports a Swift 6.4 or newer toolchain — the - /// same toolchain `compilationResult` compiles the fixture with. + /// same toolchain `image()` compiles the fixture with. static let compilesWithSwift64OrNewer: Bool = { guard let output = try? run(swiftcArguments: ["-version"]), output.terminationStatus == 0 else { return false } let combined = output.standardOutput + output.standardError @@ -110,14 +74,19 @@ enum RawLayoutBuiltinDescriptorFixture { return (process.terminationStatus, String(decoding: standardOutputData, as: UTF8.self), String(decoding: standardErrorData, as: UTF8.self)) } + /// Compiled once per process by the shared compiler. static func image() throws -> MachOFile { - let libraryURL = try compilationResult.get() - switch try File.loadFromFile(url: libraryURL) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - return try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }) - } + let libraryURL = try FixtureCompiler.shared.dynamicLibrary( + named: moduleName, + language: .swift, + sourceFiles: [FixtureSourceFile(name: "RawLayouts.swift", contents: source)], + arguments: [ + "-O", + "-enable-experimental-feature", "RawLayout", + "-target", "arm64-apple-macos27.0", + ] + ) + return try HostSlice.machOFile(at: libraryURL) } } diff --git a/Tests/SwiftLayoutTests/SameNamedPrivateTypeLayoutTests.swift b/Tests/SwiftLayoutTests/SameNamedPrivateTypeLayoutTests.swift new file mode 100644 index 000000000..b14bbf659 --- /dev/null +++ b/Tests/SwiftLayoutTests/SameNamedPrivateTypeLayoutTests.swift @@ -0,0 +1,111 @@ +import Foundation +import Testing +import MachOKit +import MachOFoundation +@testable import MachOSwiftSection +@_spi(Internals) import SwiftInspection +@testable import SwiftLayout +import SwiftSectionFixtureSupport + +/// Two files of one module each declare a `private struct Storage`, of +/// different sizes, and each lays out a holder around its own. The layout +/// engine's type index used to key both on `Module.Storage`: the second +/// descriptor replaced the first, and the first file's holder was laid out +/// around the second file's `Storage` — wrong offsets, printed as computed +/// ones (2026-11-29 codebase audit, finding 1). +/// +/// With its symbols, the image names the anonymous context holding each +/// `Storage`, which carries the file's discriminator: the two get two keys. +/// Stripped, it no longer can; the name then resolves to neither, and the +/// field reads as unknown rather than as the other type. +@Suite +struct SameNamedPrivateTypeLayoutTests { + private static let moduleName = "SameNamedPrivateTypeLayoutFixture" + + /// `FixtureAnchor` is ballast: a fixture dylib with no class has no + /// `__DATA` segment, which older MachOKit releases mis-walked. + private static let firstFile = """ + public final class FixtureAnchor {} + + private struct Storage { + var byte: Int8 = 0 + } + + public struct NarrowHolder { + private var storage = Storage() + public var after: Int64 = 0 + public init() {} + } + """ + + private static let secondFile = """ + private struct Storage { + var first: Int64 = 0 + var second: Int64 = 0 + var third: Int64 = 0 + } + + public struct WideHolder { + private var storage = Storage() + public var after: Int8 = 0 + public init() {} + } + """ + + /// The holders as the compiler lays them out: `after` follows a one-byte + /// `Storage` at 8, a 24-byte one at 24. + private static let expectedLayouts: [(holderName: String, afterOffset: Int, size: Int)] = [ + ("NarrowHolder", 8, 16), + ("WideHolder", 24, 25), + ] + + private func compiledLibrary() throws -> URL { + try FixtureCompiler.shared.dynamicLibrary( + named: Self.moduleName, + language: .swift, + sourceFiles: [ + FixtureSourceFile(name: "NarrowStorage.swift", contents: Self.firstFile), + FixtureSourceFile(name: "WideStorage.swift", contents: Self.secondFile), + ], + arguments: ["-swift-version", "5", "-Onone", "-target", "arm64-apple-macosx15.0"] + ) + } + + private func holderLayout(named holderName: String, in machOFile: MachOFile) throws -> AggregateFieldLayout { + let descriptor = try #require( + try machOFile.swift.typeContextDescriptors.first { try $0.namedContextDescriptor.name(in: machOFile.context) == holderName }, + "no \(holderName) in the fixture" + ) + let calculator = StaticLayoutCalculator(imageUniverse: try ImageUniverse.singleImage(machOFile)) + return try calculator.fieldLayout(of: descriptor) + } + + @Test func eachHolderIsLaidOutAroundItsOwnFilesStorage() throws { + let machOFile = try HostSlice.machOFile(at: try compiledLibrary()) + for expected in Self.expectedLayouts { + let layout = try holderLayout(named: expected.holderName, in: machOFile) + let after = try #require(layout.fields.first { $0.fieldName == "after" }) + #expect(after.resolution == .computed, "\(expected.holderName).after: \(after.resolution)") + #expect(after.offset == expected.afterOffset, "\(expected.holderName).after") + #expect(layout.size == expected.size, "\(expected.holderName)") + } + } + + @Test func aStrippedImageReadsTheNameItCannotTellApartAsAmbiguous() throws { + // Without its local symbols, the `…MXX` symbols naming the anonymous + // contexts among them. + let machOFile = try HostSlice.machOFile(at: try CompiledFixtureCopies.strippedCopy(of: try compiledLibrary())) + for expected in Self.expectedLayouts { + let layout = try holderLayout(named: expected.holderName, in: machOFile) + let storage = try #require(layout.fields.first { $0.fieldName == "storage" }) + let after = try #require(layout.fields.first { $0.fieldName == "after" }) + if storage.resolution == .computed { + // Whatever still tells the two apart, the offsets are right. + #expect(after.resolution == .computed && after.offset == expected.afterOffset, "\(expected.holderName).after: \(after.resolution) at \(after.offset)") + } else { + #expect(storage.resolution == .unknown(reason: .ambiguousTypeName(qualifiedTypeName: "\(Self.moduleName).Storage")), "\(expected.holderName).storage: \(storage.resolution)") + #expect(after.resolution != .computed, "\(expected.holderName).after: \(after.resolution)") + } + } + } +} diff --git a/Tests/SwiftLayoutTests/SameTypePinnedParameterLayoutTests.swift b/Tests/SwiftLayoutTests/SameTypePinnedParameterLayoutTests.swift index d8620d74d..326b25928 100644 --- a/Tests/SwiftLayoutTests/SameTypePinnedParameterLayoutTests.swift +++ b/Tests/SwiftLayoutTests/SameTypePinnedParameterLayoutTests.swift @@ -7,6 +7,7 @@ import MachOFoundation @testable import SwiftLayout @testable import SwiftSectionTestingSupport import Demangling +import SwiftStdlibToolbox /// Validates concrete same-type pinning: a generic parameter pinned to a /// concrete type by a **constrained extension** (`extension Foo where Value == diff --git a/Tests/SwiftLayoutTests/SimulatorRuntimeObjCAncestorLayoutTests.swift b/Tests/SwiftLayoutTests/SimulatorRuntimeObjCAncestorLayoutTests.swift index fafdd3c56..c466580ba 100644 --- a/Tests/SwiftLayoutTests/SimulatorRuntimeObjCAncestorLayoutTests.swift +++ b/Tests/SwiftLayoutTests/SimulatorRuntimeObjCAncestorLayoutTests.swift @@ -4,6 +4,7 @@ import MachOKit import MachOFoundation @testable import MachOSwiftSection @testable import SwiftLayout +import SwiftSectionFixtureSupport /// Where the simulator-runtime-gated suite below finds its runtime. A /// separate type on purpose: a `@Suite(.enabled(if:))` condition that reads a @@ -21,13 +22,7 @@ enum IOS18SimulatorRuntimeFixtures { }() static func swiftUI(underRuntimeRoot runtimeRootPath: String) throws -> MachOFile { - let url = URL(fileURLWithPath: "\(runtimeRootPath)/System/Library/Frameworks/SwiftUI.framework/SwiftUI") - switch try MachOKit.loadFromFile(url: url) { - case .machO(let thinFile): - return thinFile - case .fat(let fatFile): - return try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }, "the runtime's SwiftUI has no arm64 slice") - } + try HostSlice.machOFile(at: URL(fileURLWithPath: "\(runtimeRootPath)/System/Library/Frameworks/SwiftUI.framework/SwiftUI")) } } diff --git a/Tests/SwiftObjCInteropTests/ObjCInstanceVariableSwiftTypeTests.swift b/Tests/SwiftObjCInteropTests/ObjCInstanceVariableSwiftTypeTests.swift new file mode 100644 index 000000000..8fa7dc5b1 --- /dev/null +++ b/Tests/SwiftObjCInteropTests/ObjCInstanceVariableSwiftTypeTests.swift @@ -0,0 +1,150 @@ +import Foundation +import Testing +import MachOKit +import MachOFoundation +import SwiftSectionFixtureSupport +@_spi(Internals) import Demangling +@testable import MachOSwiftSection +@_spi(Internals) @testable import SwiftInspection +@_spi(Internals) @testable import SwiftObjCInterop + +/// The Swift type behind an `@objc @implementation` ivar's encoding +/// (evolution proposal `objc-ivar-type-recovery`), checked encoding by +/// encoding against AppKit loaded into the test process, which only serves as +/// the image class names are looked up in. +@Suite +struct ObjCInstanceVariableSwiftTypeTests { + private static func appKit() throws -> MachOImage { + _ = dlopen("/System/Library/Frameworks/AppKit.framework/AppKit", RTLD_NOW) + return try #require(MachOImage(named: .AppKit)) + } + + private static func instanceVariable(encoding: String, size: Int = 8) -> ObjCImplementationClassFacts.InstanceVariable { + ObjCImplementationClassFacts.InstanceVariable(name: "storage", offset: 8, size: size, alignment: 8, typeEncoding: encoding, swiftFieldOffsetSymbolName: nil, swiftPropertyName: nil, swiftTypeNode: nil) + } + + /// The printed type recovered from an ivar with `encoding`, or `nil`. + private static func recoveredType(encoding: String, propertyAttributes: String? = nil) throws -> String? { + let objcProperty = propertyAttributes.map { ObjCImplementationClassFacts.Property(name: "storage", attributes: $0) } + return ObjCInstanceVariableSwiftType(instanceVariable: instanceVariable(encoding: encoding), objcProperty: objcProperty, in: try appKit()) + .map { $0.typeNode.print(using: .interface) } + } + + /// How the fixed print preset spells the class named `runtimeName`, which + /// is how a class the recovery keeps prints, whatever the spelling of + /// imported names. + private static func printedClass(_ runtimeName: String) throws -> String { + ObjCRuntimeNames.classNode(forRuntimeName: runtimeName, in: try appKit()).print(using: .interface) + } + + /// The importer's type for an Objective-C type, as a declaration imports it. + private static func importedType(_ encoding: String) throws -> String { + let type = try #require(ObjCTypeEncodingParser.type(from: encoding)) + return ObjCImportedTypes(machO: try appKit()).typeNode(type, position: .topLevel).print(using: .interface) + } + + @Test func completeEncodingOfABridgeableClassKeepsTheClass() throws { + // A Swift `NSString` property: the compiler writes `@"NSString"` only + // because the type is the class itself, never for a `String`. + let string = try Self.recoveredType(encoding: "@\"NSString\"") + #expect(string == (try Self.printedClass("NSString")) + "!") + #expect(string != (try Self.importedType("@\"NSString\""))) + let array = try Self.recoveredType(encoding: "@\"NSArray\"") + #expect(array == (try Self.printedClass("NSArray")) + "!") + } + + @Test func completeEncodingOfABareIdIsAnyObject() throws { + #expect(try Self.recoveredType(encoding: "@") == "Swift.AnyObject!") + } + + @Test func completeEncodingOfAProtocolIsTheExistential() throws { + // As the importer gives it: no bridging touches a protocol. + let existential = try Self.recoveredType(encoding: "@\"\"") + #expect(existential == (try Self.importedType("@\"\""))) + #expect(existential?.hasSuffix("!") == true) + } + + @Test func scalarEncodingsNameTheirSwiftTypes() throws { + #expect(try Self.recoveredType(encoding: "B") == "Swift.Bool") + #expect(try Self.recoveredType(encoding: "d") == "Swift.Double") + #expect(try Self.recoveredType(encoding: "q") == "Swift.Int") + #expect(try Self.recoveredType(encoding: "^d") == "Swift.UnsafeMutablePointer!") + } + + @Test func encodingsThatDoNotDetermineATypeRecoverNothing() throws { + // A block's signature is in no ivar encoding. + #expect(try Self.recoveredType(encoding: "@?") == nil) + // A CF type and a pointer to a structure encode alike. + #expect(try Self.recoveredType(encoding: "^{CGColor=}") == nil) + #expect(try Self.recoveredType(encoding: "{?=ii}") == nil) + #expect(try Self.recoveredType(encoding: "b3") == nil) + #expect(try Self.recoveredType(encoding: "") == nil) + } + + @Test func bridgedEncodingTakesTheImportedTypeOfTheObjCProperty() throws { + #expect(try Self.recoveredType(encoding: "?", propertyAttributes: "T@\"NSString\",C,N,Vstorage") == "Swift.String!") + #expect(try Self.recoveredType(encoding: "?", propertyAttributes: "T@\"NSArray\",C,N,Vstorage") == (try Self.importedType("@\"NSArray\""))) + #expect(try Self.recoveredType(encoding: "?", propertyAttributes: "T@,&,N,Vstorage") == (try Self.importedType("@"))) + let appKit = try Self.appKit() + let bridged = try #require(ObjCInstanceVariableSwiftType(instanceVariable: Self.instanceVariable(encoding: "?"), objcProperty: .init(name: "storage", attributes: "T@\"NSString\",C,N,Vstorage"), in: appKit)) + #expect(bridged.source == .objcProperty) + } + + @Test func bridgedEncodingWithoutATypedObjCPropertyRecoversNothing() throws { + #expect(try Self.recoveredType(encoding: "?") == nil) + // The `?` proves the type is no Objective-C class: a class imported as + // itself is an `unowned` property's storage or a bridging the table + // does not know, and says nothing reliable. + #expect(try Self.recoveredType(encoding: "?", propertyAttributes: "T@\"NSObject\",&,N,Vstorage") == nil) + #expect(try Self.recoveredType(encoding: "?", propertyAttributes: "T@\"\",&,N,Vstorage") == nil) + #expect(try Self.recoveredType(encoding: "?", propertyAttributes: "Tq,N,Vstorage") == nil) + // A Swift closure bridges to a block, whose attribute has no signature. + #expect(try Self.recoveredType(encoding: "?", propertyAttributes: "T@?,C,N,Vstorage") == nil) + } + + @Test func weakStorageReadsItsClassUnbridged() throws { + // `weak` makes the compiler write `?` for any class, and holds no + // value type: `NSString` stays a class. + #expect(try Self.recoveredType(encoding: "?", propertyAttributes: "T@\"NSObject\",W,N,Vstorage") == (try Self.printedClass("NSObject")) + "?") + #expect(try Self.recoveredType(encoding: "?", propertyAttributes: "T@\"NSString\",W,N,Vstorage") == (try Self.printedClass("NSString")) + "?") + } + + @Test func readOnlyAndWeakAreReadOffTheObjCProperty() throws { + let appKit = try Self.appKit() + let readOnly = try #require(ObjCInstanceVariableSwiftType(instanceVariable: Self.instanceVariable(encoding: "q"), objcProperty: .init(name: "storage", attributes: "Tq,R,N,Vstorage"), in: appKit)) + #expect(readOnly.isReadOnly) + #expect(!readOnly.isWeak) + #expect(readOnly.source == .instanceVariableEncoding) + let settable = try #require(ObjCInstanceVariableSwiftType(instanceVariable: Self.instanceVariable(encoding: "q"), objcProperty: nil, in: appKit)) + #expect(!settable.isReadOnly) + let weak = try #require(ObjCInstanceVariableSwiftType(instanceVariable: Self.instanceVariable(encoding: "?"), objcProperty: .init(name: "storage", attributes: "T@\"NSObject\",W,N,Vstorage"), in: appKit)) + #expect(weak.isWeak) + #expect(!weak.isReadOnly) + } + + /// The compiler gives a `weak` and an `unowned(unsafe)` property the same + /// `?` ivar and `W` attribute, and a read-only one bridged to a value the + /// same `R` as a read-only `unowned(unsafe)` class — told apart only by + /// the storage, one pointer for `unowned(unsafe)` (2026-11-29 codebase + /// audit, finding 2). + @Test func objCPropertiesTwoDeclarationsShareSayWhatElseTheyMayBe() throws { + let appKit = try Self.appKit() + func recovered(_ attributes: String, size: Int = 8) throws -> ObjCInstanceVariableSwiftType { + try #require(ObjCInstanceVariableSwiftType(instanceVariable: Self.instanceVariable(encoding: "?", size: size), objcProperty: .init(name: "storage", attributes: attributes), in: appKit)) + } + let weakOrUnownedUnsafe = try recovered("T@\"NSObject\",W,N,Vstorage") + #expect(weakOrUnownedUnsafe.ambiguity == .weakOrUnownedUnsafe) + #expect(weakOrUnownedUnsafe.alternativeDeclarationNote(named: "storage") == "or unowned(unsafe) var storage: NSObject: the Objective-C property reads the same for both") + + let readOnlyClass = try recovered("T@\"NSArray\",R,N,Vstorage") + #expect(readOnlyClass.ambiguity == .bridgedValueOrUnownedUnsafeClass(className: "NSArray")) + #expect(readOnlyClass.alternativeDeclarationNote(named: "storage") == "or unowned(unsafe) let storage: NSArray: the Objective-C property reads the same for both") + #expect(try recovered("T@,R,N,Vstorage").ambiguity == .bridgedValueOrUnownedUnsafeClass(className: nil)) + + // Two words of storage hold a `String`, never one class reference. + #expect(try recovered("T@\"NSString\",R,N,Vstorage", size: 16).ambiguity == nil) + // A settable bridged property is `C`; no `unowned(unsafe)` one is. + #expect(try recovered("T@\"NSString\",C,N,Vstorage").ambiguity == nil) + #expect(try recovered("T@\"NSString\",C,N,Vstorage").alternativeDeclarationNote(named: "storage") == nil) + } +} diff --git a/Tests/SwiftObjCInteropTests/ObjCTypeEncodingNestingTests.swift b/Tests/SwiftObjCInteropTests/ObjCTypeEncodingNestingTests.swift new file mode 100644 index 000000000..73a035810 --- /dev/null +++ b/Tests/SwiftObjCInteropTests/ObjCTypeEncodingNestingTests.swift @@ -0,0 +1,37 @@ +import Foundation +import Testing +@_spi(Internals) @testable import SwiftObjCInterop + +/// A type encoding nesting deeper than any declaration spells — a malformed +/// binary's method or property type. The reader recursed once per level, and +/// ten thousand `^`s ran the thread out of stack, taking the host with it +/// (2026-11-29 codebase audit, finding 13). +@Suite +struct ObjCTypeEncodingNestingTests { + @Test func aPointerChainNestingPastTheLimitReadsAsNoType() async { + await #expect(processExitsWith: .success) { + let encoding = String(repeating: "^", count: 200_000) + "i" + exit(ObjCTypeEncodingParser.type(from: encoding) == nil ? EXIT_SUCCESS : 2) + } + } + + @Test func nestedArraysAndBlocksPastTheLimitReadAsNoType() async { + await #expect(processExitsWith: .success) { + let arrays = String(repeating: "[1", count: 200_000) + "i" + String(repeating: "]", count: 200_000) + let blocks = String(repeating: "@?<", count: 200_000) + "v" + String(repeating: "@?>", count: 200_000) + let isRejected = ObjCTypeEncodingParser.type(from: arrays) == nil + && ObjCTypeEncodingParser.methodType(from: "v16@0:8" + blocks) == nil + exit(isRejected ? EXIT_SUCCESS : 2) + } + } + + @Test func nestingWithinTheLimitStillReads() { + let depth = ObjCTypeEncodingParser.maximumNestingDepth + var expected = ObjCEncodedType.int + for _ in 0 ..< depth { + expected = .pointer(expected, isConst: false) + } + #expect(ObjCTypeEncodingParser.type(from: String(repeating: "^", count: depth) + "i") == expected) + #expect(ObjCTypeEncodingParser.type(from: String(repeating: "^", count: depth + 1) + "i") == nil) + } +} diff --git a/Tests/SwiftPrintingTests/ConcurrentDefinitionPrintingTests.swift b/Tests/SwiftPrintingTests/ConcurrentDefinitionPrintingTests.swift index 2e4a8b299..5a2e3fed8 100644 --- a/Tests/SwiftPrintingTests/ConcurrentDefinitionPrintingTests.swift +++ b/Tests/SwiftPrintingTests/ConcurrentDefinitionPrintingTests.swift @@ -9,6 +9,7 @@ import SwiftDeclarationRendering @_spi(Support) @testable import SwiftPrinting @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import OrderedCollections /// Printing the SymbolTestsCore fixture's definitions from several tasks at /// once reads byte for byte as printing them one after another (evolution diff --git a/Tests/SwiftPrintingTests/EnumCaseRenderingParityTests.swift b/Tests/SwiftPrintingTests/EnumCaseRenderingParityTests.swift index 731524a94..b304ca670 100644 --- a/Tests/SwiftPrintingTests/EnumCaseRenderingParityTests.swift +++ b/Tests/SwiftPrintingTests/EnumCaseRenderingParityTests.swift @@ -8,6 +8,8 @@ import Demangling @testable import MachOSwiftSection @testable import SwiftSectionTestingSupport import SwiftDump +import Semantic +import SwiftDeclarationRendering // MARK: - In-process fixture diff --git a/Tests/SwiftPrintingTests/InitializerFailabilityPrintingTests.swift b/Tests/SwiftPrintingTests/InitializerFailabilityPrintingTests.swift index 3ae95af16..8a27500d8 100644 --- a/Tests/SwiftPrintingTests/InitializerFailabilityPrintingTests.swift +++ b/Tests/SwiftPrintingTests/InitializerFailabilityPrintingTests.swift @@ -1,6 +1,7 @@ @_spi(Support) @testable import SwiftPrinting import Demangling import Testing +import Semantic /// An initializer is failable when ITS OWN result is `Optional` — not /// when an Optional appears somewhere else in its signature. diff --git a/Tests/SwiftPrintingTests/NodeKindParityTests.swift b/Tests/SwiftPrintingTests/NodeKindParityTests.swift index 5b6efad22..f7b194602 100644 --- a/Tests/SwiftPrintingTests/NodeKindParityTests.swift +++ b/Tests/SwiftPrintingTests/NodeKindParityTests.swift @@ -6,6 +6,8 @@ import MachOKit import MachOFoundation import MachOSwiftSection @_spi(Internals) import SwiftInspection +import SwiftSectionFixtureSupport +import Semantic // MARK: - Shared survey @@ -179,7 +181,7 @@ struct NodeKindParityTests { ] @Test func noTypePositionKindRendersEmpty() async throws { - let cache = try DyldCache(path: .current) + let cache = try #require(FullDyldCache.cachedHost, "no host dyld shared cache").mainCache let machOFile = try #require(cache.machOFile(named: .SwiftUI), "the running system's cache has no SwiftUI") let result = try await NodeKindParitySurvey.run(on: machOFile) @@ -206,7 +208,7 @@ struct NodeKindParityTests { @Suite(.disabled("Research probe — enable explicitly when auditing printer parity")) struct NodeKindParityProbe { @Test func reportsEveryKindAndSample() async throws { - let cache = try DyldCache(path: .current) + let cache = try #require(FullDyldCache.cachedHost, "no host dyld shared cache").mainCache let machOFile = try #require(cache.machOFile(named: .SwiftUI), "the running system's cache has no SwiftUI") let result = try await NodeKindParitySurvey.run(on: machOFile) diff --git a/Tests/SwiftPrintingTests/NodePrinterTests.swift b/Tests/SwiftPrintingTests/NodePrinterTests.swift index 246c98329..8873e1cf2 100644 --- a/Tests/SwiftPrintingTests/NodePrinterTests.swift +++ b/Tests/SwiftPrintingTests/NodePrinterTests.swift @@ -12,6 +12,7 @@ import SwiftSectionFixtureSupport @testable import SwiftDump @testable import SwiftInterface @testable @_spi(Internals) import SwiftInspection +import Semantic // MARK: - Unit Tests (Self-contained, no external dependencies) diff --git a/Tests/SwiftPrintingTests/PackExpansionRenderingTests.swift b/Tests/SwiftPrintingTests/PackExpansionRenderingTests.swift index 5ba0bc534..940bae328 100644 --- a/Tests/SwiftPrintingTests/PackExpansionRenderingTests.swift +++ b/Tests/SwiftPrintingTests/PackExpansionRenderingTests.swift @@ -2,6 +2,7 @@ import Foundation import Demangling import Testing +import Semantic /// Pins the `each` / `repeat` spelling of parameter packs. /// diff --git a/Tests/SwiftPrintingTests/RecordingPrinterTargetTests.swift b/Tests/SwiftPrintingTests/RecordingPrinterTargetTests.swift index ea295f818..adbd7b0fa 100644 --- a/Tests/SwiftPrintingTests/RecordingPrinterTargetTests.swift +++ b/Tests/SwiftPrintingTests/RecordingPrinterTargetTests.swift @@ -1,6 +1,7 @@ @_spi(Support) @testable import SwiftPrinting import Demangling import Testing +import Semantic /// A `NodePrinterTarget` that records every call the printers make. /// diff --git a/Tests/SwiftPrivateDiscriminatorsTests/PrivateDiscriminatorSourceFileIndexTests.swift b/Tests/SwiftPrivateDiscriminatorsTests/PrivateDiscriminatorSourceFileIndexTests.swift index f6c827974..8fe6f83ef 100644 --- a/Tests/SwiftPrivateDiscriminatorsTests/PrivateDiscriminatorSourceFileIndexTests.swift +++ b/Tests/SwiftPrivateDiscriminatorsTests/PrivateDiscriminatorSourceFileIndexTests.swift @@ -7,6 +7,8 @@ import SwiftSectionFixtureSupport import SwiftInspection import SwiftDeclarationRendering @testable @_spi(Support) import SwiftPrivateDiscriminators +import OrderedCollections +import SwiftDeclaration /// An image's private discriminators, recovered from candidates the image's /// own names make (evolution proposal `private-declarations`). diff --git a/Tests/SwiftPrivateDiscriminatorsTests/PrivateDiscriminatorSourceFileSystemImageTests.swift b/Tests/SwiftPrivateDiscriminatorsTests/PrivateDiscriminatorSourceFileSystemImageTests.swift index 706959d3f..0be450479 100644 --- a/Tests/SwiftPrivateDiscriminatorsTests/PrivateDiscriminatorSourceFileSystemImageTests.swift +++ b/Tests/SwiftPrivateDiscriminatorsTests/PrivateDiscriminatorSourceFileSystemImageTests.swift @@ -1,10 +1,13 @@ import Foundation import Testing import MachOKit +import MachOKitExtensions import SwiftSectionFixtureSupport @_spi(Support) import SwiftIndexing import SwiftInspection @_spi(Support) import SwiftPrivateDiscriminators +import OrderedCollections +import SwiftDeclaration /// Private discriminators of the running system's own images, read out of its /// dyld shared cache (evolution proposal `private-declarations`). @@ -17,7 +20,7 @@ import SwiftInspection struct PrivateDiscriminatorSourceFileSystemImageTests { /// A private class's discriminator, found through the class's own name. @Test func systemFoundationRecoversJSONEncoder() async throws { - let cache = try DyldCache(path: .current) + let cache = try #require(FullDyldCache.cachedHost, "no host dyld shared cache").mainCache let foundation = try #require(cache.machOFile(named: .Foundation)) let indexer = SwiftDeclarationIndexer(configuration: .init(), eventHandlers: [], in: foundation) try await indexer.prepare() @@ -34,7 +37,7 @@ struct PrivateDiscriminatorSourceFileSystemImageTests { /// from the image's file name recovers them. No known file names, so the /// file name too comes from the image's names (`EnabledKey`). @Test func systemSwiftUICoreHashesItsOwnModuleName() async throws { - let cache = try DyldCache(path: .current) + let cache = try #require(FullDyldCache.cachedHost, "no host dyld shared cache").mainCache let swiftUICore = try #require(cache.machOFile(named: .SwiftUICore)) let indexer = SwiftDeclarationIndexer(configuration: .init(), eventHandlers: [], in: swiftUICore) try await indexer.prepare() diff --git a/Tests/SwiftSectionCommandTests/CommandLineErrorTranslationTests.swift b/Tests/SwiftSectionCommandTests/CommandLineErrorTranslationTests.swift index 437d22f83..1a885b501 100644 --- a/Tests/SwiftSectionCommandTests/CommandLineErrorTranslationTests.swift +++ b/Tests/SwiftSectionCommandTests/CommandLineErrorTranslationTests.swift @@ -13,7 +13,7 @@ struct CommandLineErrorTranslationTests { @Test("A fat binary without -a names the option, and the slices") func fatBinary() { let translated = CommandLineErrorTranslation.translated(MachOSourceError.fatBinaryRequiresArchitecture(availableArchitectures: ["arm64", "x86_64"])) - #expect((translated as? LocalizedError)?.errorDescription == "The file is a fat (universal) binary. You must specify an architecture using --architecture (-a). Available architectures: arm64, x86_64") + #expect((translated as? (any LocalizedError))?.errorDescription == "The file is a fat (universal) binary. You must specify an architecture using --architecture (-a). Available architectures: arm64, x86_64") } @Test("The other loading errors keep their historical wording", arguments: [ @@ -21,7 +21,7 @@ struct CommandLineErrorTranslationTests { (.dyldSharedCacheImageNotFound(.name("Foundation")), "The specified image was not found in the dyld shared cache."), ]) func loadingErrors(error: MachOSourceError, expectedDescription: String) { - #expect((CommandLineErrorTranslation.translated(error) as? LocalizedError)?.errorDescription == expectedDescription) + #expect((CommandLineErrorTranslation.translated(error) as? (any LocalizedError))?.errorDescription == expectedDescription) } @Test("A snapshot document given to diff --interface is a usage error in diff's words") diff --git a/Tests/SwiftSectionCommandTests/CommandRequestMappingTests.swift b/Tests/SwiftSectionCommandTests/CommandRequestMappingTests.swift index 6e16f97a8..2b74dd90f 100644 --- a/Tests/SwiftSectionCommandTests/CommandRequestMappingTests.swift +++ b/Tests/SwiftSectionCommandTests/CommandRequestMappingTests.swift @@ -4,6 +4,9 @@ import ArgumentParser import MachOFoundation import SwiftSectionKit @testable import swift_section +import SwiftOutputTransformer +import Demangling +import SwiftPrinting /// The wrapper's one job besides wording and streams: turning flags into the /// library request. A flag that stops reaching its field produces a @@ -150,6 +153,23 @@ struct CommandRequestMappingTests { #expect(request.expandsMacros) } + @Test("interface resolves moved Swift types' modules only with --resolve-moved-type-modules") + func resolveMovedTypeModulesFlagMapsOntoTheRequest() throws { + let defaultRequest = try InterfaceCommand.parse(["/tmp/Sample"]).makeRequest() + #expect(defaultRequest.resolvesMovedTypeModules == false) + #expect(InterfaceRequest(source: defaultRequest.source).resolvesMovedTypeModules == false) + let request = try InterfaceCommand.parse(["/tmp/Sample", "--resolve-moved-type-modules"]).makeRequest() + #expect(request.resolvesMovedTypeModules) + #expect(request.cModuleNameResolution == .disabled) + } + + @Test("--resolve-c-module-names and --resolve-moved-type-modules combine") + func bothResolutionFlagsCombine() throws { + let request = try InterfaceCommand.parse(["/tmp/Sample", "--resolve-c-module-names", "--resolve-moved-type-modules"]).makeRequest() + #expect(request.resolvesMovedTypeModules) + #expect(request.cModuleNameResolution == .enabled(supplementaryAPINotesPaths: [])) + } + @Test("interface prints without module selectors unless asked") func interfaceModuleSelectorsDefaultOff() throws { #expect(try InterfaceCommand.parse(["/tmp/Sample"]).makeRequest().usesModuleSelectors == false) @@ -163,6 +183,16 @@ struct CommandRequestMappingTests { #expect(try InterfaceCommand.parse(["/tmp/Sample", "--no-existential-any"]).makeRequest().usesExistentialAny == false) } + @Test("interface spells C-imported types by their Swift names unless --c-imported-type-name-spelling c-name") + func interfaceCImportedTypeNameSpelling() throws { + let defaultRequest = try InterfaceCommand.parse(["/tmp/Sample"]).makeRequest() + #expect(defaultRequest.cImportedTypeNameSpelling == .swiftName) + #expect(InterfaceRequest(source: defaultRequest.source).cImportedTypeNameSpelling == .swiftName) + #expect(try InterfaceCommand.parse(["/tmp/Sample", "--c-imported-type-name-spelling", "c-name"]).makeRequest().cImportedTypeNameSpelling == .cName) + #expect(try InterfaceCommand.parse(["/tmp/Sample", "--c-imported-type-name-spelling", "swift-name"]).makeRequest().cImportedTypeNameSpelling == .swiftName) + #expect(throws: (any Error).self) { try InterfaceCommand.parse(["/tmp/Sample", "--c-imported-type-name-spelling", "cName"]) } + } + @Test("interface folds what an attached macro generated unless --expand-macros") func interfaceExpandMacros() throws { let defaultRequest = try InterfaceCommand.parse(["/tmp/Sample"]).makeRequest() diff --git a/Tests/SwiftSectionCommandTests/CrossReferenceCommandTests.swift b/Tests/SwiftSectionCommandTests/CrossReferenceCommandTests.swift index 026f3a325..1c50f8a16 100644 --- a/Tests/SwiftSectionCommandTests/CrossReferenceCommandTests.swift +++ b/Tests/SwiftSectionCommandTests/CrossReferenceCommandTests.swift @@ -50,6 +50,8 @@ struct CrossReferenceCommandTests { (["--function", "4096", "--function-image", "Foo"], .function(address: 4096, imageName: "Foo")), (["--ivar", "NSWindow._frame"], .instanceVariable(className: "NSWindow", name: "_frame")), (["--string", "NSWindowDidBecomeKeyNotification"], .string("NSWindowDidBecomeKeyNotification")), + (["--type", "7SwiftUI4TextV"], .swiftType("7SwiftUI4TextV", imageName: nil)), + (["--type", "$s7SwiftUI4TextVMa", "--type-image", "SwiftUICore"], .swiftType("$s7SwiftUI4TextVMa", imageName: "SwiftUICore")), ]) func refsMapsEachQuery(arguments: [String], subject: CrossReferenceSubject) throws { let request = try ReferencesCommand.parse(arguments + ["--uses-system-dyld-shared-cache"]).makeRequest() @@ -70,6 +72,8 @@ struct CrossReferenceCommandTests { ["--ivar", "Trailing."], ["--function", "nowhere"], ["--selector", "init", "--limit", "0"], + ["--selector", "init", "--type-image", "Foo"], + ["--selector", "init", "--type", "7SwiftUI4TextV"], ]) func refsRefusesIncompleteFlags(arguments: [String]) { #expect(throws: (any Error).self) { try ReferencesCommand.parse(arguments + ["--uses-system-dyld-shared-cache"]) } @@ -103,5 +107,8 @@ struct CrossReferenceCommandTests { let ambiguous = CommandLineErrorTranslation.translated(CrossReferenceRequestError.ambiguousFunction(address: 0x10, imagePaths: ["/tmp/A", "/tmp/B"])) #expect((ambiguous as? ValidationError)?.message.contains("--function-image") == true) #expect(CommandLineErrorTranslation.translated(CrossReferenceRequestError.noFunction(address: 0x10)) is CrossReferenceRequestError) + let unexportedType = CommandLineErrorTranslation.translated(CrossReferenceRequestError.swiftTypeNeedsImage(mangling: "7SwiftUI13PinnedBarViewC")) + #expect((unexportedType as? ValidationError)?.message.contains("--type-image") == true) + #expect(CommandLineErrorTranslation.translated(CrossReferenceRequestError.swiftTypeNotFound(mangling: "3Foo3BarV")) is CrossReferenceRequestError) } } diff --git a/Tests/SwiftSectionCommandTests/MultilineTypesFlagTests.swift b/Tests/SwiftSectionCommandTests/MultilineTypesFlagTests.swift new file mode 100644 index 000000000..1c75ffbe3 --- /dev/null +++ b/Tests/SwiftSectionCommandTests/MultilineTypesFlagTests.swift @@ -0,0 +1,59 @@ +import Foundation +import Testing +import ArgumentParser +import SwiftSectionKit +import SwiftDeclarationRendering +@testable import swift_section + +/// `--multiline-types` and `--maximum-line-width` on `dump` and `interface` +/// (evolution proposal `multiline-type-formatting`): off by default, mapped +/// onto the request's `multilineTypeFormatting`, and a width without the flag +/// or below one column is a usage error, exit code 64. +@Suite +struct MultilineTypesFlagTests { + @Test func formattingIsOffByDefault() throws { + #expect(try DumpCommand.parse(["/tmp/example"]).makeRequest().multilineTypeFormatting == nil) + #expect(try InterfaceCommand.parse(["/tmp/example"]).makeRequest().multilineTypeFormatting == nil) + } + + @Test func multilineTypesFlagMapsOntoTheRequest() throws { + #expect(try DumpCommand.parse(["/tmp/example", "--multiline-types"]).makeRequest().multilineTypeFormatting == MultilineTypeFormatting()) + #expect(try InterfaceCommand.parse(["/tmp/example", "--multiline-types"]).makeRequest().multilineTypeFormatting == MultilineTypeFormatting()) + } + + @Test func maximumLineWidthMapsOntoTheRequest() throws { + let arguments = ["/tmp/example", "--multiline-types", "--maximum-line-width", "120"] + #expect(try DumpCommand.parse(arguments).makeRequest().multilineTypeFormatting == MultilineTypeFormatting(maximumLineWidth: 120)) + #expect(try InterfaceCommand.parse(arguments).makeRequest().multilineTypeFormatting == MultilineTypeFormatting(maximumLineWidth: 120)) + } + + @Test(arguments: [ + (["/tmp/example", "--maximum-line-width", "120"], "--maximum-line-width needs --multiline-types"), + (["/tmp/example", "--multiline-types", "--maximum-line-width", "0"], "--maximum-line-width must be a positive number of columns"), + ]) + func usageMistakesAreValidationErrors(arguments: [String], messagePart: String) { + #expect( + performing: { + _ = try DumpCommand.parse(arguments) + }, + throws: { error in + DumpCommand.message(for: error).contains(messagePart) && DumpCommand.exitCode(for: error) == ExitCode(64) + } + ) + #expect( + performing: { + _ = try InterfaceCommand.parse(arguments) + }, + throws: { error in + InterfaceCommand.message(for: error).contains(messagePart) && InterfaceCommand.exitCode(for: error) == ExitCode(64) + } + ) + } + + @Test func helpNamesTheDefaultWidth() { + for helpMessage in [DumpCommand.helpMessage(columns: 1000), InterfaceCommand.helpMessage(columns: 1000)] { + #expect(helpMessage.contains("--maximum-line-width ")) + #expect(helpMessage.contains("--multiline-types breaks its types. (default: 100)")) + } + } +} diff --git a/Tests/SwiftSectionCommandTests/ObjC/ObjCAPICommandParsingTests.swift b/Tests/SwiftSectionCommandTests/ObjC/ObjCAPICommandParsingTests.swift index bbdb2d2e1..d8308b7f1 100644 --- a/Tests/SwiftSectionCommandTests/ObjC/ObjCAPICommandParsingTests.swift +++ b/Tests/SwiftSectionCommandTests/ObjC/ObjCAPICommandParsingTests.swift @@ -2,6 +2,7 @@ import ArgumentParser import Foundation import Testing @testable import swift_section +import SwiftSectionKit /// Option parsing for the API commands introduced by proposal 0006 /// (`snapshot` / `diff` / `evolution`). Same rationale as the dump/interface diff --git a/Tests/SwiftSectionCommandTests/ObjC/ObjCSectionCommandTests.swift b/Tests/SwiftSectionCommandTests/ObjC/ObjCSectionCommandTests.swift index 4044e1343..ad2b4f4b9 100644 --- a/Tests/SwiftSectionCommandTests/ObjC/ObjCSectionCommandTests.swift +++ b/Tests/SwiftSectionCommandTests/ObjC/ObjCSectionCommandTests.swift @@ -4,6 +4,7 @@ import Foundation import ObjCDeclarationRendering import ObjCOutputTransformer @testable import swift_section +import SwiftSectionKit /// Option parsing is the CLI's contract with its users: a flag that silently /// stops reaching the library, or one that lands on the wrong switch, produces @@ -257,6 +258,17 @@ struct ObjCSectionCommandTests { #expect(try swiftView.makeRequest().printsSwiftImport) } + @Test("The interface subcommand marks the SDK's Swift names only with --mark-sdk-swift-names, and the request knows") + func markSDKSwiftNamesFlagMapsToRequest() throws { + let plain = try ObjCInterfaceCommand.parse(["PKDrawing", "/tmp/Sample"]) + #expect(!plain.marksSDKSwiftNames) + #expect(try !plain.makeRequest().marksSDKSwiftNames) + + let marked = try ObjCInterfaceCommand.parse(["PKDrawing", "/tmp/Sample", "--mark-sdk-swift-names"]) + #expect(marked.marksSDKSwiftNames) + #expect(try marked.makeRequest().marksSDKSwiftNames) + } + // MARK: - Command Tree @Test("dump is the default objc subcommand") diff --git a/Tests/SwiftSectionCommandTests/TransformerOptionGroupTests.swift b/Tests/SwiftSectionCommandTests/TransformerOptionGroupTests.swift index 3cefea1fd..747a4fd06 100644 --- a/Tests/SwiftSectionCommandTests/TransformerOptionGroupTests.swift +++ b/Tests/SwiftSectionCommandTests/TransformerOptionGroupTests.swift @@ -7,6 +7,7 @@ import SwiftDeclarationRendering import SwiftPrinting import SwiftSectionKit @testable import swift_section +import Demangling /// Unit tests for the `swift-section` comment-template command-line surface: /// how a template value resolves (built-in name vs literal template), how the diff --git a/Tests/SwiftSectionKitTests/CrossReferenceRequestTests.swift b/Tests/SwiftSectionKitTests/CrossReferenceRequestTests.swift index f650cff4e..10aa00d4f 100644 --- a/Tests/SwiftSectionKitTests/CrossReferenceRequestTests.swift +++ b/Tests/SwiftSectionKitTests/CrossReferenceRequestTests.swift @@ -13,9 +13,11 @@ struct CrossReferenceRequestTests { static let archivedCachePath = "/Volumes/DyldSharedCaches/macOS/27.2/dyld_shared_cache_arm64e" static let selector = "makeKeyAndOrderFront:" - private static func isSend(_ target: CodeReferenceTarget, of selector: String) -> Bool { + /// A send of `selector`, or another use of it — an argument, a returned + /// selector (evolution proposal `cross-reference-recall-gaps`). + private static func isUse(_ target: CodeReferenceTarget, of selector: String) -> Bool { switch target { - case .messageSend(selector, _), .superMessageSend(selector, _): true + case .messageSend(selector, _), .superMessageSend(selector, _), .selector(selector): true default: false } } @@ -26,7 +28,7 @@ struct CrossReferenceRequestTests { let result = try await ReferencesRequest(input: .dyldSharedCache(path: Self.archivedCachePath), subject: .selector(Self.selector)).run(output: output) #expect(result.rows.count > 100) #expect(!result.isTruncated) - #expect(result.rows.allSatisfy { Self.isSend($0.reference.target, of: Self.selector) }) + #expect(result.rows.allSatisfy { Self.isUse($0.reference.target, of: Self.selector) }) #expect(result.rows.contains { $0.imagePath.hasSuffix("/AppKit.framework/Versions/C/AppKit") }) let lines = output.printedProduct.split(separator: "\n") #expect(lines.count == result.rows.count) @@ -54,10 +56,13 @@ struct CrossReferenceRequestTests { let function = try #require(reference["function"] as? [String: Any]) #expect((function["address"] as? String)?.hasPrefix("0x") == true) #expect((reference["image"] as? String)?.hasSuffix("/AppKit") == true) - #expect(["call", "tailCall"].contains(reference["kind"] as? String)) + #expect(["call", "tailCall", "reference"].contains(reference["kind"] as? String)) let target = try #require(reference["target"] as? [String: Any]) - let send = (target["messageSend"] ?? target["superMessageSend"]) as? [String: Any] - #expect(send?["selector"] as? String == Self.selector) + if let send = (target["messageSend"] ?? target["superMessageSend"]) as? [String: Any] { + #expect(send["selector"] as? String == Self.selector) + } else { + #expect(target["selector"] as? String == Self.selector) + } } } @@ -141,7 +146,7 @@ struct CrossReferenceRequestTests { let result = try await ReferencesRequest(input: .files(paths: [path], architecture: .arm64e), subject: .selector("init")).run(output: RecordingOutput()) #expect(!result.rows.isEmpty) #expect(result.scannedImageCount == 1) - #expect(result.rows.allSatisfy { $0.imagePath == path && Self.isSend($0.reference.target, of: "init") }) + #expect(result.rows.allSatisfy { $0.imagePath == path && Self.isUse($0.reference.target, of: "init") }) await #expect(performing: { try await ReferencesRequest(input: .files(paths: [path], architecture: nil), subject: .selector("init")).run(output: RecordingOutput()) }, throws: { error in @@ -167,6 +172,28 @@ struct CrossReferenceRequestTests { #expect(lines[0].hasPrefix(String(format: "0x%llx AppKit __TEXT,__text ", reference.instructionAddress))) } + /// A file name two images of the cache answer to — a framework's macOS + /// and Mac Catalyst variants — names whichever maps the address. The + /// first was taken, and an address of the second read as unmapped + /// there (2026-11-29 codebase audit, finding 5). + @Test func symbolicateReadsAnAddressInTheSameNamedImageThatMapsIt() async throws { + let cache = try #require(FullDyldCache.cachedHost) + let analyzer = try CrossReferenceAnalyzer(dyldCache: cache) + let imageIndicesByName = Dictionary(grouping: analyzer.imagePaths.indices) { (analyzer.imagePaths[$0] as NSString).lastPathComponent } + let (name, imageIndices) = try #require( + imageIndicesByName.filter { $0.value.count > 1 }.sorted { $0.key < $1.key }.first { !analyzer.functions(inImageAt: $0.value.sorted()[1]).isEmpty }, + "no two images of the cache share a file name" + ) + let laterImageIndex = imageIndices.sorted()[1] + let function = try #require(analyzer.functions(inImageAt: laterImageIndex).first) + + let symbolications = try await SymbolicateRequest(input: .systemDyldSharedCache, addresses: [function.location.address], imageName: name).run(output: RecordingOutput()) + + let symbolication = try #require(symbolications.first) + #expect(symbolication.imagePath == analyzer.imagePaths[laterImageIndex], "\(name): \(symbolication)") + #expect(symbolication.meaning.functionStart == function.location.address, "\(name): \(symbolication.meaning)") + } + @Test func symbolicateJSONUsesHexadecimalStringAddresses() async throws { let output = RecordingOutput() try await SymbolicateRequest(input: .systemDyldSharedCache, addresses: [0x10], format: .json).run(output: output) diff --git a/Tests/SwiftSectionKitTests/DumpAndInterfaceRequestTests.swift b/Tests/SwiftSectionKitTests/DumpAndInterfaceRequestTests.swift index a9bedbbb0..52cc7d7dd 100644 --- a/Tests/SwiftSectionKitTests/DumpAndInterfaceRequestTests.swift +++ b/Tests/SwiftSectionKitTests/DumpAndInterfaceRequestTests.swift @@ -3,6 +3,8 @@ import Testing import OutputTransformer import SwiftOutputTransformer import SwiftSectionKit +import SwiftPrinting +import Semantic /// `dump` and `interface` against the SymbolTestsCore fixture: which sections /// are read and how a failure surfaces, where the product goes, and the diff --git a/Tests/SwiftSectionKitTests/MachOSourceTests.swift b/Tests/SwiftSectionKitTests/MachOSourceTests.swift index 7eb82dfb3..f1d56467b 100644 --- a/Tests/SwiftSectionKitTests/MachOSourceTests.swift +++ b/Tests/SwiftSectionKitTests/MachOSourceTests.swift @@ -1,6 +1,7 @@ import Foundation import Testing import SwiftSectionKit +import MachOKit /// `MachOSource.load()` is the one loader every request shares; these pin the /// fat-binary affordance and the cache-image lookup it centralizes. diff --git a/Tests/SwiftSectionKitTests/MovedTypeModuleRequestTests.swift b/Tests/SwiftSectionKitTests/MovedTypeModuleRequestTests.swift new file mode 100644 index 000000000..07e0b9d3a --- /dev/null +++ b/Tests/SwiftSectionKitTests/MovedTypeModuleRequestTests.swift @@ -0,0 +1,52 @@ +#if os(macOS) + +import Foundation +import Testing +import Semantic +import SwiftSectionKit +import SwiftSectionFixtureSupport + +/// `resolvesMovedTypeModules` on the `interface` request (evolution proposal +/// `moved-swift-type-modules`): off by default, the product spells a moved +/// Swift type as its mangling does; on, as this Mac's SDK declares it. Reads +/// the SDK's textual interfaces only, no sourcekitd. +@Suite +struct MovedTypeModuleRequestTests { + private static func fixture() throws -> MachOSource { + let libraryURL = try FixtureCompiler.shared.dynamicLibrary( + named: "MovedTypeModuleRequestFixture", + language: .swift, + sourceFiles: [FixtureSourceFile(name: "MovedTypeModuleRequestFixture.swift", contents: """ + import Foundation + public final class FixtureAnchor {} + public struct Holder { + public var width: CGFloat + public init(width: CGFloat) { self.width = width } + } + """)], + arguments: ["-swift-version", "5", "-target", "arm64-apple-macosx15.0"] + ) + return .file(path: libraryURL.path, architecture: nil) + } + + private static func interface(resolvesMovedTypeModules: Bool) async throws -> String { + let output = RecordingOutput() + try await InterfaceRequest(source: fixture(), resolvesMovedTypeModules: resolvesMovedTypeModules).run(output: output, environment: .testing) + let declarations = output.products.compactMap { product in + if case .declarations(let semanticString) = product { semanticString.string } else { nil } + } + try #require(declarations.count == 1) + return declarations[0] + } + + @Test + func interfaceRequestResolvesMovedTypeModulesOnlyWhenAsked() async throws { + let unresolvedInterface = try await Self.interface(resolvesMovedTypeModules: false) + #expect(unresolvedInterface.contains("var width: CoreGraphics.CGFloat")) + let resolvedInterface = try await Self.interface(resolvesMovedTypeModules: true) + #expect(resolvedInterface.contains("var width: CoreFoundation.CGFloat")) + #expect(!resolvedInterface.contains("CoreGraphics.CGFloat")) + } +} + +#endif diff --git a/Tests/SwiftSectionKitTests/MultilineTypeFormattingRequestTests.swift b/Tests/SwiftSectionKitTests/MultilineTypeFormattingRequestTests.swift new file mode 100644 index 000000000..e81eff083 --- /dev/null +++ b/Tests/SwiftSectionKitTests/MultilineTypeFormattingRequestTests.swift @@ -0,0 +1,82 @@ +import Foundation +import Testing +import SwiftSectionKit +import SwiftDeclarationRendering +import Semantic + +/// `multilineTypeFormatting` on the `dump` and `interface` requests +/// (evolution proposal `multiline-type-formatting`): with it, the product is +/// exactly what formatting the product printed without it gives — the whole +/// interface at once, the dump one declaration at a time — and without it +/// nothing changes. +@Suite +struct MultilineTypeFormattingRequestTests { + private static let fixture = MachOSource.file(path: FixtureFiles.symbolTestsCore, architecture: nil) + + /// Narrow enough that the fixture's long generic field types break. + private static let formatting = MultilineTypeFormatting(maximumLineWidth: 30) + + /// A field the formatting breaks, as printed on one line. + private static let oneLineField = "var nested: SymbolTestsCore.GenericFieldLayout.Pair, Swift.Int>" + + private static func declarations(of output: RecordingOutput) -> [SemanticString] { + output.products.compactMap { product in + if case .declarations(let semanticString) = product { semanticString } else { nil } + } + } + + @Test func requestsFormatNothingUnlessAsked() { + #expect(InterfaceRequest(source: Self.fixture).multilineTypeFormatting == nil) + #expect(DumpRequest(source: Self.fixture).multilineTypeFormatting == nil) + } + + @Test func interfaceRequestFormatsLongTypesWhenAsked() async throws { + let plain = RecordingOutput() + try await InterfaceRequest(source: Self.fixture).run(output: plain, environment: .testing) + let formatted = RecordingOutput() + try await InterfaceRequest(source: Self.fixture, multilineTypeFormatting: Self.formatting).run(output: formatted, environment: .testing) + + let plainInterface = try #require(Self.declarations(of: plain).only) + let formattedInterface = try #require(Self.declarations(of: formatted).only) + #expect(plainInterface.string.contains(Self.oneLineField)) + #expect(!formattedInterface.string.contains(Self.oneLineField)) + #expect(formattedInterface.components == Self.formatting.format(plainInterface).components) + } + + @Test func interfaceWrittenToFileIsFormattedToo() async throws { + let directoryURL = try FixtureFiles.makeTemporaryDirectory() + defer { try? FileManager.default.removeItem(at: directoryURL) } + let interfacePath = directoryURL.appendingPathComponent("interface.swift").path + + let printed = RecordingOutput() + try await InterfaceRequest(source: Self.fixture, multilineTypeFormatting: Self.formatting).run(output: printed, environment: .testing) + try await InterfaceRequest(source: Self.fixture, multilineTypeFormatting: Self.formatting, destination: .file(path: interfacePath)).run(output: RecordingOutput(), environment: .testing) + + let printedInterface = try #require(Self.declarations(of: printed).only) + #expect(!printedInterface.string.contains(Self.oneLineField)) + #expect(try String(contentsOfFile: interfacePath, encoding: .utf8) == printedInterface.string) + } + + @Test func dumpRequestFormatsEachDeclarationWhenAsked() async throws { + let plain = RecordingOutput() + try await DumpRequest(source: Self.fixture, sections: .only([.types])).run(output: plain, environment: .testing) + let formatted = RecordingOutput() + try await DumpRequest(source: Self.fixture, sections: .only([.types]), multilineTypeFormatting: Self.formatting).run(output: formatted, environment: .testing) + + let plainDeclarations = Self.declarations(of: plain) + let formattedDeclarations = Self.declarations(of: formatted) + #expect(plainDeclarations.count == formattedDeclarations.count) + #expect(plainDeclarations.contains { $0.string.contains(Self.oneLineField) }) + #expect(!formattedDeclarations.contains { $0.string.contains(Self.oneLineField) }) + for (plainDeclaration, formattedDeclaration) in zip(plainDeclarations, formattedDeclarations) { + #expect(formattedDeclaration.components == Self.formatting.format(plainDeclaration).components) + } + } +} + +extension Collection { + /// The collection's single element; `nil` when it has none or several. + fileprivate var only: Element? { + count == 1 ? first : nil + } +} diff --git a/Tests/SwiftSectionKitTests/ObjCRequestTests.swift b/Tests/SwiftSectionKitTests/ObjCRequestTests.swift index 374943975..2938c01ef 100644 --- a/Tests/SwiftSectionKitTests/ObjCRequestTests.swift +++ b/Tests/SwiftSectionKitTests/ObjCRequestTests.swift @@ -237,4 +237,44 @@ struct ObjCRequestTests { } #expect(!output.messages(of: .progress).contains { $0.hasPrefix("Indexing") }) } + + // MARK: - SDK Swift names + + @Test("--mark-sdk-swift-names marks a class with the Swift name the SDK's API notes give it") + func markSDKSwiftNamesMarksAnSDKClass() async throws { + let output = RecordingOutput() + try await ObjCInterfaceRequest( + declarationName: "PKDrawing", + kind: .classes, + source: .systemDyldSharedCache(image: .name("PencilKit")), + marksSDKSwiftNames: true + ).run(output: output) + #expect(output.printedProduct.hasPrefix("NS_SWIFT_NAME(PKDrawingReference)\n@interface PKDrawing"), "\(output.printedProduct.prefix(200))") + #expect(output.messages(of: .warning).isEmpty) + } + + @Test("--mark-sdk-swift-names leaves a class the API notes do not mention as it was") + func markSDKSwiftNamesLeavesAnUnmentionedClassAlone() async throws { + let plain = RecordingOutput() + try await ObjCInterfaceRequest(declarationName: Self.bridgeClassName, source: Self.fixture).run(output: plain) + let marked = RecordingOutput() + try await ObjCInterfaceRequest(declarationName: Self.bridgeClassName, source: Self.fixture, marksSDKSwiftNames: true).run(output: marked) + #expect(marked.printedProduct == plain.printedProduct) + #expect(marked.messages(of: .warning).isEmpty) + } + + @Test("--mark-sdk-swift-names on a binary no SDK covers warns and prints the plain interface") + func missingSDKWarnsAndPrintsUnmarkedOutput() async throws { + let directoryURL = try FixtureFiles.makeTemporaryDirectory() + defer { try? FileManager.default.removeItem(at: directoryURL) } + let copyPath = try FixtureFiles.makeCopy(of: FixtureFiles.symbolTestsCore, buildPlatform: PLATFORM_BRIDGEOS, in: directoryURL) + let source = MachOSource.file(path: copyPath, architecture: nil) + + let plain = RecordingOutput() + try await ObjCInterfaceRequest(declarationName: Self.bridgeClassName, source: source).run(output: plain) + let marked = RecordingOutput() + try await ObjCInterfaceRequest(declarationName: Self.bridgeClassName, source: source, marksSDKSwiftNames: true).run(output: marked) + #expect(marked.printedProduct == plain.printedProduct) + #expect(marked.messages(of: .warning).contains { $0.contains("--mark-sdk-swift-names") }, "\(marked.messages(of: .warning))") + } } diff --git a/Tests/SwiftSectionKitTests/ReferencesRequestSwiftTypeTests.swift b/Tests/SwiftSectionKitTests/ReferencesRequestSwiftTypeTests.swift new file mode 100644 index 000000000..50f891b3c --- /dev/null +++ b/Tests/SwiftSectionKitTests/ReferencesRequestSwiftTypeTests.swift @@ -0,0 +1,75 @@ +#if os(macOS) + +import Foundation +import Testing +import MachOKit +import MachOKitExtensions +import CrossReferenceAnalysis +import SwiftSectionKit +import SwiftSectionFixtureSupport + +/// `refs --type`: the references to a Swift type, by its mangling or by a +/// symbol of it (evolution proposal `cross-reference-recall-gaps`). +@Suite +struct ReferencesRequestSwiftTypeTests { + private static func isTypeReference(_ target: CodeReferenceTarget) -> Bool { + switch target { + case .swiftType, .swiftTypeName, .objectiveCClass: true + default: false + } + } + + /// SwiftUICore's `Text`, whichever of its manglings or symbols names it. + @Test(.enabled(if: FullDyldCache.cachedHost != nil, "needs the running system's dyld shared cache")) + func typeSubjectFindsTheSameReferencesWhateverNamesTheType() async throws { + let byMangling = try await ReferencesRequest(input: .systemDyldSharedCache, subject: .swiftType("7SwiftUI4TextV", imageName: nil), imageNames: ["SwiftUICore"]).run(output: RecordingOutput()) + #expect(!byMangling.rows.isEmpty) + #expect(byMangling.rows.allSatisfy { Self.isTypeReference($0.reference.target) }) + for spelling in ["$s7SwiftUI4TextVMn", "_$s7SwiftUI4TextVMa", "$s7SwiftUI4TextVN"] { + let bySymbol = try await ReferencesRequest(input: .systemDyldSharedCache, subject: .swiftType(spelling, imageName: nil), imageNames: ["SwiftUICore"]).run(output: RecordingOutput()) + #expect(bySymbol.rows == byMangling.rows, "\(spelling)") + } + } + + @Test(.enabled(if: FullDyldCache.cachedHost != nil, "needs the running system's dyld shared cache")) + func typeSubjectInACacheNeedsTheImageOfATypeNoImageExports() async throws { + await #expect(throws: CrossReferenceRequestError.swiftTypeNeedsImage(mangling: "11NoSuchTypes7NothingV")) { + try await ReferencesRequest(input: .systemDyldSharedCache, subject: .swiftType("$s11NoSuchTypes7NothingVMn", imageName: nil)).run(output: RecordingOutput()) + } + await #expect(throws: CrossReferenceRequestError.swiftTypeNotFound(mangling: "11NoSuchTypes7NothingV")) { + try await ReferencesRequest(input: .systemDyldSharedCache, subject: .swiftType("11NoSuchTypes7NothingV", imageName: "SwiftUICore")).run(output: RecordingOutput()) + } + } + + /// A type no symbol names — its descriptor symbol stripped — is looked + /// for in every file of a set of files, which are few. The module and + /// the type share no word: a shared one would be spelled as a + /// substitution in the mangling. + @Test func typeSubjectLooksForAnUnexportedTypeInEveryStandaloneFile() async throws { + let libraryURL = try FixtureCompiler.shared.dynamicLibrary( + named: "StrippedTypes", + language: .swift, + sourceFiles: [FixtureSourceFile(name: "StrippedTypes.swift", contents: """ + struct Concealed { + var value: Int + } + + public func makeConcealed() -> Any { + Concealed(value: 1) + } + """)], + arguments: ["-swift-version", "5", "-Xlinker", "-x"] + ) + let input = CrossReferenceInput.files(paths: [libraryURL.path], architecture: nil) + let byMangling = try await ReferencesRequest(input: input, subject: .swiftType("13StrippedTypes9ConcealedV", imageName: nil)).run(output: RecordingOutput()) + #expect(!byMangling.rows.isEmpty) + #expect(byMangling.rows.allSatisfy { Self.isTypeReference($0.reference.target) }) + // A symbol of the type names it too, its prefix and suffix taken off. + for spelling in ["$s13StrippedTypes9ConcealedVMn", "_$s13StrippedTypes9ConcealedVMa", "$s13StrippedTypes9ConcealedVN"] { + let bySymbol = try await ReferencesRequest(input: input, subject: .swiftType(spelling, imageName: nil)).run(output: RecordingOutput()) + #expect(bySymbol.rows == byMangling.rows, "\(spelling)") + } + } +} + +#endif diff --git a/Tests/SwiftSectionKitTests/Support/DeclarationRecordingOutput.swift b/Tests/SwiftSectionKitTests/Support/DeclarationRecordingOutput.swift index ff130f8ec..05628f6fd 100644 --- a/Tests/SwiftSectionKitTests/Support/DeclarationRecordingOutput.swift +++ b/Tests/SwiftSectionKitTests/Support/DeclarationRecordingOutput.swift @@ -1,5 +1,6 @@ import Foundation import SwiftSectionKit +import Semantic /// A `SwiftSectionOutput` that also takes the declarations `dump` and /// `objc dump` name, keeping every product piece beside the declaration it diff --git a/Tests/SwiftSectionKitTests/Support/RecordingOutput.swift b/Tests/SwiftSectionKitTests/Support/RecordingOutput.swift index dd39701ad..32aaf44e0 100644 --- a/Tests/SwiftSectionKitTests/Support/RecordingOutput.swift +++ b/Tests/SwiftSectionKitTests/Support/RecordingOutput.swift @@ -1,6 +1,7 @@ import Foundation import SwiftDeclaration import SwiftSectionKit +import Semantic /// A `SwiftSectionOutput` that keeps everything it is handed, in order. /// diff --git a/Tests/SwiftSectionTestingMacrosTests/FixtureSuiteMacroTests.swift b/Tests/SwiftSectionTestingMacrosTests/FixtureSuiteMacroTests.swift new file mode 100644 index 000000000..3441da62b --- /dev/null +++ b/Tests/SwiftSectionTestingMacrosTests/FixtureSuiteMacroTests.swift @@ -0,0 +1,189 @@ +import Testing +import SwiftSyntaxBuilder +import SwiftSyntaxMacros +import SwiftSyntaxMacroExpansion +import SwiftSyntaxMacrosGenericTestSupport +@testable import SwiftSectionTestingMacros + +/// Expansions of `@FixtureSuite`. +@Suite +struct FixtureSuiteMacroTests { + private static let macroSpecs: [String: MacroSpec] = [ + "FixtureSuite": MacroSpec(type: FixtureSuiteMacro.self, conformances: ["FixtureSuite"]), + ] + + private static func assertExpansion( + _ originalSource: String, + expandedSource: String, + diagnostics: [DiagnosticSpec] = [], + applyFixIts: [String]? = nil, + fixedSource: String? = nil, + sourceLocation: SourceLocation = #_sourceLocation + ) { + assertMacroExpansion( + originalSource, + expandedSource: expandedSource, + diagnostics: diagnostics, + macroSpecs: macroSpecs, + applyFixIts: applyFixIts, + fixedSource: fixedSource, + failureHandler: { failure in + Issue.record(Comment(rawValue: failure.message), sourceLocation: sourceLocation) + } + ) + } + + @Test func defaultsTakeTheTestedTypeAndBaselineFromTheClassName() { + Self.assertExpansion( + """ + @FixtureSuite + final class StructDescriptorTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { + } + """, + expandedSource: """ + final class StructDescriptorTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { + + static let testedTypeName: Swift.String = "StructDescriptor" + + static var registeredTestMethodNames: Swift.Set { + StructDescriptorBaseline.registeredTestMethodNames + } + } + + extension StructDescriptorTests: FixtureSuite { + } + """ + ) + } + + @Test func anExplicitTestedTypeNameKeepsTheBaselineFromTheClassName() { + Self.assertExpansion( + """ + @FixtureSuite(testedTypeName: "EnumTagCounts") + final class EnumFunctionsTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { + } + """, + expandedSource: """ + final class EnumFunctionsTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { + + static let testedTypeName: Swift.String = "EnumTagCounts" + + static var registeredTestMethodNames: Swift.Set { + EnumFunctionsBaseline.registeredTestMethodNames + } + } + + extension EnumFunctionsTests: FixtureSuite { + } + """ + ) + } + + @Test func anExplicitBaselineIsUsedAsWritten() { + Self.assertExpansion( + """ + @FixtureSuite(testedTypeName: "OpaqueType", baseline: OpaqueTypeBaseline.self) + final class OpaqueTypeFixtureTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { + } + """, + expandedSource: """ + final class OpaqueTypeFixtureTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { + + static let testedTypeName: Swift.String = "OpaqueType" + + static var registeredTestMethodNames: Swift.Set { + OpaqueTypeBaseline.registeredTestMethodNames + } + } + + extension OpaqueTypeFixtureTests: FixtureSuite { + } + """ + ) + } + + @Test func aClassNameWithoutTestsAsksForTheTestedTypeName() { + Self.assertExpansion( + """ + @FixtureSuite + final class StructDescriptorChecks: MachOSwiftSectionFixtureTests { + } + """, + expandedSource: """ + final class StructDescriptorChecks: MachOSwiftSectionFixtureTests { + } + + extension StructDescriptorChecks: FixtureSuite { + } + """, + diagnostics: [ + DiagnosticSpec( + message: "'StructDescriptorChecks' does not end with 'Tests'; name the tested type and the baseline", + line: 1, + column: 1, + fixIts: [FixItSpec(message: "Name the tested type and the baseline")] + ), + ], + applyFixIts: ["Name the tested type and the baseline"], + fixedSource: """ + @FixtureSuite(testedTypeName: "StructDescriptorChecks", baseline: StructDescriptorChecksBaseline.self) + final class StructDescriptorChecks: MachOSwiftSectionFixtureTests { + } + """ + ) + } + + @Test func aNonLiteralArgumentIsRejected() { + Self.assertExpansion( + """ + @FixtureSuite(testedTypeName: name) + final class StructDescriptorTests: MachOSwiftSectionFixtureTests { + } + """, + expandedSource: """ + final class StructDescriptorTests: MachOSwiftSectionFixtureTests { + } + + extension StructDescriptorTests: FixtureSuite { + } + """, + diagnostics: [ + DiagnosticSpec(message: "testedTypeName: must be a string literal without interpolation", line: 1, column: 31), + ] + ) + Self.assertExpansion( + """ + @FixtureSuite(baseline: baselineType) + final class StructDescriptorTests: MachOSwiftSectionFixtureTests { + } + """, + expandedSource: """ + final class StructDescriptorTests: MachOSwiftSectionFixtureTests { + } + + extension StructDescriptorTests: FixtureSuite { + } + """, + diagnostics: [ + DiagnosticSpec(message: "baseline: must be a type literal such as SomeBaseline.self", line: 1, column: 25), + ] + ) + } + + @Test func theMacroAppliesOnlyToAClass() { + Self.assertExpansion( + """ + @FixtureSuite + struct StructDescriptorTests { + } + """, + expandedSource: """ + struct StructDescriptorTests { + } + """, + diagnostics: [ + DiagnosticSpec(message: "@FixtureSuite applies to a fixture suite class", line: 1, column: 1), + ] + ) + } +} diff --git a/Tests/SwiftSectionTestingSupportTests/Coverage/Fixtures/SuiteSampleSource.swift.txt b/Tests/SwiftSectionTestingSupportTests/Coverage/Fixtures/SuiteSampleSource.swift.txt index 2c6ed5f5b..21d694217 100644 --- a/Tests/SwiftSectionTestingSupportTests/Coverage/Fixtures/SuiteSampleSource.swift.txt +++ b/Tests/SwiftSectionTestingSupportTests/Coverage/Fixtures/SuiteSampleSource.swift.txt @@ -72,3 +72,26 @@ final class HelperReaderTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unc #expect(value == 42) } } + +@Suite +@FixtureSuite +final class MacroDefaultTypeTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { + @Test func macroDefaultMethod() async throws { + let result = try acrossAllReaders( + file: { 1 }, + image: { 1 } + ) + #expect(result == 1) + } +} + +@Suite +@FixtureSuite(testedTypeName: "MacroNamedType") +final class MacroNamedTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { + @Test func macroNamedMethod() async throws { + let result = try usingInProcessOnly { context in + 42 + } + #expect(result == 42) + } +} diff --git a/Tests/SwiftSectionTestingSupportTests/Coverage/SuiteBehaviorScannerTests.swift b/Tests/SwiftSectionTestingSupportTests/Coverage/SuiteBehaviorScannerTests.swift index 5921c6415..e2f788a49 100644 --- a/Tests/SwiftSectionTestingSupportTests/Coverage/SuiteBehaviorScannerTests.swift +++ b/Tests/SwiftSectionTestingSupportTests/Coverage/SuiteBehaviorScannerTests.swift @@ -79,4 +79,26 @@ struct SuiteBehaviorScannerTests { let key = MethodKey(typeName: "HelperReaderType", memberName: "helperUsingMethod") #expect(result[key] == .acrossAllReaders) } + + @Test func scannerTakesTheClassNameStemWhenTheMacroHasNoArgument() throws { + let root = try makeScanRoot() + defer { try? FileManager.default.removeItem(at: root) } + let result = try SuiteBehaviorScanner(suiteRoot: root).scan() + #expect(result[MethodKey(typeName: "MacroDefaultType", memberName: "macroDefaultMethod")] == .acrossAllReaders) + } + + @Test func scannerReadsTheTestedTypeNameFromTheMacroArgument() throws { + let root = try makeScanRoot() + defer { try? FileManager.default.removeItem(at: root) } + let result = try SuiteBehaviorScanner(suiteRoot: root).scan() + #expect(result[MethodKey(typeName: "MacroNamedType", memberName: "macroNamedMethod")] == .inProcessOnly) + #expect(result[MethodKey(typeName: "MacroNamed", memberName: "macroNamedMethod")] == nil) + } + + @Test func scannerStillReadsAStaticTestedTypeName() throws { + let root = try makeScanRoot() + defer { try? FileManager.default.removeItem(at: root) } + let result = try SuiteBehaviorScanner(suiteRoot: root).scan() + #expect(result[MethodKey(typeName: "CrossReaderType", memberName: "liveMethod")] == .acrossAllReaders) + } } diff --git a/Tests/SwiftSectionTestingSupportTests/DyldSharedCachePathTests.swift b/Tests/SwiftSectionTestingSupportTests/DyldSharedCachePathTests.swift index 14d022941..83dd6983a 100644 --- a/Tests/SwiftSectionTestingSupportTests/DyldSharedCachePathTests.swift +++ b/Tests/SwiftSectionTestingSupportTests/DyldSharedCachePathTests.swift @@ -1,24 +1,13 @@ import Testing import SwiftSectionFixtureSupport -/// `DyldSharedCachePath` builds an archived cache's path and label from its -/// version. The named macOS caches are built that way too, and only the -/// integration dumps — which nothing runs automatically — open them, so a -/// path or a label that came out wrong would go unnoticed until someone ran -/// one by hand. +/// The named macOS caches this package adds to `DyldSharedCachePath` are +/// built from a version. Only the integration dumps — which nothing runs +/// automatically — open them, so a path or a label that came out wrong would +/// go unnoticed until someone ran one by hand. How a version spells an +/// archived path is MachOKitExtensions' to test. @Suite struct DyldSharedCachePathTests { - @Test("A version names the cache file in that version's directory on the volume, and labels it") - func versionSpellsTheArchivedPathAndLabel() { - let internalBuild = DyldSharedCachePath.macOS("14.0(Internal)") - #expect(internalBuild.rawValue == "/Volumes/DyldSharedCaches/macOS/14.0(Internal)/dyld_shared_cache_arm64e") - #expect(internalBuild.versionLabel == "14.0(Internal)") - - let device = DyldSharedCachePath.iOS("27.0") - #expect(device.rawValue == "/Volumes/DyldSharedCaches/iOS/27.0/dyld_shared_cache_arm64e") - #expect(device.versionLabel == "27.0") - } - /// The paths these named caches spelled out before they were built from a /// version, and the labels the evolution dumps used to write out for /// them by hand. @@ -29,7 +18,7 @@ struct DyldSharedCachePathTests { (.macOS_27_0, "/Volumes/DyldSharedCaches/macOS/27.0/dyld_shared_cache_arm64e", "27.0"), ]) func namedCacheKeepsItsPathAndLabel(cachePath: DyldSharedCachePath, expectedPath: String, expectedVersionLabel: String) { - #expect(cachePath.rawValue == expectedPath) + #expect(cachePath.path == expectedPath) #expect(cachePath.versionLabel == expectedVersionLabel) } } diff --git a/Tests/SwiftSectionTestingSupportTests/ExclusiveImageAccessKeyTests.swift b/Tests/SwiftSectionTestingSupportTests/ExclusiveImageAccessKeyTests.swift new file mode 100644 index 000000000..43cbe4b17 --- /dev/null +++ b/Tests/SwiftSectionTestingSupportTests/ExclusiveImageAccessKeyTests.swift @@ -0,0 +1,30 @@ +import Testing +import SwiftSectionFixtureSupport +import SwiftSectionTestingSupport + +/// `ExclusiveImageAccess` excludes only suites that spell the same key. A +/// suite may name a SymbolTests fixture by its file and another by its image; +/// both must reach the same key, or the two run at once while each believes +/// it holds the image alone. (The trait itself is tested in +/// MachOKitExtensions.) +@Suite +struct ExclusiveImageAccessKeyTests { + @Test("A SymbolTests fixture keys the exclusion the same by its file and by its image", arguments: [ + (MachOFileName.SymbolTests, MachOImageName.SymbolTests), + (.SymbolTestsCore, .SymbolTestsCore), + ]) + func fileAndImageOfOneFixtureShareTheKey(fileName: MachOFileName, imageName: MachOImageName) { + #expect(fileName.exclusiveAccessKey == imageName.exclusiveAccessKey) + #expect(imageName.exclusiveAccessKey == imageName.name) + } + + @Test("Different SymbolTests fixtures key the exclusion differently") + func differentFixturesHaveDifferentKeys() { + let keys: Set = [ + MachOFileName.SymbolTests.exclusiveAccessKey, + MachOFileName.SymbolTestsCore.exclusiveAccessKey, + MachOFileName.SymbolTestsHelper.exclusiveAccessKey, + ] + #expect(keys.count == 3) + } +} diff --git a/Tests/SwiftSectionTestingSupportTests/ExclusiveImageAccessTests.swift b/Tests/SwiftSectionTestingSupportTests/ExclusiveImageAccessTests.swift deleted file mode 100644 index 60caffd2a..000000000 --- a/Tests/SwiftSectionTestingSupportTests/ExclusiveImageAccessTests.swift +++ /dev/null @@ -1,89 +0,0 @@ -import Foundation -import Testing -@testable import SwiftSectionTestingSupport - -/// The exclusion must be demonstrated, not asserted in prose — a promise in a -/// doc comment is exactly what failed here the first time. -/// -/// Both suites below carry `ExclusiveImageAccess` for the same key and run in -/// separate containers, so the testing library is free to interleave them. A -/// shared observer records every enter/exit; overlapping intervals would appear -/// as an enter arriving while another test is still inside. -@Suite -struct ExclusiveImageAccessTests { - @Test func concurrentAcquirersOfOneImageNeverOverlap() async throws { - let observer = OverlapObserver() - - await withTaskGroup(of: Void.self) { group in - for _ in 0 ..< 8 { - group.addTask { - await FixtureImageExclusion.withExclusiveAccess(to: "SharedImage") { - await observer.enter() - // Yield repeatedly: a lock that only excluded synchronous - // work — a global actor, say — lets a sibling run here. - for _ in 0 ..< 4 { await Task.yield() } - await observer.exit() - } - } - } - } - - #expect(await observer.maximumConcurrentHolders == 1, "two tests held the same image at once") - #expect(await observer.completedHolderCount == 8, "every acquirer must get its turn") - } - - /// Different keys must not block each other, or the trait would serialize - /// the whole suite tree instead of one image. - @Test func differentImagesProceedConcurrently() async throws { - let observer = OverlapObserver() - - await withTaskGroup(of: Void.self) { group in - for index in 0 ..< 6 { - group.addTask { - await FixtureImageExclusion.withExclusiveAccess(to: "Image\(index)") { - await observer.enter() - for _ in 0 ..< 4 { await Task.yield() } - await observer.exit() - } - } - } - } - - #expect(await observer.maximumConcurrentHolders > 1, "distinct images must not serialize against each other") - } - - /// A throwing body must still release, or one failed test wedges every later - /// one that declares the image — turning a single failure into a hang. - @Test func releasesAfterAThrowingBody() async throws { - struct BodyError: Error {} - - await #expect(throws: BodyError.self) { - try await FixtureImageExclusion.withExclusiveAccess(to: "ThrowingImage") { - throw BodyError() - } - } - - // Would hang rather than fail if the lock leaked. - var reacquired = false - await FixtureImageExclusion.withExclusiveAccess(to: "ThrowingImage") { - reacquired = true - } - #expect(reacquired) - } -} - -private actor OverlapObserver { - private var currentHolders = 0 - private(set) var maximumConcurrentHolders = 0 - private(set) var completedHolderCount = 0 - - func enter() { - currentHolders += 1 - maximumConcurrentHolders = max(maximumConcurrentHolders, currentHolders) - } - - func exit() { - currentHolders -= 1 - completedHolderCount += 1 - } -} diff --git a/Tests/SwiftSpecializationTests/ClassHierarchyBuildStackTests.swift b/Tests/SwiftSpecializationTests/ClassHierarchyBuildStackTests.swift index 13b9f7036..8bfdf0226 100644 --- a/Tests/SwiftSpecializationTests/ClassHierarchyBuildStackTests.swift +++ b/Tests/SwiftSpecializationTests/ClassHierarchyBuildStackTests.swift @@ -9,6 +9,7 @@ import Dependencies @testable import MachOSwiftSection @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import OrderedCollections /// `IndexerConformanceProvider` builds its class hierarchy on a large stack. /// diff --git a/Tests/SwiftSpecializationTests/GenericSpecializationTests.swift b/Tests/SwiftSpecializationTests/GenericSpecializationTests.swift index e6a70a43a..92fa8be71 100644 --- a/Tests/SwiftSpecializationTests/GenericSpecializationTests.swift +++ b/Tests/SwiftSpecializationTests/GenericSpecializationTests.swift @@ -16,6 +16,8 @@ import SwiftSectionFixtureSupport @testable @_spi(Internals) import SwiftInspection @testable import Demangling import OrderedCollections +import Semantic +import SwiftDeclarationRendering @Suite(.serialized) struct GenericSpecializationTests { diff --git a/Tests/SwiftSpecializationTests/GenericTypeNameSubstitutionTests.swift b/Tests/SwiftSpecializationTests/GenericTypeNameSubstitutionTests.swift index 798d86cce..38036bdcd 100644 --- a/Tests/SwiftSpecializationTests/GenericTypeNameSubstitutionTests.swift +++ b/Tests/SwiftSpecializationTests/GenericTypeNameSubstitutionTests.swift @@ -11,6 +11,7 @@ import Demangling @testable import MachOSwiftSection @testable import SwiftSectionTestingSupport @_spi(Internals) import SwiftInspection +import Semantic // MARK: - Pure helper unit tests (no fixture) @@ -497,7 +498,7 @@ struct GenericTypeNameSubstitutionEndToEndTests: GenericSpecializationTestingEnv "expected LayoutConstrainedInner among outer's typeChildren" ) let layoutRequest = try specializer.makeRequest(for: layoutConstrainedChild.typeContextDescriptorWrapper) - #expect(throws: (any Error).self, + #expect(throws: (any Swift.Error).self, "LayoutConstrainedInner must reject A = Int so the outer catch actually fires") { _ = try specializer.specialize(layoutRequest, with: ["A": .metatype(Int.self)]) } diff --git a/Tests/SwiftSpecializationTests/OfflineObjectiveCBaseClassTests.swift b/Tests/SwiftSpecializationTests/OfflineObjectiveCBaseClassTests.swift index e9304ca56..01840d570 100644 --- a/Tests/SwiftSpecializationTests/OfflineObjectiveCBaseClassTests.swift +++ b/Tests/SwiftSpecializationTests/OfflineObjectiveCBaseClassTests.swift @@ -6,6 +6,8 @@ import Testing import MachOKit @testable import MachOSwiftSection import SwiftSectionTestingSupport +import OrderedCollections +import Demangling /// A base-class requirement on an Objective-C class, checked offline /// (evolution proposal `offline-generic-specialization`). @@ -21,22 +23,6 @@ import SwiftSectionTestingSupport /// the most common base-class bounds there are. @Suite(.serialized) struct OfflineObjectiveCBaseClassTests { - private enum FixtureWorkingDirectoryCleanup { - nonisolated(unsafe) static var directories: [URL] = [] - static let registration: Void = { - atexit { - for directory in FixtureWorkingDirectoryCleanup.directories { - try? FileManager.default.removeItem(at: directory) - } - } - }() - } - - private struct FixtureCompilationError: Swift.Error, CustomStringConvertible { - let diagnostics: String - var description: String { "Objective-C base-class fixture compilation failed:\n\(diagnostics)" } - } - private static let moduleName = "ObjectiveCBaseClassFixture" private static let fixtureSource = """ @@ -51,47 +37,15 @@ struct OfflineObjectiveCBaseClassTests { } """ - private static let fixtureCompilationResult: Result = { - Result { - let workingDirectory = FileManager.default.temporaryDirectory - .appendingPathComponent("\(moduleName)-\(UUID().uuidString)") - try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) - _ = FixtureWorkingDirectoryCleanup.registration - FixtureWorkingDirectoryCleanup.directories.append(workingDirectory) - - let sourceURL = workingDirectory.appendingPathComponent("\(moduleName).swift") - let libraryURL = workingDirectory.appendingPathComponent("lib\(moduleName).dylib") - try fixtureSource.write(to: sourceURL, atomically: true, encoding: .utf8) - - let process = Process() - process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") - process.arguments = [ - "swiftc", "-swift-version", "5", "-emit-library", "-module-name", moduleName, - "-target", "arm64-apple-macosx15.0", - sourceURL.path, "-o", libraryURL.path, - ] - let standardErrorPipe = Pipe() - process.standardError = standardErrorPipe - try process.run() - // Drain before waiting, or a long diagnostic deadlocks both sides. - let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() - process.waitUntilExit() - guard process.terminationStatus == 0 else { - throw FixtureCompilationError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) - } - return libraryURL - } - }() - + /// Compiled once per process by the shared compiler. private func loadFixtureMachOFile() throws -> MachOFile { - let libraryURL = try Self.fixtureCompilationResult.get() - switch try MachOKit.loadFromFile(url: libraryURL) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } + let libraryURL = try FixtureCompiler.shared.dynamicLibrary( + named: Self.moduleName, + language: .swift, + source: Self.fixtureSource, + arguments: ["-swift-version", "5", "-target", "arm64-apple-macosx15.0"] + ) + return try HostSlice.machOFile(at: libraryURL) } /// The offline specializer over the fixture file, the request for diff --git a/Tests/SwiftSpecializationTests/OfflineProjectionDependencyResolutionTests.swift b/Tests/SwiftSpecializationTests/OfflineProjectionDependencyResolutionTests.swift index afab5025d..06435849d 100644 --- a/Tests/SwiftSpecializationTests/OfflineProjectionDependencyResolutionTests.swift +++ b/Tests/SwiftSpecializationTests/OfflineProjectionDependencyResolutionTests.swift @@ -8,6 +8,9 @@ import MachOKit @testable import MachOSwiftSection import SwiftSectionTestingSupport import SwiftDeclarationRendering +import MachODependencies +import Semantic +import OrderedCollections /// An archived iOS simulator cache: the dependency closure an iOS simulator /// binary is printed against here. Machine-specific, hence the suite's @@ -55,7 +58,7 @@ struct OfflineProjectionDependencyResolutionTests { } """ - private static let fixtureCompilationResult: Result = { + private static let fixtureCompilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("\(moduleName)-\(UUID().uuidString)") @@ -89,14 +92,7 @@ struct OfflineProjectionDependencyResolutionTests { }() private func loadFixtureMachOFile() throws -> MachOFile { - let libraryURL = try Self.fixtureCompilationResult.get() - switch try MachOKit.loadFromFile(url: libraryURL) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFile = try fatFile.machOFiles().first { $0.header.cpuType == .arm64 } - return try #require(machOFile, "fixture unexpectedly missing an arm64 slice") - } + try HostSlice.machOFile(at: Self.fixtureCompilationResult.get()) } @Test("a field's projected member and its layout are read from the same images") diff --git a/Tests/SwiftSpecializationTests/OfflineSpecializationParityTests.swift b/Tests/SwiftSpecializationTests/OfflineSpecializationParityTests.swift index e02f204a2..b612a225c 100644 --- a/Tests/SwiftSpecializationTests/OfflineSpecializationParityTests.swift +++ b/Tests/SwiftSpecializationTests/OfflineSpecializationParityTests.swift @@ -9,6 +9,7 @@ import Demangling @testable import MachOSwiftSection import SwiftSectionTestingSupport import SwiftDeclarationRendering +import Semantic /// One instantiation, specialized and printed both ways, must read the same /// byte for byte (evolution proposal `offline-generic-specialization`): the diff --git a/Tests/SwiftSpecializationTests/OfflineSpecializationTests.swift b/Tests/SwiftSpecializationTests/OfflineSpecializationTests.swift index 814b6430c..122f47c01 100644 --- a/Tests/SwiftSpecializationTests/OfflineSpecializationTests.swift +++ b/Tests/SwiftSpecializationTests/OfflineSpecializationTests.swift @@ -8,6 +8,7 @@ import Demangling @testable import MachOSwiftSection @_spi(Internals) import SwiftInspection import SwiftSectionTestingSupport +import OrderedCollections /// A host type with no conformance any indexed image records. private struct HostUnmarked { diff --git a/Tests/SwiftSpecializationTests/SpecializedRuntimeTypeNameTests.swift b/Tests/SwiftSpecializationTests/SpecializedRuntimeTypeNameTests.swift index a4ba5bfef..2c85bec77 100644 --- a/Tests/SwiftSpecializationTests/SpecializedRuntimeTypeNameTests.swift +++ b/Tests/SwiftSpecializationTests/SpecializedRuntimeTypeNameTests.swift @@ -7,6 +7,7 @@ import Testing import MachOKit @testable import MachOSwiftSection @testable import SwiftSectionTestingSupport +import Semantic // MARK: - Fixtures // @@ -130,12 +131,11 @@ struct SpecializedRuntimeTypeNameTests: GenericSpecializationTestingEnvironment let printed = try await printSpecialized("RuntimeNamedPrivateLayoutOuter", with: ["A": .metatype(RuntimeNamedPrivateArgument.self)], configuration: configuration) - // Layout comments print with `DemangleOptions.default`, which spells - // private discriminators. Since 2026-09-24 the runtime's name carries - // the discriminator the descriptor-built name does, so a runtime-named - // argument reads like every other private type in these comments. The - // hash comes from this file's name, so only its shape is pinned. - #expect(printed.contains("element (SwiftSpecializationTests.(RuntimeNamedPrivateArgument in _"), "got:\n\(printed)") + // The interface's layout comments spell their types the way its + // declarations do (evolution proposal + // `consistent-c-imported-type-spelling`): a private type keeps its + // module and loses its discriminator, as `let element:` does above. + #expect(printed.contains("element (SwiftSpecializationTests.RuntimeNamedPrivateArgument): 0x"), "got:\n\(printed)") } /// The runtime's name carries the extension context too diff --git a/Tests/SwiftSpecializationTests/SubclassMapMaterializationFailureTests.swift b/Tests/SwiftSpecializationTests/SubclassMapMaterializationFailureTests.swift index 69d707347..bc64d6b6c 100644 --- a/Tests/SwiftSpecializationTests/SubclassMapMaterializationFailureTests.swift +++ b/Tests/SwiftSpecializationTests/SubclassMapMaterializationFailureTests.swift @@ -9,6 +9,7 @@ import Dependencies @testable import MachOSwiftSection @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import OrderedCollections /// `IndexerConformanceProvider`'s subclass map must not lose a class silently. /// @@ -29,7 +30,7 @@ final class SubclassMapMaterializationFailureTests: MachOFileTests, @unchecked S override class var fileName: MachOFileName { .SymbolTestsCore } private func preparedIndexer( - eventHandlers: [SwiftIndexEvents.Handler] = [] + eventHandlers: [any SwiftIndexEvents.Handler] = [] ) async throws -> SwiftDeclarationIndexer { let unsafeMachOFile = machOFile let indexer = SwiftDeclarationIndexer(eventHandlers: eventHandlers, in: unsafeMachOFile) diff --git a/Tests/SwiftSymbolsTests/ExportedSymbolFactsTests.swift b/Tests/SwiftSymbolsTests/ExportedSymbolFactsTests.swift index a6fe31aae..da8e5aac0 100644 --- a/Tests/SwiftSymbolsTests/ExportedSymbolFactsTests.swift +++ b/Tests/SwiftSymbolsTests/ExportedSymbolFactsTests.swift @@ -6,6 +6,7 @@ import Testing @_spi(Internals) import MachOCaches @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import MachOKit /// Fixture-based coverage for the export facts (evolution proposal 0008): /// `isExported(name:in:)` answering the export-trie membership FACT, and diff --git a/Tests/SwiftSymbolsTests/SwiftSymbolLanguageRegistrationTests.swift b/Tests/SwiftSymbolsTests/SwiftSymbolLanguageRegistrationTests.swift index 18dc9c72c..9558a2548 100644 --- a/Tests/SwiftSymbolsTests/SwiftSymbolLanguageRegistrationTests.swift +++ b/Tests/SwiftSymbolsTests/SwiftSymbolLanguageRegistrationTests.swift @@ -29,6 +29,32 @@ struct SwiftSymbolLanguageRegistrationTests { #expect(SymbolLanguage(ofSymbolNamed: "__ZN4llvm5Value4dumpEv") == .cPlusPlus) } + /// A static link (a Tuist static framework, a static library) loads + /// SwiftSymbolsRegistration.c, and the constructor that registers the + /// language, only because SymbolLanguage+Swift.swift refers to its anchor: + /// the constructor is static, so the file defines nothing else, and -ObjC + /// does not load it either. SwiftPM links every target whole, so no test + /// here can watch an archive leave the file out; this pins both halves of + /// the reference instead. + @Test func languageFileRefersToTheRegistrationAnchor() throws { + let packageRoot = URL(fileURLWithPath: #filePath) + .deletingLastPathComponent() + .deletingLastPathComponent() + .deletingLastPathComponent() + let symbolSources = packageRoot.appendingPathComponent("Sources/Symbols") + let registrationSource = try String( + contentsOf: symbolSources.appendingPathComponent("SwiftSymbolsRegistration/SwiftSymbolsRegistration.c"), + encoding: .utf8 + ) + let languageSource = try String( + contentsOf: symbolSources.appendingPathComponent("SwiftSymbols/SymbolLanguage+Swift.swift"), + encoding: .utf8 + ) + // Not static: a static function is no symbol a reference can name. + #expect(registrationSource.contains("\nvoid swift_symbols_registration_anchor(void) {")) + #expect(languageSource.contains("\n swift_symbols_registration_anchor()\n")) + } + @Test func cAndCPlusPlusStoreLeavesSwiftNamesOut() throws { let (swiftCore, swiftSymbols, otherSymbols) = try Self.swiftCoreSymbols() try #require(!swiftSymbols.isEmpty && !otherSymbols.isEmpty) diff --git a/Tests/SwiftSymbolsTests/SymbolIndexDemangledIndexTests.swift b/Tests/SwiftSymbolsTests/SymbolIndexDemangledIndexTests.swift index 75056daea..e3308f09e 100644 --- a/Tests/SwiftSymbolsTests/SymbolIndexDemangledIndexTests.swift +++ b/Tests/SwiftSymbolsTests/SymbolIndexDemangledIndexTests.swift @@ -7,6 +7,7 @@ import MachOResolving @_spi(Internals) @testable import SwiftSymbols @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import OrderedCollections /// Pins when a symbol index demangles its names (evolution proposal /// `machofile-performance`): the storage's first stage — the symbol table, @@ -139,13 +140,7 @@ final class SymbolIndexDemangledIndexTests: MachOFileTests, @unchecked Sendable }.start() let machOFile: MachOFile do { - switch try loadFromFile(named: .SymbolTestsCore) { - case .machO(let machO): - machOFile = machO - case .fat(let fatFile): - guard let machO = try fatFile.machOFiles().first(where: { $0.header.cpuType == .arm64 }) else { exit(EXIT_FAILURE) } - machOFile = machO - } + machOFile = try HostSlice.machOFile(in: try loadFromFile(named: .SymbolTestsCore)) } catch { exit(EXIT_FAILURE) } diff --git a/Tests/SwiftSymbolsTests/SymbolIndexStoreFixtureTests.swift b/Tests/SwiftSymbolsTests/SymbolIndexStoreFixtureTests.swift index 530995e8c..ee696f3ab 100644 --- a/Tests/SwiftSymbolsTests/SymbolIndexStoreFixtureTests.swift +++ b/Tests/SwiftSymbolsTests/SymbolIndexStoreFixtureTests.swift @@ -7,6 +7,7 @@ import Testing @_spi(Internals) import MachOSymbols @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import OrderedCollections /// Fixture-based unit coverage for `SwiftSymbolIndexStore` against the /// `SymbolTestsCore` framework (self-built fixture, no external Xcode diff --git a/Tests/SwiftSymbolsTests/SymbolicManglingSymbolCollectionTests.swift b/Tests/SwiftSymbolsTests/SymbolicManglingSymbolCollectionTests.swift index 48a94f195..194af2503 100644 --- a/Tests/SwiftSymbolsTests/SymbolicManglingSymbolCollectionTests.swift +++ b/Tests/SwiftSymbolsTests/SymbolicManglingSymbolCollectionTests.swift @@ -1,11 +1,13 @@ import Foundation import Testing import MachOKit +import MachOKitExtensions @_spi(Internals) @testable import SwiftSymbols @_spi(Internals) import MachOCaches @_spi(Internals) import MachOSymbols @testable import SwiftSectionTestingSupport import SwiftSectionFixtureSupport +import MachOResolving /// The collection layer of evolution proposal `symbolic-mangling-symbol-index`: /// the build sweep gathers every `_symbolic ` / `_default assoc type ` symbol @@ -126,7 +128,7 @@ struct SymbolicManglingSymbolCollectionTests { /// has no default associated type witness, SwiftUICore does. @Test(.enabled(if: runsOnMacOS26OrLater, "AppKit's symbolic-mangling symbols are pinned on macOS 26")) func censusOfSystemCacheImages() throws { - let cache = try DyldCache(path: .current) + let cache = try #require(FullDyldCache.cachedHost, "no host dyld shared cache").mainCache var censusLines: [String] = [] for imageName in [MachOImageName.AppKit, .SwiftUICore] { let machOFile = try #require(cache.machOFile(named: imageName), "the running system's cache has no \(imageName)") @@ -183,7 +185,7 @@ struct SymbolicManglingSymbolCollectionTests { } private static func appKitFileInSystemCache() throws -> MachOFile { - let cache = try DyldCache(path: .current) + let cache = try #require(FullDyldCache.cachedHost, "no host dyld shared cache").mainCache return try #require(cache.machOFile(named: .AppKit), "the running system's cache has no AppKit") } } diff --git a/Tests/SwiftSymbolsTests/WrappedReaderSymbolTests.swift b/Tests/SwiftSymbolsTests/WrappedReaderSymbolTests.swift index 1d7c1a18e..1a6f38a7c 100644 --- a/Tests/SwiftSymbolsTests/WrappedReaderSymbolTests.swift +++ b/Tests/SwiftSymbolsTests/WrappedReaderSymbolTests.swift @@ -17,7 +17,7 @@ import SwiftSectionFixtureSupport /// /// Combine is an image no other suite reads, so the symbol index this suite /// builds for it is built through the wrapper. -@Suite(ExclusiveImageAccess(MachOImageName.Combine.rawValue)) +@Suite(ExclusiveImageAccess(MachOImageName.Combine.name)) struct WrappedReaderSymbolTests { @Test("a wrapper of a cache file files its Swift symbols where the file does") func cacheFileWrapperFilesSwiftSymbolsLikeTheFile() throws { @@ -52,7 +52,7 @@ struct WrappedReaderSymbolTests { } private static func combineInSystemCache() throws -> MachOFile { - let fullCache = try FullDyldCache(path: .current) + let fullCache = try #require(FullDyldCache.cachedHost, "no host dyld shared cache") return try #require(fullCache.machOFile(named: .Combine)) } } diff --git a/Tests/SwiftThunkAnalysisTests/AccessorThunkReaderTests.swift b/Tests/SwiftThunkAnalysisTests/AccessorThunkReaderTests.swift index fd39b67ca..b07de8566 100644 --- a/Tests/SwiftThunkAnalysisTests/AccessorThunkReaderTests.swift +++ b/Tests/SwiftThunkAnalysisTests/AccessorThunkReaderTests.swift @@ -51,7 +51,7 @@ struct AccessorThunkReaderTests { } @Test func resolvesAnAvailabilityConditionalThunkInSwiftUI() async throws { - let cache = try DyldCache(path: .current) + let cache = try #require(FullDyldCache.cachedHost, "no host dyld shared cache").mainCache let machO = try #require(cache.machOFile(named: .SwiftUI), "the running system's cache has no SwiftUI") guard let thunk = try firstAccessorThunk(in: machO) else { // A future SwiftUI may carry none; that is not a defect here. @@ -103,7 +103,7 @@ struct AccessorThunkReaderTests { /// sides move together with the OS, so the check stays green across /// upgrades while still failing if the disassembly reads the wrong branch. @Test func theRuntimesAnswerIsAmongTheOfflineCandidates() async throws { - let cache = try DyldCache(path: .current) + let cache = try #require(FullDyldCache.cachedHost, "no host dyld shared cache").mainCache let machO = try #require(cache.machOFile(named: .SwiftUI)) guard let thunk = try firstAccessorThunk(in: machO) else { return } diff --git a/Tests/SwiftThunkAnalysisTests/AccessorThunkTypeInGenericExtensionTests.swift b/Tests/SwiftThunkAnalysisTests/AccessorThunkTypeInGenericExtensionTests.swift index 10865c71f..e52d2226d 100644 --- a/Tests/SwiftThunkAnalysisTests/AccessorThunkTypeInGenericExtensionTests.swift +++ b/Tests/SwiftThunkAnalysisTests/AccessorThunkTypeInGenericExtensionTests.swift @@ -6,6 +6,7 @@ import MachOSwiftSection import Demangling @_spi(Internals) import SwiftInspection import SwiftDeclarationRendering +import SwiftSectionFixtureSupport @testable import SwiftThunkAnalysis /// A kind-9 accessor thunk names the type it instantiates by the accessor it @@ -20,22 +21,6 @@ import SwiftDeclarationRendering /// `offline-generic-specialization` is the reading side of the same shape. @Suite(.serialized) struct AccessorThunkTypeInGenericExtensionTests { - private enum FixtureWorkingDirectoryCleanup { - nonisolated(unsafe) static var directories: [URL] = [] - static let registration: Void = { - atexit { - for directory in FixtureWorkingDirectoryCleanup.directories { - try? FileManager.default.removeItem(at: directory) - } - } - }() - } - - private struct FixtureCompilationError: Error, CustomStringConvertible { - let diagnostics: String - var description: String { "accessor-thunk generic-extension fixture compilation failed:\n\(diagnostics)" } - } - /// `Inner` is `~Copyable`, so a field of it is instantiated by a thunk /// that first asks whether the runtime supports noncopyable types — a /// kind-9 accessor function reference in the field record. The class is @@ -69,46 +54,15 @@ struct AccessorThunkTypeInGenericExtensionTests { } """ - private static let fixtureCompilationResult: Result = { - Result { - let workingDirectory = FileManager.default.temporaryDirectory - .appendingPathComponent("AccessorThunkGenericExtensionFixture-\(UUID().uuidString)") - _ = FixtureWorkingDirectoryCleanup.registration - FixtureWorkingDirectoryCleanup.directories.append(workingDirectory) - try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) - let sourceURL = workingDirectory.appendingPathComponent("AccessorThunkGenericExtension.swift") - let libraryURL = workingDirectory.appendingPathComponent("libProbeThunkExtension.dylib") - try fixtureSource.write(to: sourceURL, atomically: true, encoding: .utf8) - - let process = Process() - process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") - // Optimized so the thunk takes the shape a shipping binary carries. - process.arguments = [ - "swiftc", "-swift-version", "5", "-O", "-emit-library", "-module-name", "ProbeThunkExtension", - "-target", "arm64-apple-macosx15.0", - sourceURL.path, "-o", libraryURL.path, - ] - let standardErrorPipe = Pipe() - process.standardError = standardErrorPipe - try process.run() - // Drain before waiting, or a long diagnostic deadlocks both sides. - let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() - process.waitUntilExit() - guard process.terminationStatus == 0 else { - throw FixtureCompilationError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) - } - return libraryURL - } - }() - private func loadFixture() throws -> MachOFile { - let libraryURL = try Self.fixtureCompilationResult.get() - switch try File.loadFromFile(url: libraryURL) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - return try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }) - } + let libraryURL = try FixtureCompiler.shared.dynamicLibrary( + named: "ProbeThunkExtension", + language: .swift, + sourceFiles: [FixtureSourceFile(name: "AccessorThunkGenericExtension.swift", contents: Self.fixtureSource)], + // Optimized so the thunk takes the shape a shipping binary carries. + arguments: ["-swift-version", "5", "-O", "-target", "arm64-apple-macosx15.0"] + ) + return try HostSlice.machOFile(at: libraryURL) } /// The `inner` field's type of the holder named `holderName`, read diff --git a/Tests/SwiftThunkAnalysisTests/ConstructedThunkOracleTests.swift b/Tests/SwiftThunkAnalysisTests/ConstructedThunkOracleTests.swift index d266536d7..5223e02bf 100644 --- a/Tests/SwiftThunkAnalysisTests/ConstructedThunkOracleTests.swift +++ b/Tests/SwiftThunkAnalysisTests/ConstructedThunkOracleTests.swift @@ -37,7 +37,7 @@ struct ConstructedThunkOracleTests { } @Test func offlineMatchesTheRuntimeForEveryNonGenericConformer() async throws { - let cache = try DyldCache(path: .current) + let cache = try #require(FullDyldCache.cachedHost, "no host dyld shared cache").mainCache let machOFile = try #require(cache.machOFile(named: .SwiftUI)) guard dlopen("/System/Library/Frameworks/SwiftUI.framework/Versions/A/SwiftUI", RTLD_LAZY) != nil, let machOImage = MachOImage(name: "SwiftUI") diff --git a/Tests/SwiftThunkAnalysisTests/MergedAccessorFixtureTests.swift b/Tests/SwiftThunkAnalysisTests/MergedAccessorFixtureTests.swift index 94ce47b0a..453b6e506 100644 --- a/Tests/SwiftThunkAnalysisTests/MergedAccessorFixtureTests.swift +++ b/Tests/SwiftThunkAnalysisTests/MergedAccessorFixtureTests.swift @@ -6,6 +6,7 @@ import MachOSwiftSection import Demangling @_spi(Internals) import SwiftInspection import SwiftDeclarationRendering +import SwiftSectionFixtureSupport @testable import SwiftThunkAnalysis /// A kind-9 field thunk that calls a **compiler-merged accessor** — the @@ -27,20 +28,9 @@ import SwiftDeclarationRendering /// `accessor function at N`, with and without symbols. @Suite(.serialized) struct MergedAccessorFixtureTests { - private enum FixtureWorkingDirectoryCleanup { - nonisolated(unsafe) static var directories: [URL] = [] - static let registration: Void = { - atexit { - for directory in FixtureWorkingDirectoryCleanup.directories { - try? FileManager.default.removeItem(at: directory) - } - } - }() - } - - private struct FixtureCompilationError: Error, CustomStringConvertible { + private struct StripError: Error, CustomStringConvertible { let diagnostics: String - var description: String { "MergedAccessorProbe fixture compilation failed:\n\(diagnostics)" } + var description: String { "stripping the MergedAccessorProbe fixture failed:\n\(diagnostics)" } } private struct CompiledFixture { @@ -48,27 +38,29 @@ struct MergedAccessorFixtureTests { let strippedLibraryURL: URL } - private static let fixtureCompilationResult: Result = { + private static let fixtureCompilationResult: Result = { Result { - let workingDirectory = FileManager.default.temporaryDirectory - .appendingPathComponent("MergedAccessorProbeFixture-\(UUID().uuidString)") - _ = FixtureWorkingDirectoryCleanup.registration - FixtureWorkingDirectoryCleanup.directories.append(workingDirectory) - try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) - let sourceURL = workingDirectory.appendingPathComponent("MergedAccessorProbe.swift") - try fixtureSource.write(to: sourceURL, atomically: true, encoding: .utf8) - let libraryURL = workingDirectory.appendingPathComponent("libMergedAccessorProbe.dylib") - let strippedLibraryURL = workingDirectory.appendingPathComponent("libMergedAccessorProbeStripped.dylib") - // `Synchronization.Mutex` needs macOS 15; optimized so the // accessors take the shapes a shipping binary carries and the // optimizer merges them. - try run(tool: "swiftc", arguments: [ - "-O", "-emit-library", "-module-name", "MergedAccessorProbe", - "-target", "arm64-apple-macosx15.0", - "-Xfrontend", "-disable-concrete-type-metadata-mangled-name-accessors", - sourceURL.path, "-o", libraryURL.path, - ]) + let libraryURL = try FixtureCompiler.shared.dynamicLibrary( + named: "MergedAccessorProbe", + language: .swift, + source: fixtureSource, + arguments: [ + "-O", + "-target", "arm64-apple-macosx15.0", + "-Xfrontend", "-disable-concrete-type-metadata-mangled-name-accessors", + ] + ) + // The compiled library is shared with every other request for it, + // so the stripped variant is a copy in a directory of its own, + // under the compiler's products directory the process removes at + // exit. + let strippedDirectory = FixtureCompiler.shared.productsDirectory + .appendingPathComponent("MergedAccessorProbeStripped-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: strippedDirectory, withIntermediateDirectories: true) + let strippedLibraryURL = strippedDirectory.appendingPathComponent("libMergedAccessorProbeStripped.dylib") try FileManager.default.copyItem(at: libraryURL, to: strippedLibraryURL) // `-x` removes the local symbols — every `…MaTm` and specialized // accessor name — the way a shipping app is stripped. @@ -88,7 +80,7 @@ struct MergedAccessorFixtureTests { let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() process.waitUntilExit() guard process.terminationStatus == 0 else { - throw FixtureCompilationError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) + throw StripError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) } } @@ -123,12 +115,7 @@ struct MergedAccessorFixtureTests { """ private func load(_ libraryURL: URL) throws -> MachOFile { - switch try File.loadFromFile(url: libraryURL) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - return try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }) - } + try HostSlice.machOFile(at: libraryURL) } /// Every kind-9 field of the fixture, keyed `Owner.field`, resolved diff --git a/Tests/SwiftThunkAnalysisTests/OpaqueTypeRenderingIntegrationTests.swift b/Tests/SwiftThunkAnalysisTests/OpaqueTypeRenderingIntegrationTests.swift index 91c9c1abe..d200a07ef 100644 --- a/Tests/SwiftThunkAnalysisTests/OpaqueTypeRenderingIntegrationTests.swift +++ b/Tests/SwiftThunkAnalysisTests/OpaqueTypeRenderingIntegrationTests.swift @@ -10,6 +10,7 @@ import Demangling import SwiftDeclarationRendering import SwiftThunkAnalysis import SwiftDump +import Semantic /// The point of the whole module: an associated-type witness that rendered as /// a bare address renders as a type once the thunk is read — and, since the @@ -47,7 +48,7 @@ struct OpaqueTypeRenderingIntegrationTests { } @Test func readingTheThunksNamesTypesThatWereBareAddresses() async throws { - let cache = try DyldCache(path: .current) + let cache = try #require(FullDyldCache.cachedHost, "no host dyld shared cache").mainCache let machO = try #require(cache.machOFile(named: .SwiftUI)) let before = try await AccessorThunkResolution.$taskResolver.withValue(UnreadableAccessorThunkResolver()) { @@ -73,7 +74,7 @@ struct OpaqueTypeRenderingIntegrationTests { /// unread — the type-construction evaluator reads the thunk the first /// landing had to refuse. @Test func everyAccessorReferenceResolves() async throws { - let cache = try DyldCache(path: .current) + let cache = try #require(FullDyldCache.cachedHost, "no host dyld shared cache").mainCache let machO = try #require(cache.machOFile(named: .SwiftUI)) let rendered = try await renderedWitnesses(in: machO) @@ -88,7 +89,7 @@ struct OpaqueTypeRenderingIntegrationTests { /// generic arguments thrown away. Now the reference prints as /// `accessor function at N` inside the type it sits in. @Test func whenTheThunkCannotBeReadTheReferenceStaysInsideItsType() async throws { - let cache = try DyldCache(path: .current) + let cache = try #require(FullDyldCache.cachedHost, "no host dyld shared cache").mainCache let machO = try #require(cache.machOFile(named: .SwiftUI)) let rendered = try await AccessorThunkResolution.$taskResolver.withValue(UnreadableAccessorThunkResolver()) { @@ -112,7 +113,7 @@ struct OpaqueTypeRenderingIntegrationTests { /// comment line per branch above the `typealias`, and the `typealias` /// itself is the branch taken on the newest platform. @Test func everyBranchPrintsAboveTheWitness() async throws { - let cache = try DyldCache(path: .current) + let cache = try #require(FullDyldCache.cachedHost, "no host dyld shared cache").mainCache let machO = try #require(cache.machOFile(named: .SwiftUI)) var dumpsWithBranches: [String] = [] @@ -148,7 +149,7 @@ struct OpaqueTypeRenderingIntegrationTests { /// The other branch is not lost: asked for candidates, the resolution /// reports every branch, each rendered in place of the whole witness. @Test func theOtherBranchIsReportedAsACandidate() async throws { - let cache = try DyldCache(path: .current) + let cache = try #require(FullDyldCache.cachedHost, "no host dyld shared cache").mainCache let machO = try #require(cache.machOFile(named: .SwiftUI)) var twoWayResolutions: [Node.OpaqueTypeResolution] = [] diff --git a/Tests/SwiftThunkAnalysisTests/RealThunkShapeProbe.swift b/Tests/SwiftThunkAnalysisTests/RealThunkShapeProbe.swift index 5397d86b9..2ee564689 100644 --- a/Tests/SwiftThunkAnalysisTests/RealThunkShapeProbe.swift +++ b/Tests/SwiftThunkAnalysisTests/RealThunkShapeProbe.swift @@ -17,7 +17,7 @@ import Demangling @Suite(.disabled("Research probe — enable explicitly when revisiting thunk shapes")) struct RealThunkShapeProbe { @Test func printsEveryDistinctThunkShape() async throws { - let cache = try DyldCache(path: .current) + let cache = try #require(FullDyldCache.cachedHost, "no host dyld shared cache").mainCache let machO = try #require(cache.machOFile(named: .SwiftUI)) var printedThunkOffsets: Set = [] diff --git a/Tests/SwiftThunkAnalysisTests/SimulatorRuntimeThunkResolutionTests.swift b/Tests/SwiftThunkAnalysisTests/SimulatorRuntimeThunkResolutionTests.swift index ac4f0b19f..d23c8928b 100644 --- a/Tests/SwiftThunkAnalysisTests/SimulatorRuntimeThunkResolutionTests.swift +++ b/Tests/SwiftThunkAnalysisTests/SimulatorRuntimeThunkResolutionTests.swift @@ -10,6 +10,7 @@ import Demangling import SwiftDeclarationRendering import SwiftThunkAnalysis import SwiftDump +import Semantic /// Where the simulator-runtime-gated suites below find their binaries. /// @@ -17,14 +18,14 @@ import SwiftDump /// reads a static of the suite it decorates is a circular macro reference. enum SimulatorRuntimeThunkFixtures { /// iOS 26.5: the last runtime that ships SwiftUI as a standalone file. - static let standaloneSwiftUIPath = MachOFileName.iOS_26_5_Simulator_SwiftUI.rawValue - static let standaloneSwiftUICorePath = MachOFileName.iOS_26_5_Simulator_SwiftUICore.rawValue + static let standaloneSwiftUIPath = MachOFileName.iOS_26_5_Simulator_SwiftUI.path + static let standaloneSwiftUICorePath = MachOFileName.iOS_26_5_Simulator_SwiftUICore.path static var hasStandaloneSwiftUI: Bool { FileManager.default.fileExists(atPath: standaloneSwiftUIPath) && FileManager.default.fileExists(atPath: standaloneSwiftUICorePath) } /// iOS 27.0: SwiftUI lives in the runtime's own dyld cache. - static let simulatorCachePath = DyldSharedCachePath.iOS_27_0_Simulator.rawValue + static let simulatorCachePath = DyldSharedCachePath.iOS_27_0_Simulator.path static var hasSimulatorCache: Bool { FileManager.default.fileExists(atPath: simulatorCachePath) } } @@ -44,12 +45,7 @@ struct SimulatorStandaloneSwiftUIThunkTests { } private func load(path: String) throws -> MachOFile { - switch try File.loadFromFile(url: URL(fileURLWithPath: path)) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - return try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }) - } + try HostSlice.machOFile(at: URL(fileURLWithPath: path)) } private func resolvedFieldTexts(ofTypeNamed typeName: String, in machOFile: MachOFile) throws -> [String: String] { diff --git a/Tests/SwiftThunkAnalysisTests/StandaloneFileThunkResolutionTests.swift b/Tests/SwiftThunkAnalysisTests/StandaloneFileThunkResolutionTests.swift index fcc10e2c1..892af0094 100644 --- a/Tests/SwiftThunkAnalysisTests/StandaloneFileThunkResolutionTests.swift +++ b/Tests/SwiftThunkAnalysisTests/StandaloneFileThunkResolutionTests.swift @@ -6,6 +6,7 @@ import MachOSwiftSection import Demangling @_spi(Internals) import SwiftInspection import SwiftDeclarationRendering +import SwiftSectionFixtureSupport @testable import SwiftThunkAnalysis /// A kind-9 thunk in a file that is **not** in a dyld shared cache calls the @@ -45,7 +46,7 @@ struct StandaloneFileThunkResolutionTests { /// The compiled dylib, placed under a fake system root at its own install /// name so the file's location also exercises search-path inference. - private static let fixtureCompilationResult: Result = { + private static let fixtureCompilationResult: Result = { Result { let workingDirectory = FileManager.default.temporaryDirectory .appendingPathComponent("ThunkProbeFixture-\(UUID().uuidString)") @@ -107,39 +108,17 @@ struct StandaloneFileThunkResolutionTests { /// `__swift_instantiateConcreteTypeFromMangledNameV2`, found by its local /// symbol — whose value is an address, which a dylib's `__TEXT` at 0 had /// let pass for a file offset. - private static let executableCompilationResult: Result = { - Result { - let workingDirectory = FileManager.default.temporaryDirectory - .appendingPathComponent("ThunkProbeExecutableFixture-\(UUID().uuidString)") - try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) - _ = FixtureWorkingDirectoryCleanup.registration - FixtureWorkingDirectoryCleanup.directories.append(workingDirectory) - - let sourceURL = workingDirectory.appendingPathComponent("ThunkProbe.swift") - let mainSourceURL = workingDirectory.appendingPathComponent("main.swift") - let executableURL = workingDirectory.appendingPathComponent("ThunkProbe") - try fixtureSource.write(to: sourceURL, atomically: true, encoding: .utf8) - try executableMainSource.write(to: mainSourceURL, atomically: true, encoding: .utf8) - - let process = Process() - process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") - process.arguments = [ - "swiftc", "-O", "-module-name", "ThunkProbe", - "-target", "arm64-apple-macosx15.0", - sourceURL.path, mainSourceURL.path, "-o", executableURL.path, - ] - let standardErrorPipe = Pipe() - process.standardError = standardErrorPipe - try process.run() - // Drain before waiting, or a long diagnostic deadlocks both sides. - let diagnosticsData = standardErrorPipe.fileHandleForReading.readDataToEndOfFile() - process.waitUntilExit() - guard process.terminationStatus == 0 else { - throw FixtureCompilationError(diagnostics: String(decoding: diagnosticsData, as: UTF8.self)) - } - return executableURL - } - }() + private static func compileExecutableFixture() throws -> URL { + try FixtureCompiler.shared.executable( + named: "ThunkProbe", + language: .swift, + sourceFiles: [ + FixtureSourceFile(name: "ThunkProbe.swift", contents: fixtureSource), + FixtureSourceFile(name: "main.swift", contents: executableMainSource), + ], + arguments: ["-O", "-target", "arm64-apple-macosx15.0"] + ) + } private static let executableMainSource = """ let holder = ProbeHolder() @@ -147,23 +126,11 @@ struct StandaloneFileThunkResolutionTests { """ private func loadExecutableFixture() throws -> MachOFile { - let executableURL = try Self.executableCompilationResult.get() - switch try File.loadFromFile(url: executableURL) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - return try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }) - } + try HostSlice.machOFile(at: try Self.compileExecutableFixture()) } private func loadFixture() throws -> MachOFile { - let libraryURL = try Self.fixtureCompilationResult.get() - switch try File.loadFromFile(url: libraryURL) { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - return try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }) - } + try HostSlice.machOFile(at: try Self.fixtureCompilationResult.get()) } private struct ResolvedField { diff --git a/Tests/SwiftThunkAnalysisTests/ThunkEnvironmentImageTablesTests.swift b/Tests/SwiftThunkAnalysisTests/ThunkEnvironmentImageTablesTests.swift index 976068a23..af3708bec 100644 --- a/Tests/SwiftThunkAnalysisTests/ThunkEnvironmentImageTablesTests.swift +++ b/Tests/SwiftThunkAnalysisTests/ThunkEnvironmentImageTablesTests.swift @@ -25,7 +25,7 @@ import SwiftThunkAnalysis struct ThunkEnvironmentImageTablesTests { @Test("A fresh environment does not walk the symbol table again") func freshEnvironmentReusesTheImagesRuntimeSymbols() throws { - let cache = try DyldCache(path: .current) + let cache = try #require(FullDyldCache.cachedHost, "no host dyld shared cache").mainCache let machOFile = try #require(cache.machOFile(named: .SwiftUI)) // A type descriptor: inside the image and not a metadata accessor, // so a lookup gets as far as the image's own runtime symbols. @@ -54,7 +54,7 @@ struct ThunkEnvironmentImageTablesTests { @Test("A fresh environment does not read the cache's image list again") func freshEnvironmentReusesTheCachesImageTable() throws { - let cache = try DyldCache(path: .current) + let cache = try #require(FullDyldCache.cachedHost, "no host dyld shared cache").mainCache let machOFile = try #require(cache.machOFile(named: .SwiftUI)) let swiftCore = try #require(cache.machOFile(by: .path("/usr/lib/swift/libswiftCore.dylib"))) // A runtime entry point another image of the cache exports: naming it diff --git a/Tests/SwiftThunkAnalysisTests/ThunkResolutionSurveyProbe.swift b/Tests/SwiftThunkAnalysisTests/ThunkResolutionSurveyProbe.swift index 248d1b9c8..d4409963d 100644 --- a/Tests/SwiftThunkAnalysisTests/ThunkResolutionSurveyProbe.swift +++ b/Tests/SwiftThunkAnalysisTests/ThunkResolutionSurveyProbe.swift @@ -21,7 +21,7 @@ import Demangling @Suite(.disabled("Survey probe — enable explicitly to measure the resolution rate")) struct ThunkResolutionSurveyProbe { @Test func printsResolutionOfEveryThunk() async throws { - let cache = try DyldCache(path: .current) + let cache = try #require(FullDyldCache.cachedHost, "no host dyld shared cache").mainCache let machO = try #require(cache.machOFile(named: .SwiftUI)) var seenThunkOffsets: Set = [] diff --git a/Tests/SwiftTypeNameResolutionTests/CFDeclaredTypeNamesTests.swift b/Tests/SwiftTypeNameResolutionTests/CFDeclaredTypeNamesTests.swift new file mode 100644 index 000000000..08f2cbe2c --- /dev/null +++ b/Tests/SwiftTypeNameResolutionTests/CFDeclaredTypeNamesTests.swift @@ -0,0 +1,70 @@ +#if os(macOS) + +import Darwin +import Foundation +import MachOKit +import SwiftSectionFixtureSupport +import SwiftTypeNameResolution +import Testing + +/// `CFDeclaredTypeNames` names the CF types an image defines after the +/// `…GetTypeID` functions it exports (evolution proposal +/// `private-cf-type-modules`). +@Suite +struct CFDeclaredTypeNamesTests { + /// Two type-ID functions — one spelled as a private function, with a + /// leading underscore — beside exports that name no type: a function of + /// the type that is not its type-ID function, and type-ID functions with + /// no type name before the suffix. + private static let fixtureSource = """ + unsigned long ProbeWidgetGetTypeID(void) { return 1; } + unsigned long _ProbeSecretGetTypeID(void) { return 2; } + void *ProbeWidgetCreate(void) { return 0; } + unsigned long GetTypeID(void) { return 3; } + unsigned long __GetTypeID(void) { return 4; } + """ + + /// What the fixture defines, written out by hand: each type-ID function's + /// typedef, and the private one's unprefixed spelling too. + private static let fixtureTypedefNames: Set = ["ProbeWidgetRef", "_ProbeSecretRef", "ProbeSecretRef"] + + private static let fixtureImagePath = "/Library/Frameworks/ProbeCF.framework/ProbeCF" + + private static func fixtureLibraryURL() throws -> URL { + try FixtureCompiler.shared.dynamicLibrary(named: "CFDeclaredTypeNamesFixture", language: .c, source: fixtureSource) + } + + @Test + func fileNamesTheTypedefOfEveryExportedTypeIDFunction() async throws { + let machOFile = try HostSlice.machOFile(at: Self.fixtureLibraryURL()) + let declaredTypeNames = await CFDeclaredTypeNames(machO: machOFile, imagePath: Self.fixtureImagePath).declaredTypeNames() + #expect(Set(declaredTypeNames) == Self.fixtureTypedefNames) + } + + @Test + func loadedImageNamesTheSameTypedefs() async throws { + let libraryURL = try Self.fixtureLibraryURL() + let libraryHandle = try #require(dlopen(libraryURL.path, RTLD_LAZY), "the fixture library did not load") + let typeIDFunctionAddress = try #require(dlsym(libraryHandle, "ProbeWidgetGetTypeID")) + let machOImage = try #require(ProcessImages.image(containing: typeIDFunctionAddress)) + let declaredTypeNames = await CFDeclaredTypeNames(machO: machOImage, imagePath: Self.fixtureImagePath).declaredTypeNames() + #expect(Set(declaredTypeNames) == Self.fixtureTypedefNames) + } + + /// The case the source exists for: CoreSVG is a private framework, so no + /// SDK header declares `CGSVGDocumentRef`, and SwiftUICore's references to + /// it found no module until CoreSVG's export of `CGSVGDocumentGetTypeID` + /// was read. Read from this Mac's shared cache and as loaded in-process. + @Test + func coreSVGDeclaresItsPrivateDocumentType() async throws { + let coreSVGPath = "/System/Library/PrivateFrameworks/CoreSVG.framework/Versions/A/CoreSVG" + _ = try #require(dlopen(coreSVGPath, RTLD_LAZY), "CoreSVG did not load") + let (machOFile, machOImage) = try ProcessImages.cacheFileAndLoadedImage(path: coreSVGPath) + let fileTypeNames = await CFDeclaredTypeNames(machO: machOFile, imagePath: coreSVGPath).declaredTypeNames() + let imageTypeNames = await CFDeclaredTypeNames(machO: machOImage, imagePath: coreSVGPath).declaredTypeNames() + #expect(fileTypeNames.contains("CGSVGDocumentRef")) + #expect(imageTypeNames.contains("CGSVGDocumentRef")) + } +} + +#endif diff --git a/Tests/SwiftTypeNameResolutionTests/ImageDeclaredTypeNamesTests.swift b/Tests/SwiftTypeNameResolutionTests/ImageDeclaredTypeNamesTests.swift new file mode 100644 index 000000000..ff6f291b1 --- /dev/null +++ b/Tests/SwiftTypeNameResolutionTests/ImageDeclaredTypeNamesTests.swift @@ -0,0 +1,29 @@ +#if os(macOS) + +import Darwin +import MachOKit +import ObjCMetadataSource +import SwiftSectionFixtureSupport +import SwiftTypeNameResolution +import Testing + +/// `ImageDeclaredTypeNames` lists both kinds of names one image declares, +/// because `TypeDatabase` reads only the first source registered for an image +/// path (evolution proposal `private-cf-type-modules`). +@Suite +struct ImageDeclaredTypeNamesTests { + /// IOSurface declares both under nearly one name: the Objective-C class + /// `IOSurface`, and the CF type `IOSurfaceRef`, which keeps its `Ref` in + /// Swift because the class already took the stripped name. + @Test + func listsTheObjectiveCClassAndTheCFTypeOfOneImage() async throws { + let ioSurfacePath = "/System/Library/Frameworks/IOSurface.framework/Versions/A/IOSurface" + _ = try #require(dlopen(ioSurfacePath, RTLD_LAZY), "IOSurface did not load") + let (machOFile, _) = try ProcessImages.cacheFileAndLoadedImage(path: ioSurfacePath) + let declaredTypeNames = try await ImageDeclaredTypeNames(machO: machOFile, imagePath: ioSurfacePath).declaredTypeNames() + #expect(declaredTypeNames.contains("IOSurface")) + #expect(declaredTypeNames.contains("IOSurfaceRef")) + } +} + +#endif diff --git a/Tests/SwiftTypeNameResolutionTests/PrivateCFTypeModuleTests.swift b/Tests/SwiftTypeNameResolutionTests/PrivateCFTypeModuleTests.swift new file mode 100644 index 000000000..1253c722d --- /dev/null +++ b/Tests/SwiftTypeNameResolutionTests/PrivateCFTypeModuleTests.swift @@ -0,0 +1,157 @@ +#if os(macOS) + +import Foundation +import MachODependencies +import MachOKit +import Semantic +import SwiftInterface +import SwiftSectionFixtureSupport +import SwiftTypeNameResolution +import Testing + +/// Evolution proposal `private-cf-type-modules`, end to end: a CF type no SDK +/// header declares prints under the module of the image exporting its +/// `GetTypeID` function, through `SwiftInterfaceBuilderTypeNameProvider`. +/// +/// `ProbeCF` stands for a private framework such as CoreSVG: a C library +/// exporting `ProbeWidgetGetTypeID`. `ProbeKit` stands for SwiftUICore: a Swift +/// library whose bridging header declares the CF types, which links `ProbeCF` +/// and defines a CF type of its own, exporting `ProbeGadgetGetTypeID` through +/// `@_cdecl`, and declares a third, `ProbeLonelyRef`, that no image exports a +/// `GetTypeID` for — a bridged type made up without the CF convention. `ProbeCF` +/// also exports `ProbeDecoyGetTypeID` while `ProbeKit`'s `ProbeDecoyRef` is a +/// `swift_wrapper` struct, no CF class: a `GetTypeID` export alone must not claim it. +/// `FixtureCompiler` gives every library the install name +/// `@rpath/lib.dylib`, and `TypeDatabase` names a module after the +/// install name's file, so the two modules read `libProbeCF` and `libProbeKit`. +@Suite +struct PrivateCFTypeModuleTests { + private static let probeCFSource = """ + unsigned long ProbeWidgetGetTypeID(void) { return 1; } + unsigned long ProbeDecoyGetTypeID(void) { return 3; } + """ + + private static let probeKitBridgingHeader = """ + #include + typedef struct CF_BRIDGED_TYPE(id) __ProbeWidget *ProbeWidgetRef; + typedef struct CF_BRIDGED_TYPE(id) __ProbeGadget *ProbeGadgetRef; + typedef struct CF_BRIDGED_TYPE(id) __ProbeLonely *ProbeLonelyRef; + typedef unsigned int ProbeDecoyRef __attribute__((swift_wrapper(struct))); + CFTypeID ProbeWidgetGetTypeID(void); + """ + + /// `Anchor` keeps a `__DATA` segment in the dylib. Hashing the CF + /// types through a generic function makes the library carry their type + /// descriptors, and calling `ProbeWidgetGetTypeID` keeps `ProbeCF` among + /// its load commands. + private static let probeKitSource = """ + import Foundation + + public final class Anchor {} + + public struct Holder { + public var widget: ProbeWidget + public var gadget: ProbeGadget + public var lonely: ProbeLonely + public var decoy: ProbeDecoyRef + + public init(widget: ProbeWidget, gadget: ProbeGadget, lonely: ProbeLonely, decoy: ProbeDecoyRef) { + self.widget = widget + self.gadget = gadget + self.lonely = lonely + self.decoy = decoy + } + } + + @_cdecl("ProbeGadgetGetTypeID") + public func probeGadgetGetTypeID() -> UInt { + 2 + } + + @inline(never) + public func hashValue(of value: Value) -> Int { + value.hashValue + } + + public func exercise(_ holder: Holder) -> Int { + hashValue(of: holder.widget) &+ hashValue(of: holder.gadget) &+ hashValue(of: holder.lonely) &+ hashValue(of: holder.decoy) &+ Int(ProbeWidgetGetTypeID()) + } + """ + + private struct FixtureLibraries: Sendable { + let probeKitURL: URL + let probeCFURL: URL + } + + private static let fixtureLibraries = Result(catching: { + let probeCFURL = try FixtureCompiler.shared.dynamicLibrary(named: "ProbeCF", language: .c, source: probeCFSource) + let headerDirectoryURL = FileManager.default.temporaryDirectory + .appending(component: "PrivateCFTypeModuleTests-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: headerDirectoryURL, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: headerDirectoryURL) } + let headerURL = headerDirectoryURL.appending(component: "ProbeKit-Bridging-Header.h") + try probeKitBridgingHeader.write(to: headerURL, atomically: true, encoding: .utf8) + let probeKitURL = try FixtureCompiler.shared.dynamicLibrary( + named: "ProbeKit", + language: .swift, + sourceFiles: [FixtureSourceFile(name: "ProbeKit.swift", contents: probeKitSource)], + arguments: ["-swift-version", "5", "-import-objc-header", headerURL.path, "-Xlinker", probeCFURL.path] + ) + return FixtureLibraries(probeKitURL: probeKitURL, probeCFURL: probeCFURL) + }) + + /// `ProbeKit`'s interface; with the provider, `ProbeCF` is its one + /// resolvable dependency. + private static func probeKitInterface(attachingTypeNameProvider: Bool) async throws -> String { + let libraries = try fixtureLibraries.get() + let probeKit = try HostSlice.machOFile(at: libraries.probeKitURL) + let builder = try SwiftInterfaceBuilder(in: probeKit) + if attachingTypeNameProvider { + let dependencies = SwiftInterfaceBuilderDependencies(machO: probeKit, searchPaths: [.machOFile(path: libraries.probeCFURL.path)]) + let typeNameProvider = try #require(SwiftInterfaceBuilderTypeNameProvider(machO: probeKit, dependencies: dependencies)) + builder.addExtraDataProvider(typeNameProvider) + } + try await builder.prepare() + return try await builder.printRoot().string + } + + @Test + func aPrivateCFTypePrintsUnderTheImageExportingItsTypeID() async throws { + let interface = try await Self.probeKitInterface(attachingTypeNameProvider: true) + #expect(interface.contains("widget: libProbeCF.ProbeWidget"), "\(interface)") + } + + @Test + func aCFTypeTheRootDefinesPrintsUnderTheRootsModule() async throws { + let interface = try await Self.probeKitInterface(attachingTypeNameProvider: true) + #expect(interface.contains("gadget: libProbeKit.ProbeGadget"), "\(interface)") + } + + /// No image exports `ProbeLonelyGetTypeID`, and nothing else in the binaries + /// names the module that declares `ProbeLonelyRef` — the class it is + /// bridged to is not recorded — so it keeps the descriptor's bare name. + @Test + func aBridgedTypeWithoutATypeIDFunctionKeepsItsBareSwiftName() async throws { + let interface = try await Self.probeKitInterface(attachingTypeNameProvider: true) + #expect(interface.contains("lonely: ProbeLonely\n"), "\(interface)") + } + + /// The decoy's descriptor is a struct promoted from a C typedef, not the + /// foreign class ClangImporter gives a CF type, so `ProbeCF`'s + /// `ProbeDecoyGetTypeID` says nothing about it. + @Test + func aGetTypeIDExportDoesNotClaimATypedefThatIsNoCFClass() async throws { + let interface = try await Self.probeKitInterface(attachingTypeNameProvider: true) + #expect(interface.contains("var decoy: "), "\(interface)") + #expect(!interface.contains("libProbeCF.ProbeDecoyRef"), "\(interface)") + } + + /// What 0106 alone prints: the descriptor's Swift name, with no module. + @Test + func withoutTheProviderAPrivateCFTypeKeepsItsBareSwiftName() async throws { + let interface = try await Self.probeKitInterface(attachingTypeNameProvider: false) + #expect(interface.contains("widget: ProbeWidget"), "\(interface)") + } +} + +#endif diff --git a/Tests/SwiftTypeNameResolutionTests/TypeDatabaseMovedTypeModuleResolverTests.swift b/Tests/SwiftTypeNameResolutionTests/TypeDatabaseMovedTypeModuleResolverTests.swift new file mode 100644 index 000000000..2522dfca0 --- /dev/null +++ b/Tests/SwiftTypeNameResolutionTests/TypeDatabaseMovedTypeModuleResolverTests.swift @@ -0,0 +1,89 @@ +#if os(macOS) + +import Foundation +import MachOKit +import SwiftInterface +import SwiftPrinting +import SwiftSectionFixtureSupport +import Testing +import TypeIndexing +@testable import SwiftTypeNameResolution + +/// The adapters between swift-type-indexing's moved-type answers and the +/// printer (evolution proposal `moved-swift-type-modules`). Reads this Mac's +/// macOS SDK — its textual module interfaces, no sourcekitd — into a +/// temporary cache directory. +@Suite +struct TypeDatabaseMovedTypeModuleResolverTests { + private static func indexedDatabase() async throws -> (typeDatabase: TypeDatabase, cacheDirectoryURL: URL) { + let cacheDirectoryURL = FileManager.default.temporaryDirectory + .appending(component: "TypeDatabaseMovedTypeModuleResolverTests-\(UUID().uuidString)") + let typeDatabase = TypeDatabase(platform: .macOS, cacheDirectory: cacheDirectoryURL) + try await typeDatabase.index(dependencies: [], moduleFilter: { _ in false }) + return (typeDatabase, cacheDirectoryURL) + } + + /// A small library built against this Mac's SDK, so its `LC_BUILD_VERSION` + /// names an SDK every move recorded in it is in effect for. + private static func fixtureMachOFile() throws -> MachOFile { + let libraryURL = try FixtureCompiler.shared.dynamicLibrary( + named: "MovedTypeModuleResolverFixture", + language: .swift, + sourceFiles: [FixtureSourceFile(name: "MovedTypeModuleResolverFixture.swift", contents: """ + import Foundation + public final class FixtureAnchor {} + public struct Holder { + public var width: CGFloat + public init(width: CGFloat) { self.width = width } + } + """)], + arguments: ["-swift-version", "5", "-target", "arm64-apple-macosx15.0"] + ) + return try HostSlice.machOFile(at: libraryURL) + } + + @Test + func resolverAnswersForTheImagesSDKVersion() async throws { + let (typeDatabase, cacheDirectoryURL) = try await Self.indexedDatabase() + defer { try? FileManager.default.removeItem(at: cacheDirectoryURL) } + let macOS15Resolver = TypeDatabaseMovedTypeModuleResolver(typeDatabase: typeDatabase, sdkVersion: OperatingSystemVersion(majorVersion: 15, minorVersion: 0, patchVersion: 0)) + let macOS14Resolver = TypeDatabaseMovedTypeModuleResolver(typeDatabase: typeDatabase, sdkVersion: OperatingSystemVersion(majorVersion: 14, minorVersion: 6, patchVersion: 0)) + + #expect(await macOS15Resolver.declaringModuleName(ofMovedTypeNamed: "View", originallyDefinedIn: "SwiftUI") == "SwiftUICore") + #expect(await macOS14Resolver.declaringModuleName(ofMovedTypeNamed: "View", originallyDefinedIn: "SwiftUI") == nil) + #expect(await macOS14Resolver.declaringModuleName(ofMovedTypeNamed: "CGFloat", originallyDefinedIn: "CoreGraphics") == "CoreFoundation") + #expect(await macOS15Resolver.declaringModuleName(ofMovedTypeNamed: "Int", originallyDefinedIn: "Swift") == nil) + } + + /// Only moved types: the setup reads the SDK's interfaces as text and + /// generates no module interface, and the `__C` questions are not + /// answered. + @Test + func providerWithOnlyMovedTypesAnswersNoCImportedQuestion() async throws { + let machOFile = try Self.fixtureMachOFile() + let provider = try #require(SwiftInterfaceBuilderTypeNameProvider( + machO: machOFile, + dependencies: SwiftInterfaceBuilderDependencies(machO: machOFile, searchPaths: []), + resolutions: .movedTypeModules + )) + try await provider.setup() + #expect(await provider.declaringModuleName(ofMovedTypeNamed: "CGFloat", originallyDefinedIn: "CoreGraphics") == "CoreFoundation") + #expect(await provider.moduleName(forTypeName: "NSObject") == nil) + #expect(await provider.swiftName(forCName: "CFStringRef", category: .other) == nil) + } + + /// The default keeps what the provider resolved before moved types + /// existed; it is not asked about moves, so nothing is indexed here. + @Test + func providerDefaultKeepsTodaysResolutions() async throws { + let machOFile = try Self.fixtureMachOFile() + let provider = try #require(SwiftInterfaceBuilderTypeNameProvider( + machO: machOFile, + dependencies: SwiftInterfaceBuilderDependencies(machO: machOFile, searchPaths: []) + )) + #expect(provider.resolutions == .cImportedModules) + #expect(await provider.declaringModuleName(ofMovedTypeNamed: "CGFloat", originallyDefinedIn: "CoreGraphics") == nil) + } +} + +#endif diff --git a/Tests/SwiftTypeNameResolutionTests/TypeDatabaseTypeNameResolverTests.swift b/Tests/SwiftTypeNameResolutionTests/TypeDatabaseTypeNameResolverTests.swift new file mode 100644 index 000000000..33b7b7e76 --- /dev/null +++ b/Tests/SwiftTypeNameResolutionTests/TypeDatabaseTypeNameResolverTests.swift @@ -0,0 +1,72 @@ +#if os(macOS) + +import Foundation +import MachOKit +import SwiftPrinting +import Testing +import TypeIndexing +@testable import SwiftTypeNameResolution + +/// The adapter between swift-type-indexing's `TypeDatabase` and the printer's +/// type-name resolver roles. +@Suite +struct TypeDatabaseTypeNameResolverTests { + @Test + func resolverMapsEveryPrinterCategory() { + #expect(ImportedTypeNameCategory(CImportedTypeNameCategory.objcClass) == .objcClass) + #expect(ImportedTypeNameCategory(CImportedTypeNameCategory.objcProtocol) == .objcProtocol) + #expect(ImportedTypeNameCategory(CImportedTypeNameCategory.valueType) == .valueType) + #expect(ImportedTypeNameCategory(CImportedTypeNameCategory.other) == .other) + } + + /// A Mac Catalyst binary reads the macOS SDK through `System/iOSSupport`: + /// mapped to `.macOS`, as before the index moved out, its UIKit types + /// found no API notes. + @Test + func buildPlatformsMapToTheirSDKs() { + guard #available(macOS 13.0, *) else { return } + #expect(SDKPlatform(MachOKit.Platform.macOS) == .macOS) + #expect(SDKPlatform(MachOKit.Platform.macCatalyst) == .macCatalyst) + #expect(SDKPlatform(MachOKit.Platform.iOS) == .iOS) + #expect(SDKPlatform(MachOKit.Platform.iOSSimulator) == .iOSSimulator) + } + + /// The printer's two questions, answered from API notes: the declaring + /// module, and the Swift name of a `SwiftPrivate` class and of a + /// protocol-only rename. Reads this Mac's macOS SDK (API notes only, no + /// sourcekitd) plus a supplementary file. + @Test + func resolverAnswersModuleAndSwiftName() async throws { + guard #available(macOS 13.0, *) else { return } + let temporaryDirectoryURL = FileManager.default.temporaryDirectory + .appending(component: "TypeDatabaseTypeNameResolverTests-\(UUID().uuidString)") + let apiNotesDirectoryURL = temporaryDirectoryURL.appending(component: "APINotes") + try FileManager.default.createDirectory(at: apiNotesDirectoryURL, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: temporaryDirectoryURL) } + try """ + Name: SampleKit + Classes: + - Name: SMPHiddenState + SwiftPrivate: true + Protocols: + - Name: SMPDelegate + SwiftName: SampleDelegate + """.write(to: apiNotesDirectoryURL.appending(component: "SampleKit.apinotes"), atomically: true, encoding: .utf8) + + let typeDatabase = TypeDatabase( + platform: .macOS, + cacheDirectory: temporaryDirectoryURL.appending(component: "Cache"), + supplementaryAPINotesURLs: [apiNotesDirectoryURL] + ) + try await typeDatabase.index(dependencies: [], moduleFilter: { _ in false }) + let resolver = TypeDatabaseTypeNameResolver(typeDatabase: typeDatabase) + + #expect(await resolver.moduleName(forTypeName: "SMPHiddenState") == "SampleKit") + #expect(await resolver.swiftName(forCName: "SMPHiddenState", category: .objcClass) == "__SMPHiddenState") + #expect(await resolver.swiftName(forCName: "SMPDelegate", category: .objcProtocol) == "SampleDelegate") + #expect(await resolver.swiftName(forCName: "SMPDelegate", category: .objcClass) == nil) + #expect(await resolver.moduleName(forTypeName: "NSObject") == "ObjectiveC") + } +} + +#endif diff --git a/Tests/TypeIndexingTests/APINotesIndexTests.swift b/Tests/TypeIndexingTests/APINotesIndexTests.swift deleted file mode 100644 index 93e30ee53..000000000 --- a/Tests/TypeIndexingTests/APINotesIndexTests.swift +++ /dev/null @@ -1,101 +0,0 @@ -#if os(macOS) - -import Foundation -import SwiftPrinting -import Testing -@testable import TypeIndexing - -@Suite -struct APINotesIndexTests { - /// Writes a minimal APINotes YAML to a temporary file and parses it the - /// same way SDK discovery does. - private static func makeIndex() throws -> APINotesIndex { - let apiNotesYAML = """ - Name: TestModule - Classes: - - Name: TSTRenamedThing - SwiftName: RenamedThing - - Name: TSTPlainThing - - Name: TSTPrivateThing - SwiftName: __PrivateThing - SwiftPrivate: true - Tags: - - Name: TSTOptions - SwiftName: RenamedThing.Options - Typedefs: - - Name: TSTIdentifier - """ - let temporaryFileURL = FileManager.default.temporaryDirectory - .appending(component: "APINotesIndexTests-\(UUID().uuidString).apinotes") - try apiNotesYAML.write(to: temporaryFileURL, atomically: true, encoding: .utf8) - defer { try? FileManager.default.removeItem(at: temporaryFileURL) } - let apiNotesFile = try APINotesFile(path: temporaryFileURL.path(percentEncoded: false)) - return APINotesIndex(files: [apiNotesFile]) - } - - /// The historical implementation stored the *Swift name* into the - /// `moduleName` field of the C-name → Swift-name mapping, so the declaring - /// module was unrecoverable. The declaring module must be the module whose - /// APINotes file carries the entry. - @Test - func swiftNameLookupCarriesTheDeclaringModule() throws { - let index = try Self.makeIndex() - let swiftName = index.swiftName(forCName: "TSTRenamedThing", category: .objcClass) - #expect(swiftName?.name == "RenamedThing") - #expect(swiftName?.moduleName == "TestModule") - } - - /// ObjC declares both a class and a protocol named `NSObject`, and only - /// the protocol is renamed — the tables must be category-isolated so the - /// protocol's rename never rewrites class references. - @Test - func renameTablesAreCategoryIsolated() throws { - let apiNotesYAML = """ - Name: ObjectiveC - Classes: - - Name: NSObject - Protocols: - - Name: NSObject - SwiftName: NSObjectProtocol - """ - let temporaryFileURL = FileManager.default.temporaryDirectory - .appending(component: "APINotesIndexTests-\(UUID().uuidString).apinotes") - try apiNotesYAML.write(to: temporaryFileURL, atomically: true, encoding: .utf8) - defer { try? FileManager.default.removeItem(at: temporaryFileURL) } - let index = try APINotesIndex(files: [APINotesFile(path: temporaryFileURL.path(percentEncoded: false))]) - - #expect(index.swiftName(forCName: "NSObject", category: .objcProtocol)?.name == "NSObjectProtocol") - #expect(index.swiftName(forCName: "NSObject", category: .objcClass) == nil) - #expect(index.swiftName(forCName: "NSObject", category: .other) == nil) - } - - @Test - func cNameLookupIsTheReverseDirection() throws { - let index = try Self.makeIndex() - let cName = index.cName(forSwiftName: "RenamedThing.Options") - #expect(cName?.name == "TSTOptions") - #expect(cName?.moduleName == "TestModule") - } - - @Test - func everyListedEntityGetsModuleAttributionRenamedOrNot() throws { - let index = try Self.makeIndex() - #expect(index.moduleName(forCName: "TSTRenamedThing") == "TestModule") - #expect(index.moduleName(forCName: "TSTPlainThing") == "TestModule") - #expect(index.moduleName(forCName: "TSTOptions") == "TestModule") - #expect(index.moduleName(forCName: "TSTIdentifier") == "TestModule") - #expect(index.moduleName(forCName: "TSTUnknown") == nil) - } - - /// `SwiftPrivate` entities keep their module attribution (their C name - /// still appears in manglings) but stay out of the rename tables. - @Test - func swiftPrivateEntitiesAreAttributedButNotRenamed() throws { - let index = try Self.makeIndex() - #expect(index.moduleName(forCName: "TSTPrivateThing") == "TestModule") - #expect(index.swiftName(forCName: "TSTPrivateThing", category: .objcClass) == nil) - #expect(index.cName(forSwiftName: "__PrivateThing") == nil) - } -} - -#endif diff --git a/Tests/TypeIndexingTests/ImportScanTests.swift b/Tests/TypeIndexingTests/ImportScanTests.swift deleted file mode 100644 index ba45dfb5c..000000000 --- a/Tests/TypeIndexingTests/ImportScanTests.swift +++ /dev/null @@ -1,55 +0,0 @@ -#if os(macOS) - -import Testing -@testable import TypeIndexing - -@Suite -struct ImportScanTests { - @Test - func plainAndAttributedImportsAreCollectedInOrder() { - let sourceText = """ - import Foundation - @_exported import ObjectiveC - public import CoreGraphics - """ - #expect(SourceKitManager.importedModuleNames(inInterfaceSourceText: sourceText) == [ - "Foundation", - "ObjectiveC", - "CoreGraphics", - ]) - } - - @Test - func subModuleImportsKeepTheirDottedSpelling() { - let sourceText = """ - import Foundation.NSObject - import Foundation.NSString - """ - #expect(SourceKitManager.importedModuleNames(inInterfaceSourceText: sourceText) == [ - "Foundation.NSObject", - "Foundation.NSString", - ]) - } - - @Test - func duplicatesCommentsAndNonImportLinesAreIgnored() { - let sourceText = """ - // import CommentedOut - import Foundation - import Foundation - let importCount = 1 - func doSomething() { } - """ - #expect(SourceKitManager.importedModuleNames(inInterfaceSourceText: sourceText) == ["Foundation"]) - } - - @Test - func importAppearingAfterNonModifierTokensIsRejected() { - let sourceText = """ - let value = import Foundation - """ - #expect(SourceKitManager.importedModuleNames(inInterfaceSourceText: sourceText).isEmpty) - } -} - -#endif diff --git a/Tests/TypeIndexingTests/InterfaceTypeNameExtractorTests.swift b/Tests/TypeIndexingTests/InterfaceTypeNameExtractorTests.swift deleted file mode 100644 index d4e855b63..000000000 --- a/Tests/TypeIndexingTests/InterfaceTypeNameExtractorTests.swift +++ /dev/null @@ -1,113 +0,0 @@ -#if os(macOS) - -import Testing -@testable import TypeIndexing - -@Suite -struct InterfaceTypeNameExtractorTests { - private typealias Node = InterfaceDeclarationNode - - @Test - func topLevelTypeDeclarationsAreCollected() { - let declarations = [ - Node(kind: .typeDeclaration, name: "NSString"), - Node(kind: .typeDeclaration, name: "NSURLSession"), - Node(kind: .typeAlias, name: "NSStringEncoding"), - Node(kind: .other, name: "someGlobalFunction()"), - ] - #expect(InterfaceTypeNameExtractor.fullyQualifiedTypeNames(in: declarations) == [ - "NSString", - "NSURLSession", - "NSStringEncoding", - ]) - } - - @Test - func nestedTypesAreQualifiedByTheirParentChain() { - let declarations = [ - Node(kind: .typeDeclaration, name: "Outer", children: [ - Node(kind: .typeDeclaration, name: "Inner", children: [ - Node(kind: .typeDeclaration, name: "Innermost"), - ]), - Node(kind: .other, name: "someMethod()"), - ]), - ] - #expect(InterfaceTypeNameExtractor.fullyQualifiedTypeNames(in: declarations) == [ - "Outer", - "Outer.Inner", - "Outer.Inner.Innermost", - ]) - } - - /// The historical SwiftSyntax-based parser registered a type declared in - /// an extension under its bare name — `extension Foo { struct Bar }` - /// produced a `Bar` key. The extractor must qualify through the extended - /// type instead. - @Test - func typesNestedInExtensionsAreQualifiedByTheExtendedTypeName() { - let declarations = [ - Node(kind: .extension, name: "Foo", children: [ - Node(kind: .typeDeclaration, name: "Bar"), - ]), - ] - #expect(InterfaceTypeNameExtractor.fullyQualifiedTypeNames(in: declarations) == ["Foo.Bar"]) - } - - @Test - func dotQualifiedExtendedTypeNamesQualifyTransitively() { - let declarations = [ - Node(kind: .extension, name: "Foo.Bar", children: [ - Node(kind: .typeDeclaration, name: "Baz"), - ]), - ] - #expect(InterfaceTypeNameExtractor.fullyQualifiedTypeNames(in: declarations) == ["Foo.Bar.Baz"]) - } - - @Test - func extensionsThemselvesAreNotIndexedNames() { - let declarations = [ - Node(kind: .extension, name: "NSString", children: [ - Node(kind: .other, name: "someMethod()"), - ]), - ] - #expect(InterfaceTypeNameExtractor.fullyQualifiedTypeNames(in: declarations).isEmpty) - } - - @Test - func otherNodesAreNeverDescendedInto() { - let declarations = [ - Node(kind: .other, name: "someGlobalFunction()", children: [ - Node(kind: .typeDeclaration, name: "LocalTypeThatMustNotLeak"), - ]), - ] - #expect(InterfaceTypeNameExtractor.fullyQualifiedTypeNames(in: declarations).isEmpty) - } - - @Test - func namelessDeclarationsAreSkipped() { - let declarations = [ - Node(kind: .typeDeclaration, name: nil), - Node(kind: .typeDeclaration, name: ""), - Node(kind: .typeDeclaration, name: "Survivor"), - ] - #expect(InterfaceTypeNameExtractor.fullyQualifiedTypeNames(in: declarations) == ["Survivor"]) - } - - @Test - func sourceKitDeclarationKindsMapOntoTheExtractorVocabulary() { - #expect(InterfaceDeclarationNode.kind(forUIDString: "source.lang.swift.decl.struct") == .typeDeclaration) - #expect(InterfaceDeclarationNode.kind(forUIDString: "source.lang.swift.decl.class") == .typeDeclaration) - #expect(InterfaceDeclarationNode.kind(forUIDString: "source.lang.swift.decl.actor") == .typeDeclaration) - #expect(InterfaceDeclarationNode.kind(forUIDString: "source.lang.swift.decl.enum") == .typeDeclaration) - #expect(InterfaceDeclarationNode.kind(forUIDString: "source.lang.swift.decl.protocol") == .typeDeclaration) - #expect(InterfaceDeclarationNode.kind(forUIDString: "source.lang.swift.decl.typealias") == .typeAlias) - #expect(InterfaceDeclarationNode.kind(forUIDString: "source.lang.swift.decl.extension") == .extension) - #expect(InterfaceDeclarationNode.kind(forUIDString: "source.lang.swift.decl.extension.struct") == .extension) - #expect(InterfaceDeclarationNode.kind(forUIDString: "source.lang.swift.decl.function.method.instance") == .other) - #expect(InterfaceDeclarationNode.kind(forUIDString: "source.lang.swift.decl.var.instance") == .other) - #expect(InterfaceDeclarationNode.kind(forUIDString: "source.lang.swift.decl.enumcase") == .other) - #expect(InterfaceDeclarationNode.kind(forUIDString: "source.lang.swift.decl.associatedtype") == .other) - } -} - -#endif diff --git a/Tests/TypeIndexingTests/ModuleIndexCacheTests.swift b/Tests/TypeIndexingTests/ModuleIndexCacheTests.swift deleted file mode 100644 index de90ab54c..000000000 --- a/Tests/TypeIndexingTests/ModuleIndexCacheTests.swift +++ /dev/null @@ -1,55 +0,0 @@ -#if os(macOS) - -import Foundation -import Testing -@testable import TypeIndexing - -@Suite -struct ModuleIndexCacheTests { - private static func makeTemporaryCache() -> ModuleIndexCache { - ModuleIndexCache( - directoryURL: FileManager.default.temporaryDirectory - .appending(component: "ModuleIndexCacheTests-\(UUID().uuidString)") - ) - } - - @Test - func storedEntriesRoundTrip() { - let cache = Self.makeTemporaryCache() - defer { try? FileManager.default.removeItem(at: cache.directoryURL) } - let entry = ModuleIndexCacheEntry( - moduleName: "Foundation", - typeNames: ["NSString", "NSURLSession.Configuration"], - subModuleNames: ["Foundation.NSObject"] - ) - cache.store(entry) - let loadedEntry = cache.entry(forModuleNamed: "Foundation") - #expect(loadedEntry?.moduleName == "Foundation") - #expect(loadedEntry?.typeNames == ["NSString", "NSURLSession.Configuration"]) - #expect(loadedEntry?.subModuleNames == ["Foundation.NSObject"]) - } - - @Test - func missingEntriesReadAsNil() { - let cache = Self.makeTemporaryCache() - #expect(cache.entry(forModuleNamed: "NeverStored") == nil) - } - - /// An entry written by an older extractor must not survive a generator - /// bump — stale extraction semantics regenerate instead of being served. - @Test - func mismatchedGeneratorVersionInvalidatesTheEntry() { - let cache = Self.makeTemporaryCache() - defer { try? FileManager.default.removeItem(at: cache.directoryURL) } - let outdatedEntry = ModuleIndexCacheEntry( - moduleName: "Foundation", - typeNames: ["NSString"], - subModuleNames: [], - generatorVersion: ModuleIndexCacheEntry.currentGeneratorVersion - 1 - ) - cache.store(outdatedEntry) - #expect(cache.entry(forModuleNamed: "Foundation") == nil) - } -} - -#endif diff --git a/Tests/TypeIndexingTests/ModuleInterfaceIndexerTests.swift b/Tests/TypeIndexingTests/ModuleInterfaceIndexerTests.swift deleted file mode 100644 index 5c048c805..000000000 --- a/Tests/TypeIndexingTests/ModuleInterfaceIndexerTests.swift +++ /dev/null @@ -1,93 +0,0 @@ -#if os(macOS) - -import Foundation -import Testing -@testable import TypeIndexing - -/// The cache-write discipline of `ModuleInterfaceIndexer`, driven through its -/// interface-generator test seam — no sourcekitd. -@Suite -struct ModuleInterfaceIndexerTests { - private static func makeCache() throws -> ModuleIndexCache { - let directoryURL = FileManager.default.temporaryDirectory - .appending(component: "ModuleInterfaceIndexerTests-\(UUID().uuidString)") - try FileManager.default.createDirectory(at: directoryURL, withIntermediateDirectories: true) - return ModuleIndexCache(directoryURL: directoryURL) - } - - private static func makeIndexer(cache: ModuleIndexCache, interfaceGenerator: @escaping ModuleInterfaceIndexer.InterfaceGenerator) -> ModuleInterfaceIndexer { - ModuleInterfaceIndexer( - platform: .macOS, - sdkSettings: SDKSettings(sdkPath: "/nonexistent-sdk", version: "0.0", productBuildVersion: nil), - cache: cache, - interfaceGenerator: interfaceGenerator - ) - } - - private static func interface(moduleName: String, typeNames: [String], importedModuleNames: [String] = []) -> SourceKitManager.GeneratedModuleInterface { - SourceKitManager.GeneratedModuleInterface( - moduleName: moduleName, - sourceText: "", - declarations: typeNames.map { InterfaceDeclarationNode(kind: .typeDeclaration, name: $0) }, - importedModuleNames: importedModuleNames - ) - } - - enum StubError: Error { - case submoduleTimedOut - } - - /// A submodule whose generation fails degrades the entry for THIS run but - /// must not be cached: the cache has no completeness marker, so a stored - /// partial entry would freeze the gap until the SDK or generator version - /// changes (PR #110 review, finding 4). - @Test - func partialEntryIsServedButNeverCached() async throws { - let cache = try Self.makeCache() - let indexer = Self.makeIndexer(cache: cache) { moduleName in - if moduleName == "Foo" { - return Self.interface(moduleName: "Foo", typeNames: ["FooType"], importedModuleNames: ["Foo.Sub", "Unrelated"]) - } - throw StubError.submoduleTimedOut - } - - let entry = await indexer.indexEntry(forModuleNamed: "Foo") - #expect(entry?.typeNames == ["FooType"]) - #expect(cache.entry(forModuleNamed: "Foo") == nil) - } - - @Test - func completeEntryIsCached() async throws { - let cache = try Self.makeCache() - let indexer = Self.makeIndexer(cache: cache) { moduleName in - switch moduleName { - case "Foo": - return Self.interface(moduleName: "Foo", typeNames: ["FooType"], importedModuleNames: ["Foo.Sub"]) - case "Foo.Sub": - return Self.interface(moduleName: "Foo.Sub", typeNames: ["SubType"]) - default: - throw StubError.submoduleTimedOut - } - } - - let entry = await indexer.indexEntry(forModuleNamed: "Foo") - #expect(entry?.typeNames == ["FooType", "SubType"]) - #expect(cache.entry(forModuleNamed: "Foo")?.typeNames == ["FooType", "SubType"]) - } - - /// The whole module failing still returns `nil` and caches nothing — the - /// pre-existing contract, pinned alongside the partial-entry rule. - @Test - func failedModuleCachesNothing() async throws { - let cache = try Self.makeCache() - let indexer = Self.makeIndexer(cache: cache) { _ in - throw StubError.submoduleTimedOut - } - - let entry = await indexer.indexEntry(forModuleNamed: "Foo") - #expect(entry == nil) - #expect(cache.entry(forModuleNamed: "Foo") == nil) - } -} - -#endif diff --git a/Tests/TypeIndexingTests/SupplementaryAPINotesTests.swift b/Tests/TypeIndexingTests/SupplementaryAPINotesTests.swift deleted file mode 100644 index 08036a70a..000000000 --- a/Tests/TypeIndexingTests/SupplementaryAPINotesTests.swift +++ /dev/null @@ -1,200 +0,0 @@ -#if os(macOS) - -import Foundation -import MachOKit -import SwiftPrinting -import Testing -@testable import TypeIndexing - -/// Supplementary APINotes files (evolution proposal 0009): user-provided -/// mappings for frameworks with no SDK module, and the merge priority that -/// lets them override SDK entries. The library ships no mappings of its own. -@Suite -struct SupplementaryAPINotesTests { - private static func writeAPINotesFile(yaml apiNotesYAML: String, into directoryURL: URL, named fileName: String) throws -> URL { - let fileURL = directoryURL.appending(component: fileName) - try apiNotesYAML.write(to: fileURL, atomically: true, encoding: .utf8) - return fileURL - } - - private static func makeTemporaryDirectory() throws -> URL { - let directoryURL = FileManager.default.temporaryDirectory - .appending(component: "SupplementaryAPINotesTests-\(UUID().uuidString)") - try FileManager.default.createDirectory(at: directoryURL, withIntermediateDirectories: true) - return directoryURL - } - - /// The AttributeGraph-shaped mapping every example in the contribution - /// guide is written against: both C spellings of each CF-bridged type. - private static let attributeGraphYAML = """ - Name: AttributeGraph - Typedefs: - - Name: AGGraphRef - SwiftName: Graph - - Name: AGSubgraphRef - SwiftName: Subgraph - Tags: - - Name: AGGraphStorage - SwiftName: Graph - - Name: AGSubgraphStorage - SwiftName: Subgraph - """ - - /// The end-to-end data flow for a user-supplied AttributeGraph mapping, - /// in both mangling shapes a CF-bridged type reaches Swift metadata as: - /// the typedef name (`AGGraphRef`, a typealias node → `.other`) and the - /// storage/tag name (`AGGraphStorage`, a foreign *class* descriptor the - /// consuming binary emits → `.objcClass`). - /// - /// The imported Swift spelling (`Graph`) is attributed as well, though - /// no printed name carries it any more: a foreign descriptor records it, - /// but the demangler names the descriptor by the ABI name in its import - /// info (evolution proposal `type-import-info-identity`). Why the - /// spellings are still registered: - /// `TypeDatabaseMergePriorityTests.renamingEntryKeepsItsModuleAgainstLaterListings`. - @Test - func userSuppliedMappingsResolveInAllManglingShapes() async throws { - let directoryURL = try Self.makeTemporaryDirectory() - defer { try? FileManager.default.removeItem(at: directoryURL) } - _ = try Self.writeAPINotesFile(yaml: Self.attributeGraphYAML, into: directoryURL, named: "AttributeGraph.apinotes") - - let typeDatabase = TypeDatabase(platform: .macOS) - await typeDatabase.register(supplementaryAPINotesFiles: SupplementaryAPINotesLoader.files(atSupplementaryLocations: [directoryURL])) - - #expect(await typeDatabase.moduleName(forTypeName: "AGGraphRef") == "AttributeGraph") - #expect(await typeDatabase.moduleName(forTypeName: "AGGraphStorage") == "AttributeGraph") - #expect(await typeDatabase.moduleName(forTypeName: "Graph") == "AttributeGraph") - #expect(await typeDatabase.moduleName(forTypeName: "Subgraph") == "AttributeGraph") - #expect(await typeDatabase.swiftName(forCName: "AGGraphRef", category: .other) == "Graph") - #expect(await typeDatabase.swiftName(forCName: "AGGraphStorage", category: .objcClass) == "Graph") - #expect(await typeDatabase.swiftName(forCName: "Graph", category: .objcClass) == nil) - #expect(await typeDatabase.swiftName(forCName: "AGSubgraphRef", category: .other) == "Subgraph") - #expect(await typeDatabase.swiftName(forCName: "AGSubgraphStorage", category: .objcClass) == "Subgraph") - } - - /// A `Tags` rename must be visible to a class-category lookup: the - /// field-metadata shape of a CF-bridged type is a foreign *class* node - /// spelled with the C tag name, while APINotes files the entry under - /// `Tags` per C semantics. A class-table entry still wins over a - /// same-named tag entry, and the protocol table never falls back. - @Test - func classCategoryLookupFallsBackToTheValueTypeTable() throws { - let directoryURL = try Self.makeTemporaryDirectory() - defer { try? FileManager.default.removeItem(at: directoryURL) } - let fileURL = try Self.writeAPINotesFile(yaml: """ - Name: TestModule - Classes: - - Name: TSTSharedName - SwiftName: ClassSpelling - Tags: - - Name: TSTSharedName - SwiftName: TagSpelling - - Name: TSTStorage - SwiftName: Renamed - Protocols: - - Name: TSTProtocolOnly - SwiftName: ProtocolSpelling - """, into: directoryURL, named: "TestModule.apinotes") - let index = APINotesIndex(files: [try APINotesFile(path: fileURL.path(percentEncoded: false))]) - - #expect(index.swiftName(forCName: "TSTStorage", category: .objcClass)?.name == "Renamed") - #expect(index.swiftName(forCName: "TSTSharedName", category: .objcClass)?.name == "ClassSpelling") - #expect(index.swiftName(forCName: "TSTProtocolOnly", category: .objcClass) == nil) - #expect(index.swiftName(forCName: "TSTProtocolOnly", category: .other) == nil) - } - - // MARK: - Merge priority - - /// A supplementary entry overrides the SDK APINotes entry for the same C - /// name — the "hit it, replace it" contract for user-supplied files. - @Test - func supplementaryEntriesOverrideSDKAPINotesEntries() async throws { - let directoryURL = try Self.makeTemporaryDirectory() - defer { try? FileManager.default.removeItem(at: directoryURL) } - let sdkFileURL = try Self.writeAPINotesFile(yaml: """ - Name: SDKModule - Typedefs: - - Name: TSTThingRef - SwiftName: SDKSpelling - """, into: directoryURL, named: "SDKModule.apinotes") - let supplementaryFileURL = try Self.writeAPINotesFile(yaml: """ - Name: CommunityModule - Typedefs: - - Name: TSTThingRef - SwiftName: CommunitySpelling - """, into: directoryURL, named: "CommunityModule.apinotes") - - let typeDatabase = TypeDatabase(platform: .macOS) - await typeDatabase.register(apiNotesIndex: APINotesIndex(files: [try APINotesFile(path: sdkFileURL.path(percentEncoded: false))])) - await typeDatabase.register(supplementaryAPINotesFiles: [try APINotesFile(path: supplementaryFileURL.path(percentEncoded: false))]) - - #expect(await typeDatabase.swiftName(forCName: "TSTThingRef", category: .other) == "CommunitySpelling") - #expect(await typeDatabase.moduleName(forTypeName: "TSTThingRef") == "CommunityModule") - } - - /// Within one supplementary registration, a later file overwrites an - /// earlier one — caller order is the override order. - @Test - func laterSupplementaryFilesOverrideEarlierOnes() async throws { - let directoryURL = try Self.makeTemporaryDirectory() - defer { try? FileManager.default.removeItem(at: directoryURL) } - let earlierFileURL = try Self.writeAPINotesFile(yaml: """ - Name: EarlierModule - Tags: - - Name: TSTStorage - SwiftName: EarlierSpelling - """, into: directoryURL, named: "EarlierModule.apinotes") - let laterFileURL = try Self.writeAPINotesFile(yaml: """ - Name: LaterModule - Tags: - - Name: TSTStorage - SwiftName: LaterSpelling - """, into: directoryURL, named: "LaterModule.apinotes") - - let typeDatabase = TypeDatabase(platform: .macOS) - await typeDatabase.register(supplementaryAPINotesFiles: [ - try APINotesFile(path: earlierFileURL.path(percentEncoded: false)), - try APINotesFile(path: laterFileURL.path(percentEncoded: false)), - ]) - - #expect(await typeDatabase.swiftName(forCName: "TSTStorage", category: .valueType) == "LaterSpelling") - } - - // MARK: - Supplied locations - - /// A location may be a directory (its immediate `.apinotes` entries load - /// in file-name order) or a single file; unparsable and missing entries - /// are skipped, never fatal. - @Test - func suppliedLocationsExpandDirectoriesAndSkipBrokenEntries() throws { - let directoryURL = try Self.makeTemporaryDirectory() - defer { try? FileManager.default.removeItem(at: directoryURL) } - _ = try Self.writeAPINotesFile(yaml: """ - Name: FirstModule - Typedefs: - - Name: TSTFirstRef - SwiftName: First - """, into: directoryURL, named: "AFirst.apinotes") - _ = try Self.writeAPINotesFile(yaml: """ - Name: SecondModule - Typedefs: - - Name: TSTSecondRef - SwiftName: Second - """, into: directoryURL, named: "BSecond.apinotes") - _ = try Self.writeAPINotesFile(yaml: "{ not apinotes", into: directoryURL, named: "CBroken.apinotes") - _ = try Self.writeAPINotesFile(yaml: "ignored", into: directoryURL, named: "NotAPINotes.txt") - let standaloneFileURL = try Self.writeAPINotesFile(yaml: """ - Name: StandaloneModule - Typedefs: - - Name: TSTStandaloneRef - SwiftName: Standalone - """, into: FileManager.default.temporaryDirectory, named: "SupplementaryAPINotesTests-standalone-\(UUID().uuidString).apinotes") - defer { try? FileManager.default.removeItem(at: standaloneFileURL) } - let missingURL = directoryURL.appending(component: "Missing.apinotes") - - let loadedFiles = SupplementaryAPINotesLoader.files(atSupplementaryLocations: [directoryURL, standaloneFileURL, missingURL]) - #expect(loadedFiles.map(\.moduleName) == ["FirstModule", "SecondModule", "StandaloneModule"]) - } -} - -#endif diff --git a/Tests/TypeIndexingTests/TypeDatabaseMergePriorityTests.swift b/Tests/TypeIndexingTests/TypeDatabaseMergePriorityTests.swift deleted file mode 100644 index de0f8b943..000000000 --- a/Tests/TypeIndexingTests/TypeDatabaseMergePriorityTests.swift +++ /dev/null @@ -1,198 +0,0 @@ -#if os(macOS) - -import Foundation -import MachOKit -import SwiftPrinting -import Testing -@testable import TypeIndexing - -/// Merge-priority behavior of `TypeDatabase`, exercised through its -/// registration steps directly — no sourcekitd, no SDK scan, no Mach-O. -@Suite -struct TypeDatabaseMergePriorityTests { - private static func makeAPINotesIndex(yaml apiNotesYAML: String) throws -> APINotesIndex { - try makeAPINotesIndex(yamls: [apiNotesYAML]) - } - - /// One index over several files, registered in the order given. - private static func makeAPINotesIndex(yamls apiNotesYAMLs: [String]) throws -> APINotesIndex { - var temporaryFileURLs: [URL] = [] - defer { - for temporaryFileURL in temporaryFileURLs { - try? FileManager.default.removeItem(at: temporaryFileURL) - } - } - for apiNotesYAML in apiNotesYAMLs { - let temporaryFileURL = FileManager.default.temporaryDirectory - .appending(component: "TypeDatabaseMergePriorityTests-\(UUID().uuidString).apinotes") - try apiNotesYAML.write(to: temporaryFileURL, atomically: true, encoding: .utf8) - temporaryFileURLs.append(temporaryFileURL) - } - return try APINotesIndex(files: temporaryFileURLs.map { try APINotesFile(path: $0.path(percentEncoded: false)) }) - } - - @Test - func interfaceExtractedNamesResolve() async { - let typeDatabase = TypeDatabase(platform: .macOS) - await typeDatabase.register(moduleEntries: [ - ModuleIndexCacheEntry(moduleName: "Foundation", typeNames: ["NSString", "NSURLSession.Configuration"], subModuleNames: []), - ModuleIndexCacheEntry(moduleName: "CoreGraphics", typeNames: ["CGRect"], subModuleNames: []), - ]) - #expect(await typeDatabase.moduleName(forTypeName: "NSString") == "Foundation") - #expect(await typeDatabase.moduleName(forTypeName: "NSURLSession.Configuration") == "Foundation") - #expect(await typeDatabase.moduleName(forTypeName: "CGRect") == "CoreGraphics") - #expect(await typeDatabase.moduleName(forTypeName: "UnknownType") == nil) - } - - /// APINotes is the compiler's own attribution record, so it overrides an - /// interface-derived entry for the same name. - @Test - func apiNotesAttributionOverridesInterfaceNames() async throws { - let typeDatabase = TypeDatabase(platform: .macOS) - await typeDatabase.register(moduleEntries: [ - ModuleIndexCacheEntry(moduleName: "WrongModule", typeNames: ["TSTThing"], subModuleNames: []), - ]) - let apiNotesIndex = try Self.makeAPINotesIndex(yaml: """ - Name: RightModule - Classes: - - Name: TSTThing - SwiftName: Thing - """) - await typeDatabase.register(apiNotesIndex: apiNotesIndex) - #expect(await typeDatabase.moduleName(forTypeName: "TSTThing") == "RightModule") - } - - /// A C name several modules' APINotes list keeps the module whose entry - /// renames it. Foundation's and AppKit's APINotes list `NSObject` only to - /// annotate category methods, and among C-name entries the last file - /// wins; ObjectiveC's entry renames `NSObject` to itself, and that - /// spelling, registered after the C names, keeps the class in - /// ObjectiveC. Without it AppKit's resolved interface printed - /// `Foundation.NSObject`. - @Test - func renamingEntryKeepsItsModuleAgainstLaterListings() async throws { - let typeDatabase = TypeDatabase(platform: .macOS) - let apiNotesIndex = try Self.makeAPINotesIndex(yamls: [ - """ - Name: DeclaringModule - Classes: - - Name: TSTBase - SwiftName: TSTBase - """, - """ - Name: AnnotatingModule - Classes: - - Name: TSTBase - """, - ]) - await typeDatabase.register(apiNotesIndex: apiNotesIndex) - #expect(await typeDatabase.moduleName(forTypeName: "TSTBase") == "DeclaringModule") - } - - @Test - func swiftNameForCNameComesFromAPINotes() async throws { - let typeDatabase = TypeDatabase(platform: .macOS) - let apiNotesIndex = try Self.makeAPINotesIndex(yaml: """ - Name: TestModule - Tags: - - Name: TSTOptions - SwiftName: Thing.Options - """) - await typeDatabase.register(apiNotesIndex: apiNotesIndex) - #expect(await typeDatabase.swiftName(forCName: "TSTOptions", category: .valueType) == "Thing.Options") - #expect(await typeDatabase.swiftName(forCName: "TSTUnknown", category: .valueType) == nil) - } - - /// The category split end-to-end through the database: the protocol-only - /// `NSObject` → `NSObjectProtocol` rename applies to protocol references - /// and never to class references. - @Test - func nsObjectClassAndProtocolReferencesResolveSeparately() async throws { - let typeDatabase = TypeDatabase(platform: .macOS) - let apiNotesIndex = try Self.makeAPINotesIndex(yaml: """ - Name: ObjectiveC - Classes: - - Name: NSObject - Protocols: - - Name: NSObject - SwiftName: NSObjectProtocol - """) - await typeDatabase.register(apiNotesIndex: apiNotesIndex) - #expect(await typeDatabase.swiftName(forCName: "NSObject", category: .objcProtocol) == "NSObjectProtocol") - #expect(await typeDatabase.swiftName(forCName: "NSObject", category: .objcClass) == nil) - } - - /// `CFStringRef` is the C spelling of the natively-bridged `CFString` - /// class (ClangImporter strips the CF `Ref` suffix), so the Swift-name - /// lookup must translate it whenever the stripped name really exists — - /// and must not touch a name whose stripped form is unknown. - @Test - func cfRefSpellingsTranslateToTheirStrippedSwiftNames() async { - let typeDatabase = TypeDatabase(platform: .macOS) - await typeDatabase.register(moduleEntries: [ - ModuleIndexCacheEntry(moduleName: "CoreFoundation", typeNames: ["CFString", "CFStringRef"], subModuleNames: []), - ]) - #expect(await typeDatabase.swiftName(forCName: "CFStringRef", category: .other) == "CFString") - #expect(await typeDatabase.swiftName(forCName: "CFStringRef", category: .objcClass) == "CFString") - #expect(await typeDatabase.swiftName(forCName: "CFStringRef", category: .objcProtocol) == nil) - #expect(await typeDatabase.swiftName(forCName: "SomeUnknownRef", category: .other) == nil) - #expect(await typeDatabase.swiftName(forCName: "CFString", category: .other) == nil) - #expect(await typeDatabase.swiftName(forCName: "Ref", category: .other) == nil) - } - - /// An APINotes rename outranks the CF `Ref`-stripping rule for the same - /// C name — the compiler's own record wins. - @Test - func apiNotesRenameOutranksTheCFRefRule() async throws { - let typeDatabase = TypeDatabase(platform: .macOS) - await typeDatabase.register(moduleEntries: [ - ModuleIndexCacheEntry(moduleName: "TestModule", typeNames: ["TSTThing"], subModuleNames: []), - ]) - let apiNotesIndex = try Self.makeAPINotesIndex(yaml: """ - Name: TestModule - Typedefs: - - Name: TSTThingRef - SwiftName: RenamedThing - """) - await typeDatabase.register(apiNotesIndex: apiNotesIndex) - #expect(await typeDatabase.swiftName(forCName: "TSTThingRef", category: .other) == "RenamedThing") - } - - @Test - func imagePathsReduceToModuleNames() { - #expect(TypeDatabase.moduleName(forImagePath: "/System/Library/Frameworks/Foundation.framework/Versions/C/Foundation") == "Foundation") - #expect(TypeDatabase.moduleName(forImagePath: "/usr/lib/swift/libswiftFoundation.dylib") == "Foundation") - #expect(TypeDatabase.moduleName(forImagePath: "/usr/lib/libobjc.A.dylib") == "libobjc") - #expect(TypeDatabase.moduleName(forImagePath: "/usr/lib/system/libsystem_c.dylib") == "libsystem_c") - } - - /// A leading-dot last path component is a fixed point of extension - /// stripping (`.hidden` → `.hidden`), which spun the strip loop forever - /// before the fixed-point guard (PR #110 review, finding 5). - @Test - func leadingDotImagePathsTerminate() { - #expect(TypeDatabase.moduleName(forImagePath: "/usr/lib/.hidden") == ".hidden") - #expect(TypeDatabase.moduleName(forImagePath: "/usr/lib/.x.y") == ".x") - #expect(TypeDatabase.moduleName(forImagePath: ".hidden") == ".hidden") - } - - /// Task-group results arrive in completion order, but registration is - /// last-writer-wins and must follow the SDK discovery order — the re-sort - /// restores it regardless of arrival order, dropping entries discovery - /// never named (PR #110 review, finding 7). - @Test - func collectedEntriesAreReorderedToDiscoveryOrder() { - let arrivalOrderedEntries = [ - ModuleIndexCacheEntry(moduleName: "Third", typeNames: [], subModuleNames: []), - ModuleIndexCacheEntry(moduleName: "First", typeNames: [], subModuleNames: []), - ModuleIndexCacheEntry(moduleName: "Second", typeNames: [], subModuleNames: []), - ] - let orderedEntries = TypeDatabase.entriesInDiscoveryOrder( - arrivalOrderedEntries, - discoveryOrder: ["First", "Second", "Third", "NeverIndexed"] - ) - #expect(orderedEntries.map(\.moduleName) == ["First", "Second", "Third"]) - } -} - -#endif diff --git a/Tuist.swift b/Tuist.swift new file mode 100644 index 000000000..33249a244 --- /dev/null +++ b/Tuist.swift @@ -0,0 +1,23 @@ +import ProjectDescription + +// Every target of MachOSwiftSection and of the five upstream packages its native workspace lists +// (MachOKit, MachOKitExtensions, MachOObjCSection, swift-demangling, swift-semantic-string) stays +// source, in both dependency modes; every other dependency comes out of the binary cache once +// `./TuistScript.sh warm` has filled it. The script reads the names from the packages' manifests and +// passes them in TUIST_SOURCE_TARGET_NAMES. No fullHandle: the cache stays on this machine and +// nothing is uploaded. Documentations/Internal/TuistDevelopment.md. +let sourceTargetNames = Environment.sourceTargetNames + .getString(default: "") + .split(separator: ",") + .map(String.init) + +let tuist = Tuist( + project: .tuist( + cacheOptions: .options( + profiles: .profiles( + ["development": .profile(.onlyExternal, except: sourceTargetNames.map { .named($0) })], + default: "development" + ) + ) + ) +) diff --git a/Tuist/CommandLine/Project.swift b/Tuist/CommandLine/Project.swift new file mode 100644 index 000000000..cd70aa1be --- /dev/null +++ b/Tuist/CommandLine/Project.swift @@ -0,0 +1,101 @@ +import ProjectDescription + +// What Tuist cannot convert from ../../Package.swift (Documentations/Internal/TuistDevelopment.md): +// the swift-section executable, and SwiftSectionCommandTests, which imports the executable's module +// (`@testable import swift_section`). Tuist converts no executable target and rejects a test that +// depends on one, so Package.swift leaves that test out while Tuist resolves it and it is described +// here instead. swift_section compiles the command's sources as a static framework for the test; the +// tool compiles them again, so its link needs no trick around the @main entry point. +// +// The dependency list mirrors the swift-section target in Package.swift and is the one hand-written +// copy in the Tuist description: a dependency added there that is missing here fails to compile. +let commandLineDependencies: [TargetDependency] = [ + .external(name: "SwiftSectionKit"), + .external(name: "MachOFoundation"), + .external(name: "SwiftSymbols"), + .external(name: "SwiftDump"), + .external(name: "SwiftOutputTransformer"), + .external(name: "SwiftDeclaration"), + .external(name: "SwiftDeclarationRendering"), + .external(name: "SwiftIndexing"), + .external(name: "Semantic"), + .external(name: "OutputTransformer"), + .external(name: "ObjCDeclarationRendering"), + .external(name: "ObjCOutputTransformer"), + .external(name: "Rainbow"), + .external(name: "ArgumentParser"), +] + +// Tuist builds swift-argument-parser for macOS 12, the minimum that package declares; the package's +// own 10.15 does not reach the executable here the way SwiftPM's build of it does. +let commandLineDeploymentTargets: DeploymentTargets = .macOS("12.0") + +let commandLineSources: SourceFilesList = ["../../Sources/Executables/swift-section/**"] + +// The link flags Tuist/Package.swift gives the package's test targets, for the same reasons: -ObjC, so +// that the archive members defining Swift types and extensions (protocol conformances among them) are +// loaded, and -force_load of the constructor targets the swift-section executable reaches in +// Package.swift, which TuistScript.sh lists in TUIST_FORCE_LOADS. +let forceLoadedTargetNames: [String] = Environment.forceLoads.getString(default: "") + .split(separator: ",") + .compactMap { pair in + let parts = pair.split(separator: ":").map(String.init) + return parts.count == 2 && parts[0] == "swift-section" ? parts[1] : nil + } +let linkFlags: SettingsDictionary = [ + "OTHER_LDFLAGS": .array(["$(inherited)", "-ObjC"] + forceLoadedTargetNames.map { targetName in + "-Wl,-force_load,$(BUILT_PRODUCTS_DIR)/\(targetName).framework/\(targetName)" + }), +] + +// MACHO_SWIFT_SECTION_SILENT_TEST=1, which Package.swift turns into SILENT_TEST for its test targets; +// TuistScript.sh passes it on as TUIST_SILENT_TEST, the only form a Tuist manifest can read. +let commandTestSettings: Settings = .settings(base: linkFlags.merging( + Environment.silentTest.getBoolean(default: false) ? ["SWIFT_ACTIVE_COMPILATION_CONDITIONS": ["$(inherited)", "SILENT_TEST"]] : [:] +) { $1 }) + +let project = Project( + name: "MachOSwiftSectionCommandLine", + // In SwiftPM these targets belong to the MachOSwiftSection package, whose `package` declarations + // they use (SwiftSectionCommandTests calls SwiftSectionKit's applyTransformersEnablingCommentKinds). + // Tuist gives the targets it converts SWIFT_PACKAGE_NAME = MachOSwiftSection; these need the same. + settings: .settings(base: ["SWIFT_PACKAGE_NAME": "MachOSwiftSection"]), + targets: [ + .target( + name: "swift-section", + destinations: .macOS, + product: .commandLineTool, + // Tuist would name the executable swift_section, as it turns every dash of a target's name + // into an underscore. + productName: "swift-section", + bundleId: "com.machoswiftsection.swift-section", + deploymentTargets: commandLineDeploymentTargets, + sources: commandLineSources, + dependencies: commandLineDependencies, + settings: .settings(base: linkFlags) + ), + .target( + name: "swift_section", + destinations: .macOS, + product: .staticFramework, + bundleId: "com.machoswiftsection.swift-section.module", + deploymentTargets: commandLineDeploymentTargets, + sources: commandLineSources, + dependencies: commandLineDependencies + ), + .target( + name: "SwiftSectionCommandTests", + destinations: .macOS, + product: .unitTests, + bundleId: "com.machoswiftsection.SwiftSectionCommandTests", + deploymentTargets: .macOS("14.0"), + sources: ["../../Tests/SwiftSectionCommandTests/**"], + dependencies: [ + .target(name: "swift_section"), + .external(name: "SwiftDeclarationRendering"), + .external(name: "SwiftPrinting"), + ] + commandLineDependencies, + settings: commandTestSettings + ), + ] +) diff --git a/Tuist/Package.swift b/Tuist/Package.swift new file mode 100644 index 000000000..236637f74 --- /dev/null +++ b/Tuist/Package.swift @@ -0,0 +1,151 @@ +// swift-tools-version: 6.2 +import Foundation +import PackageDescription + +// The dependencies of MachOSwiftSection-Tuist.xcworkspace, the development-only Tuist workspace +// (Documentations/Internal/TuistDevelopment.md). Generate it with ./TuistScript.sh, never with a bare +// `tuist generate`: the script sets the variables everything below reads. +// +// MachOSwiftSection itself is declared by path, so its Package.swift stays the only definition of its +// targets and dependencies. In the local dependency mode (`./TuistScript.sh +// --local-dependencies`) the script names the upstream packages the native workspace lists beside +// the checkout in TUIST_LOCAL_PACKAGE_NAMES and the directory holding them in +// TUIST_LOCAL_PACKAGE_CHECKOUTS. A root's path dependency stands in for every other declaration of the +// same package in the graph — MachOSwiftSection's URLs and the upstream packages' own — so they build +// from those checkouts, uncommitted edits included. A path package's identity is its directory's name. +let processEnvironment = ProcessInfo.processInfo.environment +let localPackageCheckoutsDirectory = processEnvironment["TUIST_LOCAL_PACKAGE_CHECKOUTS"] ?? "" +let localPackageNames = (processEnvironment["TUIST_LOCAL_PACKAGE_NAMES"] ?? "") + .split(separator: ",") + .map(String.init) +// Qualified: Tuist evaluates this file with ProjectDescription imported too, which has a Package of +// its own. +let localPackageDependencies: [PackageDescription.Package.Dependency] = localPackageCheckoutsDirectory.isEmpty + ? [] + : localPackageNames.map { packageName in .package(path: "\(localPackageCheckoutsDirectory)/\(packageName)") } + +#if TUIST + import ProjectDescription + + func targetNames(in variable: String) -> [String] { + (processEnvironment[variable] ?? "").split(separator: ",").map(String.init) + } + + // Tuist suppresses warnings in every package; Xcode does so for remote packages only. The targets + // of the packages declared by path get theirs back: MachOSwiftSection always, the upstream + // packages in the local dependency mode. + let warningSettings: [String: Settings] = Dictionary( + targetNames(in: "TUIST_WARNING_TARGET_NAMES").map { targetName in + (targetName, Settings.settings(base: ["SWIFT_SUPPRESS_WARNINGS": "NO", "GCC_WARN_INHIBIT_ALL_WARNINGS": "NO"])) + }, + uniquingKeysWith: { first, _ in first } + ) + + // Tuist drops a package setting whose only condition is a trait. MachOSwiftSection enables + // swift-capstone's AARCH64 trait, which defines CAPSTONE_HAS_AARCH64 for both the Swift wrapper and + // the C library that way. Without it the wrapper does not compile, and the C library would compile + // but support no architecture at all. + let restatedTraitDefinitions: [String: Settings] = [ + "Capstone": .settings(base: [ + "SWIFT_ACTIVE_COMPILATION_CONDITIONS": ["$(inherited)", "CAPSTONE_HAS_AARCH64"], + "GCC_PREPROCESSOR_DEFINITIONS": ["$(inherited)", "CAPSTONE_HAS_AARCH64=1"], + ]), + "Ccapstone": .settings(base: [ + "GCC_PREPROCESSOR_DEFINITIONS": ["$(inherited)", "CAPSTONE_HAS_AARCH64=1"], + ]), + ] + + // A library target that imports Testing, such as a package's testing support, uses Swift Testing's + // macros (#expect, #require). Xcode points only test targets at the toolchain's TestingMacros + // plugin; SwiftPM gives it to every target. TUIST_TESTING_SUPPORT_TARGET_NAMES lists the library + // targets whose sources import Testing. + let testingSupportSettings: [String: Settings] = Dictionary( + targetNames(in: "TUIST_TESTING_SUPPORT_TARGET_NAMES").map { targetName in + (targetName, Settings.settings(base: [ + "ENABLE_TESTING_SEARCH_PATHS": "YES", + "OTHER_SWIFT_FLAGS": ["$(inherited)", "-plugin-path", "$(TOOLCHAIN_DIR)/usr/lib/swift/host/plugins/testing"], + ])) + }, + uniquingKeysWith: { first, _ in first } + ) + + // The test targets, which SwiftPM builds and links differently in three ways: + // - It builds a test target for at least the macOS version XCTest and Swift Testing require (14.0 + // with Xcode 26 and 27), whatever its package declares; Tuist takes the package's own minimum, and + // MachOSwiftSection's 10.15 leaves TypeIndexingTests without the macOS 13 APIs it tests. + // TUIST_RAISED_TEST_TARGET_NAMES lists the test targets of the packages that declare less. + // - It links each package target's object files whole, where Tuist links static frameworks and the + // linker loads only the archive members something refers to by symbol. A protocol conformance + // nothing names goes missing, and `as?` fails without a word: the readers that wrap a MachOImage + // or MachOFile (MachOReaderWrapper) read as neither. -ObjC also loads every member that defines an + // Objective-C class or category or a Swift type or extension (Xcode 27's linker), as it does for + // RuntimeViewer's Tuist workspace. + // - A load-time constructor nothing refers to never runs that way at all: MachOSwiftSection's + // SwiftSymbolsRegistration registers Swift as a symbol language from one. TUIST_FORCE_LOADS pairs + // each final link with the constructor targets its in-package dependencies reach, as + // ":,…"; those archives are loaded whole. + // TUIST_TEST_TARGET_NAMES lists every mapped test target, IntegrationTests included, so that a build + // of the whole workspace compiles and links too. Tuist/CommandLine/Project.swift gives the + // swift-section executable and SwiftSectionCommandTests the same link flags. + let forceLoadedTargetsByLinkingTarget: [String: [String]] = Dictionary( + targetNames(in: "TUIST_FORCE_LOADS").compactMap { pair -> (String, [String])? in + let parts = pair.split(separator: ":").map(String.init) + return parts.count == 2 ? (parts[0], [parts[1]]) : nil + }, + uniquingKeysWith: + + ) + let raisedTestTargetNames = Set(targetNames(in: "TUIST_RAISED_TEST_TARGET_NAMES")) + let testTargetSettings: [String: Settings] = Dictionary( + targetNames(in: "TUIST_TEST_TARGET_NAMES").map { targetName in + let forceLoadFlags = (forceLoadedTargetsByLinkingTarget[targetName] ?? []).map { loadedTarget in + "-Wl,-force_load,$(BUILT_PRODUCTS_DIR)/\(loadedTarget).framework/\(loadedTarget)" + } + var settings: SettingsDictionary = ["OTHER_LDFLAGS": .array(["$(inherited)", "-ObjC"] + forceLoadFlags)] + if raisedTestTargetNames.contains(targetName) { + settings["MACOSX_DEPLOYMENT_TARGET"] = "14.0" + } + return (targetName, Settings.settings(base: settings)) + }, + uniquingKeysWith: { first, _ in first } + ) + + // A Debug build of the cross-reference scan spends most of its time in the Swift runtime, not in + // the scan: an unspecialized range loop looks tuple metadata up on every instruction, under one + // lock every thread shares, so CrossReferenceAnalysisTests' whole-cache scans take minutes instead + // of the seconds a Release build needs. The scan's two hottest modules, both MachOKitExtensions', + // compile optimized in every configuration here; this package's own CrossReferenceAnalysis stays + // debuggable (evolution proposal cross-reference-test-scan-load). + let optimizedScanSettings: [String: Settings] = Dictionary( + ["MachOCodeReferences", "ARM64InstructionDecoding"].map { targetName in + (targetName, Settings.settings(base: ["SWIFT_OPTIMIZATION_LEVEL": "-O"])) + }, + uniquingKeysWith: { first, _ in first } + ) + + // One target may need several of the settings above; their keys never overlap. + func mergingSettings(_ settingsByTarget: [String: Settings]...) -> [String: Settings] { + settingsByTarget.reduce(into: [:]) { merged, settings in + merged.merge(settings) { first, second in .settings(base: first.base.merging(second.base) { $1 }) } + } + } + + let packageSettings = PackageSettings( + targetSettings: mergingSettings(warningSettings, restatedTraitDefinitions, testTargetSettings, testingSupportSettings, optimizedScanSettings), + // TuistScript.sh sets the variable to 1 unless a package declared by path still has a test of + // a shape Tuist rejects (the manifests' TUIST_MAPS_LOCAL_PACKAGE_TESTS block removes them). + includeLocalPackageTestTargets: processEnvironment["TUIST_MAPS_LOCAL_PACKAGE_TESTS"] == "1" + ) +#endif + +let package = Package( + name: "MachOSwiftSectionTuistDependencies", + dependencies: [ + .package(path: ".."), + // Stands in for swift-syntax in every macro package, as it does as a member of the native + // workspace: SwiftPM matches it by package identity. + .package(path: "../PrecompiledLibraries/swift-syntax"), + // Used only by MachOSwiftSection's tests. Tuist maps a test target only when every package + // its dependencies come from is declared here, with the requirement Package.swift gives it. + .package(url: "https://github.com/pointfreeco/swift-snapshot-testing", from: "1.18.9"), + ] + localPackageDependencies +) diff --git a/TuistScript.sh b/TuistScript.sh new file mode 100755 index 000000000..dfc2de819 --- /dev/null +++ b/TuistScript.sh @@ -0,0 +1,916 @@ +#!/usr/bin/env bash +# TuistScript.sh — MachOSwiftSection-Tuist.xcworkspace, the development-only Tuist workspace: this +# package and the five upstream packages the native MachOSwiftSection.xcworkspace lists beside the +# checkout (MachOKit, MachOKitExtensions, MachOObjCSection, swift-demangling, swift-semantic-string) +# built from source, every other dependency taken from Tuist's binary cache on this machine, and the +# packages' tests mapped into schemes. Releases, CI, `swift build` / `swift test` and the native +# workspace do not use it. Documentations/Internal/TuistDevelopment.md explains the setup. +# +# Usage: +# ./TuistScript.sh install # resolve the dependencies (tuist install) +# ./TuistScript.sh generate [--configuration ] +# # generate MachOSwiftSection-Tuist.xcworkspace +# # against the binary cache of one configuration +# # (Debug or Release; default: Debug) +# ./TuistScript.sh warm [--configuration ] # build the third-party dependencies into the +# # binary cache of one configuration, then generate +# ./TuistScript.sh build [--configuration ] [--scheme ] [-- ] +# # generate, then build the swift-section scheme, or +# # another +# ./TuistScript.sh test [--configuration ] [--scheme ] [-- ] +# # generate, then run the "MachOSwiftSection Tests" +# # scheme, or another (in the local mode each upstream +# # package has " Tests"); exits with +# # xcodebuild's exit code +# ./TuistScript.sh release # give up every checkout this one claimed: remove the +# # projects Tuist generated into them and the workspace +# ./TuistScript.sh --local-dependencies +# # from now on take the five upstream packages from +# # the checkouts beside this one (`.worktrees/` in a +# # worktree), uncommitted edits included +# ./TuistScript.sh --remote-dependencies +# # from now on take them at the lock file's pins again +# # (the default) +# ./TuistScript.sh --dry-run # print what would run +# ./TuistScript.sh --help +# +# The mode holds for the commands after the one that switched it ($LOCAL_DEPENDENCIES_MARKER records +# it). Each mode has its own dependency checkouts; switching resolves again. When the local mode is +# switched on, TUIST_LOCAL_PACKAGE_CHECKOUTS names another directory to take the upstream packages +# from, each in a directory named like the package. +# +# Tuist writes a project into every package declared by path — this checkout always, the upstream +# checkouts in the local mode — and RuntimeViewer's TuistScript.sh does the same into the same +# checkouts. Both scripts claim a checkout before generating into it (the claim record below), and +# refuse a checkout another one holds. +# +# Every command uses the Xcode that DEVELOPER_DIR or xcode-select names. Tuist's dependency +# checkouts, its binary cache and the build products live under /Volumes/DerivedData/MachOSwiftSection/ +# Tuist when that volume is mounted, and inside the checkout otherwise; TUIST_SCRIPT_ROOT names another +# directory. `warm`, `build` and `test` compile: run them through queued-build where that applies. +set -euo pipefail + +PROJECT_DIR="$(cd "$(dirname "$0")" && pwd)" +PROJECT_REAL_PATH="$(cd "$PROJECT_DIR" && pwd -P)" +cd "$PROJECT_DIR" + +WORKSPACE="MachOSwiftSection-Tuist.xcworkspace" +NATIVE_WORKSPACE="MachOSwiftSection.xcworkspace" +PACKAGE_NAME="MachOSwiftSection" +BUILD_SCHEME="swift-section" +TEST_SCHEME="MachOSwiftSection Tests" +COMMAND_LINE_PROJECT_DIRECTORY="Tuist/CommandLine" +# The lock file SwiftPM and Xcode resolved for this checkout, not committed: Tuist starts from its pins. +SEED_LOCK_FILE="Package.resolved" +TUIST_PACKAGE_RESOLVED="Tuist/Package.resolved" +# Test targets no scheme lists: IntegrationTests is the maintainer's manual-inspection target. +UNLISTED_TEST_TARGETS="IntegrationTests" +# The local dependency mode: the file recording the directory the upstream packages are taken from +# (absent in the remote mode). +LOCAL_DEPENDENCIES_MARKER="Tuist/.local-dependencies" +# The claim record, shared with RuntimeViewer's TuistScript.sh. A claimed checkout's git directory +# holds $OWNER_RECORD_NAME: the owner checkout's path, the command that releases the claim there, and +# the project Tuist generated into the claimed checkout. The owner lists the real paths it holds in +# its $CLAIMED_CHECKOUTS_FILE; a claim is live only while that list holds the claimed checkout. +OWNER_RECORD_NAME="tuist-generated-project-owner" +CLAIMED_CHECKOUTS_FILE="Tuist/.claimed-checkouts" +RELEASE_COMMAND="./TuistScript.sh release" +# RuntimeViewer's record before the shared one: live while its owner's Tuist/.local-dependencies, +# joined with the package's name, is the claimed checkout. +LEGACY_OWNER_RECORD_NAME="runtimeviewer-tuist-local-dependencies" +EXCLUDE_COMMENT="# Generated by MachOSwiftSection's TuistScript.sh" + +COMMAND="" +CONFIGURATION="Debug" +REQUESTED_SCHEME="" +DRY_RUN=false +REQUESTED_DEPENDENCY_MODE="" +EXTRA_ARGUMENTS=() + +fail() { echo "error: $*" >&2; exit 1; } +log() { echo "[TuistScript] $*"; } +warn() { echo "[TuistScript] warning: $*" >&2; } + +run() { + if $DRY_RUN; then + printf '+ '; printf '%q ' "$@"; echo + else + "$@" + fi +} + +# Runs a command with its output in a log under $LOG_DIR, echoing only its errors and last lines when +# it fails. For xcodebuild, whose output runs to thousands of lines. Returns the command's exit code. +run_logged() { + local log_name="$1"; shift + if $DRY_RUN; then + printf '+ '; printf '%q ' "$@"; printf '> %q\n' "$LOG_DIR/$log_name.log" + return 0 + fi + mkdir -p "$LOG_DIR" + local log_path="$LOG_DIR/$log_name.log" + log " log: $log_path" + local exit_code=0 + "$@" > "$log_path" 2>&1 || exit_code=$? + if [[ $exit_code -ne 0 ]]; then + grep -E 'error:|✘|failed' "$log_path" | head -20 | sed 's/^/ /' >&2 || true + tail -5 "$log_path" | sed 's/^/ /' >&2 + fi + return $exit_code +} + +# Runs a Tuist command with its output on the terminal as well as in a log under $LOG_DIR. On a +# terminal it runs under script(1), which keeps Tuist's colors; anywhere else through tee. Returns the +# command's own exit code either way. +run_tuist() { + local log_name="$1"; shift + if $DRY_RUN; then + printf '+ '; printf '%q ' "$@"; printf '| tee %q\n' "$LOG_DIR/$log_name.log" + return 0 + fi + mkdir -p "$LOG_DIR" + local log_path="$LOG_DIR/$log_name.log" + log " log: $log_path" + local exit_code=0 + if [[ -t 0 && -t 1 ]]; then + script -q "$log_path" "$@" || exit_code=$? + else + "$@" 2>&1 | tee "$log_path" || exit_code=${PIPESTATUS[0]} + fi + return $exit_code +} + +while [[ $# -gt 0 ]]; do + case "$1" in + install|generate|warm|build|test|release) + [[ -z "$COMMAND" ]] || fail "one command at a time: $COMMAND, $1" + COMMAND="$1"; shift;; + --configuration) + [[ $# -ge 2 ]] || fail "--configuration needs a name (Debug or Release)" + CONFIGURATION="$2"; shift 2;; + --scheme) + [[ $# -ge 2 ]] || fail "--scheme needs a scheme name" + REQUESTED_SCHEME="$2"; shift 2;; + --local-dependencies|--remote-dependencies) + [[ -z "$REQUESTED_DEPENDENCY_MODE" ]] || fail "one of --local-dependencies and --remote-dependencies at a time" + REQUESTED_DEPENDENCY_MODE="${1#--}"; REQUESTED_DEPENDENCY_MODE="${REQUESTED_DEPENDENCY_MODE%-dependencies}"; shift;; + --dry-run) DRY_RUN=true; shift;; + --) shift; EXTRA_ARGUMENTS=("$@"); break;; + -h|--help) awk 'NR > 1 && /^#/ { sub(/^# ?/, ""); print; next } NR > 1 { exit }' "$0"; exit 0;; + *) fail "unknown argument: $1 (see --help)";; + esac +done +[[ -n "$COMMAND" ]] || fail "no command given (see --help)" +case "$CONFIGURATION" in + Debug|Release) ;; + *) fail "unknown configuration: $CONFIGURATION (expected Debug or Release)";; +esac +if [[ ( ${#EXTRA_ARGUMENTS[@]} -gt 0 || -n "$REQUESTED_SCHEME" ) && "$COMMAND" != build && "$COMMAND" != test ]]; then + fail "only build and test take --scheme and pass arguments on to xcodebuild" +fi +if [[ -n "$REQUESTED_SCHEME" ]]; then + BUILD_SCHEME="$REQUESTED_SCHEME" + TEST_SCHEME="$REQUESTED_SCHEME" +fi + +# One directory per checkout: two worktrees must not share Tuist's dependency checkouts, which record +# where the packages declared by path are. The binary cache is shared; it is keyed by content. +CHECKOUT_NAME="$(basename "$PROJECT_DIR")-$(printf '%s' "$PROJECT_DIR" | shasum | cut -c1-8)" +if [[ -n "${TUIST_SCRIPT_ROOT:-}" ]]; then + STORAGE_ROOT="$TUIST_SCRIPT_ROOT" +elif [[ -d "/Volumes/DerivedData" ]]; then + STORAGE_ROOT="/Volumes/DerivedData/MachOSwiftSection/Tuist" +else + STORAGE_ROOT="" +fi +if [[ -n "$STORAGE_ROOT" ]]; then + export TUIST_XDG_CACHE_HOME="$STORAGE_ROOT/Cache" + export TUIST_CACHE_WARM_SCRATCH_DIRECTORY="$STORAGE_ROOT/WarmScratch/$CHECKOUT_NAME" + WORK_ROOT="$STORAGE_ROOT/Work/$CHECKOUT_NAME" +else + WORK_ROOT="$PROJECT_DIR/DerivedData/Tuist" +fi +LOG_DIR="${LOG_DIR:-$PROJECT_DIR/Products/Logs/Tuist}" +# What the dependencies were last resolved for: the mode and the manifests. The two modes share +# Tuist/Package.resolved, so running in the other one, or after a manifest changed, resolves again. +INSTALLED_DEPENDENCIES_STAMP="$WORK_ROOT/InstalledDependencies" +# Every package's evaluated manifest, read once per install (dump_manifests). +MANIFESTS_DIRECTORY="$WORK_ROOT/Manifests" + +# The manifests choose local checkouts or remote packages by this variable, for every package at +# once, swift-capstone included. The upstream packages come from their checkouts through +# --local-dependencies instead. +if [[ -n "${USING_LOCAL_DEPENDENCIES:-}" ]]; then + warn "ignoring USING_LOCAL_DEPENDENCIES=$USING_LOCAL_DEPENDENCIES; --local-dependencies takes the upstream packages from their checkouts" + unset USING_LOCAL_DEPENDENCIES +fi + +# The Tuist that mise.toml pins: through mise when it is installed, from PATH otherwise. +PINNED_TUIST_VERSION="$(sed -n 's/^tuist *= *"\(.*\)"$/\1/p' mise.toml)" +if command -v mise >/dev/null 2>&1; then + TUIST=(mise exec -- tuist) +elif command -v tuist >/dev/null 2>&1; then + TUIST=(tuist) +else + fail "Tuist not found. Install mise (https://mise.jdx.dev) and run \`mise install\` here, or install Tuist $PINNED_TUIST_VERSION." +fi +if ! $DRY_RUN; then + tuist_version="$("${TUIST[@]}" version 2>/dev/null | tail -1)" || fail "\`${TUIST[*]} version\` failed; run \`mise install\` here" + [[ "$tuist_version" == "$PINNED_TUIST_VERSION" ]] \ + || fail "Tuist $tuist_version found, mise.toml pins $PINNED_TUIST_VERSION; run \`mise install\` here" +fi + +command -v xcodebuild >/dev/null 2>&1 || fail "xcodebuild not found" +command -v python3 >/dev/null 2>&1 || fail "python3 not found (the script reads the manifests with it)" + +# The upstream packages the local mode takes from their checkouts: the members of the native +# workspace beside the checkout (`container:../`), so a package added there is local here too. +read_local_package_names() { + python3 - "$PROJECT_DIR/$NATIVE_WORKSPACE/contents.xcworkspacedata" <<'PYTHON' +import sys +import xml.etree.ElementTree as ElementTree + +prefix = "container:../" +for element in ElementTree.parse(sys.argv[1]).getroot().iter("FileRef"): + location = element.get("location", "") + if location.startswith(prefix) and "/" not in location[len(prefix):]: + print(location[len(prefix):]) +PYTHON +} + +LOCAL_PACKAGE_NAMES=() +local_package_names_output="$(read_local_package_names)" \ + || fail "cannot read which packages $NATIVE_WORKSPACE takes from beside the checkout" +for package_name in $local_package_names_output; do + LOCAL_PACKAGE_NAMES+=("$package_name") +done +[[ ${#LOCAL_PACKAGE_NAMES[@]} -gt 0 ]] || fail "$NATIVE_WORKSPACE takes no package from beside the checkout" + +# --- The claim record ----------------------------------------------------------------------------- + +git_directory_of() { # $1: a checkout; prints nothing when it is not a git checkout + git -C "$1" rev-parse --absolute-git-dir 2>/dev/null || true +} + +real_path_of() { + (cd "$1" 2>/dev/null && pwd -P) || true +} + +# Prints "\t" for a live claim another checkout holds on $1 (a checkout), +# $2 being the package's name; prints nothing when none does. +foreign_live_claim() { + local checkout="$1" package_name="$2" git_directory checkout_real_path owner release_command owner_directory + git_directory="$(git_directory_of "$checkout")" + [[ -n "$git_directory" ]] || return 0 + checkout_real_path="$(real_path_of "$checkout")" + if [[ -f "$git_directory/$OWNER_RECORD_NAME" ]]; then + owner="$(sed -n 1p "$git_directory/$OWNER_RECORD_NAME")" + release_command="$(sed -n 2p "$git_directory/$OWNER_RECORD_NAME")" + if [[ -n "$owner" && "$(real_path_of "$owner")" != "$PROJECT_REAL_PATH" ]] \ + && grep -qxF -- "$checkout_real_path" "$owner/$CLAIMED_CHECKOUTS_FILE" 2>/dev/null; then + printf '%s\t%s\n' "$owner" "${release_command:-its TuistScript.sh}" + return 0 + fi + fi + if [[ -f "$git_directory/$LEGACY_OWNER_RECORD_NAME" ]]; then + owner="$(sed -n 1p "$git_directory/$LEGACY_OWNER_RECORD_NAME")" + if [[ -n "$owner" && "$(real_path_of "$owner")" != "$PROJECT_REAL_PATH" ]]; then + owner_directory="$(cat "$owner/Tuist/.local-dependencies" 2>/dev/null || true)" + if [[ -n "$owner_directory" && "$(real_path_of "$owner_directory/$package_name")" == "$checkout_real_path" ]]; then + printf '%s\t%s\n' "$owner" "./TuistScript.sh generate --remote-dependencies" + fi + fi + fi +} + +# Claims $1 (a checkout) for this one before Tuist generates $3 into it; $2 is the package's name. +# Refuses a checkout another checkout's Tuist workspace holds and a project file git tracks. An upstream +# checkout's repository gets the generated files in its info/exclude, which stays on this Mac; this +# checkout ignores its own in .gitignore. +claim_checkout() { + local checkout="$1" package_name="$2" project_name="$3" claim git_directory checkout_real_path exclude_file pattern + git_directory="$(git_directory_of "$checkout")" + [[ -n "$git_directory" ]] || return 0 + claim="$(foreign_live_claim "$checkout" "$package_name")" + if [[ -n "$claim" ]]; then + fail "$checkout is in the Tuist workspace of ${claim%%$'\t'*}, and generating here would replace the project that workspace uses; run \`${claim#*$'\t'}\` there first" + fi + if git -C "$checkout" ls-files --error-unmatch "$project_name.xcodeproj" >/dev/null 2>&1; then + fail "$checkout tracks $project_name.xcodeproj, which Tuist would overwrite" + fi + checkout_real_path="$(real_path_of "$checkout")" + if $DRY_RUN; then + log "would claim $checkout_real_path ($project_name.xcodeproj)" + return 0 + fi + printf '%s\n%s\n%s\n' "$PROJECT_DIR" "$RELEASE_COMMAND" "$project_name.xcodeproj" > "$git_directory/$OWNER_RECORD_NAME" + mkdir -p "$(dirname "$CLAIMED_CHECKOUTS_FILE")" + grep -qxF -- "$checkout_real_path" "$CLAIMED_CHECKOUTS_FILE" 2>/dev/null \ + || printf '%s\n' "$checkout_real_path" >> "$CLAIMED_CHECKOUTS_FILE" + if [[ "$checkout_real_path" != "$PROJECT_REAL_PATH" ]]; then + exclude_file="$(git -C "$checkout" rev-parse --path-format=absolute --git-path info/exclude)" + mkdir -p "$(dirname "$exclude_file")" + for pattern in "$EXCLUDE_COMMENT" "/$project_name.xcodeproj/" "/Derived/"; do + grep -qxF -- "$pattern" "$exclude_file" 2>/dev/null || printf '%s\n' "$pattern" >> "$exclude_file" + done + fi +} + +# Gives up the claim on $1 (a checkout's real path) when this checkout holds it: removes the project +# Tuist generated there unless git tracks it, so that opening the folder in Xcode opens its +# Package.swift again, and the record. Derived/ stays; it changes nothing for Xcode. +release_checkout() { + local checkout_real_path="$1" git_directory project_file_name remaining + git_directory="$(git_directory_of "$checkout_real_path")" + if [[ -n "$git_directory" && -f "$git_directory/$OWNER_RECORD_NAME" ]] \ + && [[ "$(real_path_of "$(sed -n 1p "$git_directory/$OWNER_RECORD_NAME")")" == "$PROJECT_REAL_PATH" ]]; then + project_file_name="$(sed -n 3p "$git_directory/$OWNER_RECORD_NAME")" + if [[ -n "$project_file_name" && "$project_file_name" == *.xcodeproj ]] \ + && ! git -C "$checkout_real_path" ls-files --error-unmatch "$project_file_name" >/dev/null 2>&1; then + run rm -rf "$checkout_real_path/$project_file_name" + fi + run rm -f "$git_directory/$OWNER_RECORD_NAME" + fi + if [[ -f "$CLAIMED_CHECKOUTS_FILE" ]] && ! $DRY_RUN; then + remaining="$(grep -vxF -- "$checkout_real_path" "$CLAIMED_CHECKOUTS_FILE" || true)" + if [[ -n "$remaining" ]]; then + printf '%s\n' "$remaining" > "$CLAIMED_CHECKOUTS_FILE" + else + rm -f "$CLAIMED_CHECKOUTS_FILE" + fi + fi +} + +# Gives up every claim on a checkout other than this one: the upstream checkouts of the local mode. +release_upstream_checkouts() { + local checkout_real_path + [[ -f "$CLAIMED_CHECKOUTS_FILE" ]] || return 0 + while IFS= read -r checkout_real_path; do + [[ -n "$checkout_real_path" && "$checkout_real_path" != "$PROJECT_REAL_PATH" ]] || continue + release_checkout "$checkout_real_path" + done < <(cat "$CLAIMED_CHECKOUTS_FILE") +} + +# --- The dependency mode -------------------------------------------------------------------------- + +# Points this process at the dependencies of one mode ($1: local or remote). Each mode resolves into a +# directory of its own, so switching back and forth keeps both sets of checkouts. +use_dependency_mode() { + CURRENT_DEPENDENCY_MODE="$1" + local directory_suffix="" + if [[ "$1" == local ]]; then + directory_suffix="-LocalDependencies" + export TUIST_LOCAL_PACKAGE_CHECKOUTS="$LOCAL_DEPENDENCIES_DIRECTORY" + export TUIST_LOCAL_PACKAGE_NAMES + TUIST_LOCAL_PACKAGE_NAMES="$(IFS=,; printf '%s' "${LOCAL_PACKAGE_NAMES[*]}")" + else + unset TUIST_LOCAL_PACKAGE_CHECKOUTS TUIST_LOCAL_PACKAGE_NAMES + fi + if [[ -n "$STORAGE_ROOT" ]]; then + export SWIFTPM_BUILD_DIR="$STORAGE_ROOT/Dependencies/$CHECKOUT_NAME$directory_suffix" + elif [[ -n "$directory_suffix" ]]; then + export SWIFTPM_BUILD_DIR="$PROJECT_DIR/Tuist/.build$directory_suffix" + else + unset SWIFTPM_BUILD_DIR + fi + DEPENDENCIES_DIRECTORY="${SWIFTPM_BUILD_DIR:-$PROJECT_DIR/Tuist/.build}" +} + +# The mode from now on: what --local-dependencies or --remote-dependencies asks for, or what +# $LOCAL_DEPENDENCIES_MARKER recorded the last time. +RECORDED_LOCAL_DEPENDENCIES_DIRECTORY="$(cat "$LOCAL_DEPENDENCIES_MARKER" 2>/dev/null || true)" +case "$REQUESTED_DEPENDENCY_MODE" in + local) LOCAL_DEPENDENCIES_DIRECTORY="${TUIST_LOCAL_PACKAGE_CHECKOUTS:-$(dirname "$PROJECT_DIR")}";; + remote) LOCAL_DEPENDENCIES_DIRECTORY="";; + *) LOCAL_DEPENDENCIES_DIRECTORY="$RECORDED_LOCAL_DEPENDENCIES_DIRECTORY";; +esac +if [[ -n "$LOCAL_DEPENDENCIES_DIRECTORY" ]]; then + resolved_directory="$(cd "$LOCAL_DEPENDENCIES_DIRECTORY" 2>/dev/null && pwd)" \ + || fail "no directory $LOCAL_DEPENDENCIES_DIRECTORY to take the local dependencies from (./TuistScript.sh --remote-dependencies goes back to the remote packages)" + LOCAL_DEPENDENCIES_DIRECTORY="$resolved_directory" + for package_name in "${LOCAL_PACKAGE_NAMES[@]}"; do + [[ -f "$LOCAL_DEPENDENCIES_DIRECTORY/$package_name/Package.swift" ]] \ + || fail "no package $package_name in $LOCAL_DEPENDENCIES_DIRECTORY. The local dependency mode takes the packages $NATIVE_WORKSPACE lists beside the checkout, from directories with the same names." + done + DEPENDENCY_MODE=local +else + DEPENDENCY_MODE=remote +fi + +# A switch gives up the upstream checkouts the old mode generated projects into and records the new +# mode; ensure_dependencies resolves again before Tuist next runs. +if [[ "$LOCAL_DEPENDENCIES_DIRECTORY" != "$RECORDED_LOCAL_DEPENDENCIES_DIRECTORY" ]]; then + log "switching to the $DEPENDENCY_MODE dependencies" + release_upstream_checkouts + if $DRY_RUN; then + log "would record the $DEPENDENCY_MODE mode in $LOCAL_DEPENDENCIES_MARKER" + elif [[ "$DEPENDENCY_MODE" == local ]]; then + printf '%s\n' "$LOCAL_DEPENDENCIES_DIRECTORY" > "$LOCAL_DEPENDENCIES_MARKER" + else + rm -f "$LOCAL_DEPENDENCIES_MARKER" + fi +fi +use_dependency_mode "$DEPENDENCY_MODE" + +# The manifests evaluate MACHO_SWIFT_SECTION_SILENT_TEST; the hand-written test target and the test +# schemes (MACHO_TESTING_SILENT in their environment) read it as TUIST_SILENT_TEST, the only form a Tuist +# manifest sees. +if [[ "${MACHO_SWIFT_SECTION_SILENT_TEST:-}" == "1" ]]; then + export TUIST_SILENT_TEST=1 +else + unset TUIST_SILENT_TEST +fi + +log "command=$COMMAND configuration=$CONFIGURATION tuist=$PINNED_TUIST_VERSION" +log "xcode: $(xcodebuild -version | tr '\n' ' ')(${DEVELOPER_DIR:-$(xcode-select -p)})" +log "storage: ${STORAGE_ROOT:-inside the checkout} (dependencies: $DEPENDENCIES_DIRECTORY)" +if [[ "$DEPENDENCY_MODE" == local ]]; then + log "upstream packages: the checkouts in $LOCAL_DEPENDENCIES_DIRECTORY (${LOCAL_PACKAGE_NAMES[*]})" +else + log "upstream packages: the lock file's pins (--local-dependencies takes them from their checkouts)" +fi + +# --- Resolving ----------------------------------------------------------------------------------- + +# Compares the pins of Tuist/Package.resolved with those of the seed lock file, leaving out the +# packages named in the arguments: swift-syntax, which Tuist takes from PrecompiledLibraries, and the +# local mode's packages, which have no pin when they are declared by path. Prints the differences and +# returns 1 when there are any. +compare_lock_files() { + python3 - "$TUIST_PACKAGE_RESOLVED" "$SEED_LOCK_FILE" "$@" <<'PYTHON' +import json +import sys + +def read_pins(path): + with open(path) as handle: + document = json.load(handle) + pins = {} + for pin in document.get("pins", []): + state = pin.get("state", {}) + pins[pin["identity"]] = state.get("version") or f"{state.get('branch')}@{state.get('revision', '')[:8]}" + return pins + +tuist_path, seed_path = sys.argv[1:3] +left_out = {package_name.lower() for package_name in sys.argv[3:]} +try: + tuist_pins, seed_pins = read_pins(tuist_path), read_pins(seed_path) +except OSError as error: + print(f" cannot compare the lock files: {error}") + sys.exit(1) +differences = [ + f" {identity}: Tuist {tuist_pins.get(identity, 'absent')}, {seed_path} {seed_pins.get(identity, 'absent')}" + for identity in sorted((tuist_pins.keys() | seed_pins.keys()) - left_out) + if tuist_pins.get(identity) != seed_pins.get(identity) +] +if differences: + print("\n".join(differences)) + sys.exit(1) +PYTHON +} + +# What $INSTALLED_DEPENDENCIES_STAMP says once the current mode's dependencies are resolved: the mode, +# and the manifests and seed lock file the resolution read. +installed_dependencies_description() { + local package_name + if [[ "$CURRENT_DEPENDENCY_MODE" == local ]]; then + echo "local $LOCAL_DEPENDENCIES_DIRECTORY" + else + echo "remote" + fi + echo "silent test: ${MACHO_SWIFT_SECTION_SILENT_TEST:-}" + shasum Tuist/Package.swift Package.swift 2>/dev/null || true + [[ -f "$SEED_LOCK_FILE" ]] && shasum "$SEED_LOCK_FILE" + if [[ "$CURRENT_DEPENDENCY_MODE" == local ]]; then + for package_name in "${LOCAL_PACKAGE_NAMES[@]}"; do + shasum "$LOCAL_DEPENDENCIES_DIRECTORY/$package_name/Package.swift" + done + fi +} + +install_dependencies() { + # Tuist/Package.resolved is not committed. Every install starts it from the lock file SwiftPM + # resolved for this checkout, so Tuist resolves the versions `swift build` and the native + # workspace use rather than the newest ones. + if [[ -f "$SEED_LOCK_FILE" ]]; then + run cp "$SEED_LOCK_FILE" "$TUIST_PACKAGE_RESOLVED" + else + warn "no $SEED_LOCK_FILE to start from; Tuist resolves the newest versions the manifests allow" + run rm -f "$TUIST_PACKAGE_RESOLVED" + fi + log "Resolving the $CURRENT_DEPENDENCY_MODE dependencies (tuist install)" + # The manifests' TUIST_MAPS_LOCAL_PACKAGE_TESTS block leaves out or gives a product to the tests + # Tuist would reject; Tuist records each manifest as it evaluates it here. + run_tuist "install" env TUIST_MAPS_LOCAL_PACKAGE_TESTS=1 "${TUIST[@]}" install || fail "tuist install failed" + if ! $DRY_RUN; then + if [[ -f "$SEED_LOCK_FILE" ]]; then + local differences + if [[ "$CURRENT_DEPENDENCY_MODE" == local ]]; then + differences="$(compare_lock_files swift-syntax "${LOCAL_PACKAGE_NAMES[@]}")" || true + else + differences="$(compare_lock_files swift-syntax)" || true + fi + if [[ -n "$differences" ]]; then + warn "$TUIST_PACKAGE_RESOLVED resolved other versions than $SEED_LOCK_FILE:" + printf '%s\n' "$differences" >&2 + warn "usually another Xcode resolved one of them: some packages pick their manifest by Swift version" + fi + fi + mkdir -p "$WORK_ROOT" + dump_manifests + installed_dependencies_description > "$INSTALLED_DEPENDENCIES_STAMP" + fi +} + +# Evaluates the manifest of every package in the graph the way Tuist did, with +# TUIST_MAPS_LOCAL_PACKAGE_TESTS=1, into $MANIFESTS_DIRECTORY: this package and the upstream ones +# (from their checkouts in the local mode, from Tuist's checkouts in the remote mode), and every +# third-party checkout. $MANIFESTS_DIRECTORY/packages.tsv lists them as +# "\t\t", the role being own-path, own-remote or third-party. +dump_manifests() { + local package_name identity directory checkout + run rm -rf "$MANIFESTS_DIRECTORY" + mkdir -p "$MANIFESTS_DIRECTORY" + { + printf '%s\t%s\t%s\n' "$(lowercased "$PACKAGE_NAME")" own-path "$PROJECT_DIR" + for package_name in "${LOCAL_PACKAGE_NAMES[@]}"; do + if [[ "$CURRENT_DEPENDENCY_MODE" == local ]]; then + printf '%s\t%s\t%s\n' "$(lowercased "$package_name")" own-path "$LOCAL_DEPENDENCIES_DIRECTORY/$package_name" + else + printf '%s\t%s\t%s\n' "$(lowercased "$package_name")" own-remote "$DEPENDENCIES_DIRECTORY/checkouts/$package_name" + fi + done + for checkout in "$DEPENDENCIES_DIRECTORY"/checkouts/*; do + [[ -f "$checkout/Package.swift" ]] || continue + identity="$(lowercased "$(basename "$checkout")")" + is_local_package_name "$identity" || printf '%s\t%s\t%s\n' "$identity" third-party "$checkout" + done + } > "$MANIFESTS_DIRECTORY/packages.tsv" + log "Reading the manifests of $(wc -l < "$MANIFESTS_DIRECTORY/packages.tsv" | tr -d ' ') packages" + # Eight at a time; each is a manifest evaluation, not a build. + cut -f1,3 "$MANIFESTS_DIRECTORY/packages.tsv" | tr '\t' '\n' | tr '\n' '\0' \ + | xargs -0 -n 2 -P 8 /bin/bash -c ' + TUIST_MAPS_LOCAL_PACKAGE_TESTS=1 swift package --package-path "$2" --scratch-path "$0/Scratch/$1" dump-package \ + > "$0/$1.json" 2> "$0/$1.err" || rm -f "$0/$1.json" + ' "$MANIFESTS_DIRECTORY" + while IFS=$'\t' read -r identity _ directory; do + if [[ ! -f "$MANIFESTS_DIRECTORY/$identity.json" ]]; then + cat "$MANIFESTS_DIRECTORY/$identity.err" >&2 2>/dev/null || true + fail "cannot read the manifest of $directory" + fi + done < <(grep -v $'\tthird-party\t' "$MANIFESTS_DIRECTORY/packages.tsv") +} + +lowercased() { + printf '%s' "$1" | tr '[:upper:]' '[:lower:]' +} + +is_local_package_name() { # $1: an identity + local package_name + for package_name in "${LOCAL_PACKAGE_NAMES[@]}"; do + [[ "$(lowercased "$package_name")" == "$1" ]] && return 0 + done + return 1 +} + +# Resolves the dependencies unless they were last resolved for the current mode and manifests. +ensure_dependencies() { + if [[ ! -d "$DEPENDENCIES_DIRECTORY/checkouts" || ! -f "$MANIFESTS_DIRECTORY/packages.tsv" ]]; then + install_dependencies + elif [[ "$(cat "$INSTALLED_DEPENDENCIES_STAMP" 2>/dev/null || true)" != "$(installed_dependencies_description)" ]]; then + log "the dependencies were last resolved for another mode or other manifests" + install_dependencies + fi +} + +# --- Reading the manifests ------------------------------------------------------------------------ + +# Reads $MANIFESTS_DIRECTORY and sets what the Tuist manifests read: the targets that stay source, the +# targets that get their warnings back, the test targets each scheme lists, and whether the tests can +# be mapped at all. Tuist maps the tests of every package declared by path or of none, and rejects a +# test that depends on an executable target or on a target no product contains; the manifests' block +# takes both away, so one left means that package's manifest has no block yet (an upstream checkout +# at an older commit, say), and the tests stay out this time. +read_manifests() { + $DRY_RUN && return 0 + local key value analysis_path="$WORK_ROOT/ManifestAnalysis.txt" + python3 - "$MANIFESTS_DIRECTORY" "$(lowercased "$PACKAGE_NAME")" "$UNLISTED_TEST_TARGETS" > "$analysis_path" <<'PYTHON' \ + || fail "cannot read the manifests in $MANIFESTS_DIRECTORY; run ./TuistScript.sh install" +import json +import os +import re +import sys + +manifests_directory, own_identity, unlisted_tests = sys.argv[1:4] +unlisted_tests = set(unlisted_tests.split(",")) + +packages = [] +with open(os.path.join(manifests_directory, "packages.tsv")) as handle: + for line in handle: + identity, role, directory = line.rstrip("\n").split("\t") + packages.append((identity, role, directory)) + +def load(identity): + with open(os.path.join(manifests_directory, f"{identity}.json")) as handle: + return json.load(handle) + +def dependency_name(dependency): + for kind in ("target", "byName"): + if kind in dependency: + return dependency[kind][0] + return None + +source_targets, warning_targets, test_entries, test_names, testing_support_names, rejected = [], [], [], [], [], [] +# The test targets of a package that declares a macOS minimum below the one XCTest and Swift Testing need. +raised_test_names = [] +minimum_test_macos = (14, 0) + +def declared_macos(manifest): + for platform in manifest.get("platforms", []): + if platform["platformName"] == "macos": + return tuple(int(part) for part in platform["version"].split(".")) + return (10, 13) +testing_import = re.compile(r"^\s*(@\w+\s+)*((public|package|internal)\s+)?import\s+Testing\b", re.MULTILINE) + +constructor_attribute = re.compile(r"__attribute__\s*\(\(\s*constructor\b") + +def target_files(package_directory, target, extensions): + target_directory = os.path.join(package_directory, target.get("path") or os.path.join("Sources", target["name"])) + for root, _, file_names in os.walk(target_directory): + for file_name in file_names: + if file_name.endswith(extensions): + yield os.path.join(root, file_name) + +def has_load_time_constructor(package_directory, target): + for path in target_files(package_directory, target, (".c", ".m", ".mm", ".cpp", ".cc")): + with open(path, errors="replace") as handle: + if constructor_attribute.search(handle.read()): + return True + return False + +# The final links (test bundles, the swift-section executable) that reach, through the package's own +# target dependencies, a target whose only job happens in a load-time constructor. SwiftPM links each +# target's object files whole; Tuist builds a static library, and the linker loads no member nothing +# refers to, so the constructor would never run. +force_loads = [] + +def force_loaded_targets(targets, root_name, constructor_names): + dependencies_by_name = {target["name"]: [dependency_name(dependency) for dependency in target["dependencies"]] for target in targets} + reached, pending = set(), [root_name] + while pending: + name = pending.pop() + for dependency in dependencies_by_name.get(name, []): + if dependency in dependencies_by_name and dependency not in reached: + reached.add(dependency) + pending.append(dependency) + return sorted(reached & constructor_names) + +def imports_testing(package_directory, target): + target_directory = os.path.join(package_directory, target.get("path") or os.path.join("Sources", target["name"])) + for root, _, file_names in os.walk(target_directory): + for file_name in file_names: + if file_name.endswith(".swift"): + with open(os.path.join(root, file_name), errors="replace") as handle: + if testing_import.search(handle.read()): + return True + return False +own_target_names = set() +for identity, role, directory in packages: + if role == "third-party": + continue + manifest = load(identity) + targets = manifest["targets"] + names = [target["name"] for target in targets] + # Tuist names the resource bundle of a target with resources _. + names += [f"{manifest['name']}_{target['name']}" for target in targets if target.get("resources")] + own_target_names.update(names) + source_targets += names + # An upstream package built from Tuist's checkout (the remote mode) has library targets that import + # Testing too, such as MachOKitExtensions' MachOTestingSupport; they need the plugin path all the same. + testing_support_names += [ + target["name"] for target in targets if target["type"] == "regular" and imports_testing(directory, target) + ] + if role != "own-path": + continue + warning_targets += [target["name"] for target in targets if target["type"] != "test"] + constructor_names = {target["name"] for target in targets if target["type"] == "regular" and has_load_time_constructor(directory, target)} + if constructor_names: + for target in targets: + if target["type"] in ("test", "executable"): + for name in force_loaded_targets(targets, target["name"], constructor_names): + force_loads.append(f"{target['name']}:{name}") + executable_names = {target["name"] for target in targets if target["type"] == "executable"} + product_target_names = { + name + for product in manifest["products"] if "library" in product["type"] + for name in product["targets"] + } + regular_names = {target["name"] for target in targets if target["type"] == "regular"} + tests = [target for target in targets if target["type"] == "test"] + test_names += [test["name"] for test in tests] + if declared_macos(manifest) < minimum_test_macos: + raised_test_names += [test["name"] for test in tests] + for test in tests: + for dependency in test["dependencies"]: + name = dependency_name(dependency) + if name in executable_names: + rejected.append(f"{manifest['name']}'s {test['name']}, which depends on the executable target {name}") + elif name in regular_names and name not in product_target_names: + rejected.append(f"{manifest['name']}'s {test['name']}, which depends on {name}, a target no product contains") + listed = [test["name"] for test in tests if test["name"] not in unlisted_tests] + if listed: + test_entries.append(f"{'.' if identity == own_identity else directory}={','.join(listed)}") + +# Cache exceptions match target names in every package: a third-party target named like one of ours +# stays source too. +for identity, role, directory in packages: + if role != "third-party": + continue + try: + manifest = load(identity) + except OSError: + print(f"UNREAD={directory}") + continue + shared = sorted(own_target_names & {target["name"] for target in manifest["targets"]}) + if shared: + print(f"SHARED_NAME={manifest['name']} has targets named like ones that stay source ({', '.join(shared)}); they stay source too") + +print("SOURCE_TARGETS=" + ",".join(source_targets)) +print("WARNING_TARGETS=" + ",".join(warning_targets)) +print("TEST_TARGETS=" + ";".join(test_entries)) +print("TEST_TARGET_NAMES=" + ",".join(test_names)) +print("RAISED_TEST_TARGET_NAMES=" + ",".join(raised_test_names)) +print("TESTING_SUPPORT_TARGET_NAMES=" + ",".join(testing_support_names)) +print("FORCE_LOADS=" + ",".join(force_loads)) +for reason in rejected: + print("REJECTED=" + reason) +PYTHON + TUIST_SOURCE_TARGET_NAMES="" + TUIST_WARNING_TARGET_NAMES="" + TUIST_PACKAGE_TEST_TARGETS="" + TUIST_TEST_TARGET_NAMES="" + TUIST_RAISED_TEST_TARGET_NAMES="" + TUIST_TESTING_SUPPORT_TARGET_NAMES="" + TUIST_FORCE_LOADS="" + TUIST_MAPS_LOCAL_PACKAGE_TESTS=1 + while IFS='=' read -r key value; do + case "$key" in + SOURCE_TARGETS) TUIST_SOURCE_TARGET_NAMES="$value";; + WARNING_TARGETS) TUIST_WARNING_TARGET_NAMES="$value";; + TEST_TARGETS) TUIST_PACKAGE_TEST_TARGETS="$value";; + TEST_TARGET_NAMES) TUIST_TEST_TARGET_NAMES="$value";; + RAISED_TEST_TARGET_NAMES) TUIST_RAISED_TEST_TARGET_NAMES="$value";; + TESTING_SUPPORT_TARGET_NAMES) TUIST_TESTING_SUPPORT_TARGET_NAMES="$value";; + FORCE_LOADS) TUIST_FORCE_LOADS="$value";; + REJECTED) + warn "Tuist would reject $value" + TUIST_MAPS_LOCAL_PACKAGE_TESTS=0;; + SHARED_NAME) warn "$value";; + UNREAD) warn "cannot read the manifest of $value; a target of it named like one of ours would stay source unnoticed";; + esac + done < "$analysis_path" + if [[ "$TUIST_MAPS_LOCAL_PACKAGE_TESTS" != 1 ]]; then + warn "the tests stay out of the workspace this time. Each manifest above needs the TUIST_MAPS_LOCAL_PACKAGE_TESTS block MachOSwiftSection's Package.swift ends with (Documentations/Internal/TuistDevelopment.md)." + TUIST_PACKAGE_TEST_TARGETS="" + TUIST_TEST_TARGET_NAMES="" + TUIST_RAISED_TEST_TARGET_NAMES="" + fi + export TUIST_SOURCE_TARGET_NAMES TUIST_WARNING_TARGET_NAMES TUIST_PACKAGE_TEST_TARGETS TUIST_TEST_TARGET_NAMES \ + TUIST_RAISED_TEST_TARGET_NAMES \ + TUIST_TESTING_SUPPORT_TARGET_NAMES TUIST_FORCE_LOADS TUIST_MAPS_LOCAL_PACKAGE_TESTS +} + +# --- Commands ------------------------------------------------------------------------------------- + +claim_checkouts() { + local package_name + claim_checkout "$PROJECT_DIR" "$PACKAGE_NAME" "$PACKAGE_NAME" + if [[ "$CURRENT_DEPENDENCY_MODE" == local ]]; then + for package_name in "${LOCAL_PACKAGE_NAMES[@]}"; do + claim_checkout "$LOCAL_DEPENDENCIES_DIRECTORY/$package_name" "$package_name" \ + "$(local_package_project_name "$package_name")" + done + fi +} + +# The name Tuist gives the project it generates into an upstream checkout: the package's own name. +local_package_project_name() { + python3 -c 'import json, sys; print(json.load(open(sys.argv[1]))["name"])' \ + "$MANIFESTS_DIRECTORY/$(lowercased "$1").json" 2>/dev/null || printf '%s\n' "$1" +} + +# Generates the workspace against the binary cache of one configuration ($1, $CONFIGURATION by +# default). +generate_workspace() { + local configuration="${1:-$CONFIGURATION}" + ensure_dependencies + read_manifests + claim_checkouts + log "Generating $WORKSPACE ($configuration, $CURRENT_DEPENDENCY_MODE dependencies)" + run_tuist "generate-$configuration" "${TUIST[@]}" generate --no-open --configuration "$configuration" \ + || fail "tuist generate failed" + turn_off_the_thread_performance_checker +} + +# The test schemes run their tests the way `swift test` does, without Xcode's Thread Performance +# Checker: it inserts libRPAC.dylib, which rebinds calls in the loaded images, and the cross-reference +# tests that compare a cache image read in process with the same image read from its file then see +# calls into libRPAC. Workspace.swift asks for it to be off, but Tuist 4.210 writes only the Main +# Thread Checker's attribute into a scheme's TestAction, so this adds the other one. +turn_off_the_thread_performance_checker() { + $DRY_RUN && return 0 + python3 - "$WORKSPACE/xcshareddata/xcschemes" <<'SCHEME_EDIT' +import glob +import os +import re +import sys + +for path in glob.glob(os.path.join(sys.argv[1], "* Tests.xcscheme")): + with open(path) as handle: + scheme = handle.read() + def add_attribute(match): + element = match.group(0) + if "disablePerformanceAntipatternChecker" in element: + return element + return element[:-1].rstrip() + '\n disablePerformanceAntipatternChecker = "YES">' + updated = re.sub(r"]*>", add_attribute, scheme, count=1) + if updated != scheme: + with open(path, "w") as handle: + handle.write(updated) +SCHEME_EDIT +} + +warm_cache() { + ensure_dependencies + read_manifests + claim_checkouts + if [[ -n "$STORAGE_ROOT" ]]; then + # Tuist refuses to start with anything left in it from an earlier run, and never empties it. + run rm -rf "$TUIST_CACHE_WARM_SCRATCH_DIRECTORY" + run mkdir -p "$TUIST_CACHE_WARM_SCRATCH_DIRECTORY" + fi + log "Building the third-party dependencies into the binary cache ($CONFIGURATION)" + # Without --cache-profile, `tuist cache warm` ignores the default profile in Tuist.swift and caches + # every target it can, ours included. + run_tuist "warm-$CONFIGURATION" "${TUIST[@]}" cache warm --configuration "$CONFIGURATION" \ + --cache-profile development --no-upload \ + || fail "tuist cache warm failed" + # A workspace generated before the warm-up still builds the dependencies from source. + generate_workspace "$CONFIGURATION" +} + +xcodebuild_arguments() { + printf '%s\n' -workspace "$WORKSPACE" -configuration "$CONFIGURATION" -destination 'platform=macOS' \ + -derivedDataPath "$WORK_ROOT/DerivedData/$CONFIGURATION" -skipPackagePluginValidation -skipMacroValidation +} + +build_command() { + generate_workspace + local arguments=() + while IFS= read -r argument; do arguments+=("$argument"); done < <(xcodebuild_arguments) + log "Building $BUILD_SCHEME ($CONFIGURATION)" + run_logged "build-$CONFIGURATION" xcodebuild build -scheme "$BUILD_SCHEME" "${arguments[@]}" \ + ${EXTRA_ARGUMENTS[@]+"${EXTRA_ARGUMENTS[@]}"} || fail "the build failed" + if ! $DRY_RUN && [[ "$BUILD_SCHEME" == swift-section ]]; then + log "swift-section: $WORK_ROOT/DerivedData/$CONFIGURATION/Build/Products/$CONFIGURATION/swift-section" + fi +} + +test_command() { + generate_workspace + [[ -n "${TUIST_PACKAGE_TEST_TARGETS:-}" ]] || $DRY_RUN \ + || fail "the workspace has no test scheme this time (see the warning above)" + local arguments=() result_bundle exit_code=0 + while IFS= read -r argument; do arguments+=("$argument"); done < <(xcodebuild_arguments) + result_bundle="$WORK_ROOT/TestResults/$(date +%Y%m%d-%H%M%S).xcresult" + log "Testing $TEST_SCHEME ($CONFIGURATION)" + log " result bundle: $result_bundle" + run_logged "test-$CONFIGURATION" xcodebuild test -scheme "$TEST_SCHEME" "${arguments[@]}" \ + -resultBundlePath "$result_bundle" ${EXTRA_ARGUMENTS[@]+"${EXTRA_ARGUMENTS[@]}"} || exit_code=$? + if ! $DRY_RUN && [[ -d "$result_bundle" ]]; then + xcrun xcresulttool get test-results summary --path "$result_bundle" --compact 2>/dev/null \ + | python3 -c 'import json, sys; summary = json.load(sys.stdin); print("[TuistScript] result: {result}, {passedTests} passed, {failedTests} failed, {skippedTests} skipped".format(**summary))' \ + || true + fi + exit $exit_code +} + +release_command() { + local checkout_real_path + if [[ -f "$CLAIMED_CHECKOUTS_FILE" ]]; then + while IFS= read -r checkout_real_path; do + [[ -n "$checkout_real_path" ]] && release_checkout "$checkout_real_path" + done < <(cat "$CLAIMED_CHECKOUTS_FILE") + fi + run rm -f "$CLAIMED_CHECKOUTS_FILE" + run rm -rf "$WORKSPACE" "$COMMAND_LINE_PROJECT_DIRECTORY/MachOSwiftSectionCommandLine.xcodeproj" + log "released every checkout this one claimed; ./TuistScript.sh generate claims them again" +} + +case "$COMMAND" in + install) install_dependencies;; + generate) generate_workspace;; + warm) warm_cache;; + build) build_command;; + test) test_command;; + release) release_command;; +esac diff --git a/Workspace.swift b/Workspace.swift new file mode 100644 index 000000000..20a36f1cb --- /dev/null +++ b/Workspace.swift @@ -0,0 +1,66 @@ +import ProjectDescription + +// MachOSwiftSection-Tuist.xcworkspace, the development-only workspace Tuist generates beside the +// native MachOSwiftSection.xcworkspace (Documentations/Internal/TuistDevelopment.md). +// +// The packages' test targets live in the projects Tuist converts from their Package.swift files, which +// only a workspace scheme can reference. TuistScript.sh lists them in TUIST_PACKAGE_TEST_TARGETS as +// "=,;…", one entry per package whose tests are mapped: +// MachOSwiftSection always (directory "."), the upstream packages in the local dependency mode +// (absolute directories). IntegrationTests, the maintainer's manual-inspection target, is never listed. +let packageTestTargets: [(directory: String, targets: [String])] = Environment.packageTestTargets + .getString(default: "") + .split(separator: ";") + .compactMap { entry in + let parts = entry.split(separator: "=", maxSplits: 1).map(String.init) + guard parts.count == 2 else { return nil } + return (parts[0], parts[1].split(separator: ",").map(String.init)) + } + +// MACHO_SWIFT_SECTION_SILENT_TEST=1, which TuistScript.sh passes on as TUIST_SILENT_TEST, also quiets +// `.print()` of MachOKitExtensions' MachOFixtureSupport. That one reads MACHO_TESTING_SILENT in the test +// process at run time rather than a compilation condition, so the test action sets it, as CI does. +let testArguments: Arguments? = Environment.silentTest.getBoolean(default: false) + ? .arguments(environmentVariables: ["MACHO_TESTING_SILENT": "1"]) + : nil + +func packageName(ofDirectory directory: String) -> String { + directory == "." ? "MachOSwiftSection" : String(directory.split(separator: "/").last ?? Substring(directory)) +} + +func projectPath(ofDirectory directory: String) -> Path { + directory.hasPrefix("/") ? .path(directory) : .relativeToRoot(directory) +} + +let workspace = Workspace( + name: "MachOSwiftSection-Tuist", + projects: ["Tuist/CommandLine"], + schemes: packageTestTargets.map { entry in + var testableTargets = entry.targets.map { targetName in + TestableTarget.testableTarget( + target: .project(path: projectPath(ofDirectory: entry.directory), target: targetName), + parallelization: .swiftTestingOnly + ) + } + if entry.directory == "." { + testableTargets.append(.testableTarget( + target: .project(path: "Tuist/CommandLine", target: "SwiftSectionCommandTests"), + parallelization: .swiftTestingOnly + )) + } + return .scheme( + name: "\(packageName(ofDirectory: entry.directory)) Tests", + testAction: .targets( + testableTargets, + arguments: testArguments, + // The test process as `swift test` runs it. The Thread Performance Checker inserts + // libRPAC.dylib, which rebinds calls in the loaded images: the cross-reference tests that + // compare a cache image read in process with the same image read from its file then + // see calls into libRPAC. The Main Thread Checker swizzles Objective-C methods the same + // way. Tuist 4.210 writes only the Main Thread Checker's attribute; TuistScript.sh adds + // disablePerformanceAntipatternChecker to the generated schemes. + diagnosticsOptions: .options(mainThreadCheckerEnabled: false, performanceAntipatternCheckerEnabled: false) + ) + ) + } +) diff --git a/mise.toml b/mise.toml new file mode 100644 index 000000000..bac4a79e6 --- /dev/null +++ b/mise.toml @@ -0,0 +1,5 @@ +# The Tuist that generates MachOSwiftSection-Tuist.xcworkspace, the development-only Tuist workspace +# (Documentations/Internal/TuistDevelopment.md). Releases, CI and `swift build` / `swift test` do not +# use it. RuntimeViewer pins the same version. +[tools] +tuist = "4.210.0"