From a05bd485deeb5a04453d00502cbeb4863e22f54c Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sat, 24 Oct 2026 22:42:47 +0800 Subject: [PATCH 001/318] feat(SwiftDiffing): record local Swift symbols and export verdicts in snapshots A snapshot now records whether its image carries any local Swift symbol, and each symbol-backed member record whether the member is exported. These are the facts a comparison needs to tell a member an image stripped of its local symbols cannot show from one that is gone: SwiftUI in the macOS 13.0-14.8 dyld shared caches keeps only its exported Swift names. - SymbolIndexStore reads the N_EXT bit of every Swift symbol the symbol-table legs collect (NlistProtocol.isLocal). Its isExternal names an undefined import only, so the legs collect exported symbols too and could not answer this on their own. - The member export verdict moves into SymbolIndexStore.isExportedIncludingDerivedSymbols(names:in:), which the interface's export-status comment and the snapshot both ask. - ABIModule carries both facts and ABIDiffer.snapshot(of:) freezes them; MemberRecord.isExported and ABISnapshot.hasLocalSwiftSymbols are verdict metadata, never part of the keys. The snapshot format version is 8. - UnobservablePresenceFixture compiles three versions of one module and strips the middle one, the shape the rest of the proposal is tested against. --- Documentations/Evolutions/README.md | 2 +- .../draft-evolution-unobservable-presence.md | 8 +- Documentations/README.md | 2 +- .../MachO/MachOSymbols/SymbolIndexStore.swift | 72 +++++- Sources/Output/SwiftDiffing/ABIDiffer.swift | 105 +++++--- Sources/Output/SwiftDiffing/ABIModule.swift | 19 +- Sources/Output/SwiftDiffing/ABISnapshot.swift | 13 +- .../SwiftDiffing/ABISnapshotDocument.swift | 12 +- .../Output/SwiftDiffing/MemberRecord.swift | 55 ++++- .../SwiftDiffableInterfaceBuilder.swift | 21 +- .../SwiftDeclarationPrinter.swift | 9 +- .../UnobservablePresenceFixture.swift | 232 ++++++++++++++++++ Tests/SwiftDiffingTests/ABIDifferTests.swift | 7 + .../ABISnapshotDocumentTests.swift | 15 ++ .../UnobservablePresenceTests.swift | 56 +++++ 15 files changed, 569 insertions(+), 59 deletions(-) create mode 100644 Sources/TestSupport/MachOTestingSupport/UnobservablePresenceFixture.swift create mode 100644 Tests/SwiftInterfaceTests/UnobservablePresenceTests.swift diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index 9005ed460..2f07d1129 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -83,4 +83,4 @@ | [0071](0071-swift-capstone-7.md) | 迁到 swift-capstone 7.0:解码器改用 `Disassembler` | Implemented | | [0072](0072-cross-reference-analysis.md) | 交叉引用分析:从机器码读出每个函数引用了什么 | Implemented | | [0073](0073-protocol-requirement-placement.md) | 协议约束可选写在各自的关联类型上 | Implemented | -| draft | [evolution 与 diff 区分「不存在」和「看不见」](draft-evolution-unobservable-presence.md) | Accepted | +| draft | [evolution 与 diff 区分「不存在」和「看不见」](draft-evolution-unobservable-presence.md) | In Progress | diff --git a/Documentations/Evolutions/draft-evolution-unobservable-presence.md b/Documentations/Evolutions/draft-evolution-unobservable-presence.md index 249034ce1..85d85fe4c 100644 --- a/Documentations/Evolutions/draft-evolution-unobservable-presence.md +++ b/Documentations/Evolutions/draft-evolution-unobservable-presence.md @@ -1,6 +1,6 @@ # Draft - evolution 与 diff 区分「不存在」和「看不见」 -- **状态**: Accepted +- **状态**: In Progress - **创建日期**: 2026-10-24 - **最后更新**: 2026-10-24 - **所属愿景**: 无 @@ -57,7 +57,7 @@ evolution 和 diff 把每个声明在每个版本里只记成「在」或「不 **落地步骤**(每一步单独构建通过、相关测试通过后提交): -1. 快照记下两件事,格式版本升到 8:`SymbolIndexStore` 的判据与查询,`MemberRecord` 的导出判定与 `ABISnapshot` 的镜像级标记,`SwiftDiffableInterfaceBuilder` 冻结时填好。测试判据(fixture 的被剥变体)、冻结结果与编解码。 +1. (已完成)快照记下两件事,格式版本升到 8:`SymbolIndexStore` 的判据与查询,`MemberRecord` 的导出判定与 `ABISnapshot` 的镜像级标记,`SwiftDiffableInterfaceBuilder` 冻结时填好。测试判据(fixture 的被剥变体)、冻结结果与编解码。 2. SwiftDiffing 里的看不见规则与按两侧推断:lineage 的状态数组、区间事件、收录规则;diff 的判定层(看不见的成员单列、不算 breaking);两个文本报告与 JSON。测试方案里列出的手工快照用例。 3. evolution 联合接口:`EvolutionAnnotation` 带上状态与区间,`EvolutionMarking` 的新符号、短语、图例和 `@available` 规则。测试 `EvolutionMarkingTests` 与 `SwiftEvolutionInterfaceBuilderTests`。 4. 文档与 skill 同步;用 CLI 重跑 macOS 27.0 SwiftUI 的 51 版 evolution 做实数据核对,结果写进本提案。 @@ -75,3 +75,7 @@ evolution 和 diff 把每个声明在每个版本里只记成「在」或「不 | 2026-10-24 | 模型只增不改,`presence: [Bool]` 保留 | 未提问自定。它是 `evolution --json` 的现有输出,脚本可能依赖;本机的下游仓库(RuntimeViewer、MachOKitUI、swift-decompiler)都不读 lineage 模型 | | 2026-10-24 | 落地拆成四步 | 精简提案原本没有落地步骤;按「快照事实 → 判定规则 → 接口呈现 → 文档与实数据」拆开,每一步都能单独构建和测试 | | 2026-10-24 | 用户批准(Draft → Accepted),开始实现 | 方案与全部假设照单通过 | +| 2026-10-24 | 判据读符号表条目的 `N_EXT` 位(新增 `NlistProtocol.isLocal`),不沿用 `isExternal` | 实现中发现本库的 `isExternal` 只指未定义的导入,符号表那两条收集路径收的是全部已定义符号、导出的也在内;照字面用它,被剥的版本也会因为导出符号而被判成「有 local Swift 符号」,fixture 的测试当场抓到。`ExportFacts` 注释里「只收 local 符号」的旧说法顺带更正 | +| 2026-10-24 | 成员导出判定的组合规则收进 `SymbolIndexStore.isExportedIncludingDerivedSymbols(names:in:)` | 快照要的判定和 interface 的 `// not exported` 注释是同一条规则(任一入口导出即为导出、查不到就不下结论);printer 原来自己写了一份,现在两边都调这一处,不会走样 | +| 2026-10-24 | 测试改用专门的三版本 fixture(`UnobservablePresenceFixture`,中间一版 `strip -x`),在快照这一层验证判据 | 方案原想用 `ObjCImplementationFixture` 的被剥变体单测 `SymbolIndexStore`;改在冻结结果上测能同时覆盖判据与导出判定,而且第 3 步的端到端测试要的正是这样三个版本,一个 fixture 两用 | +| 2026-10-24 | 第 1 步完成(In Progress) | 定向测试通过:`UnobservablePresenceTests` 3 个、`ABISnapshotDocumentTests` 与 `ABIDifferAlgorithmTests` 共 14 个、`ExportedSymbolFactsTests` 5 个,以及受 printer 改动影响的导出注释与 `--exported-only` 套件,原始退出码 0。真实数据核对:此前导出的 nlist 里,12.7 与 15.0 的 SwiftUI 各有 149,409 与 167,325 个 local `_$s` 符号,13.0 与 14.8 一个都没有 | diff --git a/Documentations/README.md b/Documentations/README.md index 27d313735..7c1825788 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -175,7 +175,7 @@ selects names using each access's offset and width. | [Evolutions/0071-swift-capstone-7.md](Evolutions/0071-swift-capstone-7.md) | **提案 0071(Implemented)**:迁到 swift-capstone 7.0。`SwiftThunkAnalysis` 的解码器改用不可复制的 `Disassembler`,在 `forEachInstruction` 的闭包里把每条指令就地转成 `ThunkInstruction`;别名改看 `alias`,写回改看 `writesBackBaseRegister`。只改 `CapstoneThunkDecoder.swift`,对外接口不变;依赖下限从 swift-capstone 6.0.1 提到 7.0.0。 | | [Evolutions/0072-cross-reference-analysis.md](Evolutions/0072-cross-reference-analysis.md) | **提案 0072(Implemented)**:新 target `CrossReferenceAnalysis`——从 arm64 机器码读出一个镜像的函数表与每个函数引用了什么(直接调用、ObjC 消息、跨库调用、类型引用、间接调用及其候选),认 macOS 27 / iOS 27 起全缓存共用的桩与更早的镜像自带桩;RuntimeViewer 交叉引用功能(0056-cross-references)的分析层。 | | [Evolutions/0073-protocol-requirement-placement.md](Evolutions/0073-protocol-requirement-placement.md) | **提案 0073(Implemented)**:interface 的新开关 `protocolRequirementPlacement`(CLI `interface --requirements-on-associated-types`),打开后把关于协议自己某个关联类型的约束写到那个 `associatedtype` 上(`associatedtype Failure: Swift.Error`),摆法与编译器写 `.swiftinterface` 时一致;唯一不照抄的是递归协议的 `Self.Child.Leaf: Hashable`,编译器把它挂到 `Leaf` 上改变了含义,这里挂在 `Child` 上。默认仍全部写在协议的 `where` 子句,输出逐字节不变;dump 与 diff / evolution 不接。两种写法表达的约束相同,由往返编译测试保证。顺带修好约束右侧的复合类型被印成另一条约束的 bug(`Self.Second == [Self.First]` 印成 `Self.Second == Self.First`),dump 与 interface 都受影响。 | -| [Evolutions/draft-evolution-unobservable-presence.md](Evolutions/draft-evolution-unobservable-presence.md) | **提案 draft(Accepted)**:evolution 与 diff 区分「不存在」和「看不见」——macOS 13.0–14.8 的 SwiftUI 被剥掉了全部 local Swift 符号,非导出成员在这些版本里全部缺席,27.0 的 51 版 evolution 因此有 5,189 条假缺口(`removed in 13.0 · added in 15.0`)。快照记下镜像有没有 local Swift 符号、每个成员是否导出(格式版本 8),被剥版本里本来就看不见的声明记为看不见;一段看不见的版本两侧状态相同时按两侧推断并在位图里画 `◍`,两侧不同时记成区间事件(`removed between 12.7 and 15.0`)。规则放在 SwiftDiffing,diff 的判定一并适用,`diff --interface` 的渲染不动。 | +| [Evolutions/draft-evolution-unobservable-presence.md](Evolutions/draft-evolution-unobservable-presence.md) | **提案 draft(In Progress)**:evolution 与 diff 区分「不存在」和「看不见」——macOS 13.0–14.8 的 SwiftUI 被剥掉了全部 local Swift 符号,非导出成员在这些版本里全部缺席,27.0 的 51 版 evolution 因此有 5,189 条假缺口(`removed in 13.0 · added in 15.0`)。快照记下镜像有没有 local Swift 符号、每个成员是否导出(格式版本 8),被剥版本里本来就看不见的声明记为看不见;一段看不见的版本两侧状态相同时按两侧推断并在位图里画 `◍`,两侧不同时记成区间事件(`removed between 12.7 and 15.0`)。规则放在 SwiftDiffing,diff 的判定一并适用,`diff --interface` 的渲染不动。 | | [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),不重复登记。提案与专题文档引入新术语时同批登记。 | | [SymbolIndexStoreMemoryOptimization.md](Internal/SymbolIndexStoreMemoryOptimization.md) | **`SymbolIndexStore` 内存优化专题——读这批内存文档先读这篇**:三波优化各自解决什么、今天的存储模型长什么样、付出了哪些约束、实测收益全曲线(RuntimeViewer 五镜像稳态 842 → 262 MB)。 | | [SymbolicManglingSymbols.md](Internal/SymbolicManglingSymbols.md) | **`_symbolic` 符号**(提案 0050-symbolic-mangling-symbol-index 的实现说明):编译器为每条带 symbolic reference 的 mangled name 生成的去重符号,名字里按引用顺序写出每个被引用者的完整 mangling(含 private 鉴别符);`SymbolIndexStore` 在已有扫描里收进一张独立的表,`SwiftInspection.SymbolicManglingIndex` 按顺序配对、按被引用位置建索引。被引用者会借用前面的 substitution,只能一起 demangle;私有鉴别符还原与 `SymbolicDemangler` 的对照测试是两个消费者;附 AppKit / SwiftUICore / SwiftUI 的数量与内存实测。 | diff --git a/Sources/MachO/MachOSymbols/SymbolIndexStore.swift b/Sources/MachO/MachOSymbols/SymbolIndexStore.swift index a5d1f85b6..3c67ad22e 100644 --- a/Sources/MachO/MachOSymbols/SymbolIndexStore.swift +++ b/Sources/MachO/MachOSymbols/SymbolIndexStore.swift @@ -224,9 +224,10 @@ public final class SymbolIndexStore: @unchecked Sendable { /// Export-trie facts for the image (evolution proposal 0008), the /// backing for `isExported(name:)`. Collected explicitly during the /// build sweep because no existing structure records them: both - /// symtab collection legs filter on `!nlist.isExternal` (local - /// symbols only), so an exported symbol's row is minted by the - /// export-trie leg — but that leg's row-minting is *conditional* + /// symtab collection legs filter on `!nlist.isExternal`, which skips + /// imports only — an exported symbol the symbol table lists gets its + /// row there, one it does not list from the export-trie leg — and + /// that leg's row-minting is *conditional* /// (only names the symtab missed, only entries carrying an offset), /// so "row came from the trie leg" is not recoverable after the /// fact and offset-less re-export entries never mint a row at all. @@ -250,6 +251,15 @@ public final class SymbolIndexStore: @unchecked Sendable { let exportFacts: ExportFacts + /// Whether the symbol table holds any local Swift symbol — one whose + /// `N_EXT` bit is clear (evolution proposal + /// `evolution-unobservable-presence`). `false` for an image stripped + /// of its local symbols — SwiftUI in the macOS 13.0–14.8 dyld shared + /// caches — which keeps only its exported Swift names. A debug-map + /// entry only reserves a row and does not count; a name refused by + /// the packed-reference budget still does, since the symbol is there. + let hasLocalSwiftSymbols: Bool + /// The image's symbolic-mangling symbols (`_symbolic ` / /// `_default assoc type `), collected by the same symtab pass into a /// table of their own (evolution proposal @@ -299,6 +309,7 @@ public final class SymbolIndexStore: @unchecked Sendable { rootNodeIndexByTableRow: [NodeStore.NodeIndex?], symbolRowsByOffset: [Int: SymbolRowBucket], exportFacts: ExportFacts, + hasLocalSwiftSymbols: Bool, symbolicManglingSymbolTable: SymbolTable, rowIndexes: consuming RowIndexes ) { @@ -307,6 +318,7 @@ public final class SymbolIndexStore: @unchecked Sendable { self.rootNodeIndexByTableRow = rootNodeIndexByTableRow self.symbolRowsByOffset = symbolRowsByOffset self.exportFacts = exportFacts + self.hasLocalSwiftSymbols = hasLocalSwiftSymbols self.symbolicManglingSymbolTable = symbolicManglingSymbolTable self.typeInfoByName = rowIndexes.typeInfoByName self.globalSymbolRowsByKind = rowIndexes.globalSymbolRowsByKind @@ -673,6 +685,12 @@ public final class SymbolIndexStore: @unchecked Sendable { } } + // Set by either symtab leg on the first Swift symbol it collects whose + // `N_EXT` bit is clear (see `Storage.hasLocalSwiftSymbols`). The legs + // collect every defined symbol, exported ones included — they skip + // only imports (`isExternal`) — so the bit has to be read here. + var hasLocalSwiftSymbols = false + /// Mapped-name collection leg: iterates the image's own symbol /// sequence so each entry exposes `nameC` (a pointer into the /// mapped string table). The Swift-symbol test runs byte-level on @@ -694,6 +712,9 @@ public final class SymbolIndexStore: @unchecked Sendable { ) continue } + if symbol.nlist.isLocal { + hasLocalSwiftSymbols = true + } // A `nil` row means the name's binary-supplied geometry // exceeds the packed budgets (malformed/hostile string // table) — skip the symbol instead of trapping (M3). @@ -748,6 +769,9 @@ public final class SymbolIndexStore: @unchecked Sendable { continue } if isSwiftSymbol { + if symbol.nlist.isLocal { + hasLocalSwiftSymbols = true + } guard let (row, isNewRow) = tableBuilder.canonicalRow(forName: name, canonicalOffset: canonicalOffset, isExternal: symbol.nlist.isExternal) else { continue } registerRow(row, rawOffset: rawOffset, canonicalOffset: canonicalOffset, isNewRow: isNewRow) } else { @@ -893,6 +917,7 @@ public final class SymbolIndexStore: @unchecked Sendable { rootNodeIndexByTableRow: rootNodeIndexByTableRow, symbolRowsByOffset: symbolRowsByOffset, exportFacts: exportFacts, + hasLocalSwiftSymbols: hasLocalSwiftSymbols, symbolicManglingSymbolTable: symbolicManglingSymbolTable, rowIndexes: rowIndexes ) @@ -1178,6 +1203,36 @@ public final class SymbolIndexStore: @unchecked Sendable { return false } + /// The export verdict of a member whose entry points are `names` — a + /// function's one symbol, a property's or subscript's accessors: `true` + /// as soon as one of them is exported in its own or a derived form + /// (``isExportedIncludingDerivedSymbols(name:in:)``), `false` only when + /// none is, `nil` when `names` is empty or the image carries no export + /// information. The interface's `// not exported` annotation and the ABI + /// snapshot's per-member verdict both ask this, so the two cannot + /// disagree. + public func isExportedIncludingDerivedSymbols(names: [String], in machO: some MachORepresentableWithCache) -> Bool? { + guard !names.isEmpty else { return nil } + for name in names { + guard let isExported = isExportedIncludingDerivedSymbols(name: name, in: machO) else { return nil } + if isExported { + return true + } + } + return false + } + + /// Whether `machO`'s symbol table carries at least one local + /// (non-external) Swift symbol (evolution proposal + /// `evolution-unobservable-presence`). `false` for an image stripped of + /// its local symbols — SwiftUI in the macOS 13.0–14.8 dyld shared caches + /// — where a non-exported declaration has no name the index could find, + /// so its absence there says nothing about whether it exists. `nil` when + /// the store is unavailable. + public func hasLocalSwiftSymbols(in machO: some MachORepresentableWithCache) -> Bool? { + storage(in: machO)?.hasLocalSwiftSymbols + } + /// Returns the pre-extracted thunk-attribute members whose parent type /// name matches `typeName`. `thunkKind` is the demangler attribute marker /// kind (e.g. `.objCAttribute`, `.nonObjCAttribute`). Lookup is O(1) in the @@ -1567,6 +1622,17 @@ extension NlistProtocol { return flags.contains(.ext) && type == .undf } + /// A symbol private to its image: the `N_EXT` bit clear, so neither an + /// export nor an import. Not the negation of ``isExternal``, which names + /// an undefined import only. A linker turns a private external + /// (`N_PEXT`) into one of these, which is how a Swift declaration below + /// `public` reaches a linked image's symbol table, and what a strip of + /// the local symbols removes. + package var isLocal: Bool { + guard let flags else { return false } + return !flags.contains(.ext) + } + /// A debug-map (STABS) entry: it describes a symbol for the debugger and /// is not one. An `N_GSYM` entry carries the value 0 under the very name /// of the symbol it describes; indexed like a symbol, it was filed at the diff --git a/Sources/Output/SwiftDiffing/ABIDiffer.swift b/Sources/Output/SwiftDiffing/ABIDiffer.swift index 8dff56113..71c664914 100644 --- a/Sources/Output/SwiftDiffing/ABIDiffer.swift +++ b/Sources/Output/SwiftDiffing/ABIDiffer.swift @@ -71,27 +71,29 @@ public struct ABIDiffer: Sendable { /// projecting every declaration into its diff records. All of the model /// knowledge lives here; the diff above is then pure data over the result. public func snapshot(of module: ABIModule) -> ABISnapshot { - ABISnapshot( + let exportVerdicts = MemberExportVerdicts(module.memberExportVerdict) + return ABISnapshot( types: containerSnapshots( Array(module.allTypeDefinitions.values), containerKind: .type, key: { ABIKey.makeUnwrappingType(for: $0.typeName.node) }, name: { $0.typeName.name(using: .default) }, - members: { self.memberRecords(of: $0) } + members: { self.memberRecords(of: $0, exportVerdicts: exportVerdicts) } ), protocols: containerSnapshots( Array(module.allProtocolDefinitions.values), containerKind: .protocol, key: { ABIKey.makeUnwrappingType(for: $0.protocolName.node) }, name: { $0.protocolName.name(using: .default) }, - members: { self.memberRecords(of: $0) } + members: { self.memberRecords(of: $0, exportVerdicts: exportVerdicts) } ), - typeExtensions: extensionContainerSnapshots(module.typeExtensionDefinitions, .typeExtension), - protocolExtensions: extensionContainerSnapshots(module.protocolExtensionDefinitions, .protocolExtension), - typeAliasExtensions: extensionContainerSnapshots(module.typeAliasExtensionDefinitions, .typeAliasExtension), - conformanceExtensions: extensionContainerSnapshots(module.conformanceExtensionDefinitions, .conformanceExtension), - globalVariables: module.globalVariableDefinitions.map(MemberRecord.make), - globalFunctions: module.globalFunctionDefinitions.map(MemberRecord.make) + typeExtensions: extensionContainerSnapshots(module.typeExtensionDefinitions, .typeExtension, exportVerdicts), + protocolExtensions: extensionContainerSnapshots(module.protocolExtensionDefinitions, .protocolExtension, exportVerdicts), + typeAliasExtensions: extensionContainerSnapshots(module.typeAliasExtensionDefinitions, .typeAliasExtension, exportVerdicts), + conformanceExtensions: extensionContainerSnapshots(module.conformanceExtensionDefinitions, .conformanceExtension, exportVerdicts), + globalVariables: module.globalVariableDefinitions.map { MemberRecord.make($0).withIsExported(exportVerdicts.isExported($0)) }, + globalFunctions: module.globalFunctionDefinitions.map { MemberRecord.make($0).withIsExported(exportVerdicts.isExported($0)) }, + hasLocalSwiftSymbols: module.hasLocalSwiftSymbols ) } @@ -119,7 +121,8 @@ public struct ABIDiffer: Sendable { /// structurally (the diagnostics channel stays as a backstop). private func extensionContainerSnapshots( _ buckets: OrderedDictionary, - _ containerKind: ContainerKind + _ containerKind: ContainerKind, + _ exportVerdicts: MemberExportVerdicts ) -> [ContainerSnapshot] { buckets.flatMap { name, definitions -> [ContainerSnapshot] in var groupedDefinitions: OrderedDictionary = [:] @@ -142,7 +145,7 @@ public struct ABIDiffer: Sendable { kind: containerKind, conformedProtocolName: protocolText, whereClauseText: whereText, - members: groupDefinitions.flatMap { self.memberRecords(of: $0) } + members: groupDefinitions.flatMap { self.memberRecords(of: $0, exportVerdicts: exportVerdicts) } ) } } @@ -228,23 +231,23 @@ public struct ABIDiffer: Sendable { /// protocols, and extensions all expose them). The kind-specific extras — /// stored fields / enum cases / `deinit` for types, associated types for /// protocols — are layered on by the concrete overloads below. - func sharedMemberRecords(of definition: some Definition) -> [MemberRecord] { + func sharedMemberRecords(of definition: some Definition, exportVerdicts: MemberExportVerdicts = MemberExportVerdicts(nil)) -> [MemberRecord] { var records: [MemberRecord] = [] - records.append(contentsOf: definition.variables.map(MemberRecord.make)) - records.append(contentsOf: definition.staticVariables.map(MemberRecord.make)) - records.append(contentsOf: definition.functions.map(MemberRecord.make)) - records.append(contentsOf: definition.staticFunctions.map(MemberRecord.make)) - records.append(contentsOf: definition.subscripts.map(MemberRecord.make)) - records.append(contentsOf: definition.staticSubscripts.map(MemberRecord.make)) - records.append(contentsOf: definition.allocators.map(MemberRecord.make)) - records.append(contentsOf: definition.constructors.map(MemberRecord.make)) + records.append(contentsOf: definition.variables.map { MemberRecord.make($0).withIsExported(exportVerdicts.isExported($0)) }) + records.append(contentsOf: definition.staticVariables.map { MemberRecord.make($0).withIsExported(exportVerdicts.isExported($0)) }) + records.append(contentsOf: definition.functions.map { MemberRecord.make($0).withIsExported(exportVerdicts.isExported($0)) }) + records.append(contentsOf: definition.staticFunctions.map { MemberRecord.make($0).withIsExported(exportVerdicts.isExported($0)) }) + records.append(contentsOf: definition.subscripts.map { MemberRecord.make($0).withIsExported(exportVerdicts.isExported($0)) }) + records.append(contentsOf: definition.staticSubscripts.map { MemberRecord.make($0).withIsExported(exportVerdicts.isExported($0)) }) + records.append(contentsOf: definition.allocators.map { MemberRecord.make($0).withIsExported(exportVerdicts.isExported($0)) }) + records.append(contentsOf: definition.constructors.map { MemberRecord.make($0).withIsExported(exportVerdicts.isExported($0)) }) return records } /// A type adds stored fields (or order-sensitive enum cases) and `deinit` /// on top of the shared members. - func memberRecords(of definition: TypeDefinition) -> [MemberRecord] { - var records = sharedMemberRecords(of: definition) + func memberRecords(of definition: TypeDefinition, exportVerdicts: MemberExportVerdicts = MemberExportVerdicts(nil)) -> [MemberRecord] { + var records = sharedMemberRecords(of: definition, exportVerdicts: exportVerdicts) if case .enum = definition.typeContextDescriptorWrapper { for (tag, field) in definition.fields.enumerated() { records.append(.makeCase(field, tag: tag)) @@ -258,7 +261,7 @@ public struct ABIDiffer: Sendable { records.append(contentsOf: definition.fields.filter { !$0.isRawLayoutStorage }.map(MemberRecord.make)) } if definition.hasDeallocator { - records.append(.makeDeinit()) + records.append(MemberRecord.makeDeinit().withIsExported(exportVerdicts.isExported(deallocatorOf: definition))) } return records } @@ -279,20 +282,20 @@ public struct ABIDiffer: Sendable { /// degrades to the status rule). Deliberately built per-collection rather /// than via `sharedMemberRecords`, which serves types/extensions where the /// fact does not apply. - func memberRecords(of definition: ProtocolDefinition) -> [MemberRecord] { + func memberRecords(of definition: ProtocolDefinition, exportVerdicts: MemberExportVerdicts = MemberExportVerdicts(nil)) -> [MemberRecord] { let defaultedOffsets = definition.defaultedRequirementPWTOffsets func flag(_ slotOffsets: [Int?]) -> Bool? { Self.requirementDefaultImplementationFlag(slotOffsets: slotOffsets, defaultedOffsets: defaultedOffsets) } var records: [MemberRecord] = [] - records.append(contentsOf: definition.variables.map { MemberRecord.make($0).withHasDefaultImplementation(flag($0.accessors.map(\.offset))) }) - records.append(contentsOf: definition.staticVariables.map { MemberRecord.make($0).withHasDefaultImplementation(flag($0.accessors.map(\.offset))) }) - records.append(contentsOf: definition.functions.map { MemberRecord.make($0).withHasDefaultImplementation(flag([$0.offset])) }) - records.append(contentsOf: definition.staticFunctions.map { MemberRecord.make($0).withHasDefaultImplementation(flag([$0.offset])) }) - records.append(contentsOf: definition.subscripts.map { MemberRecord.make($0).withHasDefaultImplementation(flag($0.accessors.map(\.offset))) }) - records.append(contentsOf: definition.staticSubscripts.map { MemberRecord.make($0).withHasDefaultImplementation(flag($0.accessors.map(\.offset))) }) - records.append(contentsOf: definition.allocators.map { MemberRecord.make($0).withHasDefaultImplementation(flag([$0.offset])) }) - records.append(contentsOf: definition.constructors.map { MemberRecord.make($0).withHasDefaultImplementation(flag([$0.offset])) }) + records.append(contentsOf: definition.variables.map { MemberRecord.make($0).withHasDefaultImplementation(flag($0.accessors.map(\.offset))).withIsExported(exportVerdicts.isExported($0)) }) + records.append(contentsOf: definition.staticVariables.map { MemberRecord.make($0).withHasDefaultImplementation(flag($0.accessors.map(\.offset))).withIsExported(exportVerdicts.isExported($0)) }) + records.append(contentsOf: definition.functions.map { MemberRecord.make($0).withHasDefaultImplementation(flag([$0.offset])).withIsExported(exportVerdicts.isExported($0)) }) + records.append(contentsOf: definition.staticFunctions.map { MemberRecord.make($0).withHasDefaultImplementation(flag([$0.offset])).withIsExported(exportVerdicts.isExported($0)) }) + records.append(contentsOf: definition.subscripts.map { MemberRecord.make($0).withHasDefaultImplementation(flag($0.accessors.map(\.offset))).withIsExported(exportVerdicts.isExported($0)) }) + records.append(contentsOf: definition.staticSubscripts.map { MemberRecord.make($0).withHasDefaultImplementation(flag($0.accessors.map(\.offset))).withIsExported(exportVerdicts.isExported($0)) }) + records.append(contentsOf: definition.allocators.map { MemberRecord.make($0).withHasDefaultImplementation(flag([$0.offset])).withIsExported(exportVerdicts.isExported($0)) }) + records.append(contentsOf: definition.constructors.map { MemberRecord.make($0).withHasDefaultImplementation(flag([$0.offset])).withIsExported(exportVerdicts.isExported($0)) }) records.append(contentsOf: definition.associatedTypes.map(MemberRecord.makeAssociatedType)) records.append(contentsOf: definition.strippedSymbolicRequirements.map { MemberRecord.makeProtocolRequirement( @@ -320,8 +323,8 @@ public struct ABIDiffer: Sendable { /// **witnesses** — frozen into `AssociatedTypeWitnessProjection` at index /// time precisely because the raw `AssociatedType` records' name accessors /// are Mach-O-bound and cannot be resolved here. - func memberRecords(of definition: ExtensionDefinition) -> [MemberRecord] { - var records = sharedMemberRecords(of: definition) + func memberRecords(of definition: ExtensionDefinition, exportVerdicts: MemberExportVerdicts = MemberExportVerdicts(nil)) -> [MemberRecord] { + var records = sharedMemberRecords(of: definition, exportVerdicts: exportVerdicts) records.append(contentsOf: definition.resolvedAssociatedTypeWitnesses.map { MemberRecord.makeAssociatedTypeWitness(name: $0.name, substitutedTypeText: $0.substitutedTypeText) }) @@ -389,3 +392,37 @@ public struct ABIDiffer: Sendable { } } } + +/// The module's member export verdict as the freeze asks it: once per +/// symbol-backed record, with the symbol names its definition carries (see +/// ``ABIModule/memberExportVerdict``). Without a verdict every answer is +/// `nil`. +struct MemberExportVerdicts { + private let verdict: ((_ symbolNames: [String]) -> Bool?)? + + init(_ verdict: ((_ symbolNames: [String]) -> Bool?)?) { + self.verdict = verdict + } + + func isExported(_ function: FunctionDefinition) -> Bool? { + answer([function.symbol.name]) + } + + func isExported(_ variable: VariableDefinition) -> Bool? { + answer(variable.accessors.map(\.symbol.name)) + } + + func isExported(_ subscriptDefinition: SubscriptDefinition) -> Bool? { + answer(subscriptDefinition.accessors.map(\.symbol.name)) + } + + func isExported(deallocatorOf typeDefinition: TypeDefinition) -> Bool? { + guard let deallocatorSymbol = typeDefinition.deallocatorSymbol else { return nil } + return answer([deallocatorSymbol.name]) + } + + private func answer(_ symbolNames: [String]) -> Bool? { + guard let verdict else { return nil } + return verdict(symbolNames) + } +} diff --git a/Sources/Output/SwiftDiffing/ABIModule.swift b/Sources/Output/SwiftDiffing/ABIModule.swift index abfbd76e7..f9113010d 100644 --- a/Sources/Output/SwiftDiffing/ABIModule.swift +++ b/Sources/Output/SwiftDiffing/ABIModule.swift @@ -51,6 +51,19 @@ public struct ABIModule { public let globalVariableDefinitions: [VariableDefinition] public let globalFunctionDefinitions: [FunctionDefinition] + // MARK: Symbol-table facts (evolution proposal `evolution-unobservable-presence`) + + /// Whether the image carries any local (non-external) Swift symbol — + /// frozen into ``ABISnapshot/hasLocalSwiftSymbols``. + public let hasLocalSwiftSymbols: Bool + + /// The export verdict of a member, asked with its symbol names (a + /// function's one symbol, a property's or subscript's accessors) and + /// frozen into ``MemberRecord/isExported``. `nil` freezes every record + /// without a verdict. The builder that indexed the image supplies it, + /// since only the image's symbol index can answer. + public let memberExportVerdict: ((_ symbolNames: [String]) -> Bool?)? + public init( rootTypeDefinitions: OrderedDictionary = [:], allTypeDefinitions: OrderedDictionary = [:], @@ -61,7 +74,9 @@ public struct ABIModule { typeAliasExtensionDefinitions: OrderedDictionary = [:], conformanceExtensionDefinitions: OrderedDictionary = [:], globalVariableDefinitions: [VariableDefinition] = [], - globalFunctionDefinitions: [FunctionDefinition] = [] + globalFunctionDefinitions: [FunctionDefinition] = [], + hasLocalSwiftSymbols: Bool = true, + memberExportVerdict: ((_ symbolNames: [String]) -> Bool?)? = nil ) { self.rootTypeDefinitions = rootTypeDefinitions self.allTypeDefinitions = allTypeDefinitions @@ -73,5 +88,7 @@ public struct ABIModule { self.conformanceExtensionDefinitions = conformanceExtensionDefinitions self.globalVariableDefinitions = globalVariableDefinitions self.globalFunctionDefinitions = globalFunctionDefinitions + self.hasLocalSwiftSymbols = hasLocalSwiftSymbols + self.memberExportVerdict = memberExportVerdict } } diff --git a/Sources/Output/SwiftDiffing/ABISnapshot.swift b/Sources/Output/SwiftDiffing/ABISnapshot.swift index e2a5d8462..07791b342 100644 --- a/Sources/Output/SwiftDiffing/ABISnapshot.swift +++ b/Sources/Output/SwiftDiffing/ABISnapshot.swift @@ -27,6 +27,15 @@ public struct ABISnapshot: Codable, Equatable, Sendable { // "…|acc:…") are the de-facto format, so a key-scheme bump must invalidate // old snapshots. + /// Whether the image this snapshot was frozen from carries any local + /// (non-external) Swift symbol. `false` for an image stripped of its + /// local symbols — SwiftUI in the macOS 13.0–14.8 dyld shared caches — + /// which shows only its exported Swift names: a member whose only + /// evidence is a non-exported symbol cannot be seen there, so a + /// comparison treats its absence as unobservable rather than as a + /// removal (evolution proposal `evolution-unobservable-presence`). + public var hasLocalSwiftSymbols: Bool + public init( types: [ContainerSnapshot] = [], protocols: [ContainerSnapshot] = [], @@ -35,7 +44,8 @@ public struct ABISnapshot: Codable, Equatable, Sendable { typeAliasExtensions: [ContainerSnapshot] = [], conformanceExtensions: [ContainerSnapshot] = [], globalVariables: [MemberRecord] = [], - globalFunctions: [MemberRecord] = [] + globalFunctions: [MemberRecord] = [], + hasLocalSwiftSymbols: Bool = true ) { self.types = types self.protocols = protocols @@ -45,6 +55,7 @@ public struct ABISnapshot: Codable, Equatable, Sendable { self.conformanceExtensions = conformanceExtensions self.globalVariables = globalVariables self.globalFunctions = globalFunctions + self.hasLocalSwiftSymbols = hasLocalSwiftSymbols } } diff --git a/Sources/Output/SwiftDiffing/ABISnapshotDocument.swift b/Sources/Output/SwiftDiffing/ABISnapshotDocument.swift index ccce5ce56..b9ee9cad7 100644 --- a/Sources/Output/SwiftDiffing/ABISnapshotDocument.swift +++ b/Sources/Output/SwiftDiffing/ABISnapshotDocument.swift @@ -16,6 +16,16 @@ public struct ABISnapshotDocument: Sendable, Codable, Equatable { /// `ABIDiffer.extensionBucketKey(for:)`). /// /// History: + /// - 8: a snapshot records whether its image carries any local Swift + /// symbol (`ABISnapshot.hasLocalSwiftSymbols`), and each symbol-backed + /// member record whether the member is exported + /// (`MemberRecord.isExported`) — what an evolution or a diff needs to + /// tell a member an image stripped of its local symbols cannot show + /// from one that is gone (evolution proposal + /// `evolution-unobservable-presence`). Key scheme unchanged; an older + /// baseline would read as an image with local symbols and no export + /// verdicts, so every non-exported member of a stripped version would + /// report as removed again. /// - 7: a type declared in a function or closure body is keyed by the /// compiler's name for it (`Visitor #1 in Holder.countValues()`), or by /// the address of its anonymous context when the image records no name @@ -49,7 +59,7 @@ public struct ABISnapshotDocument: Sendable, Codable, Equatable { /// (`tag:N|indirect|…`), so a version-1 baseline would silently miss /// that transition. /// - 1: initial versioned format. - public static let currentFormatVersion = 7 + public static let currentFormatVersion = 8 public let formatVersion: Int public var provenance: ABIProvenance? diff --git a/Sources/Output/SwiftDiffing/MemberRecord.swift b/Sources/Output/SwiftDiffing/MemberRecord.swift index 7f144dbf3..43b91f212 100644 --- a/Sources/Output/SwiftDiffing/MemberRecord.swift +++ b/Sources/Output/SwiftDiffing/MemberRecord.swift @@ -37,12 +37,35 @@ public struct MemberRecord: Sendable, Codable, Equatable { /// them regardless of any default. public let hasDefaultImplementation: Bool? - public init(identityKey: ABIKey, payloadKey: ABIKey, kind: MemberKind, signature: String, hasDefaultImplementation: Bool? = nil) { + /// Whether the member's symbol — for a property or subscript, any of its + /// accessors — is exported in its own or a derived form (`Tj`, `Tq`, + /// `Tu`): the verdict the interface's `// not exported` annotation + /// prints. Visibility metadata only, never part of the keys. A + /// comparison reads it to tell, in a version whose image carries no + /// local Swift symbols, a member that cannot be seen there from one that + /// is gone (evolution proposal `evolution-unobservable-presence`): a + /// non-exported member has no name left in such an image. + /// + /// `nil` for a record no symbol backs (a stored field, an enum case, an + /// associated type or witness, a stripped requirement slot), when the + /// image carries no export information, and on a record built without a + /// verdict. + public let isExported: Bool? + + public init( + identityKey: ABIKey, + payloadKey: ABIKey, + kind: MemberKind, + signature: String, + hasDefaultImplementation: Bool? = nil, + isExported: Bool? = nil + ) { self.identityKey = identityKey self.payloadKey = payloadKey self.kind = kind self.signature = signature self.hasDefaultImplementation = hasDefaultImplementation + self.isExported = isExported } /// A copy with the default-implementation fact attached — used by the @@ -53,9 +76,37 @@ public struct MemberRecord: Sendable, Codable, Equatable { payloadKey: payloadKey, kind: kind, signature: signature, - hasDefaultImplementation: hasDefaultImplementation + hasDefaultImplementation: hasDefaultImplementation, + isExported: isExported ) } + + /// A copy with the export verdict attached — used by the freeze, which + /// asks the module's verdict for every symbol-backed member. + func withIsExported(_ isExported: Bool?) -> MemberRecord { + MemberRecord( + identityKey: identityKey, + payloadKey: payloadKey, + kind: kind, + signature: signature, + hasDefaultImplementation: hasDefaultImplementation, + isExported: isExported + ) + } + + /// Whether only a symbol shows this member: a function, property, + /// subscript, initializer or `deinit`. The other kinds — stored fields, + /// enum cases, associated types and their witnesses, stripped + /// requirement slots — are read from the image's metadata, which a strip + /// leaves intact. + var isSymbolBacked: Bool { + switch kind { + case .function, .allocator, .constructor, .variable, .subscript, .deinit: + return true + case .enumCase, .field, .associatedType, .associatedTypeWitness, .protocolRequirement: + return false + } + } } // MARK: - Projection from the declaration model diff --git a/Sources/Output/SwiftInterface/SwiftDiffableInterfaceBuilder.swift b/Sources/Output/SwiftInterface/SwiftDiffableInterfaceBuilder.swift index 4167d3d82..2d0dbebda 100644 --- a/Sources/Output/SwiftInterface/SwiftDiffableInterfaceBuilder.swift +++ b/Sources/Output/SwiftInterface/SwiftDiffableInterfaceBuilder.swift @@ -3,7 +3,8 @@ import SwiftDeclaration import SwiftDeclarationRendering import SwiftDiffing import MachOSwiftSection -import MachOSymbols +@_spi(Internals) import MachOSymbols +import Dependencies /// The ABI-diff analogue of ``SwiftInterfaceBuilder``. /// @@ -74,10 +75,14 @@ public final class SwiftDiffableInterfaceBuilder ABIModule { - ABIModule( + @Dependency(\.symbolIndexStore) var symbolIndexStore + let machO = machO + return ABIModule( rootTypeDefinitions: indexer.rootTypeDefinitions, allTypeDefinitions: indexer.allTypeDefinitions, rootProtocolDefinitions: indexer.rootProtocolDefinitions, @@ -87,7 +92,13 @@ public final class SwiftDiffableInterfaceBuilder: S /// annotation never fires on a guess. Internal (not private): the /// stored-field leg lives in `SwiftDeclarationPrinter+Headers.swift`. func exportVerdict(forSymbolNames symbolNames: [String]) -> Bool? { - guard !symbolNames.isEmpty else { return nil } @Dependency(\.symbolIndexStore) var symbolIndexStore - for symbolName in symbolNames { - guard let isExported = symbolIndexStore.isExportedIncludingDerivedSymbols(name: symbolName, in: machO) else { return nil } - if isExported { - return true - } - } - return false + return symbolIndexStore.isExportedIncludingDerivedSymbols(names: symbolNames, in: machO) } /// - Parameter propertyWrapperAttributeTypeNode: The wrapper type to print diff --git a/Sources/TestSupport/MachOTestingSupport/UnobservablePresenceFixture.swift b/Sources/TestSupport/MachOTestingSupport/UnobservablePresenceFixture.swift new file mode 100644 index 000000000..cb3188450 --- /dev/null +++ b/Sources/TestSupport/MachOTestingSupport/UnobservablePresenceFixture.swift @@ -0,0 +1,232 @@ +import Foundation +import MachOFoundation +import MachOKit +import Testing + +/// An on-the-fly fixture for telling a declaration a version cannot show from +/// one that is gone (evolution proposal `evolution-unobservable-presence`): +/// three versions of one module, the middle one stripped of its local symbols +/// (`strip -x`) — the shape of SwiftUI in the macOS 13.0–14.8 dyld shared +/// caches, between the symbol-rich 12.x and 15.0 builds. +/// +/// The public surface is the same in every version except `retiredRender()`, +/// removed in 2.0: it is public, so the stripped version still names its +/// absence through the export trie and the removal is exact. The internal +/// members tell the other stories: +/// +/// - `Panel.layout()` is in every version: invisible in 2.0, inferred present +/// there. +/// - `Panel.legacyLayout()` is in 1.0 and 2.0 and gone from 3.0: removed +/// somewhere between 1.0 and 3.0. +/// - `Panel.freshLayout()` arrives in 3.0: added somewhere between 1.0 and +/// 3.0. +/// - `Int.panelScale()` is in every version, and its extension declares +/// nothing else, so in 2.0 the whole extension is invisible. +/// +/// `Anchor` is `__DATA`-segment ballast: a module without a class compiles to +/// a dylib without one, a layout MachOKit releases before 0.52.103 mis-walked. +package enum UnobservablePresenceFixture { + package static let moduleName = "UnobservablePresenceFixture" + + /// The version-axis labels, oldest first. + package static let labels = ["1.0", "2.0", "3.0"] + + /// The index of the version stripped of its local symbols. + package static let strippedVersionIndex = 1 + + package static let sources: [String] = [ + // 1.0 + """ + public struct Panel { + public var title: String + + public init(title: String) { + self.title = title + } + + public func render() -> Int { + layout() + legacyLayout() + } + + public func retiredRender() -> Int { + 0 + } + + func layout() -> Int { + 1 + } + + func legacyLayout() -> Int { + 2 + } + } + + extension Int { + func panelScale() -> Int { + self * 2 + } + } + + public class Anchor { + public init() {} + + public func run() -> Int { + Panel(title: "anchor").render() + 1.panelScale() + } + } + """, + // 2.0, stripped of its local symbols after linking + """ + public struct Panel { + public var title: String + + public init(title: String) { + self.title = title + } + + public func render() -> Int { + layout() + legacyLayout() + } + + func layout() -> Int { + 1 + } + + func legacyLayout() -> Int { + 2 + } + } + + extension Int { + func panelScale() -> Int { + self * 2 + } + } + + public class Anchor { + public init() {} + + public func run() -> Int { + Panel(title: "anchor").render() + 1.panelScale() + } + } + """, + // 3.0 + """ + public struct Panel { + public var title: String + + public init(title: String) { + self.title = title + } + + public func render() -> Int { + layout() + freshLayout() + } + + func layout() -> Int { + 1 + } + + func freshLayout() -> Int { + 4 + } + } + + extension Int { + func panelScale() -> Int { + self * 2 + } + } + + public class Anchor { + public init() {} + + public func run() -> Int { + Panel(title: "anchor").render() + 1.panelScale() + } + } + """, + ] + + 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; the versions share one working directory. + private static let compilationResult: Result<[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) + + var libraryURLs: [URL] = [] + for (versionIndex, source) in sources.enumerated() { + let versionName = "V\(versionIndex + 1)" + let sourceURL = workingDirectory.appendingPathComponent("\(moduleName)\(versionName).swift") + let libraryURL = workingDirectory.appendingPathComponent("lib\(moduleName)\(versionName).dylib") + try source.write(to: sourceURL, atomically: true, encoding: .utf8) + // One module name across every version, so declarations key + // identically; the language mode pinned, so CI's toolchain and + // a newer local one compile the source the same way. + try run(step: "swiftc (\(versionName))", [ + "swiftc", "-swift-version", "5", "-emit-library", "-Onone", "-module-name", moduleName, + sourceURL.path, "-o", libraryURL.path, + ]) + if versionIndex == strippedVersionIndex { + try run(step: "strip (\(versionName))", ["strip", "-x", libraryURL.path]) + } + libraryURLs.append(libraryURL) + } + return libraryURLs + } + }() + + 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 compiled versions, oldest first. + package static func libraryURLs() throws -> [URL] { + try compilationResult.get() + } + + /// 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") + } + } + } +} diff --git a/Tests/SwiftDiffingTests/ABIDifferTests.swift b/Tests/SwiftDiffingTests/ABIDifferTests.swift index 850041cb8..075774720 100644 --- a/Tests/SwiftDiffingTests/ABIDifferTests.swift +++ b/Tests/SwiftDiffingTests/ABIDifferTests.swift @@ -79,6 +79,13 @@ struct ABIDifferAlgorithmTests { let keys = changes.map(\.key.sortKey) #expect(keys == keys.sorted()) } + + @Test("a member's export verdict is not part of its identity or payload") + func exportVerdictIsNotCompared() { + let old = [MemberRecord(identityKey: .mangled("foo"), payloadKey: .mangled("foo"), kind: .function, signature: "foo", isExported: false)] + let new = [MemberRecord(identityKey: .mangled("foo"), payloadKey: .mangled("foo"), kind: .function, signature: "foo", isExported: true)] + #expect(ABIDiffer().diffMembers(old: old, new: new).isEmpty) + } } // MARK: - Projection from the model + keying diff --git a/Tests/SwiftDiffingTests/ABISnapshotDocumentTests.swift b/Tests/SwiftDiffingTests/ABISnapshotDocumentTests.swift index 2e89ba8e1..d8002c451 100644 --- a/Tests/SwiftDiffingTests/ABISnapshotDocumentTests.swift +++ b/Tests/SwiftDiffingTests/ABISnapshotDocumentTests.swift @@ -34,6 +34,21 @@ struct ABISnapshotDocumentTests { #expect(decoded == document) } + @Test("the symbol-table facts survive a round trip") + func symbolTableFactsRoundTrip() throws { + let member = MemberRecord( + identityKey: .mangled("$s3Foo3baryyF"), + payloadKey: .mangled("$s3Foo3baryyF"), + kind: .function, + signature: "bar()", + isExported: false + ) + let document = ABISnapshotDocument(snapshot: ABISnapshot(globalFunctions: [member], hasLocalSwiftSymbols: false)) + let decoded = try ABISnapshotDocument.decode(from: document.encoded()) + #expect(decoded.snapshot.hasLocalSwiftSymbols == false) + #expect(decoded.snapshot.globalFunctions.first?.isExported == false) + } + @Test("encoding is byte-stable") func byteStableEncoding() throws { let document = sampleDocument() diff --git a/Tests/SwiftInterfaceTests/UnobservablePresenceTests.swift b/Tests/SwiftInterfaceTests/UnobservablePresenceTests.swift new file mode 100644 index 000000000..4518f9399 --- /dev/null +++ b/Tests/SwiftInterfaceTests/UnobservablePresenceTests.swift @@ -0,0 +1,56 @@ +import Foundation +import Testing +import MachOKit +import SwiftDiffing +import SwiftInterface +@testable import MachOTestingSupport + +/// Telling a declaration a version cannot show from one that is gone +/// (evolution proposal `evolution-unobservable-presence`), over +/// `UnobservablePresenceFixture`'s three compiled versions, the middle one +/// stripped of its local symbols. +@Suite(.serialized) +struct UnobservablePresenceTests { + private static let panelName = "\(UnobservablePresenceFixture.moduleName).Panel" + + private func snapshots() async throws -> [ABISnapshot] { + var snapshots: [ABISnapshot] = [] + for machOFile in try UnobservablePresenceFixture.machOFiles() { + let builder = SwiftDiffableInterfaceBuilder(in: machOFile) + try await builder.prepare() + snapshots.append(builder.snapshot()) + } + return snapshots + } + + private func panelMembers(in snapshot: ABISnapshot) throws -> [MemberRecord] { + try #require(snapshot.types.first { $0.name == Self.panelName }).members + } + + // MARK: - Snapshot facts + + @Test("a snapshot records whether its image keeps local Swift symbols") + func snapshotsRecordLocalSwiftSymbols() async throws { + let hasLocalSwiftSymbols = try await snapshots().map(\.hasLocalSwiftSymbols) + #expect(hasLocalSwiftSymbols == [true, false, true]) + } + + @Test("a snapshot records each symbol-backed member's export verdict") + func snapshotsRecordExportVerdicts() async throws { + let members = try panelMembers(in: try await snapshots()[0]) + let layout = try #require(members.first { $0.kind == .function && $0.signature.contains(".layout()") }) + let render = try #require(members.first { $0.kind == .function && $0.signature.contains(".render()") }) + let title = try #require(members.first { $0.kind == .field }) + #expect(layout.isExported == false) + #expect(render.isExported == true) + // A stored field is read from the field descriptor, not a symbol. + #expect(title.isExported == nil) + } + + @Test("the stripped version shows the public members and none of the internal ones") + func strippedVersionHidesInternalMembers() async throws { + let signatures = try panelMembers(in: try await snapshots()[UnobservablePresenceFixture.strippedVersionIndex]).map(\.signature) + #expect(signatures.contains { $0.contains(".render()") }) + #expect(!signatures.contains { $0.contains(".layout()") }) + } +} From 3cbbbee58c0dc5efa014abe495884f2df7a3aacd Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sat, 24 Oct 2026 22:59:44 +0800 Subject: [PATCH 002/318] feat(SwiftDiffing): tell a member a stripped version cannot show from a removal Evolution and diff no longer read a member's absence from a version without local Swift symbols as a removal when only a non-exported symbol evidences the member: that version could not have shown it. One set of rules in UnobservablePresence.swift serves both, so a two-version evolution and a diff still agree. - A span of versions that cannot show a member takes the state the observations around it share: present on both sides makes it inferred present; different sides make one event placed between them (LineageEvent.earliestVersionIndex); an end of the axis claims nothing. - Lineages carry per-version states (LineagePresenceState) when some version was not observed, and are kept even without events; ABIEvolution lists the versions without local Swift symbols. - ABIDiff lists what one side cannot show in unobservableDeclarations, apart from the changes and never breaking. - The timeline and diff reports draw the two new bitmap glyphs, place spanning changes between the versions that saw them, and list what a side cannot show. - Every new field is optional and left out of the encoding when empty, so an axis whose every version keeps its local symbols encodes as before. --- .../draft-evolution-unobservable-presence.md | 7 +- Sources/Output/SwiftDiffing/ABIDiff.swift | 10 +- .../Output/SwiftDiffing/ABIDiffReporter.swift | 20 ++ Sources/Output/SwiftDiffing/ABIDiffer.swift | 132 ++++++-- .../Output/SwiftDiffing/ABIEvolution.swift | 97 +++++- .../SwiftDiffing/ABIEvolutionBuilder.swift | 179 ++++++---- .../SwiftDiffing/ABIEvolutionReporter.swift | 87 ++++- .../SwiftDiffing/UnobservablePresence.swift | 295 ++++++++++++++++ .../ABIUnobservablePresenceTests.swift | 318 ++++++++++++++++++ 9 files changed, 1034 insertions(+), 111 deletions(-) create mode 100644 Sources/Output/SwiftDiffing/UnobservablePresence.swift create mode 100644 Tests/SwiftDiffingTests/ABIUnobservablePresenceTests.swift diff --git a/Documentations/Evolutions/draft-evolution-unobservable-presence.md b/Documentations/Evolutions/draft-evolution-unobservable-presence.md index 85d85fe4c..117d874c7 100644 --- a/Documentations/Evolutions/draft-evolution-unobservable-presence.md +++ b/Documentations/Evolutions/draft-evolution-unobservable-presence.md @@ -58,7 +58,7 @@ evolution 和 diff 把每个声明在每个版本里只记成「在」或「不 **落地步骤**(每一步单独构建通过、相关测试通过后提交): 1. (已完成)快照记下两件事,格式版本升到 8:`SymbolIndexStore` 的判据与查询,`MemberRecord` 的导出判定与 `ABISnapshot` 的镜像级标记,`SwiftDiffableInterfaceBuilder` 冻结时填好。测试判据(fixture 的被剥变体)、冻结结果与编解码。 -2. SwiftDiffing 里的看不见规则与按两侧推断:lineage 的状态数组、区间事件、收录规则;diff 的判定层(看不见的成员单列、不算 breaking);两个文本报告与 JSON。测试方案里列出的手工快照用例。 +2. (已完成)SwiftDiffing 里的看不见规则与按两侧推断:lineage 的状态数组、区间事件、收录规则;diff 的判定层(看不见的成员单列、不算 breaking);两个文本报告与 JSON。测试方案里列出的手工快照用例。 3. evolution 联合接口:`EvolutionAnnotation` 带上状态与区间,`EvolutionMarking` 的新符号、短语、图例和 `@available` 规则。测试 `EvolutionMarkingTests` 与 `SwiftEvolutionInterfaceBuilderTests`。 4. 文档与 skill 同步;用 CLI 重跑 macOS 27.0 SwiftUI 的 51 版 evolution 做实数据核对,结果写进本提案。 @@ -79,3 +79,8 @@ evolution 和 diff 把每个声明在每个版本里只记成「在」或「不 | 2026-10-24 | 成员导出判定的组合规则收进 `SymbolIndexStore.isExportedIncludingDerivedSymbols(names:in:)` | 快照要的判定和 interface 的 `// not exported` 注释是同一条规则(任一入口导出即为导出、查不到就不下结论);printer 原来自己写了一份,现在两边都调这一处,不会走样 | | 2026-10-24 | 测试改用专门的三版本 fixture(`UnobservablePresenceFixture`,中间一版 `strip -x`),在快照这一层验证判据 | 方案原想用 `ObjCImplementationFixture` 的被剥变体单测 `SymbolIndexStore`;改在冻结结果上测能同时覆盖判据与导出判定,而且第 3 步的端到端测试要的正是这样三个版本,一个 fixture 两用 | | 2026-10-24 | 第 1 步完成(In Progress) | 定向测试通过:`UnobservablePresenceTests` 3 个、`ABISnapshotDocumentTests` 与 `ABIDifferAlgorithmTests` 共 14 个、`ExportedSymbolFactsTests` 5 个,以及受 printer 改动影响的导出注释与 `--exported-only` 套件,原始退出码 0。真实数据核对:此前导出的 nlist 里,12.7 与 15.0 的 SwiftUI 各有 149,409 与 167,325 个 local `_$s` 符号,13.0 与 14.8 一个都没有 | +| 2026-10-24 | 规则集中在 `UnobservablePresence.swift`,evolution 与 diff 共用 | 「看不见」的判定(`MemberRecord` / `ContainerSnapshot.needsLocalSymbolsToBeSeen`)、逐版本观测与按两侧推断(`PresenceObservation`、`PresenceResolution`)只写一份,两版本时两条路径不可能给出不同结论 | +| 2026-10-24 | 模型另加两个可选字段 `ABIEvolution.versionIndicesWithoutLocalSwiftSymbols` 与 `MemberLineage.latestSignature`,以及报告共用的 `UnobservedSpan` 和版本区间的标签函数 | 方案没写到。图例与报告要知道哪些版本没有 local Swift 符号;只为看不见的版本才收录、没有事件的 lineage 没有地方带签名,报告只能印出 mangled key。新字段都是可选的,值为空时不编码,所以没有被剥版本的轴,`evolution --json` 输出逐字节不变(测试钉住) | +| 2026-10-24 | diff 把看不见的东西放进 `ABIDiff.unobservableDeclarations`;看不见的容器连同它的成员一起列出 | 两版本的 evolution 会给容器和每个成员各留一条「看不见」的 lineage,diff 列出同样的集合,一致性测试据此比对。列表为空时同样不编码 | +| 2026-10-24 | 报告的 Transitions 段把区间事件计入首次观测到它的那一步,下面另起一行注明其中几条发生在哪两个版本之间 | 与兼容性判定的归属一致,又不让人误以为变化就发生在那一步 | +| 2026-10-24 | 第 2 步完成 | SwiftDiffing 108 个测试全过(新增 19 个),原始退出码 0;变异检验:去掉「两侧都在则推断存在」、让导出成员也算看不见,新测试有 7 个变红(退出码 1),还原后转绿。SwiftSectionKitTests 65 个、SwiftSectionCommandTests 106 个、SwiftInterfaceTests 317 个全过 | diff --git a/Sources/Output/SwiftDiffing/ABIDiff.swift b/Sources/Output/SwiftDiffing/ABIDiff.swift index b91e20598..3d7d79f12 100644 --- a/Sources/Output/SwiftDiffing/ABIDiff.swift +++ b/Sources/Output/SwiftDiffing/ABIDiff.swift @@ -153,6 +153,12 @@ public struct ABIDiff: Sendable, Codable, Equatable { /// `nil` when nothing. Not part of `isEmpty` — a clean diff with /// collisions still warns, because a dropped record can hide a change. public let diagnostics: ABIDiffDiagnostics? + /// What one side has and the other side's image could not show — it + /// carries no local Swift symbols, and only a non-exported symbol + /// evidences these — listed apart from the changes and never part of the + /// verdict or of `isEmpty`; `nil` when there is none (evolution proposal + /// `evolution-unobservable-presence`). + public let unobservableDeclarations: [UnobservableDeclaration]? public init( types: [ContainerChange] = [], @@ -165,7 +171,8 @@ public struct ABIDiff: Sendable, Codable, Equatable { globalFunctions: [MemberChange] = [], oldProvenance: ABIProvenance? = nil, newProvenance: ABIProvenance? = nil, - diagnostics: ABIDiffDiagnostics? = nil + diagnostics: ABIDiffDiagnostics? = nil, + unobservableDeclarations: [UnobservableDeclaration]? = nil ) { self.types = types self.protocols = protocols @@ -178,6 +185,7 @@ public struct ABIDiff: Sendable, Codable, Equatable { self.oldProvenance = oldProvenance self.newProvenance = newProvenance self.diagnostics = diagnostics + self.unobservableDeclarations = unobservableDeclarations } public var isEmpty: Bool { diff --git a/Sources/Output/SwiftDiffing/ABIDiffReporter.swift b/Sources/Output/SwiftDiffing/ABIDiffReporter.swift index 07a91a444..db9f112c5 100644 --- a/Sources/Output/SwiftDiffing/ABIDiffReporter.swift +++ b/Sources/Output/SwiftDiffing/ABIDiffReporter.swift @@ -21,12 +21,32 @@ public struct ABIDiffReporter: Sendable { appendMemberSection(§ions, "Global functions", diff.globalFunctions) var report = sections.isEmpty ? "No ABI changes." : sections.joined(separator: "\n\n") + if let unobservableDeclarations = diff.unobservableDeclarations, !unobservableDeclarations.isEmpty { + report += "\n\n" + unobservableSection(unobservableDeclarations) + } if let diagnostics = diff.diagnostics, !diagnostics.isEmpty { report += "\n\n" + warningsSection(diagnostics) } return report } + /// What one side could not show (evolution proposal + /// `evolution-unobservable-presence`), one block per side: neither + /// removed nor added, so never part of the verdict. + private func unobservableSection(_ unobservableDeclarations: [UnobservableDeclaration]) -> String { + var blocks: [String] = [] + for side in [UnobservableDeclaration.Side.old, .new] { + let declarations = unobservableDeclarations.filter { $0.side == side } + guard !declarations.isEmpty else { continue } + var lines = ["Not observable on the \(side.rawValue) side — it carries no local Swift symbols, so these are neither removed nor added:"] + for declaration in declarations { + lines.append(declaration.memberKind == nil ? " \(declaration.signature) (the whole container)" : " \(declaration.signature)") + } + blocks.append(lines.joined(separator: "\n")) + } + return blocks.joined(separator: "\n\n") + } + /// Diagnostics surfaced so the verdict is never quietly weaker than it /// looks: a collision-dropped record was not compared (see /// `ABIKeyCollision`), and a remangle-fallback key can flip identity diff --git a/Sources/Output/SwiftDiffing/ABIDiffer.swift b/Sources/Output/SwiftDiffing/ABIDiffer.swift index 71c664914..bce6358b5 100644 --- a/Sources/Output/SwiftDiffing/ABIDiffer.swift +++ b/Sources/Output/SwiftDiffing/ABIDiffer.swift @@ -50,18 +50,37 @@ public struct ABIDiffer: Sendable { newSideRemangleFallbacks: new.remangleFallbacks() ) let diagnostics = candidateDiagnostics.isEmpty ? nil : candidateDiagnostics + let visibility = DiffVisibility( + oldHidesNonExportedMembers: !old.hasLocalSwiftSymbols, + newHidesNonExportedMembers: !new.hasLocalSwiftSymbols + ) + var unobservableDeclarations: [UnobservableDeclaration] = [] + let types = diffContainerSnapshots(old.types, new.types, visibility, &unobservableDeclarations) + let protocols = diffContainerSnapshots(old.protocols, new.protocols, visibility, &unobservableDeclarations) + let typeExtensions = diffContainerSnapshots(old.typeExtensions, new.typeExtensions, visibility, &unobservableDeclarations) + let protocolExtensions = diffContainerSnapshots(old.protocolExtensions, new.protocolExtensions, visibility, &unobservableDeclarations) + let typeAliasExtensions = diffContainerSnapshots(old.typeAliasExtensions, new.typeAliasExtensions, visibility, &unobservableDeclarations) + let conformanceExtensions = diffContainerSnapshots(old.conformanceExtensions, new.conformanceExtensions, visibility, &unobservableDeclarations) + let globalVariables = diffMembers(old: old.globalVariables, new: new.globalVariables, visibility, container: nil, &unobservableDeclarations) + let globalFunctions = diffMembers(old: old.globalFunctions, new: new.globalFunctions, visibility, container: nil, &unobservableDeclarations) + // Grouped by container, the container itself ahead of its members. + unobservableDeclarations.sort { lhs, rhs in + (lhs.containerName ?? "", lhs.memberKind == nil ? 0 : 1, lhs.key.sortKey, lhs.side.rawValue) + < (rhs.containerName ?? "", rhs.memberKind == nil ? 0 : 1, rhs.key.sortKey, rhs.side.rawValue) + } return ABIDiff( - types: diffContainerSnapshots(old.types, new.types), - protocols: diffContainerSnapshots(old.protocols, new.protocols), - typeExtensions: diffContainerSnapshots(old.typeExtensions, new.typeExtensions), - protocolExtensions: diffContainerSnapshots(old.protocolExtensions, new.protocolExtensions), - typeAliasExtensions: diffContainerSnapshots(old.typeAliasExtensions, new.typeAliasExtensions), - conformanceExtensions: diffContainerSnapshots(old.conformanceExtensions, new.conformanceExtensions), - globalVariables: diffMembers(old: old.globalVariables, new: new.globalVariables), - globalFunctions: diffMembers(old: old.globalFunctions, new: new.globalFunctions), + types: types, + protocols: protocols, + typeExtensions: typeExtensions, + protocolExtensions: protocolExtensions, + typeAliasExtensions: typeAliasExtensions, + conformanceExtensions: conformanceExtensions, + globalVariables: globalVariables, + globalFunctions: globalFunctions, oldProvenance: oldProvenance, newProvenance: newProvenance, - diagnostics: diagnostics + diagnostics: diagnostics, + unobservableDeclarations: unobservableDeclarations.isEmpty ? nil : unobservableDeclarations ) } @@ -156,18 +175,36 @@ public struct ABIDiffer: Sendable { /// Match container snapshots by key, then diff each matched pair's members. /// One helper serves every axis — types, protocols, and all four extension /// buckets — since they are all `[ContainerSnapshot]` once frozen. - private func diffContainerSnapshots(_ old: [ContainerSnapshot], _ new: [ContainerSnapshot]) -> [ContainerChange] { + /// + /// A container one side has and the other side's image could not show + /// (see `UnobservablePresence.swift`) is neither removed nor added: it and + /// its members go to `unobservableDeclarations`, exactly the lineages a + /// two-version evolution leaves unobservable. + private func diffContainerSnapshots( + _ old: [ContainerSnapshot], + _ new: [ContainerSnapshot], + _ visibility: DiffVisibility, + _ unobservableDeclarations: inout [UnobservableDeclaration] + ) -> [ContainerChange] { let matched = threeWayMatch(old: old, new: new) { $0.key } var changes: [ContainerChange] = [] - changes.append(contentsOf: matched.removed.map { - ContainerChange(key: $0.key, name: $0.name, containerKind: $0.kind, status: .removed, memberChanges: []) - }) - changes.append(contentsOf: matched.added.map { - ContainerChange(key: $0.key, name: $0.name, containerKind: $0.kind, status: .added, memberChanges: []) - }) + for container in matched.removed { + if visibility.newHidesNonExportedMembers, container.needsLocalSymbolsToBeSeen { + unobservableDeclarations.append(contentsOf: Self.unobservableDeclarations(of: container, side: .new)) + } else { + changes.append(ContainerChange(key: container.key, name: container.name, containerKind: container.kind, status: .removed, memberChanges: [])) + } + } + for container in matched.added { + if visibility.oldHidesNonExportedMembers, container.needsLocalSymbolsToBeSeen { + unobservableDeclarations.append(contentsOf: Self.unobservableDeclarations(of: container, side: .old)) + } else { + changes.append(ContainerChange(key: container.key, name: container.name, containerKind: container.kind, status: .added, memberChanges: [])) + } + } for (oldContainer, newContainer) in matched.common { - let memberChanges = diffMembers(old: oldContainer.members, new: newContainer.members) + let memberChanges = diffMembers(old: oldContainer.members, new: newContainer.members, visibility, container: newContainer, &unobservableDeclarations) if !memberChanges.isEmpty { changes.append(ContainerChange( key: newContainer.key, @@ -335,17 +372,40 @@ public struct ABIDiffer: Sendable { /// Three-way set difference over member records, keyed by `identityKey`. /// Public so it can be unit-tested without constructing a `Definition` - /// (whose initializers need a Mach-O). + /// (whose initializers need a Mach-O). Both sides are taken as able to + /// show every member. public func diffMembers(old: [MemberRecord], new: [MemberRecord]) -> [MemberChange] { + var unobservableDeclarations: [UnobservableDeclaration] = [] + return diffMembers(old: old, new: new, .everySideObservable, container: nil, &unobservableDeclarations) + } + + /// ``diffMembers(old:new:)`` with the sides' visibility: a member one + /// side has and the other side's image could not show goes to + /// `unobservableDeclarations` instead of being removed or added. + func diffMembers( + old: [MemberRecord], + new: [MemberRecord], + _ visibility: DiffVisibility, + container: ContainerSnapshot?, + _ unobservableDeclarations: inout [UnobservableDeclaration] + ) -> [MemberChange] { let matched = threeWayMatch(old: old, new: new) { $0.identityKey } var changes: [MemberChange] = [] - changes.append(contentsOf: matched.removed.map { - MemberChange(key: $0.identityKey, kind: $0.kind, status: .removed, oldSignature: $0.signature, newSignature: nil, compatibilityOverride: MemberRecord.compatibilityOverride(old: $0, new: nil)) - }) - changes.append(contentsOf: matched.added.map { - MemberChange(key: $0.identityKey, kind: $0.kind, status: .added, oldSignature: nil, newSignature: $0.signature, compatibilityOverride: MemberRecord.compatibilityOverride(old: nil, new: $0)) - }) + for record in matched.removed { + if visibility.newHidesNonExportedMembers, record.needsLocalSymbolsToBeSeen { + unobservableDeclarations.append(Self.unobservableDeclaration(of: record, in: container, side: .new)) + } else { + changes.append(MemberChange(key: record.identityKey, kind: record.kind, status: .removed, oldSignature: record.signature, newSignature: nil, compatibilityOverride: MemberRecord.compatibilityOverride(old: record, new: nil))) + } + } + for record in matched.added { + if visibility.oldHidesNonExportedMembers, record.needsLocalSymbolsToBeSeen { + unobservableDeclarations.append(Self.unobservableDeclaration(of: record, in: container, side: .old)) + } else { + changes.append(MemberChange(key: record.identityKey, kind: record.kind, status: .added, oldSignature: nil, newSignature: record.signature, compatibilityOverride: MemberRecord.compatibilityOverride(old: nil, new: record))) + } + } for (oldRecord, newRecord) in matched.common where oldRecord.payloadKey != newRecord.payloadKey { changes.append(MemberChange(key: newRecord.identityKey, kind: newRecord.kind, status: .modified, oldSignature: oldRecord.signature, newSignature: newRecord.signature, compatibilityOverride: MemberRecord.compatibilityOverride(old: oldRecord, new: newRecord))) } @@ -393,6 +453,30 @@ public struct ABIDiffer: Sendable { } } +/// Which sides of a two-sided diff carry no local Swift symbols, and so +/// cannot show a member only a non-exported symbol evidences (see +/// `UnobservablePresence.swift`). +struct DiffVisibility { + let oldHidesNonExportedMembers: Bool + let newHidesNonExportedMembers: Bool + + static let everySideObservable = DiffVisibility(oldHidesNonExportedMembers: false, newHidesNonExportedMembers: false) +} + +extension ABIDiffer { + /// A container `side` cannot show, and every member it holds. + static func unobservableDeclarations(of container: ContainerSnapshot, side: UnobservableDeclaration.Side) -> [UnobservableDeclaration] { + [UnobservableDeclaration(side: side, key: container.key, containerName: container.name, containerKind: container.kind, memberKind: nil, signature: container.name)] + + container.members.map { unobservableDeclaration(of: $0, in: container, side: side) } + } + + /// A member `side` cannot show, filed under its container (`nil` for a + /// global). + static func unobservableDeclaration(of record: MemberRecord, in container: ContainerSnapshot?, side: UnobservableDeclaration.Side) -> UnobservableDeclaration { + UnobservableDeclaration(side: side, key: record.identityKey, containerName: container?.name, containerKind: container?.kind, memberKind: record.kind, signature: record.signature) + } +} + /// The module's member export verdict as the freeze asks it: once per /// symbol-backed record, with the symbol names its definition carries (see /// ``ABIModule/memberExportVerdict``). Without a verdict every answer is diff --git a/Sources/Output/SwiftDiffing/ABIEvolution.swift b/Sources/Output/SwiftDiffing/ABIEvolution.swift index 3594f5b51..3577995c7 100644 --- a/Sources/Output/SwiftDiffing/ABIEvolution.swift +++ b/Sources/Output/SwiftDiffing/ABIEvolution.swift @@ -18,6 +18,11 @@ public struct ABIVersionDescriptor: Sendable, Codable, Equatable { /// `versionIndex` is always ≥ 1 — an event at index `i` describes the /// `versions[i-1] → versions[i]` step. Presence at the first version is not an /// event; it is the lineage's `presence[0]` baseline. +/// +/// An event can also span versions that cannot show the declaration (see +/// ``LineagePresenceState/unobservable``): then `earliestVersionIndex` names +/// the first of them, the change happened at some version from there through +/// `versionIndex`, and `versionIndex` is where it was first observed. public struct LineageEvent: Sendable, Codable, Equatable { public let versionIndex: Int public let status: ChangeStatus @@ -30,25 +35,66 @@ public struct LineageEvent: Sendable, Codable, Equatable { /// `MemberRecord.compatibilityOverride(old:new:)`); `nil` means the plain /// status rule applies. Always `nil` on container-level events. public let compatibilityOverride: Compatibility? + /// For an event placed only between two observations (evolution + /// proposal `evolution-unobservable-presence`): the earliest version it + /// may have happened at — the first of the versions in between, none of + /// which could show the declaration. `nil` for an event placed exactly, + /// at `versionIndex`. + public let earliestVersionIndex: Int? - public init(versionIndex: Int, status: ChangeStatus, oldSignature: String? = nil, newSignature: String? = nil, compatibilityOverride: Compatibility? = nil) { + public init( + versionIndex: Int, + status: ChangeStatus, + oldSignature: String? = nil, + newSignature: String? = nil, + compatibilityOverride: Compatibility? = nil, + earliestVersionIndex: Int? = nil + ) { self.versionIndex = versionIndex self.status = status self.oldSignature = oldSignature self.newSignature = newSignature self.compatibilityOverride = compatibilityOverride + self.earliestVersionIndex = earliestVersionIndex + } +} + +/// What one version of the axis shows of a lineage (evolution proposal +/// `evolution-unobservable-presence`). A version whose image carries no +/// local Swift symbols cannot show a member that only a non-exported symbol +/// evidences, so its absence there is not an observation; the versions +/// around such a span decide what is inferred inside it. +public enum LineagePresenceState: String, Sendable, Codable, Equatable { + /// The version shows the declaration. + case present + /// The version would show the declaration and does not. + case absent + /// The version cannot show the declaration, and the nearest observations + /// on both sides found it present: inferred present. + case inferredPresent + /// The version cannot show the declaration, and its neighbours do not + /// both find it present — they disagree (an event spans the gap), both + /// find it absent, or the axis ends first. + case unobservable + + /// Whether this state was seen rather than inferred or unknown. + public var isObserved: Bool { + self == .present || self == .absent } } /// The lifeline of one member identity across the version axis. /// /// Only lineages with at least one event are materialized — an API that never -/// changes never appears, mirroring `ABIDiff`'s "changes only" contract. +/// changes never appears, mirroring `ABIDiff`'s "changes only" contract — and +/// lineages some version cannot show, so a reader learns which versions said +/// nothing about it. public struct MemberLineage: Sendable, Codable, Equatable { public let key: ABIKey public let kind: MemberKind - /// Per-version existence, one entry per version on the axis. For a member - /// of a container this means "container present AND member present", so a + /// Per-version existence, one entry per version on the axis — observed or + /// inferred (``LineagePresenceState/inferredPresent``). For a member of + /// a container this means "container present AND member present", so a /// container-level disappearance turns every member's bit off too. public let presence: [Bool] /// Adjacent-version transitions, ordered by `versionIndex`. Member events @@ -57,12 +103,29 @@ public struct MemberLineage: Sendable, Codable, Equatable { /// container's own event is the change (same rule as `ABIDiff`, whose /// added/removed containers carry no `memberChanges`). public let events: [LineageEvent] + /// What each version shows of the member, when some version cannot show + /// it; `nil` when every version was observed and `presence` is the whole + /// story (evolution proposal `evolution-unobservable-presence`). + public let presenceStates: [LineagePresenceState]? + /// The member's rendering from the latest version that shows it, carried + /// only by a lineage without events — one materialized for its + /// unobservable versions alone — since an event otherwise carries it. + public let latestSignature: String? - public init(key: ABIKey, kind: MemberKind, presence: [Bool], events: [LineageEvent]) { + public init( + key: ABIKey, + kind: MemberKind, + presence: [Bool], + events: [LineageEvent], + presenceStates: [LineagePresenceState]? = nil, + latestSignature: String? = nil + ) { self.key = key self.kind = kind self.presence = presence self.events = events + self.presenceStates = presenceStates + self.latestSignature = latestSignature } } @@ -74,14 +137,21 @@ public struct ContainerLineage: Sendable, Codable, Equatable { /// appearance on the axis. public let name: String public let containerKind: ContainerKind - /// Per-version existence, one entry per version on the axis. + /// Per-version existence, one entry per version on the axis — observed or + /// inferred (``LineagePresenceState/inferredPresent``). public let presence: [Bool] /// Container-level presence transitions only (`.added` / `.removed`). /// "Modified at version i" is not a container event — it is derivable as /// "has a member event at i", so it is not stored twice. public let events: [LineageEvent] - /// Member lifelines with at least one event, sorted by key. + /// Member lifelines with at least one event or an unobservable version, + /// sorted by key. public let memberLineages: [MemberLineage] + /// What each version shows of the container, when some version cannot + /// show it — an extension only non-exported members make up, in a + /// version without local Swift symbols; `nil` when every version was + /// observed (evolution proposal `evolution-unobservable-presence`). + public let presenceStates: [LineagePresenceState]? public init( key: ABIKey, @@ -89,7 +159,8 @@ public struct ContainerLineage: Sendable, Codable, Equatable { containerKind: ContainerKind, presence: [Bool], events: [LineageEvent], - memberLineages: [MemberLineage] + memberLineages: [MemberLineage], + presenceStates: [LineagePresenceState]? = nil ) { self.key = key self.name = name @@ -97,6 +168,7 @@ public struct ContainerLineage: Sendable, Codable, Equatable { self.presence = presence self.events = events self.memberLineages = memberLineages + self.presenceStates = presenceStates } } @@ -132,6 +204,11 @@ public struct ABIEvolution: Sendable, Codable, Equatable { /// identity `.mangled`↔`.printed` — the reporters surface these as /// warnings (see `ABIRemangleFallback`). public let remangleFallbacksByVersion: [[ABIRemangleFallback]]? + /// The versions whose image carries no local Swift symbols, ascending, or + /// `nil` when every version has them. Such a version cannot show a + /// member only a non-exported symbol evidences (evolution proposal + /// `evolution-unobservable-presence`). + public let versionIndicesWithoutLocalSwiftSymbols: [Int]? public init( versions: [ABIVersionDescriptor], @@ -144,7 +221,8 @@ public struct ABIEvolution: Sendable, Codable, Equatable { globalVariables: [MemberLineage] = [], globalFunctions: [MemberLineage] = [], keyCollisionsByVersion: [[ABIKeyCollision]]? = nil, - remangleFallbacksByVersion: [[ABIRemangleFallback]]? = nil + remangleFallbacksByVersion: [[ABIRemangleFallback]]? = nil, + versionIndicesWithoutLocalSwiftSymbols: [Int]? = nil ) { self.versions = versions self.types = types @@ -157,6 +235,7 @@ public struct ABIEvolution: Sendable, Codable, Equatable { self.globalFunctions = globalFunctions self.keyCollisionsByVersion = keyCollisionsByVersion self.remangleFallbacksByVersion = remangleFallbacksByVersion + self.versionIndicesWithoutLocalSwiftSymbols = versionIndicesWithoutLocalSwiftSymbols } public var allContainerLineages: [ContainerLineage] { diff --git a/Sources/Output/SwiftDiffing/ABIEvolutionBuilder.swift b/Sources/Output/SwiftDiffing/ABIEvolutionBuilder.swift index ee3618daf..41fef5ad6 100644 --- a/Sources/Output/SwiftDiffing/ABIEvolutionBuilder.swift +++ b/Sources/Output/SwiftDiffing/ABIEvolutionBuilder.swift @@ -37,18 +37,23 @@ public struct ABIEvolutionBuilder: Sendable { } let keyCollisionsByVersion = snapshots.map { $0.keyCollisions() } let remangleFallbacksByVersion = snapshots.map { $0.remangleFallbacks() } + let hidesNonExportedMembers = snapshots.map { !$0.hasLocalSwiftSymbols } + let versionIndicesWithoutLocalSwiftSymbols = hidesNonExportedMembers.indices.filter { hidesNonExportedMembers[$0] } + // Globals have no container: every version can hold them. + let everyVersionPresent = [PresenceObservation](repeating: .present, count: snapshots.count) return ABIEvolution( versions: versions, - types: containerLineages(snapshots.map(\.types)), - protocols: containerLineages(snapshots.map(\.protocols)), - typeExtensions: containerLineages(snapshots.map(\.typeExtensions)), - protocolExtensions: containerLineages(snapshots.map(\.protocolExtensions)), - typeAliasExtensions: containerLineages(snapshots.map(\.typeAliasExtensions)), - conformanceExtensions: containerLineages(snapshots.map(\.conformanceExtensions)), - globalVariables: memberLineages(perVersionMembers: snapshots.map(\.globalVariables)), - globalFunctions: memberLineages(perVersionMembers: snapshots.map(\.globalFunctions)), + types: containerLineages(snapshots.map(\.types), hidesNonExportedMembers), + protocols: containerLineages(snapshots.map(\.protocols), hidesNonExportedMembers), + typeExtensions: containerLineages(snapshots.map(\.typeExtensions), hidesNonExportedMembers), + protocolExtensions: containerLineages(snapshots.map(\.protocolExtensions), hidesNonExportedMembers), + typeAliasExtensions: containerLineages(snapshots.map(\.typeAliasExtensions), hidesNonExportedMembers), + conformanceExtensions: containerLineages(snapshots.map(\.conformanceExtensions), hidesNonExportedMembers), + globalVariables: memberLineages(perVersionMembers: snapshots.map(\.globalVariables), containerObservations: everyVersionPresent, hidesNonExportedMembers), + globalFunctions: memberLineages(perVersionMembers: snapshots.map(\.globalFunctions), containerObservations: everyVersionPresent, hidesNonExportedMembers), keyCollisionsByVersion: keyCollisionsByVersion.allSatisfy(\.isEmpty) ? nil : keyCollisionsByVersion, - remangleFallbacksByVersion: remangleFallbacksByVersion.allSatisfy(\.isEmpty) ? nil : remangleFallbacksByVersion + remangleFallbacksByVersion: remangleFallbacksByVersion.allSatisfy(\.isEmpty) ? nil : remangleFallbacksByVersion, + versionIndicesWithoutLocalSwiftSymbols: versionIndicesWithoutLocalSwiftSymbols.isEmpty ? nil : versionIndicesWithoutLocalSwiftSymbols ) } @@ -56,17 +61,25 @@ public struct ABIEvolutionBuilder: Sendable { /// One container bucket (types, protocols, or an extension bucket) across /// all versions: `perVersionContainers[i]` is that bucket in version `i`. - private func containerLineages(_ perVersionContainers: [[ContainerSnapshot]]) -> [ContainerLineage] { + /// `hidesNonExportedMembers[i]` says version `i`'s image carries no local + /// Swift symbols (see `UnobservablePresence.swift`). + private func containerLineages(_ perVersionContainers: [[ContainerSnapshot]], _ hidesNonExportedMembers: [Bool]) -> [ContainerLineage] { let keyedPerVersion = perVersionContainers.map { keyedFirstWins($0, by: \.key) } let orderedKeys = unionOfKeys(keyedPerVersion) var lineages: [ContainerLineage] = [] for containerKey in orderedKeys { let perVersion = keyedPerVersion.map { $0[containerKey] } - let presence = perVersion.map { $0 != nil } - let containerEvents = presenceTransitionEvents(presence) - let members = memberLineages(perVersionMembers: perVersion.map { $0?.members }) - guard !containerEvents.isEmpty || !members.isEmpty else { continue } + let observations = PresenceObservation.observations( + of: perVersion, + hidesNonExportedMembers: hidesNonExportedMembers, + needsLocalSymbolsToBeSeen: \.needsLocalSymbolsToBeSeen + ) + let resolution = PresenceResolution(observations) + let containerEvents = resolution.presenceEvents() + let members = memberLineages(perVersionMembers: perVersion.map { $0?.members }, containerObservations: observations, hidesNonExportedMembers) + let presenceStates = resolution.presenceStatesIfAnyUnobserved + guard !containerEvents.isEmpty || !members.isEmpty || presenceStates != nil else { continue } // Name/kind from the latest appearance, so a report shows the most // recent spelling of the container. let latest = perVersion.reversed().compactMap { $0 }.first! @@ -74,9 +87,10 @@ public struct ABIEvolutionBuilder: Sendable { key: containerKey, name: latest.name, containerKind: latest.kind, - presence: presence, + presence: resolution.presence, events: containerEvents, - memberLineages: members + memberLineages: members, + presenceStates: presenceStates )) } return lineages.sorted { $0.key.sortKey < $1.key.sortKey } @@ -85,56 +99,78 @@ public struct ABIEvolutionBuilder: Sendable { // MARK: - Member axis /// Member lifelines across versions. `perVersionMembers[i] == nil` means - /// the owning container is absent in version `i` (globals pass every - /// version non-nil). Member events are computed only for transitions where - /// both adjacent versions have the container — a container-level + /// the owning container is absent from version `i` or hidden there, as + /// `containerObservations[i]` tells (globals pass every version present). + /// Member events are computed only for transitions where the container + /// is observed present on both sides — a container-level /// appearance/disappearance is the container's own event, and enumerating /// members across the gap would diverge from the two-sided differ (which - /// leaves an added/removed container's `memberChanges` empty). - private func memberLineages(perVersionMembers: [[MemberRecord]?]) -> [MemberLineage] { + /// leaves an added/removed container's `memberChanges` empty). A member + /// cannot be seen where its container cannot. + private func memberLineages( + perVersionMembers: [[MemberRecord]?], + containerObservations: [PresenceObservation], + _ hidesNonExportedMembers: [Bool] + ) -> [MemberLineage] { let keyedPerVersion = perVersionMembers.map { members in members.map { keyedFirstWins($0, by: \.identityKey) } } let orderedKeys = unionOfKeys(keyedPerVersion.map { $0 ?? [:] }) + let versionCount = perVersionMembers.count var lineages: [MemberLineage] = [] for memberKey in orderedKeys { let perVersion = keyedPerVersion.map { $0?[memberKey] } - let presence = perVersion.map { $0 != nil } + let memberObservations = PresenceObservation.observations( + of: perVersion, + hidesNonExportedMembers: hidesNonExportedMembers, + needsLocalSymbolsToBeSeen: \.needsLocalSymbolsToBeSeen + ) + let observations = (0 ..< versionCount).map { versionIndex -> PresenceObservation in + switch containerObservations[versionIndex] { + case .present: memberObservations[versionIndex] + case .absent: .absent + case .hidden: .hidden + } + } + let resolution = PresenceResolution(observations) var events: [LineageEvent] = [] - for versionIndex in 1 ..< perVersion.count { - guard keyedPerVersion[versionIndex - 1] != nil, keyedPerVersion[versionIndex] != nil else { - continue + for versionIndex in 1 ..< versionCount { + guard containerObservations[versionIndex - 1] == .present, containerObservations[versionIndex] == .present, + observations[versionIndex - 1] != .hidden, observations[versionIndex] != .hidden + else { continue } + if let event = Self.memberEvent(old: perVersion[versionIndex - 1], new: perVersion[versionIndex], at: versionIndex, earliestVersionIndex: nil) { + events.append(event) } - let oldRecord = perVersion[versionIndex - 1] - let newRecord = perVersion[versionIndex] - switch (oldRecord, newRecord) { - case (nil, let newRecord?): - events.append(LineageEvent(versionIndex: versionIndex, status: .added, newSignature: newRecord.signature, compatibilityOverride: MemberRecord.compatibilityOverride(old: nil, new: newRecord))) - case (let oldRecord?, nil): - events.append(LineageEvent(versionIndex: versionIndex, status: .removed, oldSignature: oldRecord.signature, compatibilityOverride: MemberRecord.compatibilityOverride(old: oldRecord, new: nil))) - case (let oldRecord?, let newRecord?) where oldRecord.payloadKey != newRecord.payloadKey: - events.append(LineageEvent( - versionIndex: versionIndex, - status: .modified, - oldSignature: oldRecord.signature, - newSignature: newRecord.signature, - compatibilityOverride: MemberRecord.compatibilityOverride(old: oldRecord, new: newRecord) - )) - default: - break + } + for hiddenSpan in resolution.boundedHiddenSpans { + let observedIndexBefore = hiddenSpan.lowerBound - 1 + let observedIndexAfter = hiddenSpan.upperBound + 1 + guard containerObservations[observedIndexBefore] == .present, containerObservations[observedIndexAfter] == .present else { continue } + if let event = Self.memberEvent( + old: perVersion[observedIndexBefore], + new: perVersion[observedIndexAfter], + at: observedIndexAfter, + earliestVersionIndex: hiddenSpan.lowerBound + ) { + events.append(event) } } - guard !events.isEmpty else { continue } - // The record must exist somewhere on the axis for an event to have - // been produced, so the latest appearance always resolves a kind. - let kind = perVersion.reversed().compactMap { $0 }.first!.kind + events.sort { $0.versionIndex < $1.versionIndex } + + let presenceStates = resolution.presenceStatesIfAnyUnobserved + guard !events.isEmpty || presenceStates != nil else { continue } + // The record exists somewhere on the axis for the key to be in the + // union, so the latest appearance always resolves a kind. + let latestRecord = perVersion.reversed().compactMap { $0 }.first! lineages.append(MemberLineage( key: memberKey, - kind: kind, - presence: presence, - events: events + kind: latestRecord.kind, + presence: resolution.presence, + events: events, + presenceStates: presenceStates, + latestSignature: events.isEmpty ? latestRecord.signature : nil )) } return lineages.sorted { $0.key.sortKey < $1.key.sortKey } @@ -142,20 +178,39 @@ public struct ABIEvolutionBuilder: Sendable { // MARK: - Primitives - /// `.added` / `.removed` events at every adjacent presence flip. - private func presenceTransitionEvents(_ presence: [Bool]) -> [LineageEvent] { - var events: [LineageEvent] = [] - for versionIndex in 1 ..< presence.count { - switch (presence[versionIndex - 1], presence[versionIndex]) { - case (false, true): - events.append(LineageEvent(versionIndex: versionIndex, status: .added)) - case (true, false): - events.append(LineageEvent(versionIndex: versionIndex, status: .removed)) - default: - break - } + /// The member-level change between two observed records, if any: added, + /// removed, or modified on a payload change. `earliestVersionIndex` marks + /// a change placed only between two observations around a hidden span. + private static func memberEvent(old oldRecord: MemberRecord?, new newRecord: MemberRecord?, at versionIndex: Int, earliestVersionIndex: Int?) -> LineageEvent? { + switch (oldRecord, newRecord) { + case (nil, let newRecord?): + return LineageEvent( + versionIndex: versionIndex, + status: .added, + newSignature: newRecord.signature, + compatibilityOverride: MemberRecord.compatibilityOverride(old: nil, new: newRecord), + earliestVersionIndex: earliestVersionIndex + ) + case (let oldRecord?, nil): + return LineageEvent( + versionIndex: versionIndex, + status: .removed, + oldSignature: oldRecord.signature, + compatibilityOverride: MemberRecord.compatibilityOverride(old: oldRecord, new: nil), + earliestVersionIndex: earliestVersionIndex + ) + case (let oldRecord?, let newRecord?) where oldRecord.payloadKey != newRecord.payloadKey: + return LineageEvent( + versionIndex: versionIndex, + status: .modified, + oldSignature: oldRecord.signature, + newSignature: newRecord.signature, + compatibilityOverride: MemberRecord.compatibilityOverride(old: oldRecord, new: newRecord), + earliestVersionIndex: earliestVersionIndex + ) + default: + return nil } - return events } /// The union of every version's keys, in stable sorted order. diff --git a/Sources/Output/SwiftDiffing/ABIEvolutionReporter.swift b/Sources/Output/SwiftDiffing/ABIEvolutionReporter.swift index cbdebca9c..a903d60a9 100644 --- a/Sources/Output/SwiftDiffing/ABIEvolutionReporter.swift +++ b/Sources/Output/SwiftDiffing/ABIEvolutionReporter.swift @@ -14,6 +14,13 @@ /// [●○○] func bar() -> () /// - removed in 18.0 /// ``` +/// +/// A version whose image carries no local Swift symbols cannot show a member +/// only a non-exported symbol evidences (evolution proposal +/// `evolution-unobservable-presence`): its position reads `◍` where the +/// versions around it both have the member (inferred present) and `◌` +/// otherwise, and a change across such a span is placed `between` the +/// versions that saw it. public struct ABIEvolutionReporter: Sendable { public init() {} @@ -94,17 +101,28 @@ public struct ABIEvolutionReporter: Sendable { if counts.modified > 0 { parts.append("\(counts.modified) modified") } let verdict = compatibilities[versionIndex - 1] == .breaking ? "ABI-breaking" : "additive" lines.append(" \(step): " + (parts + [verdict]).joined(separator: " · ")) + // A change first observed here may have happened in the + // versions before, which could not show it. + for (earliestVersionIndex, spanningCount) in counts.spanningCountsByEarliestVersionIndex.sorted(by: { $0.key < $1.key }) { + let span = "between \(evolution.versions[earliestVersionIndex - 1].label) and \(evolution.versions[versionIndex].label)" + lines.append(" (\(spanningCount) of them happened somewhere \(span): the versions in between could not show them)") + } } } if let firstBreakingVersionIndex = evolution.firstBreakingVersionIndex { let step = "\(evolution.versions[firstBreakingVersionIndex - 1].label) → \(evolution.versions[firstBreakingVersionIndex].label)" lines.append("First ABI-breaking transition: \(step)") } + if let versionIndicesWithoutLocalSwiftSymbols = evolution.versionIndicesWithoutLocalSwiftSymbols { + let labels = evolution.versions.labels(ofVersionsAt: versionIndicesWithoutLocalSwiftSymbols) + lines.append("No local Swift symbols, so non-exported members cannot be seen: \(labels) (◍ inferred present, ◌ not observable)") + } return lines.joined(separator: "\n") } - private func eventCounts(_ evolution: ABIEvolution, at versionIndex: Int) -> (added: Int, removed: Int, modified: Int, total: Int) { + private func eventCounts(_ evolution: ABIEvolution, at versionIndex: Int) -> (added: Int, removed: Int, modified: Int, total: Int, spanningCountsByEarliestVersionIndex: [Int: Int]) { var added = 0, removed = 0, modified = 0 + var spanningCountsByEarliestVersionIndex: [Int: Int] = [:] func count(_ events: [LineageEvent]) { for event in events where event.versionIndex == versionIndex { switch event.status { @@ -112,6 +130,9 @@ public struct ABIEvolutionReporter: Sendable { case .removed: removed += 1 case .modified: modified += 1 } + if let earliestVersionIndex = event.earliestVersionIndex { + spanningCountsByEarliestVersionIndex[earliestVersionIndex, default: 0] += 1 + } } } for lineage in evolution.allContainerLineages { @@ -123,7 +144,7 @@ public struct ABIEvolutionReporter: Sendable { for lineage in evolution.allGlobalLineages { count(lineage.events) } - return (added, removed, modified, added + removed + modified) + return (added, removed, modified, added + removed + modified, spanningCountsByEarliestVersionIndex) } // MARK: - Sections @@ -137,15 +158,21 @@ public struct ABIEvolutionReporter: Sendable { guard !lineages.isEmpty else { return } var lines = ["\(title):"] for lineage in lineages { - lines.append(" \(bitmap(lineage.presence)) \(lineage.name)") + lines.append(" \(bitmap(lineage.presence, lineage.presenceStates)) \(lineage.name)") for event in lineage.events { lines.append(" \(eventLine(event, evolution, signatures: false))") } + for spanLine in unobservedSpanLines(lineage.presenceStates, events: lineage.events, evolution) { + lines.append(" \(spanLine)") + } for memberLineage in lineage.memberLineages { - lines.append(" \(bitmap(memberLineage.presence)) \(latestSignature(memberLineage))") + lines.append(" \(bitmap(memberLineage.presence, memberLineage.presenceStates)) \(latestSignature(memberLineage))") for event in memberLineage.events { lines.append(" \(eventLine(event, evolution, signatures: true))") } + for spanLine in unobservedSpanLines(memberLineage.presenceStates, events: memberLineage.events, evolution) { + lines.append(" \(spanLine)") + } } } sections.append(lines.joined(separator: "\n")) @@ -160,10 +187,13 @@ public struct ABIEvolutionReporter: Sendable { guard !lineages.isEmpty else { return } var lines = ["\(title):"] for lineage in lineages { - lines.append(" \(bitmap(lineage.presence)) \(latestSignature(lineage))") + lines.append(" \(bitmap(lineage.presence, lineage.presenceStates)) \(latestSignature(lineage))") for event in lineage.events { lines.append(" \(eventLine(event, evolution, signatures: true))") } + for spanLine in unobservedSpanLines(lineage.presenceStates, events: lineage.events, evolution) { + lines.append(" \(spanLine)") + } } sections.append(lines.joined(separator: "\n")) } @@ -171,36 +201,65 @@ public struct ABIEvolutionReporter: Sendable { // MARK: - Lines /// The lineage's most recent rendering: the last event's signature (new - /// side preferred) — every lineage has at least one event by construction. + /// side preferred), or — for a lineage without events, kept for its + /// unobservable versions — the signature it carries. private func latestSignature(_ lineage: MemberLineage) -> String { for event in lineage.events.reversed() { if let signature = event.newSignature ?? event.oldSignature { return signature } } - return displayText(of: lineage.key) + return lineage.latestSignature ?? displayText(of: lineage.key) } /// One event phrased against the axis. `signatures: false` keeps container /// events to the bare phrase (containers carry no signature; their name is /// already on the lineage line). private func eventLine(_ event: LineageEvent, _ evolution: ABIEvolution, signatures: Bool) -> String { - let label = evolution.versions[event.versionIndex].label + let placement = event.placement(on: evolution.versions) switch event.status { case .added: - return "+ added in \(label)" + return "+ added \(placement)" case .removed: - return "- removed in \(label)" + return "- removed \(placement)" case .modified: guard signatures, let oldSignature = event.oldSignature, let newSignature = event.newSignature else { - return "~ modified in \(label)" + return "~ modified \(placement)" } - return "~ modified in \(label): \(oldSignature) → \(newSignature)" + return "~ modified \(placement): \(oldSignature) → \(newSignature)" } } - private func bitmap(_ presence: [Bool]) -> String { - "[" + presence.map { $0 ? "●" : "○" }.joined() + "]" + /// The spans of versions that could not show the declaration, other than + /// those an event already spans. + private func unobservedSpanLines(_ presenceStates: [LineagePresenceState]?, events: [LineageEvent], _ evolution: ABIEvolution) -> [String] { + guard let presenceStates else { return [] } + let spannedFirstIndices = Set(events.compactMap(\.earliestVersionIndex)) + return presenceStates.unobservedSpans.compactMap { span in + let labels = evolution.versions.labels(spanning: span.versionIndices) + switch span.state { + case .inferredPresent: + return "◍ inferred present in \(labels)" + case .unobservable where !spannedFirstIndices.contains(span.versionIndices.lowerBound): + return "◌ not observable in \(labels)" + default: + return nil + } + } + } + + private func bitmap(_ presence: [Bool], _ presenceStates: [LineagePresenceState]?) -> String { + guard let presenceStates else { + return "[" + presence.map { $0 ? "●" : "○" }.joined() + "]" + } + return "[" + presenceStates.map { state in + switch state { + case .present: "●" + case .absent: "○" + case .inferredPresent: "◍" + case .unobservable: "◌" + } + }.joined() + "]" } private func displayText(of key: ABIKey) -> String { diff --git a/Sources/Output/SwiftDiffing/UnobservablePresence.swift b/Sources/Output/SwiftDiffing/UnobservablePresence.swift new file mode 100644 index 000000000..3b788b273 --- /dev/null +++ b/Sources/Output/SwiftDiffing/UnobservablePresence.swift @@ -0,0 +1,295 @@ +/// What a version whose image carries no local Swift symbols cannot show, and +/// how the versions around such a span decide what is inferred inside it +/// (evolution proposal `evolution-unobservable-presence`). The evolution +/// builder and the two-sided differ share these rules, so for two versions +/// the two cannot disagree. +/// +/// Such an image keeps only its exported Swift names — SwiftUI in the macOS +/// 13.0–14.8 dyld shared caches is the motivating case — so a member that +/// only a non-exported symbol evidences has no name there, whether or not it +/// exists. What its metadata records (types, protocols, conformances, stored +/// fields, enum cases, associated types and witnesses, stripped requirement +/// slots) and what it exports stays visible, and their absence stays an +/// observation. + +extension MemberRecord { + /// Whether an image without local Swift symbols could not show this + /// member: only a symbol evidences it, and no verdict says that symbol + /// is exported. + var needsLocalSymbolsToBeSeen: Bool { + isSymbolBacked && isExported != true + } +} + +extension ContainerSnapshot { + /// Whether an image without local Swift symbols could not show this + /// container: an extension that is not a conformance — no conformance + /// record keeps it — made up only of members such an image cannot show. + var needsLocalSymbolsToBeSeen: Bool { + switch kind { + case .typeExtension, .protocolExtension, .typeAliasExtension: + return !members.isEmpty && members.allSatisfy(\.needsLocalSymbolsToBeSeen) + case .type, .protocol, .conformanceExtension: + return false + } + } +} + +/// One version's observation of an identity, before inference. +enum PresenceObservation: Equatable { + case present + case absent + /// Absent from a version that could not show it. + case hidden +} + +extension PresenceObservation { + /// Per-version observations of one identity, `perVersion[index]` being + /// its record in that version, if any. + /// + /// An absence is hidden when the version carries no local Swift symbols + /// and the record of a nearest version that has the identity — on either + /// side — needs local symbols to be seen: that is the shape the version + /// would show, had it the declaration. Only when every such neighbour is + /// visible without local symbols is the absence an observation. A + /// one-sided `hidden` claims nothing false; a wrong `absent` would. + static func observations( + of perVersion: [Record?], + hidesNonExportedMembers: [Bool], + needsLocalSymbolsToBeSeen: (Record) -> Bool + ) -> [PresenceObservation] { + let versionCount = perVersion.count + var nearestIndexBefore = [Int?](repeating: nil, count: versionCount) + var lastPresentIndex: Int? = nil + for versionIndex in 0 ..< versionCount { + nearestIndexBefore[versionIndex] = lastPresentIndex + if perVersion[versionIndex] != nil { + lastPresentIndex = versionIndex + } + } + var nearestIndexAfter = [Int?](repeating: nil, count: versionCount) + var nextPresentIndex: Int? = nil + for versionIndex in (0 ..< versionCount).reversed() { + nearestIndexAfter[versionIndex] = nextPresentIndex + if perVersion[versionIndex] != nil { + nextPresentIndex = versionIndex + } + } + return (0 ..< versionCount).map { versionIndex in + if perVersion[versionIndex] != nil { + return .present + } + guard hidesNonExportedMembers[versionIndex] else { return .absent } + let neighbourIndices = [nearestIndexBefore[versionIndex], nearestIndexAfter[versionIndex]].compactMap { $0 } + let isHidden = neighbourIndices.contains { neighbourIndex in + perVersion[neighbourIndex].map(needsLocalSymbolsToBeSeen) ?? false + } + return isHidden ? .hidden : .absent + } + } +} + +/// A lineage's per-version states once its hidden spans are inferred. +/// +/// A maximal span of hidden versions with an observation on both sides takes +/// the state the two share: two presences make it inferred present (a gap +/// that real removals and re-additions leave in under 0.6% of the +/// declarations seen at both ends of a symbol-rich span, measured on the +/// SwiftUI axis), two absences leave it unobservable with nothing claimed. +/// Two different observations mean the change happened somewhere inside: an +/// event spanning it, first observed after it. A span reaching an end of the +/// axis has one side only and stays unobservable. +struct PresenceResolution { + let states: [LineagePresenceState] + + /// Every maximal hidden span with an observation on both sides. + let boundedHiddenSpans: [ClosedRange] + + init(_ observations: [PresenceObservation]) { + var states: [LineagePresenceState] = observations.map { observation in + switch observation { + case .present: .present + case .absent: .absent + case .hidden: .unobservable + } + } + var boundedHiddenSpans: [ClosedRange] = [] + var versionIndex = 0 + while versionIndex < observations.count { + guard observations[versionIndex] == .hidden else { + versionIndex += 1 + continue + } + let firstHiddenIndex = versionIndex + while versionIndex < observations.count, observations[versionIndex] == .hidden { + versionIndex += 1 + } + let lastHiddenIndex = versionIndex - 1 + guard firstHiddenIndex > 0, versionIndex < observations.count else { continue } + boundedHiddenSpans.append(firstHiddenIndex ... lastHiddenIndex) + if observations[firstHiddenIndex - 1] == .present, observations[versionIndex] == .present { + for hiddenIndex in firstHiddenIndex ... lastHiddenIndex { + states[hiddenIndex] = .inferredPresent + } + } + } + self.states = states + self.boundedHiddenSpans = boundedHiddenSpans + } + + /// Present, observed or inferred, per version. + var presence: [Bool] { + states.map { $0 == .present || $0 == .inferredPresent } + } + + /// The states, when some version was not observed; `nil` otherwise. + var presenceStatesIfAnyUnobserved: [LineagePresenceState]? { + states.allSatisfy(\.isObserved) ? nil : states + } + + /// `.added` / `.removed` at every flip between adjacent observations, + /// and one event across every bounded hidden span whose sides differ. + func presenceEvents() -> [LineageEvent] { + var events: [LineageEvent] = [] + for versionIndex in 1 ..< max(states.count, 1) { + switch (states[versionIndex - 1], states[versionIndex]) { + case (.absent, .present): + events.append(LineageEvent(versionIndex: versionIndex, status: .added)) + case (.present, .absent): + events.append(LineageEvent(versionIndex: versionIndex, status: .removed)) + default: + break + } + } + for hiddenSpan in boundedHiddenSpans { + let observedIndexAfter = hiddenSpan.upperBound + 1 + switch (states[hiddenSpan.lowerBound - 1], states[observedIndexAfter]) { + case (.absent, .present): + events.append(LineageEvent(versionIndex: observedIndexAfter, status: .added, earliestVersionIndex: hiddenSpan.lowerBound)) + case (.present, .absent): + events.append(LineageEvent(versionIndex: observedIndexAfter, status: .removed, earliestVersionIndex: hiddenSpan.lowerBound)) + default: + break + } + } + return events.sorted { $0.versionIndex < $1.versionIndex } + } +} + +/// A maximal run of versions in which a lineage was not observed, all in one +/// state: ``LineagePresenceState/inferredPresent`` or +/// ``LineagePresenceState/unobservable``. +public struct UnobservedSpan: Sendable, Equatable { + public let versionIndices: ClosedRange + public let state: LineagePresenceState + + public init(versionIndices: ClosedRange, state: LineagePresenceState) { + self.versionIndices = versionIndices + self.state = state + } +} + +extension Array where Element == LineagePresenceState { + /// Every maximal run of one unobserved state, in axis order — what the + /// reports phrase as `inferred present in 13.0–14.8` or `not observable + /// in 13.0`. + public var unobservedSpans: [UnobservedSpan] { + var spans: [UnobservedSpan] = [] + var versionIndex = 0 + while versionIndex < count { + let state = self[versionIndex] + guard !state.isObserved else { + versionIndex += 1 + continue + } + let firstIndex = versionIndex + while versionIndex < count, self[versionIndex] == state { + versionIndex += 1 + } + spans.append(UnobservedSpan(versionIndices: firstIndex ... versionIndex - 1, state: state)) + } + return spans + } +} + +extension Array where Element == ABIVersionDescriptor { + /// The labels of a run of versions: `13.0` for one, `13.0–14.8` for + /// several. + public func labels(spanning versionIndices: ClosedRange) -> String { + let firstLabel = self[versionIndices.lowerBound].label + guard versionIndices.count > 1 else { return firstLabel } + return firstLabel + "–" + self[versionIndices.upperBound].label + } + + /// The labels of a set of versions, contiguous runs collapsed: + /// `11.0, 13.0–14.8`. + public func labels(ofVersionsAt versionIndices: [Int]) -> String { + var runs: [ClosedRange] = [] + for versionIndex in versionIndices.sorted() { + if let lastRun = runs.last, lastRun.upperBound + 1 == versionIndex { + runs[runs.count - 1] = lastRun.lowerBound ... versionIndex + } else { + runs.append(versionIndex ... versionIndex) + } + } + return runs.map { labels(spanning: $0) }.joined(separator: ", ") + } +} + +extension LineageEvent { + /// Where the event is placed, phrased against the axis: `in 3.0` when + /// exact, `between 1.0 and 3.0` — the last version seen before it and + /// the first seen after — when it spans versions that could not show it. + public func placement(on versions: [ABIVersionDescriptor]) -> String { + guard let earliestVersionIndex, earliestVersionIndex > 0, versions.indices.contains(versionIndex) else { + let label = versions.indices.contains(versionIndex) ? versions[versionIndex].label : "v\(versionIndex + 1)" + return "in " + label + } + return "between \(versions[earliestVersionIndex - 1].label) and \(versions[versionIndex].label)" + } +} + +/// A declaration one side of a two-sided diff cannot show (evolution +/// proposal `evolution-unobservable-presence`): the other side has it, only +/// a non-exported symbol evidences it there, and this side's image carries +/// no local Swift symbols. Neither added nor removed — listed apart, and +/// never part of the verdict. +public struct UnobservableDeclaration: Sendable, Codable, Equatable { + /// One side of a diff. + public enum Side: String, Sendable, Codable, Equatable { + case old + case new + } + + /// The side whose image cannot show the declaration. + public let side: Side + /// The container's identity, or the member's. + public let key: ABIKey + /// The container's name — for a member, its container's; `nil` for a + /// global. + public let containerName: String? + /// The container's kind — for a member, its container's; `nil` for a + /// global. + public let containerKind: ContainerKind? + /// The member's kind; `nil` when the declaration is a container. + public let memberKind: MemberKind? + /// The member's rendering from the side that shows it, or the + /// container's name. + public let signature: String + + public init( + side: Side, + key: ABIKey, + containerName: String?, + containerKind: ContainerKind?, + memberKind: MemberKind?, + signature: String + ) { + self.side = side + self.key = key + self.containerName = containerName + self.containerKind = containerKind + self.memberKind = memberKind + self.signature = signature + } +} diff --git a/Tests/SwiftDiffingTests/ABIUnobservablePresenceTests.swift b/Tests/SwiftDiffingTests/ABIUnobservablePresenceTests.swift new file mode 100644 index 000000000..fc76194bf --- /dev/null +++ b/Tests/SwiftDiffingTests/ABIUnobservablePresenceTests.swift @@ -0,0 +1,318 @@ +@testable import SwiftDiffing +import Testing +import Foundation + +// MARK: - Versions that cannot show non-exported members +// +// Evolution proposal `evolution-unobservable-presence`: a version whose image +// carries no local Swift symbols cannot show a member only a non-exported +// symbol evidences. Driven with hand-built snapshots, like the other +// `ABIEvolutionBuilder` suites, so each rule is pinned without a Mach-O. + +private func record( + _ identity: String, + payload: String? = nil, + kind: MemberKind = .function, + isExported: Bool? = false +) -> MemberRecord { + MemberRecord( + identityKey: .mangled(identity), + payloadKey: .mangled(payload ?? identity), + kind: kind, + signature: identity, + isExported: isExported + ) +} + +private func container(_ name: String, kind: ContainerKind = .type, members: [MemberRecord] = []) -> ContainerSnapshot { + ContainerSnapshot(key: .printed(name), name: name, kind: kind, members: members) +} + +/// A version that keeps its local Swift symbols. +private func symbolRich(_ types: [ContainerSnapshot] = [], typeExtensions: [ContainerSnapshot] = [], conformanceExtensions: [ContainerSnapshot] = []) -> ABISnapshot { + ABISnapshot(types: types, typeExtensions: typeExtensions, conformanceExtensions: conformanceExtensions) +} + +/// A version stripped of its local Swift symbols. +private func stripped(_ types: [ContainerSnapshot] = [], typeExtensions: [ContainerSnapshot] = [], conformanceExtensions: [ContainerSnapshot] = []) -> ABISnapshot { + ABISnapshot(types: types, typeExtensions: typeExtensions, conformanceExtensions: conformanceExtensions, hasLocalSwiftSymbols: false) +} + +private func evolution(_ snapshots: [ABISnapshot]) throws -> ABIEvolution { + try ABIEvolutionBuilder().evolution( + of: snapshots.map { ABISnapshotDocument(snapshot: $0) }, + labels: snapshots.indices.map { "\($0 + 1).0" } + ) +} + +private func memberLineage(_ key: String, in result: ABIEvolution, container containerName: String = "Foo") throws -> MemberLineage { + let containerLineage = try #require(result.allContainerLineages.first { $0.name == containerName }) + return try #require(containerLineage.memberLineages.first { $0.key == .mangled(key) }) +} + +@Suite("ABIEvolutionBuilder: versions without local Swift symbols") +struct ABIUnobservablePresenceTests { + @Test("a non-exported member a version cannot show is inferred present between two observations of it") + func inferredPresentBetweenObservations() throws { + let result = try evolution([ + symbolRich([container("Foo", members: [record("hidden")])]), + stripped([container("Foo")]), + symbolRich([container("Foo", members: [record("hidden")])]), + ]) + let lineage = try memberLineage("hidden", in: result) + #expect(lineage.presenceStates == [.present, .inferredPresent, .present]) + #expect(lineage.presence == [true, true, true]) + #expect(lineage.events.isEmpty) + #expect(lineage.latestSignature == "hidden") + #expect(result.versionIndicesWithoutLocalSwiftSymbols == [1]) + } + + @Test("a removal across versions that cannot show the member is placed between the observations around them") + func removalPlacedBetweenObservations() throws { + let result = try evolution([ + symbolRich([container("Foo", members: [record("retired")])]), + stripped([container("Foo")]), + symbolRich([container("Foo")]), + ]) + let lineage = try memberLineage("retired", in: result) + #expect(lineage.presenceStates == [.present, .unobservable, .absent]) + #expect(lineage.events == [LineageEvent(versionIndex: 2, status: .removed, oldSignature: "retired", earliestVersionIndex: 1)]) + } + + @Test("an addition across versions that cannot show the member is placed between the observations around them") + func additionPlacedBetweenObservations() throws { + let result = try evolution([ + symbolRich([container("Foo")]), + stripped([container("Foo")]), + symbolRich([container("Foo", members: [record("fresh")])]), + ]) + let lineage = try memberLineage("fresh", in: result) + #expect(lineage.presenceStates == [.absent, .unobservable, .present]) + #expect(lineage.events == [LineageEvent(versionIndex: 2, status: .added, newSignature: "fresh", earliestVersionIndex: 1)]) + } + + @Test("a payload change across versions that cannot show the member is placed between the observations around them") + func modificationPlacedBetweenObservations() throws { + let result = try evolution([ + symbolRich([container("Foo", members: [record("value", payload: "get", kind: .variable)])]), + stripped([container("Foo")]), + symbolRich([container("Foo", members: [record("value", payload: "get,set", kind: .variable)])]), + ]) + let lineage = try memberLineage("value", in: result) + #expect(lineage.presenceStates == [.present, .inferredPresent, .present]) + #expect(lineage.events == [LineageEvent(versionIndex: 2, status: .modified, oldSignature: "value", newSignature: "value", earliestVersionIndex: 1)]) + } + + @Test("an exported member missing from a version without local Swift symbols is an observed removal") + func exportedMemberAbsenceIsObserved() throws { + let result = try evolution([ + symbolRich([container("Foo", members: [record("public", isExported: true)])]), + stripped([container("Foo")]), + ]) + let lineage = try memberLineage("public", in: result) + #expect(lineage.presenceStates == nil) + #expect(lineage.events == [LineageEvent(versionIndex: 1, status: .removed, oldSignature: "public")]) + } + + @Test("a member the image's metadata records stays observable without local Swift symbols") + func metadataMemberAbsenceIsObserved() throws { + let result = try evolution([ + symbolRich([container("Foo", members: [record("field:count", payload: "Int", kind: .field, isExported: nil)])]), + stripped([container("Foo")]), + ]) + let lineage = try memberLineage("field:count", in: result) + #expect(lineage.presenceStates == nil) + #expect(lineage.events.map(\.status) == [.removed]) + } + + @Test("a member whose only neighbour is exported on one side and not on the other is not seen gone") + func oneNonExportedNeighbourHides() throws { + let result = try evolution([ + symbolRich([container("Foo", members: [record("promoted", isExported: false)])]), + stripped([container("Foo")]), + symbolRich([container("Foo", members: [record("promoted", isExported: true)])]), + ]) + let lineage = try memberLineage("promoted", in: result) + #expect(lineage.presenceStates == [.present, .inferredPresent, .present]) + #expect(lineage.events.isEmpty) + } + + @Test("versions that cannot show the member at an end of the axis claim nothing") + func spanReachingTheAxisEndStaysUnobservable() throws { + let result = try evolution([ + symbolRich([container("Foo", members: [record("trailing")])]), + stripped([container("Foo")]), + ]) + let lineage = try memberLineage("trailing", in: result) + #expect(lineage.presenceStates == [.present, .unobservable]) + #expect(lineage.presence == [true, false]) + #expect(lineage.events.isEmpty) + } + + @Test("two absences around versions that cannot show the member infer nothing") + func absencesAroundASpanClaimNothing() throws { + let result = try evolution([ + symbolRich([container("Foo", members: [record("gone")])]), + symbolRich([container("Foo")]), + stripped([container("Foo")]), + symbolRich([container("Foo")]), + ]) + let lineage = try memberLineage("gone", in: result) + #expect(lineage.presenceStates == [.present, .absent, .unobservable, .absent]) + #expect(lineage.events == [LineageEvent(versionIndex: 1, status: .removed, oldSignature: "gone")]) + } + + @Test("an extension made up only of non-exported members cannot be seen where they cannot") + func extensionOfHiddenMembersIsHidden() throws { + let result = try evolution([ + symbolRich(typeExtensions: [container("Swift.Int", kind: .typeExtension, members: [record("scale")])]), + stripped(), + symbolRich(typeExtensions: [container("Swift.Int", kind: .typeExtension, members: [record("scale")])]), + ]) + let lineage = try #require(result.typeExtensions.first) + #expect(lineage.presenceStates == [.present, .inferredPresent, .present]) + #expect(lineage.events.isEmpty) + let memberLineage = try memberLineage("scale", in: result, container: "Swift.Int") + #expect(memberLineage.presenceStates == [.present, .inferredPresent, .present]) + } + + @Test("a conformance stays observable without local Swift symbols") + func conformanceAbsenceIsObserved() throws { + let result = try evolution([ + symbolRich(conformanceExtensions: [container("Foo: Equatable", kind: .conformanceExtension, members: [record("equals")])]), + stripped(), + ]) + let lineage = try #require(result.conformanceExtensions.first) + #expect(lineage.presenceStates == nil) + #expect(lineage.events == [LineageEvent(versionIndex: 1, status: .removed)]) + } + + @Test("a change across versions that cannot show the member counts toward the transition that first observes it") + func spanningRemovalIsBreakingWhereObserved() throws { + let result = try evolution([ + symbolRich([container("Foo", members: [record("retired")])]), + stripped([container("Foo")]), + symbolRich([container("Foo")]), + ]) + #expect(result.transitionCompatibilities == [.additive, .breaking]) + } + + @Test("an axis whose every version keeps its local Swift symbols encodes none of the new fields") + func symbolRichAxisEncodingIsUnchanged() throws { + let result = try evolution([ + symbolRich([container("Foo", members: [record("a")])]), + symbolRich([container("Foo")]), + ]) + let json = try #require(String(data: ABIJSON.encoder().encode(result), encoding: .utf8)) + for key in ["presenceStates", "latestSignature", "earliestVersionIndex", "versionIndicesWithoutLocalSwiftSymbols"] { + #expect(!json.contains(key), "\(key) leaked into the encoding of an axis without stripped versions") + } + } +} + +// MARK: - Two-sided diff + +@Suite("ABIDiffer: a side without local Swift symbols") +struct ABIDifferUnobservablePresenceTests { + @Test("a non-exported member the new side cannot show is listed apart, neither removed nor breaking") + func hiddenOnTheNewSide() { + let diff = ABIDiffer().diff( + old: symbolRich([container("Foo", members: [record("hidden"), record("public", isExported: true)])]), + new: stripped([container("Foo")]) + ) + let fooChange = diff.types.first { $0.name == "Foo" } + #expect(fooChange?.memberChanges.map(\.key) == [.mangled("public")]) + #expect(diff.unobservableDeclarations == [ + UnobservableDeclaration(side: .new, key: .mangled("hidden"), containerName: "Foo", containerKind: .type, memberKind: .function, signature: "hidden"), + ]) + } + + @Test("a non-exported member the old side cannot show is listed apart, never added") + func hiddenOnTheOldSide() { + let diff = ABIDiffer().diff( + old: stripped([container("Foo")]), + new: symbolRich([container("Foo", members: [record("hidden")])]) + ) + #expect(diff.isEmpty) + #expect(diff.unobservableDeclarations?.map(\.side) == [.old]) + } + + @Test("an extension the new side cannot show is listed apart with its members") + func hiddenExtension() { + let diff = ABIDiffer().diff( + old: symbolRich(typeExtensions: [container("Swift.Int", kind: .typeExtension, members: [record("scale")])]), + new: stripped() + ) + #expect(diff.isEmpty) + #expect(diff.unobservableDeclarations?.map(\.key) == [.printed("Swift.Int"), .mangled("scale")]) + #expect(!diff.hasBreakingChange) + } + + @Test("for two versions the diff lists exactly what the evolution leaves unobservable") + func pairwiseConsistencyWithAStrippedSide() throws { + let old = symbolRich( + [container("Foo", members: [record("hidden"), record("public", isExported: true)])], + typeExtensions: [container("Swift.Int", kind: .typeExtension, members: [record("scale")])] + ) + let new = stripped([container("Foo")]) + let diff = ABIDiffer().diff(old: old, new: new) + let result = try evolution([old, new]) + + let changedMemberKeys = Set(diff.types.flatMap(\.memberChanges).map(\.key)) + let eventMemberKeys = Set(result.allContainerLineages.flatMap(\.memberLineages).filter { !$0.events.isEmpty }.map(\.key)) + #expect(changedMemberKeys == eventMemberKeys) + + let unobservableKeys = Set((diff.unobservableDeclarations ?? []).map(\.key)) + let unobservableLineageKeys = Set( + result.allContainerLineages.filter { $0.presenceStates?.contains(.unobservable) == true }.map(\.key) + + result.allContainerLineages.flatMap(\.memberLineages).filter { $0.presenceStates?.contains(.unobservable) == true }.map(\.key) + ) + #expect(unobservableKeys == unobservableLineageKeys) + } +} + +// MARK: - Reports + +@Suite("Reports: versions without local Swift symbols") +struct UnobservablePresenceReportTests { + @Test("the timeline report marks what the stripped version cannot show") + func timelineReport() throws { + let result = try evolution([ + symbolRich([container("Foo", members: [record("kept"), record("retired")])]), + stripped([container("Foo")]), + symbolRich([container("Foo", members: [record("kept")])]), + ]) + let report = ABIEvolutionReporter().report(result) + #expect(report == """ + ABI evolution across 3 versions: 1.0 → 2.0 → 3.0 + + Transitions: + 1.0 → 2.0: no changes + 2.0 → 3.0: 1 removed · ABI-breaking + (1 of them happened somewhere between 1.0 and 3.0: the versions in between could not show them) + First ABI-breaking transition: 2.0 → 3.0 + No local Swift symbols, so non-exported members cannot be seen: 2.0 (◍ inferred present, ◌ not observable) + + Types: + [●●●] Foo + [●◍●] kept + ◍ inferred present in 2.0 + [●◌○] retired + - removed between 1.0 and 3.0 + """) + } + + @Test("the diff report lists what one side cannot show") + func diffReport() { + let diff = ABIDiffer().diff( + old: symbolRich([container("Foo", members: [record("hidden")])]), + new: stripped([container("Foo")]) + ) + #expect(ABIDiffReporter().report(diff) == """ + No ABI changes. + + Not observable on the new side — it carries no local Swift symbols, so these are neither removed nor added: + hidden + """) + } +} From 1ea5065c8c5a3b21419378007369e25b233035b4 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sat, 24 Oct 2026 23:09:57 +0800 Subject: [PATCH 003/318] feat(SwiftInterface): mark the versions an evolution interface cannot see into MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The annotated evolution interface draws what a version without local Swift symbols cannot show: ◍ where the versions around it both have the declaration, ◌ otherwise, and phrases a change across such versions as `removed between 12.7 and 15.0`. - EvolutionAnnotation carries the lineage's per-version states, and the annotation index hands out annotations for lineages kept for those versions alone, container headers included. - EvolutionMarking draws the two glyphs, places spanning events between the versions that saw them, adds `inferred present in …` and `not observable in …` for spans no event covers, in axis order, and names the versions without local Swift symbols in the legend. - No @available attribute where a version could not show the declaration and was not inferred present: its bound is unknown. - InterfaceAnnotationStyle reads the `between` phrases, and an annotation that only marks such versions records no change. --- .../draft-evolution-unobservable-presence.md | 5 +- .../Output/SwiftSectionProduct.swift | 13 ++- .../EvolutionAnnotationIndex.swift | 22 ++--- .../Output/SwiftInterface/EvolutionLine.swift | 20 +++-- .../SwiftInterface/EvolutionMarking.swift | 89 +++++++++++++++---- .../EvolutionMarkingTests.swift | 83 +++++++++++++++++ .../UnobservablePresenceTests.swift | 54 +++++++++++ .../InterfaceAnnotationStyleTests.swift | 16 ++++ 8 files changed, 265 insertions(+), 37 deletions(-) diff --git a/Documentations/Evolutions/draft-evolution-unobservable-presence.md b/Documentations/Evolutions/draft-evolution-unobservable-presence.md index 117d874c7..3b17fdd84 100644 --- a/Documentations/Evolutions/draft-evolution-unobservable-presence.md +++ b/Documentations/Evolutions/draft-evolution-unobservable-presence.md @@ -59,7 +59,7 @@ evolution 和 diff 把每个声明在每个版本里只记成「在」或「不 1. (已完成)快照记下两件事,格式版本升到 8:`SymbolIndexStore` 的判据与查询,`MemberRecord` 的导出判定与 `ABISnapshot` 的镜像级标记,`SwiftDiffableInterfaceBuilder` 冻结时填好。测试判据(fixture 的被剥变体)、冻结结果与编解码。 2. (已完成)SwiftDiffing 里的看不见规则与按两侧推断:lineage 的状态数组、区间事件、收录规则;diff 的判定层(看不见的成员单列、不算 breaking);两个文本报告与 JSON。测试方案里列出的手工快照用例。 -3. evolution 联合接口:`EvolutionAnnotation` 带上状态与区间,`EvolutionMarking` 的新符号、短语、图例和 `@available` 规则。测试 `EvolutionMarkingTests` 与 `SwiftEvolutionInterfaceBuilderTests`。 +3. (已完成)evolution 联合接口:`EvolutionAnnotation` 带上状态与区间,`EvolutionMarking` 的新符号、短语、图例和 `@available` 规则。测试 `EvolutionMarkingTests` 与 `SwiftEvolutionInterfaceBuilderTests`。 4. 文档与 skill 同步;用 CLI 重跑 macOS 27.0 SwiftUI 的 51 版 evolution 做实数据核对,结果写进本提案。 ## 决策日志 @@ -84,3 +84,6 @@ evolution 和 diff 把每个声明在每个版本里只记成「在」或「不 | 2026-10-24 | diff 把看不见的东西放进 `ABIDiff.unobservableDeclarations`;看不见的容器连同它的成员一起列出 | 两版本的 evolution 会给容器和每个成员各留一条「看不见」的 lineage,diff 列出同样的集合,一致性测试据此比对。列表为空时同样不编码 | | 2026-10-24 | 报告的 Transitions 段把区间事件计入首次观测到它的那一步,下面另起一行注明其中几条发生在哪两个版本之间 | 与兼容性判定的归属一致,又不让人误以为变化就发生在那一步 | | 2026-10-24 | 第 2 步完成 | SwiftDiffing 108 个测试全过(新增 19 个),原始退出码 0;变异检验:去掉「两侧都在则推断存在」、让导出成员也算看不见,新测试有 7 个变红(退出码 1),还原后转绿。SwiftSectionKitTests 65 个、SwiftSectionCommandTests 106 个、SwiftInterfaceTests 317 个全过 | +| 2026-10-24 | `@available` 遇到任何一个「看不见」的版本就不发,推断存在照常算存在 | 方案只写了区间事件;实现时发现挨着轴端的看不见版本同样会让边界不成立(`[●◌]` 会被读成 `obsoleted:`),按同一原则一并排除 | +| 2026-10-24 | 着色规则 `InterfaceAnnotationStyle.lineKinds` 认 `… between` 短语,只标看不见版本的注释算 plain | 方案没写到。原规则把不含 `removed in` / `modified in` 的注释一律当新增,`removed between` 会被染成新增 | +| 2026-10-24 | 第 3 步完成 | 定向测试 `UnobservablePresenceTests`(新增 5 个端到端用例)、`EvolutionMarkingTests`(新增 7 个)、`InterfaceAnnotationStyleTests`(新增 1 个)全过;SwiftInterfaceTests 329 个、SwiftSectionKitTests 66 个、SwiftSectionCommandTests 106 个、SwiftDiffingTests 108 个全过,原始退出码 0。变异检验:去掉 `@available` 的边界判断、把着色默认值改回新增,3 个测试变红,还原后转绿。CLI 冒烟:对现编的三版 dylib(第二版 `strip -x`)跑 `evolution --interface --emit-available`、文本报告与 `diff`,输出与设计一致 | diff --git a/Sources/Commands/SwiftSectionKit/Output/SwiftSectionProduct.swift b/Sources/Commands/SwiftSectionKit/Output/SwiftSectionProduct.swift index 6de8cf911..9623f2474 100644 --- a/Sources/Commands/SwiftSectionKit/Output/SwiftSectionProduct.swift +++ b/Sources/Commands/SwiftSectionKit/Output/SwiftSectionProduct.swift @@ -77,14 +77,19 @@ extension InterfaceAnnotationStyle { // A trailing lifecycle annotation, or an overflow annotation on // its own (indented) line. Classified by the annotation text // only, so that a declaration whose name mentions these words - // stays plain. + // stays plain. A change across versions that could not show + // the declaration reads `… between A and B`; an annotation + // that only marks such versions (`inferred present in …`, + // `not observable in …`) records no change. let annotation = line[annotationRange.lowerBound...] - if annotation.contains("removed in") { + if annotation.contains("removed in") || annotation.contains("removed between") { return .removed - } else if annotation.contains("modified in") { + } else if annotation.contains("modified in") || annotation.contains("modified between") { return .modified - } else { + } else if annotation.contains("added in") || annotation.contains("added between") { return .added + } else { + return .plain } } else { return .plain diff --git a/Sources/Output/SwiftInterface/EvolutionAnnotationIndex.swift b/Sources/Output/SwiftInterface/EvolutionAnnotationIndex.swift index 5eb90ad1d..30eb04fd5 100644 --- a/Sources/Output/SwiftInterface/EvolutionAnnotationIndex.swift +++ b/Sources/Output/SwiftInterface/EvolutionAnnotationIndex.swift @@ -8,8 +8,9 @@ import SwiftDiffing /// snapshots) and looks the lineage up here. A hit yields an /// ``EvolutionAnnotation``; a miss means the declaration is present on every /// version and never changed (`ABIEvolution` materializes changed lineages -/// only), which renders with no annotation. This is what keeps the annotated -/// interface, the lineage report, and the JSON permanently in agreement. +/// only, and those some version could not show), which renders with no +/// annotation. This is what keeps the annotated interface, the lineage +/// report, and the JSON permanently in agreement. /// /// Container keys are merged across all six buckets into one map — type, /// protocol, and extension-container keys are disjoint by construction (full @@ -42,22 +43,23 @@ struct EvolutionAnnotationIndex: Sendable { } /// The annotation for a container header, or `nil` when the container has - /// no presence events of its own. A container that exists on every version - /// but has member events still returns `nil` here — the signal belongs on - /// the member lines, not the header (container lineages store only - /// `.added`/`.removed`; "modified" is derivable and deliberately unstored). + /// no presence events of its own and every version showed it. A container + /// that exists on every version but has member events still returns `nil` + /// here — the signal belongs on the member lines, not the header + /// (container lineages store only `.added`/`.removed`; "modified" is + /// derivable and deliberately unstored). func containerAnnotation(forKey key: ABIKey) -> EvolutionAnnotation? { - guard let lineage = containerLineagesByKey[key], !lineage.events.isEmpty else { return nil } - return EvolutionAnnotation(presence: lineage.presence, events: lineage.events) + guard let lineage = containerLineagesByKey[key], !lineage.events.isEmpty || lineage.presenceStates != nil else { return nil } + return EvolutionAnnotation(presence: lineage.presence, events: lineage.events, presenceStates: lineage.presenceStates) } func memberAnnotation(forContainerKey containerKey: ABIKey, memberKey: ABIKey) -> EvolutionAnnotation? { guard let lineage = memberLineagesByContainerKey[containerKey]?[memberKey] else { return nil } - return EvolutionAnnotation(presence: lineage.presence, events: lineage.events) + return EvolutionAnnotation(presence: lineage.presence, events: lineage.events, presenceStates: lineage.presenceStates) } func globalAnnotation(forKey key: ABIKey) -> EvolutionAnnotation? { guard let lineage = globalLineagesByKey[key] else { return nil } - return EvolutionAnnotation(presence: lineage.presence, events: lineage.events) + return EvolutionAnnotation(presence: lineage.presence, events: lineage.events, presenceStates: lineage.presenceStates) } } diff --git a/Sources/Output/SwiftInterface/EvolutionLine.swift b/Sources/Output/SwiftInterface/EvolutionLine.swift index ea09283e6..0d89ad8d3 100644 --- a/Sources/Output/SwiftInterface/EvolutionLine.swift +++ b/Sources/Output/SwiftInterface/EvolutionLine.swift @@ -8,17 +8,25 @@ import Semantic /// layer's job (`EvolutionMarking`), so a structured consumer can render it /// however it likes. public struct EvolutionAnnotation: Sendable, Equatable { - /// Per-version existence, aligned with the evolution's version axis. + /// Per-version existence, aligned with the evolution's version axis — + /// observed or inferred. public let presence: [Bool] - /// The lifecycle events, ordered by `versionIndex`. Never empty: a - /// declaration with no events carries no annotation at all (`nil` on its - /// ``EvolutionLine``), which is what "present throughout and never - /// changed" looks like. + /// The lifecycle events, ordered by `versionIndex`. Empty only when the + /// annotation exists for versions that could not show the declaration + /// (`presenceStates`); a declaration with no events and every version + /// observed carries no annotation at all (`nil` on its ``EvolutionLine``), + /// which is what "present throughout and never changed" looks like. public let events: [LineageEvent] + /// What each version shows of the declaration, when some version could + /// not show it — its image carries no local Swift symbols (evolution + /// proposal `evolution-unobservable-presence`); `nil` when every version + /// was observed. + public let presenceStates: [LineagePresenceState]? - public init(presence: [Bool], events: [LineageEvent]) { + public init(presence: [Bool], events: [LineageEvent], presenceStates: [LineagePresenceState]? = nil) { self.presence = presence self.events = events + self.presenceStates = presenceStates } } diff --git a/Sources/Output/SwiftInterface/EvolutionMarking.swift b/Sources/Output/SwiftInterface/EvolutionMarking.swift index 1123e5cb4..24186fddd 100644 --- a/Sources/Output/SwiftInterface/EvolutionMarking.swift +++ b/Sources/Output/SwiftInterface/EvolutionMarking.swift @@ -67,33 +67,72 @@ enum EvolutionMarking { "[" + presence.map { $0 ? "●" : "○" }.joined() + "]" } - /// One event phrased against the version axis. A modified event whose old - /// and new signatures render identically (an ABI payload change with no + /// The bitmap of an annotation: `●` / `○` where the version showed or + /// would have shown the declaration, and where it could not (evolution + /// proposal `evolution-unobservable-presence`) `◍` when the versions + /// around it both have the declaration, `◌` otherwise. + static func bitmap(for annotation: EvolutionAnnotation) -> String { + guard let presenceStates = annotation.presenceStates else { + return bitmap(annotation.presence) + } + return "[" + presenceStates.map { state in + switch state { + case .present: "●" + case .absent: "○" + case .inferredPresent: "◍" + case .unobservable: "◌" + } + }.joined() + "]" + } + + /// One event phrased against the version axis: `removed in 26.0`, or — + /// for a change across versions that could not show the declaration — + /// `removed between 12.7 and 15.0`. A modified event whose old and new + /// signatures render identically (an ABI payload change with no /// signature-visible difference — accessor set, symbolic identity) keeps /// the bare phrase: an identical `A → A` arrow is pure noise, the same /// reasoning as the two-sided renderer's identical-rendering collapse. static func phrase(for event: LineageEvent, versions: [ABIVersionDescriptor]) -> String { - let label = versions.indices.contains(event.versionIndex) - ? versions[event.versionIndex].label - : "v\(event.versionIndex + 1)" + let placement = event.placement(on: versions) switch event.status { case .added: - return "added in \(label)" + return "added \(placement)" case .removed: - return "removed in \(label)" + return "removed \(placement)" case .modified: guard let oldSignature = event.oldSignature, let newSignature = event.newSignature, oldSignature != newSignature else { - return "modified in \(label)" + return "modified \(placement)" } - return "modified in \(label): \(oldSignature) → \(newSignature)" + return "modified \(placement): \(oldSignature) → \(newSignature)" } } - /// The full trailing comment: `// [●●○] removed in 26.0`, multiple events - /// joined by ` · `. + /// The full trailing comment: `// [●●○] removed in 26.0`, multiple + /// phrases joined by ` · ` in axis order. The versions that could not + /// show the declaration add their own phrase — `inferred present in + /// 13.0–14.8`, or `not observable in 13.0` where no event spans them. static func annotationText(for annotation: EvolutionAnnotation, versions: [ABIVersionDescriptor]) -> String { - var text = "// " + bitmap(annotation.presence) - let phrases = annotation.events.map { phrase(for: $0, versions: versions) } + var placedPhrases: [(versionIndex: Int, phrase: String)] = annotation.events.map { event in + (event.earliestVersionIndex ?? event.versionIndex, phrase(for: event, versions: versions)) + } + if let presenceStates = annotation.presenceStates { + let spannedFirstIndices = Set(annotation.events.compactMap(\.earliestVersionIndex)) + for span in presenceStates.unobservedSpans { + let labels = versions.labels(spanning: span.versionIndices) + switch span.state { + case .inferredPresent: + placedPhrases.append((span.versionIndices.lowerBound, "inferred present in \(labels)")) + case .unobservable where !spannedFirstIndices.contains(span.versionIndices.lowerBound): + placedPhrases.append((span.versionIndices.lowerBound, "not observable in \(labels)")) + default: + break + } + } + } + var text = "// " + bitmap(for: annotation) + let phrases = placedPhrases.enumerated() + .sorted { ($0.element.versionIndex, $0.offset) < ($1.element.versionIndex, $1.offset) } + .map(\.element.phrase) if !phrases.isEmpty { text += " " + phrases.joined(separator: " · ") } @@ -119,6 +158,11 @@ enum EvolutionMarking { /// version literal. /// - Modified events never participate: `@available` has no vocabulary /// for them, so a modified-throughout lifecycle yields `nil`. + /// - A version that could not show the declaration and was not inferred + /// present (evolution proposal `evolution-unobservable-presence`) + /// leaves its bound unknown — an event spanning it, or an end of the + /// axis it reaches — so the lifecycle yields `nil`. Inferred presence + /// counts as presence. /// /// The facts are axis-resolution: `introduced:` names the first axis /// point carrying the declaration, not necessarily the OS release that @@ -129,6 +173,7 @@ enum EvolutionMarking { platform: String ) -> String? { guard annotation.presence.count == versions.count else { return nil } + guard annotation.presenceStates?.contains(.unobservable) != true else { return nil } guard let interval = singlePresenceInterval(annotation.presence) else { return nil } var clauses: [String] = [] if interval.firstPresentIndex > 0 { @@ -213,9 +258,12 @@ enum EvolutionMarking { } /// Two comment lines naming the axis and mapping bitmap positions to - /// version labels — the key to reading every `[●●○]` in the body. With - /// availability attributes enabled, a third line states their semantic - /// resolution once, so no attribute in the body overclaims. + /// version labels — the key to reading every `[●●○]` in the body. When + /// some version carries no local Swift symbols, a line names those + /// versions and the two glyphs their positions read (evolution proposal + /// `evolution-unobservable-presence`). With availability attributes + /// enabled, a last line states their semantic resolution once, so no + /// attribute in the body overclaims. static func legendLines(for evolution: ABIEvolution, availabilityAnnotationPlatform: String? = nil) -> SemanticString { let labels = evolution.versions.map(\.label) var result = SemanticString() @@ -228,6 +276,15 @@ enum EvolutionMarking { "// Bitmap positions: " + labels.enumerated().map { "[\($0 + 1)] \($1)" }.joined(separator: " "), type: .comment ) + if let versionIndicesWithoutLocalSwiftSymbols = evolution.versionIndicesWithoutLocalSwiftSymbols { + let labels = evolution.versions.labels(ofVersionsAt: versionIndicesWithoutLocalSwiftSymbols) + let isSingleVersion = versionIndicesWithoutLocalSwiftSymbols.count == 1 + result.append("\n", type: .standard) + result.append( + "// \(labels) \(isSingleVersion ? "carries" : "carry") no local Swift symbols, so \(isSingleVersion ? "its" : "their") non-exported declarations cannot be seen: ◌ not observable, ◍ not observable but present in the versions on both sides (inferred).", + type: .comment + ) + } if let availabilityAnnotationPlatform { result.append("\n", type: .standard) result.append( diff --git a/Tests/SwiftInterfaceTests/EvolutionMarkingTests.swift b/Tests/SwiftInterfaceTests/EvolutionMarkingTests.swift index 4ee532e95..f801b3f98 100644 --- a/Tests/SwiftInterfaceTests/EvolutionMarkingTests.swift +++ b/Tests/SwiftInterfaceTests/EvolutionMarkingTests.swift @@ -74,6 +74,82 @@ struct EvolutionMarkingTests { ) } + // MARK: - Versions that cannot show a declaration + + // Evolution proposal `evolution-unobservable-presence`: a version whose + // image carries no local Swift symbols cannot show a non-exported member. + + @Test func bitmapDrawsTheVersionsThatCouldNotShowTheDeclaration() { + let annotation = EvolutionAnnotation( + presence: [true, true, false], + events: [], + presenceStates: [.present, .inferredPresent, .unobservable] + ) + #expect(EvolutionMarking.bitmap(for: annotation) == "[●◍◌]") + } + + @Test func changeAcrossSuchVersionsIsPlacedBetweenTheVersionsThatSawIt() { + let removed = LineageEvent(versionIndex: 2, status: .removed, earliestVersionIndex: 1) + let added = LineageEvent(versionIndex: 2, status: .added, earliestVersionIndex: 1) + let modified = LineageEvent(versionIndex: 2, status: .modified, oldSignature: "var x: Swift.Int", newSignature: "let x: Swift.Int", earliestVersionIndex: 1) + #expect(EvolutionMarking.phrase(for: removed, versions: versionAxis) == "removed between 1.0 and 3.0") + #expect(EvolutionMarking.phrase(for: added, versions: versionAxis) == "added between 1.0 and 3.0") + #expect(EvolutionMarking.phrase(for: modified, versions: versionAxis) == "modified between 1.0 and 3.0: var x: Swift.Int → let x: Swift.Int") + } + + @Test func inferredPresenceIsPhrasedWithItsVersions() { + let annotation = EvolutionAnnotation( + presence: [true, true, true], + events: [], + presenceStates: [.present, .inferredPresent, .present] + ) + #expect(EvolutionMarking.annotationText(for: annotation, versions: versionAxis) == "// [●◍●] inferred present in 2.0") + } + + /// The versions an event spans are phrased by the event alone; others + /// say they could not show the declaration. + @Test func unobservableVersionsArePhrasedOnlyWhereNoEventSpansThem() { + let trailing = EvolutionAnnotation(presence: [true, false, false], events: [], presenceStates: [.present, .unobservable, .unobservable]) + #expect(EvolutionMarking.annotationText(for: trailing, versions: versionAxis) == "// [●◌◌] not observable in 2.0–3.0") + let spanned = EvolutionAnnotation( + presence: [true, false, false], + events: [LineageEvent(versionIndex: 2, status: .removed, earliestVersionIndex: 1)], + presenceStates: [.present, .unobservable, .absent] + ) + #expect(EvolutionMarking.annotationText(for: spanned, versions: versionAxis) == "// [●◌○] removed between 1.0 and 3.0") + } + + @Test func phrasesFollowAxisOrder() { + let fourVersionAxis = versionAxis + [ABIVersionDescriptor(label: "4.0")] + let annotation = EvolutionAnnotation( + presence: [false, true, true, true], + events: [LineageEvent(versionIndex: 1, status: .added)], + presenceStates: [.absent, .present, .inferredPresent, .present] + ) + #expect(EvolutionMarking.annotationText(for: annotation, versions: fourVersionAxis) == "// [○●◍●] added in 2.0 · inferred present in 3.0") + } + + /// An unknown bound — a version that could not show the declaration and + /// was not inferred present — leaves the lifecycle without an attribute; + /// inferred presence counts as presence. + @Test func availabilityAttributeNeedsKnownBounds() { + let trailing = EvolutionAnnotation(presence: [true, true, false], events: [], presenceStates: [.present, .present, .unobservable]) + #expect(EvolutionMarking.availabilityAttributeText(for: trailing, versions: versionAxis, platform: "macOS") == nil) + let spanned = EvolutionAnnotation( + presence: [true, false, false], + events: [LineageEvent(versionIndex: 2, status: .removed, earliestVersionIndex: 1)], + presenceStates: [.present, .unobservable, .absent] + ) + #expect(EvolutionMarking.availabilityAttributeText(for: spanned, versions: versionAxis, platform: "macOS") == nil) + let inferred = EvolutionAnnotation( + presence: [false, true, true, true], + events: [LineageEvent(versionIndex: 1, status: .added)], + presenceStates: [.absent, .present, .inferredPresent, .present] + ) + let fourVersionAxis = versionAxis + [ABIVersionDescriptor(label: "4.0")] + #expect(EvolutionMarking.availabilityAttributeText(for: inferred, versions: fourVersionAxis, platform: "macOS") == "@available(macOS, introduced: 2.0)") + } + // MARK: - Line classification /// A container header's attribute lines precede the declaration, so the @@ -296,6 +372,13 @@ struct EvolutionMarkingTests { #expect(annotatedLegend.contains("// @available(iOS, …) attributes are axis-resolution facts")) } + @Test func legendNamesTheVersionsWithoutLocalSwiftSymbols() { + let evolution = ABIEvolution(versions: versionAxis, versionIndicesWithoutLocalSwiftSymbols: [1]) + let legend = EvolutionMarking.legendLines(for: evolution).string + #expect(legend.contains("\n// 2.0 carries no local Swift symbols, so its non-exported declarations cannot be seen: ◌ not observable, ◍ not observable but present in the versions on both sides (inferred).")) + #expect(!EvolutionMarking.legendLines(for: ABIEvolution(versions: versionAxis)).string.contains("local Swift symbols")) + } + @Test func warningsAreNilWithoutDiagnostics() { #expect(EvolutionMarking.warningsLines(for: ABIEvolution(versions: versionAxis)) == nil) } diff --git a/Tests/SwiftInterfaceTests/UnobservablePresenceTests.swift b/Tests/SwiftInterfaceTests/UnobservablePresenceTests.swift index 4518f9399..e7892b30c 100644 --- a/Tests/SwiftInterfaceTests/UnobservablePresenceTests.swift +++ b/Tests/SwiftInterfaceTests/UnobservablePresenceTests.swift @@ -53,4 +53,58 @@ struct UnobservablePresenceTests { #expect(signatures.contains { $0.contains(".render()") }) #expect(!signatures.contains { $0.contains(".layout()") }) } + + // MARK: - Annotated evolution interface + + private func interfaceLines() async throws -> [String] { + let builder = try AnySwiftEvolutionInterfaceBuilder( + versions: try UnobservablePresenceFixture.machOFiles(), + labels: UnobservablePresenceFixture.labels, + availabilityAnnotationPlatform: "macOS" + ) + try await builder.prepare() + return try await builder.printAnnotatedInterface().string.components(separatedBy: "\n") + } + + private func lineIndex(containing fragment: String, in lines: [String]) throws -> Int { + try #require(lines.firstIndex { $0.contains(fragment) }, "no line contains \(fragment)") + } + + @Test("the legend names the version without local Swift symbols") + func legendNamesTheStrippedVersion() async throws { + let lines = try await interfaceLines() + #expect(lines.contains { $0.hasPrefix("// 2.0 carries no local Swift symbols") }) + } + + @Test("an internal member present on both sides of the stripped version is inferred present there") + func internalMemberIsInferredPresent() async throws { + let lines = try await interfaceLines() + #expect(lines[try lineIndex(containing: "func layout()", in: lines)].contains("// [●◍●] inferred present in 2.0")) + } + + @Test("an internal member's removal and addition are placed between the versions that saw them, without @available") + func internalChangesArePlacedBetweenObservations() async throws { + let lines = try await interfaceLines() + let removedIndex = try lineIndex(containing: "func legacyLayout()", in: lines) + let addedIndex = try lineIndex(containing: "func freshLayout()", in: lines) + #expect(lines[removedIndex].contains("// [●◌○] removed between 1.0 and 3.0")) + #expect(lines[addedIndex].contains("// [○◌●] added between 1.0 and 3.0")) + #expect(!lines[removedIndex - 1].contains("@available")) + #expect(!lines[addedIndex - 1].contains("@available")) + } + + @Test("a public member's removal stays exact in the stripped version") + func publicRemovalStaysExact() async throws { + let lines = try await interfaceLines() + let retiredIndex = try lineIndex(containing: "func retiredRender()", in: lines) + #expect(lines[retiredIndex].contains("// [●○○] removed in 2.0")) + #expect(lines[retiredIndex - 1].contains("@available(macOS, obsoleted: 2.0)")) + } + + @Test("an extension of internal members alone is inferred present with them") + func internalExtensionIsInferredPresent() async throws { + let lines = try await interfaceLines() + #expect(lines[try lineIndex(containing: "extension Swift.Int", in: lines)].contains("// [●◍●] inferred present in 2.0")) + #expect(lines[try lineIndex(containing: "func panelScale()", in: lines)].contains("// [●◍●] inferred present in 2.0")) + } } diff --git a/Tests/SwiftSectionKitTests/InterfaceAnnotationStyleTests.swift b/Tests/SwiftSectionKitTests/InterfaceAnnotationStyleTests.swift index 09212831e..bd57667f6 100644 --- a/Tests/SwiftSectionKitTests/InterfaceAnnotationStyleTests.swift +++ b/Tests/SwiftSectionKitTests/InterfaceAnnotationStyleTests.swift @@ -63,6 +63,22 @@ struct InterfaceAnnotationStyleTests { #expect(InterfaceAnnotationStyle.evolution.lineKinds(of: text) == [.header, .plain, .added, .plain, .removed]) } + /// Evolution proposal `evolution-unobservable-presence`: a change across + /// versions that could not show the declaration is placed `between` two + /// versions; an annotation that only marks such versions records no + /// change. + @Test("A change placed between two versions reads by its phrase; marking unobservable versions alone stays plain") + func evolutionUnobservableAnnotations() { + let text = """ + func retired() // [●◌○] removed between 1.0 and 3.0 + func fresh() // [○◌●] added between 1.0 and 3.0 + var value: Int // [●◍●] modified between 1.0 and 3.0: var value: Int → let value: Int + func kept() // [●◍●] inferred present in 2.0 + func trailing() // [●◌] not observable in 2.0 + """ + #expect(InterfaceAnnotationStyle.evolution.lineKinds(of: text) == [.removed, .added, .modified, .plain, .plain]) + } + @Test("A declaration whose name mentions a lifecycle word stays plain") func evolutionClassifiesByAnnotationOnly() { #expect(InterfaceAnnotationStyle.evolution.lineKinds(of: "public func removedInLegacyMode()") == [.plain]) From 2db789beb23868c3d94f67d2fa214271e923114a Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sun, 25 Oct 2026 00:07:19 +0800 Subject: [PATCH 004/318] docs: document unobservable presence and tighten it against the SwiftUI axis Rerunning the 51-version macOS SwiftUI evolution against next turned up two over-inclusions, both fixed here: - A member unseen only because its container is unseen, or only in a span between two absences, no longer gets a lineage of its own: the container's lineage tells that story, as it does for the members of an added or removed container, and two absences say nothing. A diff lists an unobservable container without its members. - A span between two absences adds no phrase and keeps the lifecycle's @available attribute, whose bounds stay observed. UnobservedSpan now carries the states around it to decide both. Against next, all 208,706 lines of declarations are identical, no observed bitmap position changes, and 5,097 of the 5,189 declarations present in 12.7 and 15.0 but missing in between now read as inferred present. Documentation: ABIEvolutionDesign.md gains the sixth increment, ABIDiffDesignAndLimitations.md section 6 records what is now handled, the MachOSymbols and SwiftInterface module notes describe the new facts and the rendering, the glossary defines unobservable, and the agent skill explains the glyphs, the phrases and the snapshot format 8. --- .../skills/swift-section-cli/SKILL.md | 24 ++++++++++-- .../draft-evolution-unobservable-presence.md | 11 ++++-- Documentations/Glossary.md | 9 ++++- .../Internal/ABIDiffDesignAndLimitations.md | 4 +- Documentations/Internal/ABIEvolutionDesign.md | 13 +++++++ .../Internal/Modules/MachOSymbols.md | 4 +- .../Internal/Modules/SwiftInterface.md | 5 ++- Documentations/README.md | 2 +- Sources/Output/SwiftDiffing/ABIDiffer.swift | 11 +++--- .../Output/SwiftDiffing/ABIEvolution.swift | 7 +++- .../SwiftDiffing/ABIEvolutionBuilder.swift | 12 +++++- .../SwiftDiffing/ABIEvolutionReporter.swift | 12 +++--- .../SwiftDiffing/UnobservablePresence.swift | 38 +++++++++++++++++-- .../SwiftInterface/EvolutionMarking.swift | 24 ++++++------ .../ABIUnobservablePresenceTests.swift | 35 +++++++++++++++-- .../EvolutionMarkingTests.swift | 13 +++++++ .../UnobservablePresenceTests.swift | 6 ++- 17 files changed, 181 insertions(+), 49 deletions(-) diff --git a/AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md b/AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md index 0bad31e11..9e46024fa 100644 --- a/AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md +++ b/AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md @@ -249,9 +249,23 @@ swift-section evolution 17.0.json 18.0.json /path/Foo --labels 17.0,18.0,26.0 - `evolution --interface --emit-available` adds a genuine `@available(, introduced: …, obsoleted: …)` line above each declaration whose whole lifecycle one attribute can express. **No attribute is not "no lifecycle"**: a declaration that disappeared and came back, one that was only `modified`, or any involved label that is not a numeric version (the file-name fallback!) gets none — pass numeric `--labels` and read the `// [●○●]` comment, which is always there. The versions are axis points, not exact release versions. The platform is inferred from every input's `LC_BUILD_VERSION` (a simulator counts as its device); an input whose platform `@available` has no name for (DriverKit), or inputs of different platforms, fail with exit code 64 — name it with `--platform` (only valid with `--emit-available`, which is only valid with `--interface`). - `--fail-on-breaking` makes a breaking change a nonzero exit — that, not the report text, is the CI signal. -- Compare binaries in **similar strip states**. A symbol-rich build against a stripped one - reports the same protocol requirement as a member swap, because a stripped protocol diffs by - witness-table slot rather than by symbol. +- **A version whose image carries no local Swift symbols cannot show non-exported members** + (SwiftUI in the macOS 13.0–14.8 caches is the case to know). It is detected per input, and + such a member's absence there is never read as a removal: in `evolution` its bitmap position + reads `◍` (not observable, but present in the versions on both sides — inferred) or `◌` (not + observable, nothing claimed), a change across such versions is phrased `removed between 12.7 + and 15.0` / `added between …` (first observed at the later version, which is where it counts + for the verdict), the interface legend names those versions, and a lifecycle whose `◌` span + reaches an axis end or sits between different observations gets no `@available` (between two + absences it keeps it). A member unseen only because its container is unseen carries no + annotation of its own (read the container's); neither does one unseen only between two + absences, which says nothing. `diff` lists what one side cannot show in a + `Not observable on the old/new side` section (`unobservableDeclarations` in `--json`), never + as removed or added and never breaking. Types, conformances, stored fields, enum cases and exported members stay + observable, so their absence is still a real removal. `diff --interface` does not apply this. +- Even so, compare binaries in **similar strip states** where you can. A symbol-rich build + against a stripped one reports the same protocol requirement as a member swap, because a + stripped protocol diffs by witness-table slot rather than by symbol. - **A snapshot does not cross format versions.** The JSON carries a `formatVersion`; any other version is rejected with a typed error, and the fix is to regenerate the baseline with the current tool. Format 6 (0.21.0 and later) rejects every format-5 baseline: in an image stripped @@ -259,7 +273,9 @@ swift-section evolution 17.0.json 18.0.json /path/Foo --labels 17.0,18.0,26.0 descriptor names (see §9), which an old baseline would report as added wholesale. Format 7 (0.23.0 and later) rejects every format-6 baseline: a type declared in a function or closure body is recorded under its own full name now (see §9), and an old baseline would report each one as removed — - a breaking change — and added again. + a breaking change — and added again. Format 8 (the release after 0.23.0) rejects every format-7 + baseline: a snapshot now records whether its image keeps local Swift symbols and whether each + member is exported, which the not-observable rule above needs. ## 8. `--resolve-c-module-names` (interface, macOS only) diff --git a/Documentations/Evolutions/draft-evolution-unobservable-presence.md b/Documentations/Evolutions/draft-evolution-unobservable-presence.md index 3b17fdd84..12a0aa59a 100644 --- a/Documentations/Evolutions/draft-evolution-unobservable-presence.md +++ b/Documentations/Evolutions/draft-evolution-unobservable-presence.md @@ -35,13 +35,13 @@ evolution 和 diff 把每个声明在每个版本里只记成「在」或「不 **模型只增不改**,`evolution --json` 现有的字段原样保留: - `MemberLineage` / `ContainerLineage` 保留 `presence: [Bool]`,含义改为「观测到或推断为存在」;另加一个逐版本的状态数组,区分观测到存在、观测到不存在、看不见但推断存在、看不见。 -- 有看不见的版本的 lineage 即使没有事件也要收录,否则接口标不出推断;`EvolutionAnnotationIndex`「查不到就是全程都在、从未变化」的约定因此仍然成立。 +- 有看不见的版本的 lineage 即使没有事件也要收录,否则接口标不出推断;`EvolutionAnnotationIndex`「查不到就是全程都在、从未变化」的约定因此仍然成立。成员只在它自己看不见、而容器在那个版本观测在场,并且那段区段有话可说(推断存在,或让边界变得不确定)时才因此收录;只因容器看不见而看不见的成员由容器的 lineage 交代,与增删容器的成员一样,diff 里也只列容器。 - `LineageEvent` 加一个「最早可能发生在哪一版」,只有区间事件才有;`versionIndex` 仍是第一次观测到新状态的那一版,兼容性判定把区间事件算在这一步。 **显示**: - evolution 联合接口和 lineage 报告的位图多两个符号:`◌` 看不见,`◍` 看不见、推断存在;图例说明这两个符号,并列出哪些版本没有 local Swift 符号。只有推断、没有事件的声明,注释写 `inferred present in 13.0–14.8`;区间事件写 `removed between 12.7 and 15.0`、`added between 12.7 and 15.0`。 -- `@available`:涉及区间事件的不发,沿用 0060 的可表达性规则;推断存在的位置按存在算。 +- `@available`:涉及区间事件的不发,沿用 0060 的可表达性规则;推断存在的位置按存在算。看不见的区段挨着轴端时同样不发;两侧都不在的区段按不在算,边界照旧是观测到的,属性照发。两侧都不在的区段只画 `◌`,不写短语。 - diff 的文本报告和 `--json` 多一节,列出看不见的成员。`diff --interface` 的 `-` / `+` 这次不动,写进 `ABIDiffDesignAndLimitations.md` 第 6 节。 - 单版本的 `dump` / `interface` 不受影响。 @@ -51,7 +51,7 @@ evolution 和 diff 把每个声明在每个版本里只记成「在」或「不 - 用元数据直接观测被剥版本里的成员(witness table、vtable 槽位、协议描述符、ObjC 方法表),另开提案。 - 被剥前后身份变了的声明:协议要求在被剥的版本里变成 `pwtslot:` 记录、私有类型丢了 discriminator、同一个全局变量在两种状态下由不同的符号撑起。那 1,447 条 `added in 13.0 · removed in 15.0` 里有一部分属于这类。 -**测试**:SwiftDiffingTests 用手工构造的快照覆盖两侧都在、两侧都不在、三种区间事件(added、removed、modified)、挨着轴端、导出成员与元数据记录的真缺席、普通 extension 整体看不见、一侧被剥时 N == 2 的 diff 与 evolution 一致、v8 编解码;`SymbolIndexStore` 的判据用 `ObjCImplementationFixture` 的 `.strippedLocals` 变体和普通变体各测一次;`EvolutionMarkingTests` 覆盖新符号、新短语、图例和区间事件不发 `@available`。实数据用 CLI 重跑 macOS 27.0 SwiftUI 的 51 版 evolution,核对那 5,189 条都变成推断存在,并统计区间事件的数量。 +**测试**:SwiftDiffingTests 用手工构造的快照覆盖两侧都在、两侧都不在、三种区间事件(added、removed、modified)、挨着轴端、导出成员与元数据记录的真缺席、普通 extension 整体看不见、只因容器看不见或只在两侧都不在时看不见的成员不收录、一侧被剥时 N == 2 的 diff 与 evolution 一致、轴上没有被剥版本时 JSON 不出现新字段、v8 编解码,以及两个文本报告。`UnobservablePresenceFixture` 现编三版 dylib、中间一版 `strip -x`,在快照这一层验证判据与导出判定,并端到端验证联合接口的每一种注解。`EvolutionMarkingTests` 覆盖新符号、新短语、短语顺序、图例与 `@available` 的边界规则,`InterfaceAnnotationStyleTests` 覆盖着色。实数据用 CLI 重跑 macOS 27.0 SwiftUI 的 51 版 evolution,与同一命令在 `next` 上的输出逐行对比。 **文档**:同批更新 `ABIEvolutionDesign.md`、`ABIDiffDesignAndLimitations.md` 第 6 节、`Modules/SwiftInterface.md`,在术语表登记 unobservable,并更新 `AgentPlugins/swift-section` 的 skill(evolution 输出多了两个符号和两种短语)。 @@ -60,7 +60,7 @@ evolution 和 diff 把每个声明在每个版本里只记成「在」或「不 1. (已完成)快照记下两件事,格式版本升到 8:`SymbolIndexStore` 的判据与查询,`MemberRecord` 的导出判定与 `ABISnapshot` 的镜像级标记,`SwiftDiffableInterfaceBuilder` 冻结时填好。测试判据(fixture 的被剥变体)、冻结结果与编解码。 2. (已完成)SwiftDiffing 里的看不见规则与按两侧推断:lineage 的状态数组、区间事件、收录规则;diff 的判定层(看不见的成员单列、不算 breaking);两个文本报告与 JSON。测试方案里列出的手工快照用例。 3. (已完成)evolution 联合接口:`EvolutionAnnotation` 带上状态与区间,`EvolutionMarking` 的新符号、短语、图例和 `@available` 规则。测试 `EvolutionMarkingTests` 与 `SwiftEvolutionInterfaceBuilderTests`。 -4. 文档与 skill 同步;用 CLI 重跑 macOS 27.0 SwiftUI 的 51 版 evolution 做实数据核对,结果写进本提案。 +4. (已完成)文档与 skill 同步;用 CLI 重跑 macOS 27.0 SwiftUI 的 51 版 evolution 做实数据核对,结果写进本提案。 ## 决策日志 @@ -87,3 +87,6 @@ evolution 和 diff 把每个声明在每个版本里只记成「在」或「不 | 2026-10-24 | `@available` 遇到任何一个「看不见」的版本就不发,推断存在照常算存在 | 方案只写了区间事件;实现时发现挨着轴端的看不见版本同样会让边界不成立(`[●◌]` 会被读成 `obsoleted:`),按同一原则一并排除 | | 2026-10-24 | 着色规则 `InterfaceAnnotationStyle.lineKinds` 认 `… between` 短语,只标看不见版本的注释算 plain | 方案没写到。原规则把不含 `removed in` / `modified in` 的注释一律当新增,`removed between` 会被染成新增 | | 2026-10-24 | 第 3 步完成 | 定向测试 `UnobservablePresenceTests`(新增 5 个端到端用例)、`EvolutionMarkingTests`(新增 7 个)、`InterfaceAnnotationStyleTests`(新增 1 个)全过;SwiftInterfaceTests 329 个、SwiftSectionKitTests 66 个、SwiftSectionCommandTests 106 个、SwiftDiffingTests 108 个全过,原始退出码 0。变异检验:去掉 `@available` 的边界判断、把着色默认值改回新增,3 个测试变红,还原后转绿。CLI 冒烟:对现编的三版 dylib(第二版 `strip -x`)跑 `evolution --interface --emit-available`、文本报告与 `diff`,输出与设计一致 | +| 2026-10-25 | 实数据核对后收紧两处:只因容器看不见、或只在两侧都不在的区段看不见的成员,不再因此收录,diff 里看不见的容器也只列容器本身;两侧都不在的区段不写短语,也不拦 `@available` | 第一次重跑 51 版 SwiftUI 时,新输出多了 21,805 条 `not observable in …`、`@available` 少了约 2.2 万行,抽样发现两类:容器自己已有注解(类型在 13.0 出现、15.0 迁去 SwiftUICore,或 extension 整体看不见),它的成员却跟着各标一次,与增删容器的成员一贯不标注的规则不一致;以及 12.4 就删掉的成员在 13.0–14.8 两侧都不在,什么都说不出,却写了短语、丢了本来成立的 `obsoleted:`。收紧后另有 169 条只剩位图、没有短语的成员注解随之消失 | +| 2026-10-25 | 第 4 步完成,实数据结果 | 同一命令(release 版 CLI,`--dyld-shared-cache -p …/SwiftUI --interface --emit-available`,51 份归档 cache)在 `next` 与本分支上各跑一次。`next` 的输出与 0073 之前生成的那份只差 0073 修好的 20 行。本分支对 `next`:208,706 行代码逐行相同;42,517 条注解不变,30,229 条只有 13.0–14.8 那几位变了,没有一条观测到的位置被改,也没有注解丢失;新增 151 条注解,全部是此前被容器的假缺口挡住的跨段增删。两端都在、中间缺席的 5,189 条里 5,097 条(98.2%)整段变成推断存在;`removed in 13.0 · added in 15.0` 从 5,089 条降到 24 条(类型的真实删除、丢了 discriminator 的私有类型,以及几条公开 `static let` 在被剥前后由不同的访问器撑起,属方案列出的范围外情形);`removed in 13.0` 从 18,293 降到 1,700、`added in 15.0` 从 19,596 降到 4,472,其余换成 2,084 / 2,065 / 17 条 `removed` / `added` / `modified between 12.7 and 15.0` 与 17,684 条 `not observable in …`(多是容器在 13.0 出现或 15.0 搬走、成员自己说不清何时增删的情形)。`@available` 行从 66,711 降到 48,214,去掉的都是边界不确定的。峰值内存 12.8 GB 对 12.8 GB(`next`),这台 28 核机器上用时 216 秒 | +| 2026-10-25 | 实现完成,待合并 | 全量 `swift test --skip IntegrationTests`(收紧前的第 3 步代码)2,578 个测试全过,原始退出码 0;收紧后重跑受影响的 SwiftDiffingTests 110 个、SwiftInterfaceTests 330 个、SwiftSectionKitTests 66 个、SwiftSectionCommandTests 106 个,全过。每次收紧都做了变异检验(改回原规则,对应的新测试变红,还原后转绿)。没有跑渲染 A/B:单版本的 `dump` / `interface` 只动了 printer 里导出判定的一处等价改写,相关的导出注释与 `--exported-only` 套件都过了。不另写使用指南或实现说明:规则与取舍写在 `ABIEvolutionDesign.md` 第六批与本提案;新术语 unobservable 已登记 | diff --git a/Documentations/Glossary.md b/Documentations/Glossary.md index a30fc5838..4ff2dfdc2 100644 --- a/Documentations/Glossary.md +++ b/Documentations/Glossary.md @@ -195,7 +195,7 @@ sweep 覆盖范围之外的名字走的旁路:demangle 后 intern 进 `Storage ### lifecycle annotation(生命周期注解) -演进并集接口里每条「变过的」声明行尾的注释:`// [●●○] removed in 26.0` —— 存在位图(每版本一位,文件头图例映射位置到版本标签)+ 按 ` · ` 连接的事件短语(added / removed / modified in 版本;modified 带 `旧签名 → 新签名`,两侧文本相同时省略箭头段)。**没有注解本身就是信息**:全程存在且从未变化。注解事实唯一来源是 `ABIEvolution` 的 lineage 查表,渲染器不自行推导。打开 `--emit-available` 时,生命周期能完整写成一条 `@available` 的声明上方还会多一行真属性,它由同一份事实派生,是补充不是替代,注解照旧都在。 +演进并集接口里每条「变过的」声明行尾的注释:`// [●●○] removed in 26.0` —— 存在位图(每版本一位,文件头图例映射位置到版本标签)+ 按 ` · ` 连接的事件短语(added / removed / modified in 版本;modified 带 `旧签名 → 新签名`,两侧文本相同时省略箭头段)。**没有注解本身就是信息**:全程存在且从未变化。注解事实唯一来源是 `ABIEvolution` 的 lineage 查表,渲染器不自行推导。打开 `--emit-available` 时,生命周期能完整写成一条 `@available` 的声明上方还会多一行真属性,它由同一份事实派生,是补充不是替代,注解照旧都在。有版本看不到这条声明时(见 unobservable),位图另用 `◍` / `◌`,短语多出 `inferred present in …`、`not observable in …` 与 `… between A and B`。 - **主要出现在**:`Sources/Output/SwiftInterface/EvolutionMarking.swift`、`EvolutionAnnotationIndex.swift` - **延伸阅读**:[提案 0013](Evolutions/0013-swift-evolution-interface-builder.md)、[提案 0060](Evolutions/0060-evolution-interface-available-annotations.md)(`@available` 属性) @@ -382,6 +382,13 @@ Swift runtime 的 descriptor 布局惯例:固定头之后按 flags 跟着可 - **主要出现在**:`Sources/Output/SwiftInterface/SwiftEvolutionInterfaceRenderer.swift`(`matchAcrossVersions`) - **延伸阅读**:[提案 0013](Evolutions/0013-swift-evolution-interface-builder.md) +### unobservable(看不见,`LineagePresenceState`) + +evolution 与 diff 里「这个版本看不到这条声明」的状态,与「不在」相对。镜像没有 local Swift 符号的版本(macOS 13.0–14.8 dyld shared cache 里的 SwiftUI)里,只靠非导出符号才出现的成员没有名字,它缺席并不说明它不存在;类型、conformance、存储属性、导出的成员不受影响。一段看不见的版本,两侧观测到的版本都有这条声明时记为 **inferred present**(推断存在,位图 `◍`),否则记为 unobservable(位图 `◌`);两侧不同时,变化写成 `removed between 12.7 and 15.0` 这样的跨段事件。diff 里一侧看不见的成员进 `unobservableDeclarations`,不算删除或新增。 + +- **主要出现在**:`Sources/Output/SwiftDiffing/UnobservablePresence.swift`、`ABIEvolutionBuilder.swift`、`Sources/Output/SwiftInterface/EvolutionMarking.swift` +- **延伸阅读**:[提案 evolution-unobservable-presence](Evolutions/draft-evolution-unobservable-presence.md)、[ABIEvolutionDesign.md](Internal/ABIEvolutionDesign.md) 第六批 + ### wrapper vs descriptor(高层包装 vs 描述符) 同一个二进制实体的两级表示,易混淆:**descriptor**(`ClassDescriptor`、`ProtocolConformanceDescriptor` 等)是原始布局 + 位置的薄值(几十字节,可随时重读);**wrapper**(`Class` / `Struct` / `Enum` / `ProtocolConformance` / `Protocol` / `TypeContextWrapper`)是构造时急切解析全部 trailing objects 的完整值(内联数百字节 + 堆数组)。规则口诀:descriptor 可驻留,wrapper 应物化。 diff --git a/Documentations/Internal/ABIDiffDesignAndLimitations.md b/Documentations/Internal/ABIDiffDesignAndLimitations.md index ceaeb7087..04a4ee123 100644 --- a/Documentations/Internal/ABIDiffDesignAndLimitations.md +++ b/Documentations/Internal/ABIDiffDesignAndLimitations.md @@ -182,6 +182,8 @@ ABI 事实。同一协议一侧带符号、一侧被 strip 时,diff 会报"解 pwtslot added"的假差异——无名可匹配,无廉价对策;比较双方应处于相近的 strip 状态。 +同一不对称的另一半——**非导出成员**——现已处理(演进提案 `evolution-unobservable-presence`,规则见 [`ABIEvolutionDesign.md`](ABIEvolutionDesign.md) 第六批):快照记下镜像有没有 local Swift 符号、每个成员是否导出;一侧没有 local Swift 符号时,另一侧只靠非导出符号出现的成员(以及只由这种成员组成的 extension)不报 removed / added,而是进 `ABIDiff.unobservableDeclarations`,文本报告单列一节,不算 breaking。仍未处理的有两处:上面的 `pwtslot:` 互换照旧;`diff --interface` 按两侧结构直接比对、不读 `ABIDiff`,这类成员在那里仍显示为 `-` / `+`。 + ## 局限 → 代码位置对照 | 局限 | 状态 / 位置 | @@ -191,4 +193,4 @@ pwtslot added"的假差异——无名可匹配,无廉价对策;比较双方 | 3. keyed 碰撞 | **已解决**(拆分消解 + 诊断兜底)。`Keying.swift` + `ABIDiagnostics.swift` | | 4. 字段顺序 / flags | enum case `indirect` **已修**;resilient/frozen 感知的字段顺序敏感性仍开放。`MemberRecord.swift` | | 5. per-conformance 归属 | **已解决**。`ABIDiffer.swift` `extensionContainerSnapshots` + [`PerConformanceAttribution.md`](PerConformanceAttribution.md) | -| 6. stripped requirement 投影 | **已解决**(`pwtslot:` 命名空间)。`MemberRecord.makeProtocolRequirement` + `memberRecords(of: ProtocolDefinition)` + [`ProtocolRequirementProjection.md`](ProtocolRequirementProjection.md);符号化状态不对称为新的文档化局限 | +| 6. stripped requirement 投影 | **已解决**(`pwtslot:` 命名空间)。`MemberRecord.makeProtocolRequirement` + `memberRecords(of: ProtocolDefinition)` + [`ProtocolRequirementProjection.md`](ProtocolRequirementProjection.md);符号化状态不对称为新的文档化局限,其中非导出成员一半已解决(`UnobservablePresence.swift` + `ABIDiff.unobservableDeclarations`),`pwtslot:` 互换与 `diff --interface` 仍开放 | diff --git a/Documentations/Internal/ABIEvolutionDesign.md b/Documentations/Internal/ABIEvolutionDesign.md index 8f3e5b654..aee26de6c 100644 --- a/Documentations/Internal/ABIEvolutionDesign.md +++ b/Documentations/Internal/ABIEvolutionDesign.md @@ -250,6 +250,19 @@ diff 的 verdict 交叉核对行。 - ~~注释接口的时间线版(每行标注 introduced-in)~~ —— 已由第五批落地 (`SwiftEvolutionInterfaceBuilder` 的并集注解接口,见下)。 +## 首轮落地后的增量(第六批)—— 看不见的版本 + +提案:`Evolutions/draft-evolution-unobservable-presence.md`(落地时编号)。镜像没有 local Swift 符号的版本——macOS 13.0–14.8 dyld shared cache 里的 SwiftUI——看不到只靠非导出符号才出现的成员。原来的 `presence: [Bool]` 分不出「不在」和「看不见」,macOS 27.0 SwiftUI 的 51 版 evolution 因此有 5,189 条两端都在、中间缺席的假缺口。维护时会踩的决策: + +- **事实从快照来,格式版本 8**:`ABISnapshot.hasLocalSwiftSymbols`(`SymbolIndexStore.hasLocalSwiftSymbols(in:)`,读符号表条目的 `N_EXT` 位——本库的 `isExternal` 只指未定义的导入,不能拿来判断)与 `MemberRecord.isExported`(`isExportedIncludingDerivedSymbols(names:in:)`,与 interface 的 `// not exported` 注释同一条规则)。两者都只是判定用的元数据,不进 key。冻结时由 `SwiftDiffableInterfaceBuilder` 经 `ABIModule` 交进来,`ABIDiffer` 仍不碰 Mach-O。 +- **谁会看不见**(`UnobservablePresence.swift`,evolution 与 diff 共用):`MemberRecord.needsLocalSymbolsToBeSeen` 是「只靠符号出现(函数、计算属性和下标、初始化器、`deinit`、全局)且没有判定说它导出」;`ContainerSnapshot.needsLocalSymbolsToBeSeen` 是「不是 conformance 的 extension,成员全是上面这种」。类型、协议、conformance 靠元数据,永远看得见。某个没有 local Swift 符号的版本里缺席时,取它前后最近一次出现的记录,**任一侧**需要 local 符号才看得见,这次缺席就记为 hidden——一侧的 hidden 不说假话,错判成 absent 才会。 +- **推断**(`PresenceResolution`):一段连续 hidden 两侧观测相同——都在记 `inferredPresent`,都不在记 `unobservable`、什么都不断言;两侧不同记一个跨段事件,`versionIndex` 是段后第一个观测到新状态的版本,`earliestVersionIndex` 是段首。挨着轴端的段保持 `unobservable`。容器看不见的地方成员跟着看不见;成员的跨段事件只在段两侧容器都观测在场时产生,沿用「容器缺席的转换不枚举成员」。推断的依据:都带符号的年份里,两端都在、中间某版真缺的声明只占 0.15%–0.6%(上限,见提案)。 +- **收录规则改了**:lineage 有事件,**或者**有版本没观测到它,就收录;后一种没有事件可带签名,另带 `latestSignature`。成员只在**它自己**看不见、而容器在那个版本观测在场,并且那段看不见的区段有话可说(推断存在,或让边界变得不确定)时才因此收录:只因容器看不见而看不见的成员归容器的 lineage 交代,与增删容器的成员一样不单独收录;两侧都不在的区段没什么可说,位图之外不会多一个字(两条都是实数据核对时发现的,否则 SwiftUI 那条轴上会平白多出数千条成员注解,其中 169 条只有位图、没有一个短语)。接口侧「查不到 = 全程在场、从未变化」的裁决因此仍然成立。`presence` 的含义扩成「观测到或推断为存在」。 +- **兼容性**:跨段事件计入 `versionIndex` 那一步;报告的 Transitions 段在那一步下面注明其中几条只知道发生在哪两个版本之间。 +- **N == 2 一致性保住了**:diff 用同一套规则,一侧看不见的成员和容器(看不见的容器只列容器本身,成员不展开)进 `ABIDiff.unobservableDeclarations`,不进变更、不算 breaking。`ABIUnobservablePresenceTests` 钉住「diff 的看不见清单 = 两版本 evolution 里带 `unobservable` 状态的 lineage」。 +- **JSON**:新字段全部可选,为空时不编码,所以轴上没有被剥版本时 `evolution --json` 与 `diff --json` 逐字节不变(测试钉住)。 +- **局限**:`diff --interface` 按两侧结构渲染,不走这套规则;被剥前后身份变了的声明——协议要求在被剥的版本里变成 `pwtslot:` 记录、私有类型丢了 discriminator——仍是一删一增;「有没有 local Swift 符号」是整个镜像一个布尔值,只剥了一部分 local 符号的镜像会被当成完整的,它的缺席照常算观测。 + ## 首轮落地后的增量(第五批)—— 并集注解接口(`evolution --interface`) 提案:`Evolutions/0013-swift-evolution-interface-builder.md`。把 N 版本演进渲染成 diff --git a/Documentations/Internal/Modules/MachOSymbols.md b/Documentations/Internal/Modules/MachOSymbols.md index 73c97e4fa..c18254d1d 100644 --- a/Documentations/Internal/Modules/MachOSymbols.md +++ b/Documentations/Internal/Modules/MachOSymbols.md @@ -39,7 +39,9 @@ MachOSymbols 是**符号索引**层:把一个镜像的符号表和 export trie **同一地址上的符号按归属分组**(演进提案 `faster-lazy-definition-indexing`)。identical code folding 会把许多 conformance 内容相同的 witness 实现合并到一个地址上——SwiftUI 里一个 `_destroySelf` 或值 witness 的实现挂着上千个名字。要在这样的地址上找「属于某个 conformance 的那个」或「属于某个协议的那个」,用 `symbols(for:ownedBy:ownerKind:printedWith:in:)`:`SymbolOwnerKind.conformingType` 是符号树里第一个 `protocolConformance` 的第一个子节点,`.protocol` 是第一个 `protocol` 节点,按调用方给的打印预设打印后比较;结果按 `symbols(for:in:)` 的顺序排列,带查询偏移。每个「地址 + 规则 + 预设」第一次被问到时在 `Storage` 上分组一次(锁外计算、锁内先到者胜),之后每次是两次字典查找。以前 `ExtensionDefinition`、`ProtocolDefinition`、`ProtocolConformanceDumper`、`ProtocolDumper` 都是把这个地址的名字逐个 demangle、搜索、打印再比较,每个 conformance 来一次,对别名组大小是平方级:SwiftUI 一个镜像检查 365 万次、只涉及 17,852 个不同的名字。**新的「在别名里找归属」的代码走这个查询,不要再逐个比较。**`ClassDumper.validNode` 与 `OverrideSymbolMatcher` 按声明上下文结构相等来认领,规则不同、实测开销可以忽略,没有改。 -`Storage` 同时带着镜像的**导出事实**:两条 symtab 采集腿都过滤掉 external 符号,导出符号的行只可能来自 export trie 那条腿,而那条腿的行是有条件产出的,所以 trie 归属在同一趟里单独记(逐行位图加一个给无偏移 re-export 用的名字集合),撑起三态的 `isExported(name:in:)`(`nil` = 这个镜像没有导出信息,**此时绝不标注**)。 +`Storage` 同时带着镜像的**导出事实**:两条 symtab 采集腿用 `!nlist.isExternal` 过滤,而本库的 `isExternal` 只指**未定义的导入**(`N_EXT` 加 `N_UNDF`),所以两条腿收的是全部已定义符号,导出的也在内;符号表没列出的导出符号由 export trie 那条腿补行,而那条腿的行是有条件产出的,所以 trie 归属在同一趟里单独记(逐行位图加一个给无偏移 re-export 用的名字集合),撑起三态的 `isExported(name:in:)`(`nil` = 这个镜像没有导出信息,**此时绝不标注**)。成员级的判定走 `isExportedIncludingDerivedSymbols(names:in:)`:成员任一入口(自身或 `Tj` / `Tq` / `Tu` 派生形式)导出即为导出,interface 的 `// not exported` 注释和 ABI 快照的 `MemberRecord.isExported` 都问这一处。 + +同一趟还记下镜像**有没有 local Swift 符号**(`hasLocalSwiftSymbols(in:)`,演进提案 `evolution-unobservable-presence`):两条腿收到的 Swift 符号里,只要有一个 `N_EXT` 位为 0(`NlistProtocol.isLocal`,调试用的 STABS 条目不算)就是 `true`。被剥掉 local 符号的镜像——macOS 13.0–14.8 dyld shared cache 里的 SwiftUI——只剩导出的 Swift 名字,非导出的声明在这里根本没有名字,evolution 与 diff 据此把它们记为看不见而不是删除。判据不能用 `!isExternal`:导出符号同样过得了那道过滤。 ## 子系统 2:查询出口与 detach diff --git a/Documentations/Internal/Modules/SwiftInterface.md b/Documentations/Internal/Modules/SwiftInterface.md index 389ec7357..c20e165d0 100644 --- a/Documentations/Internal/Modules/SwiftInterface.md +++ b/Documentations/Internal/Modules/SwiftInterface.md @@ -80,12 +80,13 @@ diff 与 evolution 两条比较渲染路径的公共结构核心。分工是这 N ≥ 2 版本渲染成**一份**并集接口,声明尾注生命周期注解。承重决策是**事实与文本的分工**: -- **注解事实只来自 `ABIEvolution`**:`prepare(maximumConcurrentPreparations:)` **并行**索引各版本(窗口默认取核数、`1` 即旧的串行顺序;各版本是不同文件、缓存按 UUID 键控,结果与窗口无关,由 `parallelPreparationMatchesSerialPreparation` 钉住)→ 冻结 snapshot → `ABIEvolutionBuilder` 建 lineage 矩阵;渲染期经 `EvolutionAnnotationIndex` 按键查询,**查不到即是「全程在场、从未变化」的裁决**(`ABIEvolution` 只物化有变化的 lineage),渲染为无注解。策略自己绝不重推事件,所以注解接口、lineage 报告、JSON 三个视图永不打架。 +- **注解事实只来自 `ABIEvolution`**:`prepare(maximumConcurrentPreparations:)` **并行**索引各版本(窗口默认取核数、`1` 即旧的串行顺序;各版本是不同文件、缓存按 UUID 键控,结果与窗口无关,由 `parallelPreparationMatchesSerialPreparation` 钉住)→ 冻结 snapshot → `ABIEvolutionBuilder` 建 lineage 矩阵;渲染期经 `EvolutionAnnotationIndex` 按键查询,**查不到即是「全程在场、从未变化」的裁决**(`ABIEvolution` 只物化有变化的 lineage,以及有版本看不见它的 lineage),渲染为无注解。策略自己绝不重推事件,所以注解接口、lineage 报告、JSON 三个视图永不打架。 - **渲染文本来自活模型**:每个声明由最后携带它的版本的 printer 渲染(modified 成员只显示最新一代,旧形态进注解短语 `modified in 26.0: old → new`;箭头两侧相同则塌回裸短语)。header 解析是「最新可渲染」:从新到旧找第一个渲染成功的版本,每次失败都在其版本自己的 dispatcher 上派发,全部失败才整体丢弃(diff 的 drop-whole 规则推广到 N 侧)。 - **公开面是两个类型**:`AnySwiftEvolutionInterfaceBuilder` 是类型擦除的 runtime-N 主力(同构数组 init + 异构 pack init 都全平台可用——pack 在*函数*位不需要可用性门槛),CLI 与宿主的用户选版场景都走它;`SwiftEvolutionInterfaceBuilder` 是 pack 泛型 façade(类型位的 pack 需要 Swift 5.9 运行时,故 `@available(macOS 14…)`;构造即擦除,行为逐字节一致,由 `packGenericFacadeMatchesTheErasedBuilder` 钉住)。工具链尚不支持 `repeat each MachO == M` 的同元素约束,所以数组 init 上不了 pack 类型——这是两个类型并存的直接原因。 - **格式层 `EvolutionMarking`**(+ `EvolutionContainerAssembler`):legend 头两行(轴 + bitmap 位置对照)、注解列按块对齐、上限 72 列(超限换行缩一级)、锚点规则(成员注解锚**首行**——attribute 内联,computed property 的注解不能沉到 accessor 块闭括号;容器 header 锚**末行**——带 `{` 的那行)、镜像 `ABIEvolutionReporter` 措辞的 warnings 尾巴。与 `DiffMarking` 故意不合并:marker 按行、注解按 unit 锚定,是真不同语义。 - **真 `@available` 属性**(提案 [0060-evolution-interface-available-annotations](../../Evolutions/0060-evolution-interface-available-annotations.md)):两个 builder 都有 `availabilityAnnotationPlatform: String?`,默认 `nil` 表示关闭,输出与没有这项功能时逐字节相同。设了平台名之后,生命周期能**完整**写成一个属性的声明,上方会多一行 `@available(<平台>, introduced: …, obsoleted: …)`:成员按自己的缩进放在声明行上方,容器放在 header 上方。「能完整写成」要三条同时成立:presence bitmap 只有一段连续的在场区间(`○ᵃ●ᵇ○ᶜ`;消失后又回来的 `●○●` 不行);涉及的版本标签都能解析成 1–3 段的数字版本;至少有一个边界落在轴内(从第一个版本起就在场的声明没有「引入」这个事实)。modified 事件在 `@available` 里没有对应的写法,不进属性。有一条不满足就不发属性,位图注释无论如何都承载完整事实;设了平台时 legend 多出第三行,说明 `introduced:` 指轴上第一个带有该声明的版本,不一定是真正引入它的系统版本。属性有意做成**补充**而不是替代:提案 0013 否决的是用伪 `@available` **取代**注解格式。 -- **结构化流**:`@_spi(Support) annotatedBlocks()` → `[[EvolutionLine]]`(`EvolutionAnnotation` 是纯数据——presence bitmap + `LineageEvent`s;设了平台时也包含 `@available` 属性行),宿主可自行着色/折叠。 +- **看不见的版本**(演进提案 `evolution-unobservable-presence`):镜像没有 local Swift 符号的版本(macOS 13.0–14.8 的 SwiftUI)看不到只靠非导出符号才出现的成员。这类位置在位图里画 `◍`(看不见,但前后观测到的版本都有它,推断存在)或 `◌`(看不见、不作推断);跨过这类版本的变化写成 `removed between 12.7 and 15.0`,推断存在的区段另写 `inferred present in 13.0–14.8`,挨着轴端或两侧观测不同、又没有事件覆盖的区段写 `not observable in 13.0`,两侧都不在的区段只画 `◌`、不写短语;所有短语按轴的顺序排列;legend 多一行列出这些版本和两个符号的含义。看不见的区段挨着轴端或两侧观测不同时边界不确定,不发 `@available`;两侧都在按在场算,两侧都不在按不在算。只因容器看不见而看不见的成员不单独标注,由容器的注解交代,与增删容器的成员一样;只在两侧都不在的区段看不见、又没有事件的成员也不标注。事实同样只来自 `ABIEvolution`:这类 lineage 即使没有事件也会被物化(带 `presenceStates`),所以「查不到 = 全程在场、从未变化」的裁决仍然成立。规则本身在 SwiftDiffing(见 [ABIEvolutionDesign.md](../ABIEvolutionDesign.md) 第六批),这里只负责画;着色规则 `InterfaceAnnotationStyle.lineKinds` 认 `… between` 短语,只标看不见版本的注释算 plain。 +- **结构化流**:`@_spi(Support) annotatedBlocks()` → `[[EvolutionLine]]`(`EvolutionAnnotation` 是纯数据——presence bitmap + `LineageEvent`s,有看不见的版本时再加逐版本的 `presenceStates`;设了平台时也包含 `@available` 属性行),宿主可自行着色/折叠。 限制:输入必须全是 binary(snapshot 没有可渲染接口);协议的 `pwtslot:` 记录不渲染(没有对应声明,与 `diff --interface` 一致,变化仍见于 lineage 报告与 JSON)。 diff --git a/Documentations/README.md b/Documentations/README.md index 7c1825788..a3b8d8329 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -102,7 +102,7 @@ selects names using each access's offset and width. | [OpaquePrimaryAssociatedTypeAttribution.md](Internal/OpaquePrimaryAssociatedTypeAttribution.md) | 提案 0011 的实现说明:opaque 返回类型的 primary associated type 按 anchor 协议逐条归属(anchor 直接命中 → refine 闭包 → 名字兜底,兜底要求 anchor 在组合外——塌缩与未 pin 在 descriptor 里逐字节同形);三层解析链在实现里被 `resolvedContent` 塌成「descriptor 可达性」两问;内置 stdlib 表是 primary 名单/顺序的唯一来源(SE-0346 无运行时痕迹);两种 reader 输出深度差异是接受的设计。 | | [DiffableInterfacePlan.md](Internal/DiffableInterfacePlan.md) | Implementation plan for the diffable (ABI-diff) interface. | | [ABIDiffDesignAndLimitations.md](Internal/ABIDiffDesignAndLimitations.md) | The `SwiftDiffing` ABI-diff engine: identity/payload keys, three-way match, extension-bucket merging, and the known limitations (notably: `@frozen` is unrecoverable from the binary, so the compatibility verdict treats every type as resilient). | -| [ABIEvolutionDesign.md](Internal/ABIEvolutionDesign.md) | N ≥ 2 版本的 ABI 演化追踪(`ABIEvolution` lineage 模型 + N 路矩阵算法 + timeline reporter)与作为其地基的 snapshot 持久化(`ABISnapshotDocument` 版本头、`ABIProvenance`、CLI `snapshot` / `evolution` 命令、diff 的快照输入与 `--json`)。 | +| [ABIEvolutionDesign.md](Internal/ABIEvolutionDesign.md) | N ≥ 2 版本的 ABI 演化追踪(`ABIEvolution` lineage 模型 + N 路矩阵算法 + timeline reporter)与作为其地基的 snapshot 持久化(`ABISnapshotDocument` 版本头、`ABIProvenance`、CLI `snapshot` / `evolution` 命令、diff 的快照输入与 `--json`);第六批记录「看不见的版本」:没有 local Swift 符号的镜像里非导出成员的缺席不算删除,按两侧推断(`◍` / `◌`、`… between A and B`),diff 共用同一套规则。 | | [PerConformanceAttribution.md](Internal/PerConformanceAttribution.md) | extension 变更的 per-conformance / per-`where`-block 归属:容器按 (target, protocol, where 指纹, retroactive) 拆分、索引期冻结的归属字段与 witness 投影(`assocwitness:`)、key scheme v3、键碰撞源的结构性消解、diffable renderer 的 `: Protocol` 头。 | | [ProtocolRequirementProjection.md](Internal/ProtocolRequirementProjection.md) | stripped protocol requirement(PWT slot)投影(`pwtslot:` 命名空间、flags 指纹 payload、中段插入的诚实级联、符号化状态不对称局限)+ remangle 回退键自识别(`unmangled:` 前缀)与 `remangleFallbacks()` 审计通道;key scheme v4。 | | [DefaultImplementationAwareCompatibility.md](Internal/DefaultImplementationAwareCompatibility.md) | 默认实现感知的兼容性判定:`ProtocolDefinition.defaultedRequirementPWTOffsets`(描述符相对指针,不经符号表,stripped 侧同样精确)、`MemberRecord.hasDefaultImplementation`(仅 verdict 元数据,经 PWT offset 关联已解析成员)、`MemberChange` / `LineageEvent` 的 `compatibilityOverride`(defaultless requirement 追加判 breaking,stripped slot 获得默认实现判 additive);formatVersion 5。 | diff --git a/Sources/Output/SwiftDiffing/ABIDiffer.swift b/Sources/Output/SwiftDiffing/ABIDiffer.swift index bce6358b5..fac866235 100644 --- a/Sources/Output/SwiftDiffing/ABIDiffer.swift +++ b/Sources/Output/SwiftDiffing/ABIDiffer.swift @@ -177,9 +177,10 @@ public struct ABIDiffer: Sendable { /// buckets — since they are all `[ContainerSnapshot]` once frozen. /// /// A container one side has and the other side's image could not show - /// (see `UnobservablePresence.swift`) is neither removed nor added: it and - /// its members go to `unobservableDeclarations`, exactly the lineages a - /// two-version evolution leaves unobservable. + /// (see `UnobservablePresence.swift`) is neither removed nor added: it + /// goes to `unobservableDeclarations`, its members unlisted like an added + /// or removed container's — exactly the lineages a two-version evolution + /// leaves unobservable. private func diffContainerSnapshots( _ old: [ContainerSnapshot], _ new: [ContainerSnapshot], @@ -464,10 +465,10 @@ struct DiffVisibility { } extension ABIDiffer { - /// A container `side` cannot show, and every member it holds. + /// A container `side` cannot show. Its members are not listed, as an + /// added or removed container's are not: the container is the entry. static func unobservableDeclarations(of container: ContainerSnapshot, side: UnobservableDeclaration.Side) -> [UnobservableDeclaration] { [UnobservableDeclaration(side: side, key: container.key, containerName: container.name, containerKind: container.kind, memberKind: nil, signature: container.name)] - + container.members.map { unobservableDeclaration(of: $0, in: container, side: side) } } /// A member `side` cannot show, filed under its container (`nil` for a diff --git a/Sources/Output/SwiftDiffing/ABIEvolution.swift b/Sources/Output/SwiftDiffing/ABIEvolution.swift index 3577995c7..188484bdc 100644 --- a/Sources/Output/SwiftDiffing/ABIEvolution.swift +++ b/Sources/Output/SwiftDiffing/ABIEvolution.swift @@ -87,8 +87,11 @@ public enum LineagePresenceState: String, Sendable, Codable, Equatable { /// /// Only lineages with at least one event are materialized — an API that never /// changes never appears, mirroring `ABIDiff`'s "changes only" contract — and -/// lineages some version cannot show, so a reader learns which versions said -/// nothing about it. +/// lineages of members some version cannot show while it shows their +/// container, when that span says something (inferred present, or a bound +/// left unknown), so a reader learns which versions said nothing about them. +/// A member unseen only where its container is unseen is the container's +/// story, as the members of an added or removed container are. public struct MemberLineage: Sendable, Codable, Equatable { public let key: ABIKey public let kind: MemberKind diff --git a/Sources/Output/SwiftDiffing/ABIEvolutionBuilder.swift b/Sources/Output/SwiftDiffing/ABIEvolutionBuilder.swift index 41fef5ad6..73ac6f12e 100644 --- a/Sources/Output/SwiftDiffing/ABIEvolutionBuilder.swift +++ b/Sources/Output/SwiftDiffing/ABIEvolutionBuilder.swift @@ -159,8 +159,18 @@ public struct ABIEvolutionBuilder: Sendable { } events.sort { $0.versionIndex < $1.versionIndex } + // Kept for its unobservable versions only where the member itself + // went unseen and that says something: present on both sides, or + // a bound left unknown. Where its container is unseen too, the + // container's lineage tells that story, as an added or removed + // container's does for its members; between two absences there + // is nothing to tell. + let hasTellingSpanOfItsOwn = resolution.states.unobservedSpans.contains { span in + (span.state == .inferredPresent || !span.leavesTheBoundsKnown) + && span.versionIndices.contains { containerObservations[$0] == .present } + } + guard !events.isEmpty || hasTellingSpanOfItsOwn else { continue } let presenceStates = resolution.presenceStatesIfAnyUnobserved - guard !events.isEmpty || presenceStates != nil else { continue } // The record exists somewhere on the axis for the key to be in the // union, so the latest appearance always resolves a kind. let latestRecord = perVersion.reversed().compactMap { $0 }.first! diff --git a/Sources/Output/SwiftDiffing/ABIEvolutionReporter.swift b/Sources/Output/SwiftDiffing/ABIEvolutionReporter.swift index a903d60a9..22ad529fa 100644 --- a/Sources/Output/SwiftDiffing/ABIEvolutionReporter.swift +++ b/Sources/Output/SwiftDiffing/ABIEvolutionReporter.swift @@ -230,19 +230,19 @@ public struct ABIEvolutionReporter: Sendable { } } - /// The spans of versions that could not show the declaration, other than - /// those an event already spans. + /// The spans of versions that could not show the declaration and that + /// say something: inferred present, or leaving a bound unknown without an + /// event spanning them (``UnobservedSpan/isPhrasedAsNotObservable(spannedFirstIndices:)``). private func unobservedSpanLines(_ presenceStates: [LineagePresenceState]?, events: [LineageEvent], _ evolution: ABIEvolution) -> [String] { guard let presenceStates else { return [] } let spannedFirstIndices = Set(events.compactMap(\.earliestVersionIndex)) return presenceStates.unobservedSpans.compactMap { span in let labels = evolution.versions.labels(spanning: span.versionIndices) - switch span.state { - case .inferredPresent: + if span.state == .inferredPresent { return "◍ inferred present in \(labels)" - case .unobservable where !spannedFirstIndices.contains(span.versionIndices.lowerBound): + } else if span.isPhrasedAsNotObservable(spannedFirstIndices: spannedFirstIndices) { return "◌ not observable in \(labels)" - default: + } else { return nil } } diff --git a/Sources/Output/SwiftDiffing/UnobservablePresence.swift b/Sources/Output/SwiftDiffing/UnobservablePresence.swift index 3b788b273..0b4a89ee6 100644 --- a/Sources/Output/SwiftDiffing/UnobservablePresence.swift +++ b/Sources/Output/SwiftDiffing/UnobservablePresence.swift @@ -178,14 +178,41 @@ struct PresenceResolution { /// A maximal run of versions in which a lineage was not observed, all in one /// state: ``LineagePresenceState/inferredPresent`` or -/// ``LineagePresenceState/unobservable``. +/// ``LineagePresenceState/unobservable``, with the observations on either +/// side of it. public struct UnobservedSpan: Sendable, Equatable { public let versionIndices: ClosedRange public let state: LineagePresenceState + /// The observed state just before the span; `nil` when the axis starts + /// inside it. + public let stateBefore: LineagePresenceState? + /// The observed state just after the span; `nil` when the axis ends + /// inside it. + public let stateAfter: LineagePresenceState? - public init(versionIndices: ClosedRange, state: LineagePresenceState) { + public init(versionIndices: ClosedRange, state: LineagePresenceState, stateBefore: LineagePresenceState?, stateAfter: LineagePresenceState?) { self.versionIndices = versionIndices self.state = state + self.stateBefore = stateBefore + self.stateAfter = stateAfter + } + + /// Whether both sides were observed and agree, so the span leaves the + /// lifecycle's bounds where the observations put them: two presences + /// (inferred present) or two absences (inferred absent, which nothing + /// is said about). A span reaching an end of the axis, or between + /// different observations, leaves a bound unknown. + public var leavesTheBoundsKnown: Bool { + stateBefore != nil && stateBefore == stateAfter + } + + /// Whether the report should say the versions could not show the + /// declaration: an unobservable span that does leave a bound unknown and + /// that no event already spans (`spannedFirstIndices` are the events' + /// `earliestVersionIndex`es). A span between two absences says nothing + /// the bitmap does not. + public func isPhrasedAsNotObservable(spannedFirstIndices: Set) -> Bool { + state == .unobservable && !leavesTheBoundsKnown && !spannedFirstIndices.contains(versionIndices.lowerBound) } } @@ -206,7 +233,12 @@ extension Array where Element == LineagePresenceState { while versionIndex < count, self[versionIndex] == state { versionIndex += 1 } - spans.append(UnobservedSpan(versionIndices: firstIndex ... versionIndex - 1, state: state)) + spans.append(UnobservedSpan( + versionIndices: firstIndex ... versionIndex - 1, + state: state, + stateBefore: firstIndex > 0 ? self[firstIndex - 1] : nil, + stateAfter: versionIndex < count ? self[versionIndex] : nil + )) } return spans } diff --git a/Sources/Output/SwiftInterface/EvolutionMarking.swift b/Sources/Output/SwiftInterface/EvolutionMarking.swift index 24186fddd..58b95f864 100644 --- a/Sources/Output/SwiftInterface/EvolutionMarking.swift +++ b/Sources/Output/SwiftInterface/EvolutionMarking.swift @@ -110,7 +110,9 @@ enum EvolutionMarking { /// The full trailing comment: `// [●●○] removed in 26.0`, multiple /// phrases joined by ` · ` in axis order. The versions that could not /// show the declaration add their own phrase — `inferred present in - /// 13.0–14.8`, or `not observable in 13.0` where no event spans them. + /// 13.0–14.8`, or `not observable in 13.0` where they leave a bound + /// unknown and no event spans them; between two absences the `◌`s say + /// enough. static func annotationText(for annotation: EvolutionAnnotation, versions: [ABIVersionDescriptor]) -> String { var placedPhrases: [(versionIndex: Int, phrase: String)] = annotation.events.map { event in (event.earliestVersionIndex ?? event.versionIndex, phrase(for: event, versions: versions)) @@ -119,13 +121,10 @@ enum EvolutionMarking { let spannedFirstIndices = Set(annotation.events.compactMap(\.earliestVersionIndex)) for span in presenceStates.unobservedSpans { let labels = versions.labels(spanning: span.versionIndices) - switch span.state { - case .inferredPresent: + if span.state == .inferredPresent { placedPhrases.append((span.versionIndices.lowerBound, "inferred present in \(labels)")) - case .unobservable where !spannedFirstIndices.contains(span.versionIndices.lowerBound): + } else if span.isPhrasedAsNotObservable(spannedFirstIndices: spannedFirstIndices) { placedPhrases.append((span.versionIndices.lowerBound, "not observable in \(labels)")) - default: - break } } } @@ -158,11 +157,12 @@ enum EvolutionMarking { /// version literal. /// - Modified events never participate: `@available` has no vocabulary /// for them, so a modified-throughout lifecycle yields `nil`. - /// - A version that could not show the declaration and was not inferred - /// present (evolution proposal `evolution-unobservable-presence`) - /// leaves its bound unknown — an event spanning it, or an end of the - /// axis it reaches — so the lifecycle yields `nil`. Inferred presence - /// counts as presence. + /// - Versions that could not show the declaration (evolution proposal + /// `evolution-unobservable-presence`) between different observations, + /// or reaching an end of the axis, leave a bound unknown, so the + /// lifecycle yields `nil`. Between two presences they count as + /// presence (inferred), between two absences as absence: the bounds + /// stay where the observations put them. /// /// The facts are axis-resolution: `introduced:` names the first axis /// point carrying the declaration, not necessarily the OS release that @@ -173,7 +173,7 @@ enum EvolutionMarking { platform: String ) -> String? { guard annotation.presence.count == versions.count else { return nil } - guard annotation.presenceStates?.contains(.unobservable) != true else { return nil } + guard annotation.presenceStates?.unobservedSpans.allSatisfy(\.leavesTheBoundsKnown) != false else { return nil } guard let interval = singlePresenceInterval(annotation.presence) else { return nil } var clauses: [String] = [] if interval.firstPresentIndex > 0 { diff --git a/Tests/SwiftDiffingTests/ABIUnobservablePresenceTests.swift b/Tests/SwiftDiffingTests/ABIUnobservablePresenceTests.swift index fc76194bf..555e87cc3 100644 --- a/Tests/SwiftDiffingTests/ABIUnobservablePresenceTests.swift +++ b/Tests/SwiftDiffingTests/ABIUnobservablePresenceTests.swift @@ -162,6 +162,22 @@ struct ABIUnobservablePresenceTests { #expect(lineage.events == [LineageEvent(versionIndex: 1, status: .removed, oldSignature: "gone")]) } + /// The container comes and goes around the stripped version, so the + /// member has no event of its own, and the span it cannot be seen in + /// lies between two absences: nothing to tell, so no lineage. + @Test("a member unseen only between two absences carries no lineage of its own") + func spanBetweenAbsencesKeepsNoLineage() throws { + let result = try evolution([ + symbolRich(), + stripped([container("Foo")]), + symbolRich(), + symbolRich([container("Foo", members: [record("late")])]), + ]) + let lineage = try #require(result.types.first) + #expect(lineage.events.map(\.status) == [.added, .removed, .added]) + #expect(lineage.memberLineages.isEmpty) + } + @Test("an extension made up only of non-exported members cannot be seen where they cannot") func extensionOfHiddenMembersIsHidden() throws { let result = try evolution([ @@ -172,8 +188,19 @@ struct ABIUnobservablePresenceTests { let lineage = try #require(result.typeExtensions.first) #expect(lineage.presenceStates == [.present, .inferredPresent, .present]) #expect(lineage.events.isEmpty) - let memberLineage = try memberLineage("scale", in: result, container: "Swift.Int") - #expect(memberLineage.presenceStates == [.present, .inferredPresent, .present]) + } + + /// The members of an added or removed container carry no lineage of + /// their own; neither do the members of a container a version cannot + /// show, unseen only because it is. + @Test("a member unseen only where its container is unseen is left to the container's lineage") + func memberOfAnUnseenContainerHasNoLineage() throws { + let result = try evolution([ + symbolRich(typeExtensions: [container("Swift.Int", kind: .typeExtension, members: [record("scale")])]), + stripped(), + symbolRich(typeExtensions: [container("Swift.Int", kind: .typeExtension, members: [record("scale")])]), + ]) + #expect(result.typeExtensions.first?.memberLineages.isEmpty == true) } @Test("a conformance stays observable without local Swift symbols") @@ -237,14 +264,14 @@ struct ABIDifferUnobservablePresenceTests { #expect(diff.unobservableDeclarations?.map(\.side) == [.old]) } - @Test("an extension the new side cannot show is listed apart with its members") + @Test("an extension the new side cannot show is listed apart, its members with it") func hiddenExtension() { let diff = ABIDiffer().diff( old: symbolRich(typeExtensions: [container("Swift.Int", kind: .typeExtension, members: [record("scale")])]), new: stripped() ) #expect(diff.isEmpty) - #expect(diff.unobservableDeclarations?.map(\.key) == [.printed("Swift.Int"), .mangled("scale")]) + #expect(diff.unobservableDeclarations?.map(\.key) == [.printed("Swift.Int")]) #expect(!diff.hasBreakingChange) } diff --git a/Tests/SwiftInterfaceTests/EvolutionMarkingTests.swift b/Tests/SwiftInterfaceTests/EvolutionMarkingTests.swift index f801b3f98..2b356e586 100644 --- a/Tests/SwiftInterfaceTests/EvolutionMarkingTests.swift +++ b/Tests/SwiftInterfaceTests/EvolutionMarkingTests.swift @@ -119,6 +119,19 @@ struct EvolutionMarkingTests { #expect(EvolutionMarking.annotationText(for: spanned, versions: versionAxis) == "// [●◌○] removed between 1.0 and 3.0") } + /// Between two absences the versions only infer absence: the `◌`s say + /// enough, and the bounds stay observed. + @Test func unobservableVersionsBetweenTwoAbsencesAddNoPhraseAndKeepTheAttribute() { + let fourVersionAxis = versionAxis + [ABIVersionDescriptor(label: "4.0")] + let removedEarlier = EvolutionAnnotation( + presence: [true, false, false, false], + events: [LineageEvent(versionIndex: 1, status: .removed)], + presenceStates: [.present, .absent, .unobservable, .absent] + ) + #expect(EvolutionMarking.annotationText(for: removedEarlier, versions: fourVersionAxis) == "// [●○◌○] removed in 2.0") + #expect(EvolutionMarking.availabilityAttributeText(for: removedEarlier, versions: fourVersionAxis, platform: "macOS") == "@available(macOS, obsoleted: 2.0)") + } + @Test func phrasesFollowAxisOrder() { let fourVersionAxis = versionAxis + [ABIVersionDescriptor(label: "4.0")] let annotation = EvolutionAnnotation( diff --git a/Tests/SwiftInterfaceTests/UnobservablePresenceTests.swift b/Tests/SwiftInterfaceTests/UnobservablePresenceTests.swift index e7892b30c..ba007dc57 100644 --- a/Tests/SwiftInterfaceTests/UnobservablePresenceTests.swift +++ b/Tests/SwiftInterfaceTests/UnobservablePresenceTests.swift @@ -101,10 +101,12 @@ struct UnobservablePresenceTests { #expect(lines[retiredIndex - 1].contains("@available(macOS, obsoleted: 2.0)")) } - @Test("an extension of internal members alone is inferred present with them") + @Test("an extension of internal members alone is inferred present, its members with it") func internalExtensionIsInferredPresent() async throws { let lines = try await interfaceLines() #expect(lines[try lineIndex(containing: "extension Swift.Int", in: lines)].contains("// [●◍●] inferred present in 2.0")) - #expect(lines[try lineIndex(containing: "func panelScale()", in: lines)].contains("// [●◍●] inferred present in 2.0")) + // The container's annotation tells the member's story, as it does for + // the members of an added or removed container. + #expect(!lines[try lineIndex(containing: "func panelScale()", in: lines)].contains("// [")) } } From dfab6020f602effba361c763f342e953f9c81f6e Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sun, 25 Oct 2026 00:08:06 +0800 Subject: [PATCH 005/318] docs(evolution-unobservable-presence): compare peak memory footprint, not resident size The resident size of both 51-version runs is dominated by read-only cache pages. The footprint is the comparable figure: 4.46 GB against next's 4.41 GB. --- .../Evolutions/draft-evolution-unobservable-presence.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Documentations/Evolutions/draft-evolution-unobservable-presence.md b/Documentations/Evolutions/draft-evolution-unobservable-presence.md index 12a0aa59a..27faa8e97 100644 --- a/Documentations/Evolutions/draft-evolution-unobservable-presence.md +++ b/Documentations/Evolutions/draft-evolution-unobservable-presence.md @@ -88,5 +88,5 @@ evolution 和 diff 把每个声明在每个版本里只记成「在」或「不 | 2026-10-24 | 着色规则 `InterfaceAnnotationStyle.lineKinds` 认 `… between` 短语,只标看不见版本的注释算 plain | 方案没写到。原规则把不含 `removed in` / `modified in` 的注释一律当新增,`removed between` 会被染成新增 | | 2026-10-24 | 第 3 步完成 | 定向测试 `UnobservablePresenceTests`(新增 5 个端到端用例)、`EvolutionMarkingTests`(新增 7 个)、`InterfaceAnnotationStyleTests`(新增 1 个)全过;SwiftInterfaceTests 329 个、SwiftSectionKitTests 66 个、SwiftSectionCommandTests 106 个、SwiftDiffingTests 108 个全过,原始退出码 0。变异检验:去掉 `@available` 的边界判断、把着色默认值改回新增,3 个测试变红,还原后转绿。CLI 冒烟:对现编的三版 dylib(第二版 `strip -x`)跑 `evolution --interface --emit-available`、文本报告与 `diff`,输出与设计一致 | | 2026-10-25 | 实数据核对后收紧两处:只因容器看不见、或只在两侧都不在的区段看不见的成员,不再因此收录,diff 里看不见的容器也只列容器本身;两侧都不在的区段不写短语,也不拦 `@available` | 第一次重跑 51 版 SwiftUI 时,新输出多了 21,805 条 `not observable in …`、`@available` 少了约 2.2 万行,抽样发现两类:容器自己已有注解(类型在 13.0 出现、15.0 迁去 SwiftUICore,或 extension 整体看不见),它的成员却跟着各标一次,与增删容器的成员一贯不标注的规则不一致;以及 12.4 就删掉的成员在 13.0–14.8 两侧都不在,什么都说不出,却写了短语、丢了本来成立的 `obsoleted:`。收紧后另有 169 条只剩位图、没有短语的成员注解随之消失 | -| 2026-10-25 | 第 4 步完成,实数据结果 | 同一命令(release 版 CLI,`--dyld-shared-cache -p …/SwiftUI --interface --emit-available`,51 份归档 cache)在 `next` 与本分支上各跑一次。`next` 的输出与 0073 之前生成的那份只差 0073 修好的 20 行。本分支对 `next`:208,706 行代码逐行相同;42,517 条注解不变,30,229 条只有 13.0–14.8 那几位变了,没有一条观测到的位置被改,也没有注解丢失;新增 151 条注解,全部是此前被容器的假缺口挡住的跨段增删。两端都在、中间缺席的 5,189 条里 5,097 条(98.2%)整段变成推断存在;`removed in 13.0 · added in 15.0` 从 5,089 条降到 24 条(类型的真实删除、丢了 discriminator 的私有类型,以及几条公开 `static let` 在被剥前后由不同的访问器撑起,属方案列出的范围外情形);`removed in 13.0` 从 18,293 降到 1,700、`added in 15.0` 从 19,596 降到 4,472,其余换成 2,084 / 2,065 / 17 条 `removed` / `added` / `modified between 12.7 and 15.0` 与 17,684 条 `not observable in …`(多是容器在 13.0 出现或 15.0 搬走、成员自己说不清何时增删的情形)。`@available` 行从 66,711 降到 48,214,去掉的都是边界不确定的。峰值内存 12.8 GB 对 12.8 GB(`next`),这台 28 核机器上用时 216 秒 | +| 2026-10-25 | 第 4 步完成,实数据结果 | 同一命令(release 版 CLI,`--dyld-shared-cache -p …/SwiftUI --interface --emit-available`,51 份归档 cache)在 `next` 与本分支上各跑一次。`next` 的输出与 0073 之前生成的那份只差 0073 修好的 20 行。本分支对 `next`:208,706 行代码逐行相同;42,517 条注解不变,30,229 条只有 13.0–14.8 那几位变了,没有一条观测到的位置被改,也没有注解丢失;新增 151 条注解,全部是此前被容器的假缺口挡住的跨段增删。两端都在、中间缺席的 5,189 条里 5,097 条(98.2%)整段变成推断存在;`removed in 13.0 · added in 15.0` 从 5,089 条降到 24 条(类型的真实删除、丢了 discriminator 的私有类型,以及几条公开 `static let` 在被剥前后由不同的访问器撑起,属方案列出的范围外情形);`removed in 13.0` 从 18,293 降到 1,700、`added in 15.0` 从 19,596 降到 4,472,其余换成 2,084 / 2,065 / 17 条 `removed` / `added` / `modified between 12.7 and 15.0` 与 17,684 条 `not observable in …`(多是容器在 13.0 出现或 15.0 搬走、成员自己说不清何时增删的情形)。`@available` 行从 66,711 降到 48,214,去掉的都是边界不确定的。峰值内存占用(peak memory footprint)4.46 GB 对 `next` 的 4.41 GB,多 58 MB(约 1.3%,新增的导出判定与逐版本状态);RSS 两边都是 12.8 GB,多是只读映射的 cache 页。这台 28 核机器上 release 版用时 216 秒 | | 2026-10-25 | 实现完成,待合并 | 全量 `swift test --skip IntegrationTests`(收紧前的第 3 步代码)2,578 个测试全过,原始退出码 0;收紧后重跑受影响的 SwiftDiffingTests 110 个、SwiftInterfaceTests 330 个、SwiftSectionKitTests 66 个、SwiftSectionCommandTests 106 个,全过。每次收紧都做了变异检验(改回原规则,对应的新测试变红,还原后转绿)。没有跑渲染 A/B:单版本的 `dump` / `interface` 只动了 printer 里导出判定的一处等价改写,相关的导出注释与 `--exported-only` 套件都过了。不另写使用指南或实现说明:规则与取舍写在 `ABIEvolutionDesign.md` 第六批与本提案;新术语 unobservable 已登记 | From 24db9bdc3cea22f1e07b05101f544658a4c7f3f6 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sun, 25 Oct 2026 00:32:59 +0800 Subject: [PATCH 006/318] docs(evolution-unobservable-presence): record the full run on the final commit --- .../Evolutions/draft-evolution-unobservable-presence.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Documentations/Evolutions/draft-evolution-unobservable-presence.md b/Documentations/Evolutions/draft-evolution-unobservable-presence.md index 27faa8e97..dc8b9337f 100644 --- a/Documentations/Evolutions/draft-evolution-unobservable-presence.md +++ b/Documentations/Evolutions/draft-evolution-unobservable-presence.md @@ -89,4 +89,4 @@ evolution 和 diff 把每个声明在每个版本里只记成「在」或「不 | 2026-10-24 | 第 3 步完成 | 定向测试 `UnobservablePresenceTests`(新增 5 个端到端用例)、`EvolutionMarkingTests`(新增 7 个)、`InterfaceAnnotationStyleTests`(新增 1 个)全过;SwiftInterfaceTests 329 个、SwiftSectionKitTests 66 个、SwiftSectionCommandTests 106 个、SwiftDiffingTests 108 个全过,原始退出码 0。变异检验:去掉 `@available` 的边界判断、把着色默认值改回新增,3 个测试变红,还原后转绿。CLI 冒烟:对现编的三版 dylib(第二版 `strip -x`)跑 `evolution --interface --emit-available`、文本报告与 `diff`,输出与设计一致 | | 2026-10-25 | 实数据核对后收紧两处:只因容器看不见、或只在两侧都不在的区段看不见的成员,不再因此收录,diff 里看不见的容器也只列容器本身;两侧都不在的区段不写短语,也不拦 `@available` | 第一次重跑 51 版 SwiftUI 时,新输出多了 21,805 条 `not observable in …`、`@available` 少了约 2.2 万行,抽样发现两类:容器自己已有注解(类型在 13.0 出现、15.0 迁去 SwiftUICore,或 extension 整体看不见),它的成员却跟着各标一次,与增删容器的成员一贯不标注的规则不一致;以及 12.4 就删掉的成员在 13.0–14.8 两侧都不在,什么都说不出,却写了短语、丢了本来成立的 `obsoleted:`。收紧后另有 169 条只剩位图、没有短语的成员注解随之消失 | | 2026-10-25 | 第 4 步完成,实数据结果 | 同一命令(release 版 CLI,`--dyld-shared-cache -p …/SwiftUI --interface --emit-available`,51 份归档 cache)在 `next` 与本分支上各跑一次。`next` 的输出与 0073 之前生成的那份只差 0073 修好的 20 行。本分支对 `next`:208,706 行代码逐行相同;42,517 条注解不变,30,229 条只有 13.0–14.8 那几位变了,没有一条观测到的位置被改,也没有注解丢失;新增 151 条注解,全部是此前被容器的假缺口挡住的跨段增删。两端都在、中间缺席的 5,189 条里 5,097 条(98.2%)整段变成推断存在;`removed in 13.0 · added in 15.0` 从 5,089 条降到 24 条(类型的真实删除、丢了 discriminator 的私有类型,以及几条公开 `static let` 在被剥前后由不同的访问器撑起,属方案列出的范围外情形);`removed in 13.0` 从 18,293 降到 1,700、`added in 15.0` 从 19,596 降到 4,472,其余换成 2,084 / 2,065 / 17 条 `removed` / `added` / `modified between 12.7 and 15.0` 与 17,684 条 `not observable in …`(多是容器在 13.0 出现或 15.0 搬走、成员自己说不清何时增删的情形)。`@available` 行从 66,711 降到 48,214,去掉的都是边界不确定的。峰值内存占用(peak memory footprint)4.46 GB 对 `next` 的 4.41 GB,多 58 MB(约 1.3%,新增的导出判定与逐版本状态);RSS 两边都是 12.8 GB,多是只读映射的 cache 页。这台 28 核机器上 release 版用时 216 秒 | -| 2026-10-25 | 实现完成,待合并 | 全量 `swift test --skip IntegrationTests`(收紧前的第 3 步代码)2,578 个测试全过,原始退出码 0;收紧后重跑受影响的 SwiftDiffingTests 110 个、SwiftInterfaceTests 330 个、SwiftSectionKitTests 66 个、SwiftSectionCommandTests 106 个,全过。每次收紧都做了变异检验(改回原规则,对应的新测试变红,还原后转绿)。没有跑渲染 A/B:单版本的 `dump` / `interface` 只动了 printer 里导出判定的一处等价改写,相关的导出注释与 `--exported-only` 套件都过了。不另写使用指南或实现说明:规则与取舍写在 `ABIEvolutionDesign.md` 第六批与本提案;新术语 unobservable 已登记 | +| 2026-10-25 | 实现完成,待合并 | 全量 `swift test --skip IntegrationTests`(收紧前的第 3 步代码)2,578 个测试全过,原始退出码 0;收紧后重跑受影响的 SwiftDiffingTests 110 个、SwiftInterfaceTests 330 个、SwiftSectionKitTests 66 个、SwiftSectionCommandTests 106 个,全过。每次收紧都做了变异检验(改回原规则,对应的新测试变红,还原后转绿);最终提交上再跑一次全量,2,581 个测试全过,原始退出码 0。没有跑渲染 A/B:单版本的 `dump` / `interface` 只动了 printer 里导出判定的一处等价改写,相关的导出注释与 `--exported-only` 套件都过了。不另写使用指南或实现说明:规则与取舍写在 `ABIEvolutionDesign.md` 第六批与本提案;新术语 unobservable 已登记 | From e64b10853c2a49c94e6b4f5bdf973a520a567af2 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Tue, 27 Oct 2026 16:26:38 +0800 Subject: [PATCH 007/318] fix(cross-reference-analysis): address mask, ld64 rewrites, entry-point sends Five findings of the second review of 0.24.0's cross-reference analysis, each with a test that failed before its fix: - Strip pointers read in-process with the platform's mask (InProcessContext.addressMask, now package-visible, through StoredPointer) instead of six hard-coded 47-bit masks, which left an iPhone's signature bits 39-46 in every signed slot. AddressMaskScanTests. - Read the code ld64 rewrote: a literal `ldr` loads from its slot, `adr` references a class or a type as `adrp` / `add` does, and a `nop` / `ldr x16, ` / `br x16` stub, which MachOKit reads no slot from, is read through ARM64Trampoline. SwiftThunkAnalysis decodes the literal load too (ThunkOperation.loadFromSlot). LinkerOptimizationHintTests rewrites compiled fixtures as ld64 does. - Report a call to one of libobjc's send entry points (objc_alloc_init, objc_opt_isKindOfClass ...) as the sends it stands for, and keep the images importing them in the selector prefilter. Proposal objc-runtime-send-entry-points. RuntimeSendEntryPointTests. - Read a descriptor's name only from a type descriptor: an opaque type's generic header, read as a name offset, led past a small image's end. importedTypeQueriesReadNoNameWhereNoTypeDescriptorIs. - Spell out `pc`, `lhs` and `rhs`. AbbreviatedIdentifierScanTests. --- AGENTS.md | 2 +- Documentations/Evolutions/README.md | 1 + .../draft-objc-runtime-send-entry-points.md | 53 ++++ .../Modules/CrossReferenceAnalysis.md | 50 +++- .../Internal/Modules/SwiftThunkAnalysis.md | 2 + Documentations/README.md | 1 + .../MachOSwiftSection/Extensions/Array+.swift | 12 +- .../MachOSwiftSection/Protocols/FlagSet.swift | 4 +- .../CrossReferenceAnalyzer+Prefiltering.swift | 19 +- .../CrossReferenceAnalyzer+SwiftTypes.swift | 2 +- .../CrossReferenceAnalyzer.swift | 17 +- .../Models/CodeLocation.swift | 4 +- .../Models/CodeReference.swift | 5 +- .../Scanning/ImageFallbackNames.swift | 3 +- .../Scanning/ImageFunctionTable.swift | 27 +- .../Scanning/MessageSendEntryPoints.swift | 39 +++ .../Scanning/ObjectiveCClassIndex.swift | 10 +- .../Scanning/ReferenceScanner.swift | 166 +++++++----- .../Scanning/RegisterFile.swift | 10 + .../Scanning/StoredPointer.swift | 19 ++ .../Scanning/SwiftTypeIndex.swift | 18 +- .../ClassHierarchyDumper.swift | 16 +- .../SwiftInspection/SymbolicDemangler.swift | 4 +- .../Analysis/ThunkRegisterTracker.swift | 2 +- .../Analysis/ThunkTypeEvaluator.swift | 31 ++- .../Instructions/CapstoneThunkDecoder.swift | 19 +- .../Instructions/ThunkInstruction.swift | 6 + .../Components/Names/ExtensionName.swift | 4 +- .../Components/Names/ProtocolName.swift | 4 +- .../Components/Names/TypeName.swift | 4 +- .../Components/SwiftAttribute.swift | 4 +- .../SwiftDeclarationIndexer.swift | 4 +- .../ReadingContext/InProcessContext.swift | 7 +- .../ReadingContext/ReadingContext.swift | 38 +-- Sources/MachO/MachOResolving/Symbol.swift | 4 +- .../StructuralNodeReferenceKey.swift | 4 +- .../DeclarationRenderConfiguration.swift | 4 +- Sources/Output/SwiftDiffing/ABIDiffer.swift | 4 +- .../ARM64InstructionWord.swift | 23 +- .../ARM64Trampoline.swift | 11 +- .../Coverage/MethodKey.swift | 6 +- .../ARM64InstructionDecodingTests.swift | 40 ++- .../AbbreviatedIdentifierScanTests.swift | 72 +++++ .../AddressMaskScanTests.swift | 74 ++++++ .../CompiledFixture.swift | 61 +++++ .../CrossReferenceAnalyzerTests.swift | 4 +- .../InstructionEncoding.swift | 14 + .../LinkerOptimizationHintTests.swift | 250 ++++++++++++++++++ .../RuntimeSendEntryPointTests.swift | 114 ++++++++ .../SwiftTypeReferenceTests.swift | 54 +++- .../MultiPayloadEnumTests.swift | 4 +- .../CapstoneThunkDecoderTests.swift | 12 + 52 files changed, 1172 insertions(+), 190 deletions(-) create mode 100644 Documentations/Evolutions/draft-objc-runtime-send-entry-points.md create mode 100644 Sources/Analysis/CrossReferenceAnalysis/Scanning/MessageSendEntryPoints.swift create mode 100644 Sources/Analysis/CrossReferenceAnalysis/Scanning/StoredPointer.swift create mode 100644 Tests/CrossReferenceAnalysisTests/AbbreviatedIdentifierScanTests.swift create mode 100644 Tests/CrossReferenceAnalysisTests/AddressMaskScanTests.swift create mode 100644 Tests/CrossReferenceAnalysisTests/CompiledFixture.swift create mode 100644 Tests/CrossReferenceAnalysisTests/LinkerOptimizationHintTests.swift create mode 100644 Tests/CrossReferenceAnalysisTests/RuntimeSendEntryPointTests.swift diff --git a/AGENTS.md b/AGENTS.md index c7422fc41..bd7d9b2b0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -58,7 +58,7 @@ One or two lines each; the linked document is the authority. - **SwiftDiffing** — Mach-O-free ABI comparison over the indexed model: `ABIDiffer` (two-sided), `ABIEvolution` (N versions), `ABISnapshot` (the persisted baseline). [ABIDiffDesignAndLimitations.md](Documentations/Internal/ABIDiffDesignAndLimitations.md), [ABIEvolutionDesign.md](Documentations/Internal/ABIEvolutionDesign.md). - **SwiftLayout** — the static field-offset / type-layout engine: computes offline what the runtime computes, and degrades honestly when the binary does not carry the fact. [Modules/SwiftLayout.md](Documentations/Internal/Modules/SwiftLayout.md). - **SwiftThunkAnalysis** — reads an availability-conditional opaque type (a kind-9 accessor-function symbolic reference) by symbolically evaluating the thunk instead of running it. Capstone, ARM64 only. Also home of `ObjCMembers` (`ObjCMembers/`): a class's ObjC method table is its `@objc` member list, and it survives the strip that removes every `To` thunk symbol from an OS framework — the interface's only `@objc` evidence until then (the macOS 26.6 AppKit interface carried ZERO member-level `@objc`, and mis-marked `@objc dynamic` members `final`). Each entry is tied to its Swift member by the `To` thunk symbol at the IMP or — stripped — by decoding the anonymous thunk for the implementation it calls or materializes, guarded by the member's name being the importer's spelling of the selector; that gives `@objc`, the `override` of an ObjC-inherited member (invisible to Swift metadata: the compiler emits a NEW vtable entry for it, and an `@objc @implementation` class has no vtable) where an ancestor implements the selector, and `@objc(selector)` where the selector differs from the compiler's own derivation from the Swift name (never for an override or an `@objc` protocol witness, whose selectors are inherited — and therefore only when the whole ancestor chain and every adopted protocol were read, since a standalone file's bound superclass would otherwise turn every UIKit override into a false `@objc(hitTest:withEvent:)`; an `@implementation` body is NOT exempt — the compiler derives its selectors from the Swift names too and demands the header declare them). A name-only third tier for overrides ALWAYS runs and is recorded on the definition (`evidence == .selectorName`); acting on it is the consumer's call, taken through `ResolvedObjCMemberFacts` — the dump always renders it (it names every tie's evidence), the interface takes `SwiftDeclarationPrintConfiguration.infersObjCOverridesFromSelectorNames` (CLI `interface --infer-objc-overrides`, default off). That tier must NOT write `@objc` into `attributes`: the `final` recovery runs right after it and reads the attribute as proof of `@objc dynamic`, so a verdict the consumer never took would stick. The fixture's `.optimizedStripped` variant is what the tier exists for. `isOverride` / `isClassMember` on the member definitions OR in the JOINED tiers only, so `override class func` prints where `static` did; the name-only tier reaches those keywords through the resolved facts. [Modules/SwiftThunkAnalysis.md](Documentations/Internal/Modules/SwiftThunkAnalysis.md). -- **CrossReferenceAnalysis** — what each function of an in-process `MachOImage` references, read from its arm64 machine code by a hand decoder rather than Capstone (25–50 times faster; a whole macOS shared cache scans in two to three seconds): calls, tail calls, Objective-C sends, calls through an image's own stubs or through the stubs a macOS 27 / iOS 27 cache shares between all images, indirect calls, and references to Objective-C classes and Swift types. A `CrossReferenceAnalyzer` is a snapshot of the process's images, an image outside the cache going by the path dyld loaded it from; it keeps the function tables of the images it names functions in, and its class and type indexes, linkage and re-export names, for its lifetime, while whole-image scans build their tables and drop them. A callers prefilter looks for the names other images re-export a C function under too (CoreGraphics' `_CG…` for SkyLight's `_SL…`). A `CodeReferenceTable` is a value the host keeps — and a callers query uses `references(to:inImageAt:)`, which keeps only the matches: whole tables of a cache scanned on 28 threads peak at 1.5 GB. A host that keeps the references of a few images to query again and again keeps a `CodeReferenceIndex` instead (`referenceIndex(ofImageAt:)`, a quarter to a third of a table's memory, answering exactly what the filtered scans would); building one keeps the image's function table. Such a host reads ahead what a first query would read — an image's names (`prepareNames(inImageAt:)`), the prefilters' tables across all images (`preparePrefilters()`, on the calling thread alone) — counts it with `approximateByteCount(ofImageDataAt:)`, and lets go of the other images' with `releaseImageData(exceptForImagesAt:)` rather than replacing the analyzer, which would drop it all. Read a target's memory only after confirming it is mapped — data in `__text` decodes as branches to arbitrary addresses. [Modules/CrossReferenceAnalysis.md](Documentations/Internal/Modules/CrossReferenceAnalysis.md). +- **CrossReferenceAnalysis** — what each function of an in-process `MachOImage` references, read from its arm64 machine code by a hand decoder rather than Capstone (25–50 times faster; a whole macOS shared cache scans in two to three seconds): calls, tail calls, Objective-C sends (through `objc_msgSend`, and the libobjc entry points that stand for sends — `objc_alloc_init` is `alloc` and `init`), calls through an image's own stubs or through the stubs a macOS 27 / iOS 27 cache shares between all images, indirect calls, and references to Objective-C classes and Swift types. Code ld64 rewrote — `adr`, a literal `ldr`, a `nop` / `ldr x16, ` / `br x16` stub, common in third-party apps — reads as the pair it was rewritten from. A `CrossReferenceAnalyzer` is a snapshot of the process's images, an image outside the cache going by the path dyld loaded it from; it keeps the function tables of the images it names functions in, and its class and type indexes, linkage and re-export names, for its lifetime, while whole-image scans build their tables and drop them. A callers prefilter looks for the names other images re-export a C function under too (CoreGraphics' `_CG…` for SkyLight's `_SL…`). A `CodeReferenceTable` is a value the host keeps — and a callers query uses `references(to:inImageAt:)`, which keeps only the matches: whole tables of a cache scanned on 28 threads peak at 1.5 GB. A host that keeps the references of a few images to query again and again keeps a `CodeReferenceIndex` instead (`referenceIndex(ofImageAt:)`, a quarter to a third of a table's memory, answering exactly what the filtered scans would); building one keeps the image's function table. Such a host reads ahead what a first query would read — an image's names (`prepareNames(inImageAt:)`), the prefilters' tables across all images (`preparePrefilters()`, on the calling thread alone) — counts it with `approximateByteCount(ofImageDataAt:)`, and lets go of the other images' with `releaseImageData(exceptForImagesAt:)` rather than replacing the analyzer, which would drop it all. Read a target's memory only after confirming it is mapped — data in `__text` decodes as branches to arbitrary addresses. Strip a pointer read out of the process with the platform's mask (`StoredPointer`, `InProcessContext.addressMask`), never a constant: an iPhone's addresses are 36 bits and its signature starts at bit 39, where a Mac's 47-bit mask leaves it in place (`AddressMaskScanTests`). [Modules/CrossReferenceAnalysis.md](Documentations/Internal/Modules/CrossReferenceAnalysis.md). - **ARM64InstructionDecoding** — 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. `SwiftThunkAnalysis` and `CrossReferenceAnalysis` share it. - **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). - **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). diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index 039abaa18..04e77e2af 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -86,3 +86,4 @@ | draft | [evolution 与 diff 区分「不存在」和「看不见」](draft-evolution-unobservable-presence.md) | Accepted | | [0074](0074-private-declaration-source-files.md) | dump 与 interface 标出私有声明来自哪个源文件 | Implemented | | [0075](0075-wrapped-reader-recognition.md) | 包装类型读取器的识别:库看穿宿主的包装,按底下的读取器回答 | Implemented | +| draft | [交叉引用把 libobjc 的专用发送入口记成消息发送](draft-objc-runtime-send-entry-points.md) | Accepted | diff --git a/Documentations/Evolutions/draft-objc-runtime-send-entry-points.md b/Documentations/Evolutions/draft-objc-runtime-send-entry-points.md new file mode 100644 index 000000000..8363603c8 --- /dev/null +++ b/Documentations/Evolutions/draft-objc-runtime-send-entry-points.md @@ -0,0 +1,53 @@ +# Draft - 交叉引用把 libobjc 的专用发送入口记成消息发送 + +- **状态**: Accepted +- **创建日期**: 2026-10-27 +- **最后更新**: 2026-10-27 +- **所属愿景**: 无 +- **关联提案**: [0072](0072-cross-reference-analysis.md)(交叉引用分析) +- **实现分支 / PR**: `fix/cross-reference-review-findings`(worktree `.worktrees/MachOSwiftSection-CrossReferenceReviewFixes`,基于 `next`) + +## 摘要 + +clang 不把每个 Objective-C 发送都编成 `objc_msgSend`:`[[Foo alloc] init]` 编成 `objc_alloc_init(Foo)`,`[x isKindOfClass:c]` 编成 `objc_opt_isKindOfClass(x, c)`,`[Foo new]`、`[x class]`、`[x self]`、`[x respondsToSelector:s]`、`[Foo alloc]` 也各有一个 libobjc 入口。交叉引用扫描只把 `objc_msgSend` 和 `objc_msgSendSuper2` 当发送,这些入口记成普通函数调用,按 selector 查调用者时就漏掉。macOS 26.6 的 AppKit 里,`objc_alloc_init` 有 2,488 处调用,而按 selector 发送的 `init` 只有 720 处,查 `init` 的调用者漏掉约 78%;`isKindOfClass:`、`respondsToSelector:`、`alloc`、`new` 按 selector 发送的一处都没有(`objc_opt_isKindOfClass` 3,369 处、`objc_opt_respondsToSelector` 2,977 处、`objc_alloc` 4,180 处、`objc_opt_new` 590 处),查它们的调用者结果是空的。本案把这些入口的调用记成它们代表的发送。 + +## 方案 + +**认哪些入口,记成什么。** 入口和 `objc_msgSend` 一样按 libobjc 里的位置认:经桩、GOT 或缓存共用的桩到达那里都算;桩跟不过去、只剩导入名时按名字认。 + +| 入口 | 记成的发送 | +|------|-----------| +| `objc_alloc` | `alloc` | +| `objc_allocWithZone` | `allocWithZone:` | +| `objc_alloc_init` | `alloc` 与 `init` 两条,同一条指令 | +| `objc_opt_new` | `new` | +| `objc_opt_self` | `self` | +| `objc_opt_class` | `class` | +| `objc_opt_isKindOfClass` | `isKindOfClass:` | +| `objc_opt_respondsToSelector` | `respondsToSelector:` | + +**结果的形状不变,没有公开 API 改动。** + +- 发送照旧是 `.messageSend(selector:receiver:)`,`kind` 是 `.call` 或 `.tailCall`,`isRuntimeHelperCall` 为 false,表里归在 `.selector(名字)` 下,`CodeReferenceIndex` 不用改。 +- 和 `objc_msgSend` 一样,这处调用只记发送、不再同时记成对这个 C 函数的调用:按函数查 `_objc_alloc_init` 的调用者不再有结果。这些调用的 selector 永远已知,按 selector 查才是对的问法。 +- 接收者按 `x0` 判断,和 `objc_msgSend` 相同(`methodReceiver`、`classLiteral`、`unknown`)。`objc_alloc_init` 的 `init` 发给刚分配出来的实例,不是 `x0` 里的类,接收者记 `.unknown`。给它一个「某类的新实例」的提示要往公开的 `ReceiverClassHint` 里加一个 case,RuntimeViewer 里对它的穷举 switch 会编不过,这次不做。 +- `objc_opt_self`、`objc_opt_class` 调用之后 `x0` 照旧保留,类字面量接收者的识别不受影响。 + +**不认的入口。** `objc_retain`、`objc_release`、`objc_autorelease` 不算:ARC 插入的调用和 MRC 下源码里的 `[x retain]` 编出来的是同一个调用,分不开,继续当作 runtime helper。`swift_getInitializedObjCClass` 不是发送,只保留「原样返回传入的类」的处理。 + +**预筛。** `imageIndices(referencingSelector:among:)` 只看镜像的 `__objc_selrefs`,而一个镜像可能只经 `objc_alloc_init` 发送 `init`,`__objc_selrefs` 里根本没有 `init`。查上表里的 selector 时,导入了对应入口符号(`_objc_alloc_init` 等)的镜像也留下,定义这些入口的 libobjc 也留下。 + +**测试。** 测试里现场编一个 Objective-C dylib,覆盖上表每个入口,断言每处调用记成对应的发送;修改前这些调用是对 libobjc 函数的 `.function`。预筛另测这个一个 selector 引用都没有的镜像,八个 selector 的预筛都留下它;整个缓存上的预筛测试加上 `isKindOfClass:`(AppKit 里它只经 `objc_opt_isKindOfClass` 发送)。 + +**影响。** 查这些 selector 的调用者,结果会多出很多;按函数查这些 C 入口的调用者,结果会消失。RuntimeViewer 不用改代码,发版说明里要写这个行为变化。 + +## 决策日志 + +| 日期 | 决定 | 理由 | +|------|------|------| +| 2026-10-27 | Created as Draft | 2026-10-27 的审查发现,查 selector 的调用者会漏掉经 libobjc 专用入口的发送,AppKit 里查 `init` 漏掉约 78% | +| 2026-10-27 | `objc_alloc_init` 记 `alloc` 与 `init` 两条发送 | 它就是 `[[cls alloc] init]`,查 `alloc` 和查 `init` 的人都该找到它 | +| 2026-10-27 | 只记发送,不同时记成对 C 函数的调用 | 与 `objc_msgSend` 的处理一致;同时记两种会让每处调用多一条引用,按函数查这些入口的需求又几乎不存在 | +| 2026-10-27 | `init` 的接收者记 `.unknown`,不加新的接收者提示 | 新 case 是公开 enum 的破坏性改动;`.unknown` 不失真 | +| 2026-10-27 | 不认 `objc_retain` / `objc_release` / `objc_autorelease` | ARC 插入的调用与源码里的发送分不开 | +| 2026-10-27 | 用户批准,状态改为 Accepted | — | diff --git a/Documentations/Internal/Modules/CrossReferenceAnalysis.md b/Documentations/Internal/Modules/CrossReferenceAnalysis.md index a676abb7b..e886773fa 100644 --- a/Documentations/Internal/Modules/CrossReferenceAnalysis.md +++ b/Documentations/Internal/Modules/CrossReferenceAnalysis.md @@ -36,20 +36,49 @@ macOS 27 / iOS 27 起的那种见术语表 [cache-shared stub(全缓存共用 | 缓存 | ObjC 消息 | 跨库调用 | |---|---|---| -| macOS 15 至 26、iOS 26 及更早的真机,以及 Simulator | 镜像自己的 `__objc_stubs`(经 MachOKit `objcStubs(in:)` 读 selector 引用) | 镜像自己的 `__stubs` / `__auth_stubs`(MachOKit `stubs(in:)` 给出槽位) | +| macOS 15 至 26、iOS 26 及更早的真机,以及 Simulator | 镜像自己的 `__objc_stubs`(经 MachOKit `objcStubs(in:)` 读 selector 引用) | 镜像自己的 `__stubs` / `__auth_stubs`(MachOKit `stubs(in:)` 给出槽位;它读不出的 ld64 改写形态由 `ARM64Trampoline` 补读,见「链接器改写过的代码」) | | macOS 27、iOS 27 真机 | 镜像里的段大小为 0;`bl` 落到全缓存共用的 selector 桩:`adrp x1; add x1; b `,`x1` 就是 selector 字符串 | 全缓存共用的 GOT 桩:`adrp x17; add x17; ldr x16, [x17]; braa x16, x17` | 同一个 selector 在不同子缓存里各有一份共用桩(macOS 27.2:被调用的 155 万个桩只对应 104 万个字符串),所以 selector 以字符串为键,不以桩地址为键。GOT 槽在进程内已经绑定,读出指针、去掉指针认证位就是目标;读之前先确认槽位落在缓存的映射里。 +**去掉哪些位按平台定。** 从进程内存读出的指针(GOT 槽、selector 引用、类列表与 `isa`、Swift 类元数据 +0x40 与值类型元数据 +8 的描述符)一律经 `StoredPointer.address(in:)`,用 `InProcessContext.addressMask`,即 MachOKitExtensions 按镜像平台给的 `vmaddrMask`。Mac 的用户地址是 47 位,iPhone 等真机是 36 位,arm64e 的签名从地址宽度之上开始,iPhone 上从第 39 位开始。0.24.0 在六处写死了 Mac 的 47 位掩码,在 iOS、tvOS、watchOS、visionOS 真机上会把签名的第 39–46 位留在地址里,带签名的槽位全都跟不过去(第二轮审查 N1);`AddressMaskScanTests` 扫遍库的源码,不许再出现这种常量。 + 不经桩、直接 `bl` / `b` 到 `objc_msgSend` 的传统写法还有第三种形态:缓存构建器把读 selector 引用的 `adrp` / `ldr` 改写成了 `adrp` / `add` 出字符串本身的地址,指令里只剩字符串地址。macOS 27.2 的 `-[NSObject debugDescription]` 就是 `adrp x8; add x1, x8, #…; b _objc_msgSend`(`objc_msgSend` 在 `/usr/lib/objc/libobjcMsgSend.dylib` 里)。所以传统发送的 selector 两处都要认:`x1` 从本镜像的 `__objc_selrefs` 读来,或 `x1` 是 `adrp` / `add` 算出的地址;后者要确认它落在映射里、到结尾为止是不含空格的可打印字符(最长 1,024 字节),不满足就不当作发送。第一批漏了后一种,这些发送全被当成对 `objc_msgSend` 的普通调用;RuntimeViewer 第 3 步查 `-[NSObject description]` 的调用者时发现。 +### libobjc 的发送入口(提案 `objc-runtime-send-entry-points`) + +clang 把一部分发送编成对 libobjc 专用入口的调用:`[[Foo alloc] init]` 是 `objc_alloc_init(Foo)`,`[Foo alloc]`、`[Foo allocWithZone:nil]`、`[Foo new]` 是 `objc_alloc`、`objc_allocWithZone`、`objc_opt_new`,`[x self]`、`[x class]` 是 `objc_opt_self`、`objc_opt_class`,`[x isKindOfClass:c]`、`[x respondsToSelector:s]` 是 `objc_opt_isKindOfClass`、`objc_opt_respondsToSelector`。这样的发送不经 `objc_msgSend`,镜像里也可能没有这个 selector 的引用。macOS 26.6 的 AppKit 里 `objc_alloc_init` 有 2,488 处,按 selector 发送的 `init` 只有 720 处;`objc_opt_isKindOfClass` 3,369 处、`objc_opt_respondsToSelector` 2,977 处、`objc_opt_new` 590 处,对应的 selector 一次直接发送都没有。0.24.0 只认 `objc_msgSend`,这些都记成对 libobjc 函数的普通调用,查 `init` 的调用者漏掉约 78%,查另外几个一处都查不到(第二轮审查第 2 条)。 + +现在每处这样的调用记成它代表的发送(`Scanning/MessageSendEntryPoints`): + +- 入口按 libobjc 里的位置认,经桩、GOT 或共用桩到达都算;桩跟不过去、只剩导入名时按名字认。 +- 接收者按 `x0` 判断,与 `objc_msgSend` 相同。`objc_alloc_init` 在同一条指令上记 `alloc` 与 `init` 两条发送,`init` 发给 `alloc` 返回的实例,接收者记 `.unknown`。 +- 这些调用不再同时记成对 C 函数的调用:按函数查 `_objc_alloc_init` 的调用者没有结果,按 selector 查才对,与 `objc_msgSend` 的处理一致。 +- `objc_opt_self`、`objc_opt_class` 调用之后 `x0` 照旧保留(见「类引用」的类字面量接收者)。 +- `objc_retain`、`objc_release`、`objc_autorelease` 不算:ARC 插入的调用与源码里的 `[x retain]` 编出来是同一个调用,分不开,仍是运行时辅助调用。 +- selector 预筛(`imageIndices(referencingSelector:among:)`)对这几个 selector 另外留下导入或定义对应入口的镜像:只经 `objc_alloc_init` 发送 `init` 的镜像,`__objc_selrefs` 里根本没有 `init`。 + +### 链接器改写过的代码(第二轮审查) + +ld64——Xcode 14 及更早的链接器,以及 Xcode 15、16 加 `-ld_classic` 时用的那个——排好地址之后,会按编译器留下的 linker optimization hint 改写指令:槽位在一兆字节以内的 `adrp` / `ldr` 改成 `nop` / `ldr xN, <槽>`,地址在一兆字节以内的 `adrp` / `add` 改成 `adr xN, <地址>` / `nop`,懒绑定的桩改成 `nop` / `ldr x16, <槽>` / `br x16`。Xcode 26 的链接器不做这种改写,Xcode 27 不再带 `ld-classic`,Apple 自己的二进制里也没有;用旧工具链链接的第三方 App 里却常见。抽查的 12 个第三方 App 里有 2 个,其中 Asset Catalog Viewer(macOS 12 SDK)有 357 处 selector 引用和 71 处类引用以字面量 `ldr` 载入,212 个桩全是改写过的形态。 + +扫描把这些形态读成改写之前的样子: + +- 字面量 `ldr` 是从已知槽位载入(`RegisterFile.load(into:fromSlotAt:)`),载入的偏移记成槽位在页内的偏移,与改写前那对指令记下的相同。之后按槽位认 selector、类引用与 `__objc_superrefs`,与 `adrp` / `ldr` 一样。 +- `adr` 与 `adrp` / `add` 一样:算出的地址是类对象、元数据或元数据访问器时,报一处引用。`ARM64InstructionWord.addressMaterialization` 的 `isPageAddress` 区分两者,只给出页地址的 `adrp` 不报。 +- 改写过的桩,MachOKit(0.54.101)的 `stubs(in:)` 读不出槽位,给的是 `.unknown`;`ImageFunctionTable` 这时改用 `ARM64Trampoline` 读桩自己的字节,`ARM64Trampoline` 认字面量 `ldr`。SwiftThunkAnalysis 也经 `ARM64Trampoline` 认桩,同样受益。0.24.0 时这些桩只剩导入名,经它们调用 `objc_msgSend` 的发送一处也认不出来。 + +SwiftThunkAnalysis 自己的 Capstone 解码器原先也把字面量 `ldr` 当成不建模的指令,同一轮补上了 `ThunkOperation.loadFromSlot`,求值时按槽位读,与 `adrp` / `ldr` 相同。0.24.0 之前的设计判断是「缓存与几个缓存外的系统 App 里都没有这两种形态,不解码」,那次只量了 Apple 自己的二进制。 + +`LinkerOptimizationHintTests` 现编两个 dylib,按 ld64 的做法把这几种指令改写好、重新签名后加载,核对四种形态都读对;修复前四个测试都失败。 + ### 读任何目标之前先确认它可读 `__text` 里夹着数据(跳转表之类,缓存镜像的 `LC_DATA_IN_CODE` 是空的),按指令解码会得到指向任意地址的「跳转」。扫描只在目标落在某个镜像的 `__TEXT`、或缓存的可执行映射里时才去读那里的指令;读槽位前确认它在缓存或镜像的映射里。探针第一次全量扫描就崩在没做这一步上。 ### 寄存器跟踪只记确定的事 -`RegisterFile` 只记录 `adrp` / `adr` / `add` 算出的地址、从已知地址加载的槽位、ObjC 方法入口时 `x0` 里的接收者、指针认证常量,以及「这个寄存器的值是从内存读来的」和读取时的偏移。不建模的指令一律作废它写的寄存器(宁可多忘,不留陈旧的值);调用作废 `x0`–`x18` 与 `x30`——原样返回所传类的三个函数例外,`x0` 留着(见「类引用」)。PAC 与 AUT 原地签名或认证,寄存器的含义不变,保留;XPAC 作废。 +`RegisterFile` 只记录 `adrp` / `adr` / `add` 算出的地址、从已知地址加载的槽位(`ldr` 的基址算得出来,或者是字面量 `ldr xN, <槽>`)、ObjC 方法入口时 `x0` 里的接收者、指针认证常量,以及「这个寄存器的值是从内存读来的」和读取时的偏移。不建模的指令一律作废它写的寄存器(宁可多忘,不留陈旧的值);调用作废 `x0`–`x18` 与 `x30`——原样返回所传类的三个函数例外,`x0` 留着(见「类引用」)。PAC 与 AUT 原地签名或认证,寄存器的含义不变,保留;XPAC 作废。 一条指令写哪些寄存器由 `RegisterFile.registersWritten(by:)` 按 A64 的编码分组判断,容易漏的几类:前 / 后变址的读写(单寄存器与寄存器对、通用与 SIMD 寄存器都一样)会改掉基址寄存器;原子指令不论内存序都返回旧值,不带内存序的那种(`ldadd`、`swp`)编码像存储;`ldxp` 写第二个寄存器,`casp` 写 `Rs` 与 `Rs+1`;`umov` / `smov`、浮点转整数与转定点写通用寄存器;SVE / SME 里有几条写通用寄存器(`cntd`、`addvl`、`rdsvl`);`mrs` 与 `sysl`;`svc` 的结果在 `x0`、`x1`。第一批漏了其中大半(交叉引用审查 A1);`RegisterFileTests` 用汇编器编出的 48 条指令逐条核对,并用 Capstone 的寄存器访问表独立核对那张表没有漏项(Capstone 把 `cas` / `casp` 的基址也算作被写,架构上并不写,测试里列为已知偏差)。SwiftThunkAnalysis 的两个跟踪器同一轮补上了成对回写的基址。 @@ -67,13 +96,13 @@ macOS 27 / iOS 27 起的那种见术语表 [cache-shared stub(全缓存共用 ### 类引用(第二批) -一条指令取了某个类对象的地址、但不跳转,就是一处类引用:`CodeReference.Kind.reference`,目标 `.objectiveCClass(name:location:)`。macOS 27.2 的缓存里几乎没有 `__objc_classrefs` 了,类有三种取法:`adrp` / `add` 出本镜像的类对象(AppKit 3,319 处);从本镜像的 `__got` / `__auth_got` 载入;从缓存放在所有镜像之外的共用 GOT 池载入别的镜像的类(AppKit 后两种合计 53,026 处)。缓存外的二进制还经 `__objc_classrefs`。别的槽里即使放着类指针也不算:常量字符串的 `isa`(`__cfstring`)、缓存某个类的全局变量都不是对类的静态引用。`adr` 与字面量 `ldr` 两种形态在 AppKit、SwiftUI、Foundation 与几个缓存外的系统 App 里一处都没有,不解码。元类的引用按它的类报。 +一条指令取了某个类对象的地址、但不跳转,就是一处类引用:`CodeReference.Kind.reference`,目标 `.objectiveCClass(name:location:)`。macOS 27.2 的缓存里几乎没有 `__objc_classrefs` 了,类有三种取法:`adrp` / `add` 出本镜像的类对象(AppKit 3,319 处);从本镜像的 `__got` / `__auth_got` 载入;从缓存放在所有镜像之外的共用 GOT 池载入别的镜像的类(AppKit 后两种合计 53,026 处)。缓存外的二进制还经 `__objc_classrefs`。别的槽里即使放着类指针也不算:常量字符串的 `isa`(`__cfstring`)、缓存某个类的全局变量都不是对类的静态引用。ld64 改写出的 `adr` 与字面量 `ldr` 也按这三种取法认,见下文「链接器改写过的代码」。元类的引用按它的类报。 **一个值是不是类对象,看它所在的镜像列没列它。** 不能按所在的节判断:缓存里 9.2 万个 Swift 类与元类放在 `__data` 而不是 `__objc_data`。`ObjectiveCClassIndex` 直接读 `__objc_classlist` 与每个类的 `isa`(即元类),不经 `MachOImage.objc.classes64`——后者对每个类都重新查一遍 load command,扫描全缓存时让整表扫描慢了一倍。类名只在要报出引用时经 `MachOObjCSection` 读 `class_ro_t`(类已被运行时实现时经 `class_rw_t`)。 **类的身份带位置。** 全缓存 203,621 个类名里有 18,906 个不止一个镜像定义——多是 `/System/iOSSupport` 下的 Mac Catalyst 变体,两个 SwiftUI 都定义 `_TtC7SwiftUI13PinnedBarView`。引用表的键是类名(`CodeReferenceTable.Key.objectiveCClass`,预筛与过滤都按它),引用目标另带类对象的 `CodeLocation`,宿主按位置区分。`objectiveCClassLocations(named:inImageAt:)` 把宿主手里的(镜像,类名)换成位置。 -**类字面量接收者。** 发送时 `x0` 里是这样取来的类,接收者记为 `.classLiteral(名字)`(AppKit 35,175 处,发送的 11%)。`objc_opt_self`、`objc_opt_class`、`swift_getInitializedObjCClass` 原样返回传入的类,调用之后 `x0` 不作废:Swift 调 ObjC 类方法先过 `objc_opt_self`,SwiftUI 665 处类字面量接收者里 478 处经它。 +**类字面量接收者。** 发送时 `x0` 里是这样取来的类,接收者记为 `.classLiteral(名字)`(AppKit 35,175 处,发送的 11%)。`objc_opt_self`、`objc_opt_class`、`swift_getInitializedObjCClass` 原样返回传入的类,调用之后 `x0` 不作废:Swift 调 ObjC 类方法先过 `objc_opt_self`,SwiftUI 665 处类字面量接收者里 478 处经它。前两者本身也记成 `self`、`class` 发送(见「libobjc 的发送入口」)。 **super 发送的类**取同一函数里从 `__objc_superrefs` 载入的类:分类方法(`-[NSDictionary(NSKeyValueCoding) valueForKey:]` 得到 `NSDictionary`)、类方法(槽里是元类,按类报)、没有符号的方法都对;没见到这种载入就退回方法符号里的类。这一载入本身不算类引用——它是编译器实现 `super` 的方式,报出来只会让每个调 `super` 的方法都「引用」了自己的类。Swift 代码的 super 发送不经 `__objc_superrefs`,类来自 `self` 的运行时类或元数据访问器的返回值,扫描不知道,类记为空:Foundation 1,803 处 super 发送里有 374 处、AppKit 8,336 处里有 1,133 处是这种,其余都有类。 @@ -93,7 +122,7 @@ macOS 27 / iOS 27 起的那种见术语表 [cache-shared stub(全缓存共用 **表按描述符位置归档**(`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`。 -**查询**(`references(toSwiftType:inImageAt:)`)带一个比对器:访问器与元数据的引用比描述符位置;名字逐字节走,符号引用(`\x01` 直接、`\x02` 经指针)指向的描述符就是这个类型,就算提到了它。只有名字可能直接拼出来的类型——标准库、`_Concurrency`、从 C / ObjC 导入的,key 以 `s` 或 `S` 开头——才解开名字确认;文本子串比对不可靠,mangling 会把同一名字里重复出现的单词换成替身。前提是其他类型在名字里一定以符号引用出现:在 Foundation、SwiftData、libswift_Concurrency、SwiftUI 里逐个解开全部名字核对过,没有例外(AppIntentsServices 有 56 处 key 对不上,原始字节全是符号引用,是那个镜像没有 `…Mn` 符号造成的拼法差别)。导入的类型每个用到它的镜像各有一份描述符,比的是 key。Swift 类同时比它的 ObjC 类对象的位置。macOS 与 Mac Catalyst 变体里的同一个类型按位置分开。协议没有类型描述符,不在这一批。 +**查询**(`references(toSwiftType:inImageAt:)`)带一个比对器:访问器与元数据的引用比描述符位置;名字逐字节走,符号引用(`\x01` 直接、`\x02` 经指针)指向的描述符就是这个类型,就算提到了它。只有名字可能直接拼出来的类型——标准库、`_Concurrency`、从 C / ObjC 导入的,key 以 `s` 或 `S` 开头——才解开名字确认;文本子串比对不可靠,mangling 会把同一名字里重复出现的单词换成替身。前提是其他类型在名字里一定以符号引用出现:在 Foundation、SwiftData、libswift_Concurrency、SwiftUI 里逐个解开全部名字核对过,没有例外(AppIntentsServices 有 56 处 key 对不上,原始字节全是符号引用,是那个镜像没有 `…Mn` 符号造成的拼法差别)。导入的类型每个用到它的镜像各有一份描述符,比的是 key,比 key 之前先比描述符给的名字。名字只从类型描述符读(`SwiftTypeIndex.name(ofDescriptorAt:)` 先看标志位低五位的种类是不是 16–31):符号引用指向的也可能是不透明类型(`some View`)的描述符,它在 +8 放的是泛型头,一个参数、一个约束读成偏移就是 64 KiB,在小镜像里读出镜像之外。0.24.0 没有这道检查,查导入类型时可能让宿主崩溃(第二轮审查 11,`importedTypeQueriesReadNoNameWhereNoTypeDescriptorIs` 在子进程里复现到 SIGBUS)。Swift 类同时比它的 ObjC 类对象的位置。macOS 与 Mac Catalyst 变体里的同一个类型按位置分开。协议没有类型描述符,不在这一批。 宿主的用法:类型对象 → 描述符位置(或经 `swiftTypeDescriptorLocations(withKey:inImageAt:)`,先找 `…Mn` 符号)→ `swiftTypeIdentity(ofDescriptorAt:)` → 预筛 → 每个候选镜像 `references(toSwiftType:inImageAt:)`。`swiftTypeKeys(in:)` 解开一个 `SwiftTypeName`,供显示用。 @@ -136,7 +165,7 @@ Swift 符号改按链接关系预筛(`imageIndices(linkingImageAt:among:)`,` ### 缓存外镜像的 GOT 槽 -缓存外的镜像(第三方 App 自己的二进制)经自己的 `__stubs` / `__auth_stubs` 调别的镜像,槽位由 dyld 在加载时绑定,按 macOS 11 部署目标、不用 chained fixups 编出来的懒绑定二进制也一样:macOS 27.2 上以 `RTLD_LAZY` 加载,函数第一次被调用之前槽里已经是目标地址。所以扫描直接读槽。`LazyBindingTests` 是这件事的哨兵:哪天 dyld 不再在加载时绑定,槽会指回镜像自己的 `__stub_helper`,测试变红,那时再退回桩上的导入名。 +缓存外的镜像(第三方 App 自己的二进制)经自己的 `__stubs` / `__auth_stubs` 调别的镜像,槽位由 dyld 在加载时绑定,按 macOS 11 部署目标、不用 chained fixups 编出来的懒绑定二进制也一样:macOS 27.2 上以 `RTLD_LAZY` 加载,函数第一次被调用之前槽里已经是目标地址。所以扫描直接读槽。`LazyBindingTests` 是这件事的哨兵:哪天 dyld 不再在加载时绑定,槽会指回镜像自己的 `__stub_helper`,测试变红,那时再退回桩上的导入名。它在 macOS 27.2 与 26.6 上都通过(2026-10-27 第二轮审查据此把「懒绑定的槽指向 `__stub_helper`」判为误报,[ReviewAdjudications A80](../ReviewAdjudications.md))。ld64 链接的懒绑定桩多半是改写过的 `nop` / `ldr x16, <槽>` / `br x16`,槽位由 `ARM64Trampoline` 读出,见上文「链接器改写过的代码」。 ### 缓存、内存与生命周期 @@ -144,7 +173,7 @@ Swift 符号改按链接关系预筛(`imageIndices(linkingImageAt:among:)`,` 第二批起分析器还在自己的生命期里留着:扫描碰到的每个镜像的类索引(类与元类按地址,类名读过的记住)与类型索引(描述符与访问器,key 算过的记住),链接关系,以及改名再导出表。它们以缓存里的类与类型的总数为上限(macOS 27.2 有 203,621 个类名),没有单独测过占用;下面那个约 170 MB 的数字是第二批之前测的。宿主想放掉,用 `releaseImageData(exceptForImagesAt:)` 放掉指定镜像以外按镜像留着的一切——函数表连同读过的名字、类索引、类型索引;链接关系与改名再导出表不按镜像,留着——或者换一个分析器。RuntimeViewer 的会话在缓存外的镜像变化时换分析器;起过名的镜像(预先准备的除外)超过 64 个时,只放掉预先准备之外的。2026-10-18 之前后一种情况也是换分析器,预先读好的名字跟着丢了,下一次查询又得重读。 -分析器存活期间若有缓存外的镜像被卸载,再读它会读到已释放的内存;极少见,没有防(A63)。名字的解开一律是瞬时的:类型查询碰到的访问器符号与 mangled 名字不进全局的 `NodeCache`,也不进进程级的 demangle 记忆(交叉引用审查 B2,`TypeNameRetentionTests`),按镜像的 `demangleContext` 记忆随镜像淘汰。 +分析器存活期间若有缓存外的镜像被卸载,再读它会读到已释放的内存;极少见,没有防(A63)。名字的解开一律是瞬时的:类型查询碰到的访问器符号与 mangled 名字不进全局的 `NodeCache`,也不进进程级的 demangle 记忆(交叉引用审查 B2,`TypeNameRetentionTests`)。例外是没有 `…Mn` 符号的类型算 key、起名时用的 `SymbolicDemangler.demangleContext`:它的结果记在按镜像的 `SharedCache` 里,`releaseImageData(exceptForImagesAt:)` 不管它,由宿主调 `SharedCacheRegistry.shared.evictImagesWithoutLiveOwners()` 回收,与库里其它按镜像的缓存相同([ReviewAdjudications A78](../ReviewAdjudications.md))。 `CodeReferenceTable` 是值,宿主想留多久就留多久,按 `approximateByteCount` 计预算(不含字符串的堆存储;同一次扫描里重复的名字共用一份)。大镜像的整表很大(GeoServices 约 121 MiB,全缓存合计约 9 GB),28 个线程同时建整表时峰值约 1.5 GB,分配器之后还留着 1.2 GB 脏页不还。**查调用者用 `references(to:inImageAt:)`**:扫描时只留命中的引用,同样扫完全缓存后常驻约 170 MB(4 线程约 106 MB)。 @@ -167,10 +196,13 @@ Swift 符号改按链接关系预筛(`imageIndices(linkingImageAt:among:)`,` ## 测试锚点 -- `ARM64InstructionWordTests` / `ARM64TrampolineTests`:手写编码器造指令字;`capstoneAgreesWithTheEncoders` 让 Capstone 反汇编同一批字,编码器写错也藏不住。 +- `ARM64InstructionWordTests` / `ARM64TrampolineTests`:手写编码器造指令字;`capstoneAgreesWithTheEncoders` 让 Capstone 反汇编同一批字,编码器写错也藏不住。`linkerRewrittenAddressesAndLoads` 与 `linkerRewrittenSlotStub` 核对 ld64 改写出的 `adr`、字面量 `ldr` 与桩。 +- `LinkerOptimizationHintTests`:现编的 dylib 按 ld64 的做法改写后,字面量 `ldr` 载入的 selector 认成发送、载入的类与 `adr` 取的类认成类引用,改写过的桩跟到 libsystem_c 的 `puts`。编译与改写的辅助代码在 `CompiledFixture`。 +- `RuntimeSendEntryPointTests`:现编的 dylib 里八个 libobjc 入口各调用一处,每处都记成对应的发送(`objc_alloc_init` 两条,在同一条指令上),不再有对 libobjc 函数的调用;八个 selector 的预筛都留下这个没有一个 selector 引用的镜像。修复前全部失败。 +- `AddressMaskScanTests`:库的源码里不许出现 33 到 62 位宽的地址掩码常量,指针一律按平台的掩码去掉签名。`AbbreviatedIdentifierScanTests`:`Sources` 与 `Tests` 里不许再用 `pc`、`lhs`、`rhs` 当名字(`Tests/Projects` 的 fixture 源码除外)。 - `CrossReferenceAnalyzerTests`(只在 arm64 进程里跑):`-[NSWindow makeKeyAndOrderFront:]` 发出的三条消息及接收者;SwiftUICore 经桩调用 `swift_beginAccess` 落到 libswiftCore;按键过滤与整表一致;整镜像扫描不留函数表;给一批结果起名也不留;预筛;`branchesCarryTheirStateToTheirTargets` 与 `pathsThatDisagreeLeaveTheRegisterUnknown`:寄存器状态沿着分支走(见上文),后者在第一批的顺序读法下失败;`classicSendsInsideTheCacheNameTheirSelector`:libobjc 的 `-[NSObject debugDescription]` 认出发给 `self` 的 `description`(上文「两种桩布局」末段的第三种形态);`selectorPrefilterKeepsEverySender` / `importPrefilterKeepsEveryCaller` / `swiftFunctionPrefilterKeepsEveryCaller`:预筛只丢掉引用不到主体的镜像(最后一个是 Swift 函数,见上文「预筛:缓存几乎不留 Swift 的未定义符号」)——在它丢掉的镜像里每 16 个抽 1 个扫描,一处引用也不许有(Debug 构建扫完整个缓存要几分钟,所以抽样);`callSitesMatchCapstone` 抽样 400 个 AppKit 函数,双向比对:Capstone 找到的每一处调用与跳出函数的跳转,扫描都找到了;扫描报的每一处也都是 Capstone 眼里的调用或跳转(`br` 除外,Capstone 分不出跳转表与尾调用)。Capstone 不开 detail 模式就不给操作数,那半边比对曾因此什么都没比,测试断言比对过不止一处。 - `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`)。 +- `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 出来是元数据访问器。 - `StandaloneImageTests`:SymbolTestsCore fixture 经自己的桩调用 libswiftCore,没有一条停在只有名字的导入上;它的路径是加载路径而不是 `@rpath/…`,安装名也能查回它;测试包(`MH_BUNDLE`,没有安装名)的路径等于 `dladdr` 给的;测试包算作主程序的依赖方。 - `RegisterFileTests`:48 条汇编器编出的指令,每条写的寄存器都被作废,Capstone 的寄存器访问表独立核对这张表;普通读写只作废目标寄存器。 diff --git a/Documentations/Internal/Modules/SwiftThunkAnalysis.md b/Documentations/Internal/Modules/SwiftThunkAnalysis.md index bfef02a2a..5b868135d 100644 --- a/Documentations/Internal/Modules/SwiftThunkAnalysis.md +++ b/Documentations/Internal/Modules/SwiftThunkAnalysis.md @@ -57,6 +57,8 @@ Capstone 自己的 `writeback` 标志——那个标志对任何绑定操作数 寄存器列表中同样不能判定写回,因为 `ldr x0, [x0]` 也会写 `x0`。后索引的访问偏移为零,更新量不是本次访问 的偏移。现有求值器仍保守处理写回的成对访存,未新增栈更新模拟。 +字面量 `ldr xN,